body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I have a model object class like this</p>
<pre><code>public class EventInterestsResponse
{
public string id { get; set; }
public int sortOrder { get; set; }
public string name { get; set; }
public string categoryName { get; set; }
public string categoryId { get; set; }
}
</code></pre>
<p>And I am using it to hold some data like this</p>
<pre><code>public List<EventInterestsResponse> GetEventInterests()
{
_data = _rh.ExecuteGetRequest();
var yourObject = _data != null ? (List<EventInterestsResponse>)jsonSerializer.Deserialize<List<EventInterestsResponse>>(_data) : null;
return yourObject;
}
</code></pre>
<p>Later I want to preform some operations on this.
For example, I want to check if any of the resulting objects contain a specific <code>categoryId</code> and if yes, I want to print it. I have written this working code:</p>
<pre><code>foreach (var interest in InterstList)
{
if (interest.categoryId == "11")
{
<strong>Branche:@interest.name</strong>
}
if (interest.categoryId == "22")
{
<strong>Udviklingsstadie:@interest.name</strong>
}
}
</code></pre>
<p>Now I wonder: Is this the most elegant way to do this? Maybe I don't even want to use a <code>foreach</code> loop. Can this be achieved by LINQ and using lambda expressions?</p>
<p>Can any one tell me how I can modify this code so that it uses LINQ and lambda expressions?</p>
|
[] |
[
{
"body": "<p>I'm not sure if this is any better and it might depend on how many if statements or different categories you have whether it's worth it. But an alternative could be something like:</p>\n\n<pre><code>var categoryLabelValues = new Dictionary<string, string>()\n {\n {\"11\", \"Branche\"},\n {\"22\", \"Udviklingsstadie\"}\n };\n\nforeach(var interest in InterstList\n .Where(p => categoryLabelValues.ContainsKey(p.categoryId)))\n{ \n <strong>@categoryLabelValues[interest.categoryId]:@interest.name</strong>\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T08:02:28.817",
"Id": "40247",
"ParentId": "40245",
"Score": "4"
}
},
{
"body": "<p>Some suggestions to improve your code:</p>\n\n<p>There is a convention for naming things (see <a href=\"https://msdn.microsoft.com/en-us/library/ms229043(v=vs.110).aspx\" rel=\"nofollow noreferrer\">https://msdn.microsoft.com/en-us/library/ms229043(v=vs.110).aspx</a>) Properties should be written in <code>PascalCase</code></p>\n\n<pre><code>public class EventInterestsResponse\n{\n public string Id { get; set; }\n public string Name { get; set; }\n public string CategoryName { get; set; }\n public string CategoryId { get; set; }\n public int SortOrder { get; set; }\n}\n</code></pre>\n\n<p>A better approch to returning <code>null</code> is returning an empty collection: it's safer for the caller (no need to check for null):</p>\n\n<pre><code>var list = GetEventInterests();\nif (list != null) \n{\n foreach (var item in list) \n {\n ...\n } \n}\n</code></pre>\n\n<p>VS</p>\n\n<pre><code>foreach (var item in GetEventInterests()) \n{\n ...\n}\n</code></pre>\n\n<p>I'd change your method as follow:</p>\n\n<pre><code>public IList<EventInterestsResponse> GetEventInterests()\n{\n var eventInterests = new List<EventInterestsResponse>();\n\n _data = _rh.ExecuteGetRequest();\n\n if (_data != null) \n {\n eventInterests = (List<EventInterestsResponse>) jsonSerializer.Deserialize<List<EventInterestsResponse>>(_data);\n } \n\n return eventInterests;\n}\n</code></pre>\n\n<p>ps: What is a \"EventInterests\"? It sound strange to me, maybe we can find a better name ;-)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-05-25T10:47:16.263",
"Id": "164167",
"ParentId": "40245",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "40247",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T06:48:26.953",
"Id": "40245",
"Score": "5",
"Tags": [
"c#",
"asp.net",
"linq",
"razor"
],
"Title": "Convert looping statement to linq mode"
}
|
40245
|
<p>I'm looking for a code review, clever optimizations, and good coding practices. Unit testing has been a visual inspection and concluded expectations match. Also, is the space complexity of the extra variable used to swap \$O(1)\$? Typically, is \$O(1)\$ an acceptable space to use when code requires no extra memory?</p>
<pre><code>public final class RotateNinetyInPlace {
private RotateNinetyInPlace() {}
private static void transpose(int[][] m) {
for (int i = 0; i < m.length; i++) {
for (int j = i; j < m[0].length; j++) {
int x = m[i][j];
m[i][j] = m[j][i];
m[j][i] = x;
}
}
}
public static void rotateByNinetyToLeft(int[][] m) {
// transpose
transpose(m);
// swap rows
for (int i = 0; i < m.length/2; i++) {
for (int j = 0; j < m[0].length; j++) {
int x = m[i][j];
m[i][j] = m[m.length -1 -i][j];
m[m.length -1 -i][j] = x;
}
}
}
public static void rotateByNinetyToRight(int[][] m) {
// transpose
transpose(m);
// swap columns
for (int j = 0; j < m[0].length/2; j++) {
for (int i = 0; i < m.length; i++) {
int x = m[i][j];
m[i][j] = m[i][m[0].length -1 -j];
m[i][m[0].length -1 -j] = x;
}
}
}
public static void main(String[] args) {
int[][] mEven = {{1, 3},
{2, 4}};
rotateByNinetyToLeft(mEven);
for (int i = 0; i < mEven.length; i++) {
for (int j = 0; j < mEven[0].length; j++) {
System.out.print(mEven[i][j] + " ");
}
System.out.println();
}
System.out.println("---------------------------------");
rotateByNinetyToRight(mEven);
for (int i = 0; i < mEven.length; i++) {
for (int j = 0; j < mEven[0].length; j++) {
System.out.print(mEven[i][j] + " ");
}
System.out.println();
}
System.out.println("---------------------------------");
int[][] mOdd = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
rotateByNinetyToLeft(mOdd);
for (int i = 0; i < mOdd.length; i++) {
for (int j = 0; j < mOdd[0].length; j++) {
System.out.print(mOdd[i][j] + " ");
}
System.out.println();
}
System.out.println("---------------------------------");
rotateByNinetyToRight(mOdd);
for (int i = 0; i < mOdd.length; i++) {
for (int j = 0; j < mOdd[0].length; j++) {
System.out.print(mOdd[i][j] + " ");
}
System.out.println();
}
System.out.println("---------------------------------");
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T10:19:09.967",
"Id": "67686",
"Score": "0",
"body": "this is indeed O(1) space needed (2 indexes and the swap var+ generic stack space) and yes O(1) is indeed what is understood with no extra memory"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T12:48:06.327",
"Id": "67700",
"Score": "0",
"body": "I'm not sure if it requires extra memory or not, but I do know it is slower is the trick to use the xor operator (^) to swap two variables. it's something like a=a^b; b=a^b; a=a^b; but I saw (i think on stackoverflow) where someone compared the speeds and it was slower, and another person found it about the same. Food for thought."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T14:26:29.000",
"Id": "67720",
"Score": "1",
"body": "@RobertSnyder not in the stack based +JITted java where you'd need to load both on the stack anyway and then you might as well write them out in opposite order, if the JIT optimizer thinks the xor-swap is faster then it will do so."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T14:33:08.377",
"Id": "67725",
"Score": "1",
"body": "@ratchetfreak yeah it's hard to tell what the compiler will do when it goes to optimize your code. Something that I've always struggled with."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T14:35:43.407",
"Id": "67728",
"Score": "0",
"body": "A long time ago my father-in-law had me make a matrix to matrix multiplier in Java and said find the fastest way to multiply them. So I wrote out 3 different ways to write them and timed all 3. Even though it didn't seem to matter to me which way I multiplied the order in which I accessed the variables made a very slight difference in speed. (I think overall the difference in time was like 500 milliseconds) That is my other recommendation is try different orders of accessing the variables and timing it (multiple times of course and take the average)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T16:50:30.970",
"Id": "67772",
"Score": "0",
"body": "Please include a note that describes what you think the `transpose()` method does, as text. Also, \"RotateToLeft\" means clockwise or anti-clockwise?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T08:06:45.450",
"Id": "67909",
"Score": "0",
"body": "RotateToLeft - anti-clockwise, point noted"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T15:42:59.773",
"Id": "67960",
"Score": "2",
"body": "`If question is unclear drop by a comment, I will clarify asap.` Please read [What makes a good question?](http://meta.codereview.stackexchange.com/a/76/34757)"
}
] |
[
{
"body": "<p>You ask many questions on CodeReview, which in itself is good, but you have to start helping the reviewers actually review your code. You have this habit of dumping code and expecting a review. It does not work that way (very well). For a start, let's review the ideal process for a 'real' review:</p>\n\n<ol>\n<li>you present neat and working code for review.</li>\n<li>you include a description of the context of the code - what it does, why it is needed, and what constraints it has.</li>\n<li>you provide some specifications or documentation for any complicated or significant algorithms</li>\n<li>the reviewer reviews the code, not only for neatness, and style, but to:\n<ul>\n<li>check the code works the way it is supposed to (by visual inspection)</li>\n<li>suggest alternative approaches that may achieve the same results faster or in a better way</li>\n<li>suggest alternative approaches that may produce different results but may be better for other reasons</li>\n</ul></li>\n<li>signs off that the code is:\n<ul>\n<li>good (or great and gives you a high five)</li>\n<li>good enough but has some future anticipated improvements</li>\n<li>not good enough and needs to be fixed then resubmitted</li>\n</ul></li>\n</ol>\n\n<p>The details, descriptions, references and specifications you provide with the request is essential if the reviewer is going to give a decent review.</p>\n\n<p>On Code review, the process continues with:</p>\n\n<ul>\n<li>upvoting answers that are helpful (and down-voting those that are not).</li>\n<li>accepting answers that (among other answers) best address your concerns.</li>\n</ul>\n\n<p>Your question above is lacking any description of what the code is supposed to do, and how it does it. All you do say is:</p>\n\n<ul>\n<li>I want hints and reviews</li>\n<li>it works</li>\n<li>what is the complexity</li>\n</ul>\n\n<p>As a result, the only specification available and description of what the code should be doing, is what the code actually does. Or the title of the post....</p>\n\n<hr>\n\n<p>Bottom line is that you have only given a fraction of what is needed for a good review, so, I will take a stab at doing a review with similar feedback....</p>\n\n<p>A good alternative approach for your code is:</p>\n\n<pre><code>public static void rotateByNinetyToLeft(int[][] m) {\n\n int e = m.length - 1;\n int c = e / 2;\n int b = e % 2;\n for (int r = c; r >= 0; r--) {\n for (int d = c - r; d < c + r + b; d++) {\n int t = m[c - r][d];\n m[c - r][d] = m[d][e - c + r];\n m[d][e - c + r] = m[e - c + r][e - d];\n m[e - c + r][e - d] = m[e - d][c - r];\n m[e - d][c - r] = t;\n }\n }\n}\n</code></pre>\n\n<p>This approach is <em>O(n)</em> time complexity (n is the number of pixels in the matrix), and <em>O(1)</em> space complexity</p>\n\n<p>I have tested this and it works.</p>\n\n<p>You can use the right-handed approach for <code>rotateByNinetyToRight</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T15:59:37.287",
"Id": "67963",
"Score": "3",
"body": "The top part should be FAQ'd on meta ;) +1 as soon as votes reload!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-28T01:18:09.877",
"Id": "242384",
"Score": "0",
"body": "As mat said this is not the place to inform users. Maybe chat on this case would be prefered. Also only because the OP question does not follow the good guidelines you suggested it doesnt mean you should drop the quality of your answer, you might be guiving an incentive for ppl to behave like you to other questions"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-28T02:23:03.773",
"Id": "242387",
"Score": "0",
"body": "Hey @BrunoCosta - I guess after 2.5 years things should be cleared up"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T15:26:25.143",
"Id": "40369",
"ParentId": "40246",
"Score": "15"
}
},
{
"body": "<p>You can swap entire rows.</p>\n\n<pre><code>public static void swapRows(int[][] m) {\n for (int i = 0, k = m.length - 1; i < k; ++i, --k) {\n int[] x = m[i];\n m[i] = m[k];\n m[k] = x;\n }\n}\n\npublic static void rotateByNinetyToLeft(int[][] m) {\n transpose(m);\n swapRows(m);\n}\n\npublic static void rotateByNinetyToRight(int[][] m) {\n swapRows(m);\n transpose(m);\n}\n</code></pre>\n\n<p>Rotating right can use swapRows instead of swapping columns too, if the transpose is done afterwards.</p>\n\n<hr>\n\n<p><em><strong>About complexity</em></strong></p>\n\n<p>Time complexity is irrelevant here: implementing rotateByNinetyToRight by calling three times rotateByNinetyToLeft would not change the complexity. Though physically would be three times slower.</p>\n\n<p>However the transpose and swap-rows do two for-loops. One might think that for large matrices that would imply extra memory page swapping. With a bit of juggling one could \nimmediately swap the right points:</p>\n\n<pre><code>...a.\nd....\n.....\n....b\n.c...\n</code></pre>\n\n<p>One could rotate (abcd) to (dabc). But that does not seem to help either in memory swapping. So I think the algorithm is also in physical time sufficiently optimal.</p>\n\n<p>Extra space for <code>x</code> is ofcourse irrelevant.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T17:07:42.530",
"Id": "67966",
"Score": "0",
"body": "nice answer.... BTW, the code I suggested does the exact a-b-c-d rotation for all points in a quadrant."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T17:35:04.207",
"Id": "67969",
"Score": "0",
"body": "@rolfl yes I checked and gave +1. Liked the how you picked the quarter: `[0, m.length/2] x [0, m.length - m.length/2]` as it should for `odd m.length`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-05-25T20:20:27.120",
"Id": "312216",
"Score": "0",
"body": "I didn't know you could use for loops that way :O"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T15:55:35.477",
"Id": "40372",
"ParentId": "40246",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "40372",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T07:30:31.417",
"Id": "40246",
"Score": "6",
"Tags": [
"java",
"matrix"
],
"Title": "Given N*N matrix, rotate it by 90 degree to left and right without extra memory"
}
|
40246
|
<p>Stack Overflow tag wiki: <a href="http://stackoverflow.com/tags/codenameone/info">http://stackoverflow.com/tags/codenameone/info</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T08:02:39.587",
"Id": "40248",
"Score": "0",
"Tags": null,
"Title": null
}
|
40248
|
<p>I have an entity <code>RegistrationForm</code> which has a OneToMany-relationship with <code>SurveyAnswer</code>. </p>
<p>An answer can either have a collection of <code>FormOptions</code> (when the answer is of type <code>MULTIPLE_CHOICE</code>) or a <code>content</code> represented by a string (type <code>TEXT-FIELD</code>, <code>TEXTAREA</code> etc.). </p>
<p>Below is a function inside the <code>RegistrationForm</code>-entity that tries to obtain a string-based representation of the answer's content. </p>
<pre><code>public function getAnswerByColumnId($columnId) {
foreach ($this->surveyAnswers as $answer) {
if ($answer->getFormQuestion()->getId() == $columnId) {
$formOptions = $answer->getFormOptions();
if (count($formOptions) > 0) {
$content = '';
foreach ($formOptions as $key => $option) {
if ($key == 0) {
$content .= $option->getName();
} else {
$content .= ' , ' . $option->getName();
}
}
return $content;
} else {
return $answer->getContent();
}
}
}
return 'No column match, contact admin';
}
</code></pre>
<p>I am creating a table out of the registration forms. Each registration form has a few answers that are of a multiple-choice type. </p>
<p>The result is that the <code>foreach ($formOptions as $key => $option) {...</code>-section is pumping the amount of queries up from <strong>200 to 2500</strong>. How can I improve this?</p>
|
[] |
[
{
"body": "<p>For now, one solution is to concatenate the options into a string while the answer is persisted. This is part of my <code>FormToArrayTransformer</code>:</p>\n\n<pre><code>switch ($_question->getFormField()->getType()) {\n case FormField::CHOICE:\n $content = '';\n\n foreach($answer as $_key=>$option) {\n $surveyAnswer->addFormOption($option);\n if ($_key == 0) {\n $content .= $option->getName();\n } else {\n $content .= ', ' . $option->getName();\n }\n }\n\n $surveyAnswer->setContent($content);\n break;\n</code></pre>\n\n<p>Note that now both the <code>FormOption</code> entities and their string representation is stored. When viewing you don't have to iterate over the options anymore but simply calling <code>answer.getContent()</code> will do. This saved me 2300 queries in a table for 200 forms. </p>\n\n<p>I am still unsure why this is so.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T05:37:42.733",
"Id": "40512",
"ParentId": "40254",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T10:14:20.370",
"Id": "40254",
"Score": "4",
"Tags": [
"php",
"mysql"
],
"Title": "Query optimization PHP for string concatination"
}
|
40254
|
<p>I wrote the following program to calculate <em>n</em> digits of Pi (where <em>n</em> could be anything, like 10M) in order to benchmark the CPU and it works perfectly (without OpenMP):</p>
<pre><code>/*
*
* Simple PI Benchmarking tool
* Author: Suyash Srijan
* Email: suyashsrijan@outlook.com
*
* This program calculates how much time your CPU takes to compute n digits of PI using Chudnovsky Algorithm
* (http://en.wikipedia.org/wiki/Chudnovsky_algorithm) and uses the GNU Multiple Precision Arithmetic Library
* for computation.
*
* For verification of digits, you can download the digits from here: http://piworld.calico.jp/estart.html
*
* It's a single threaded program but you can compile it with OpenMP support to enable parallelization.
* WARN: OpenMP support is experimental
*
* Compile using gcc : gcc -O2 -Wall -o pibench pibench.c -lgmp -lssl -lcrypto
* Compile using gcc (with OpenMP): gcc -O2 -Wall -o pibench pibench.c -lgmp -lssl -lcrypto -fopenmp
*
*/
#include <gmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/resource.h>
#include <sys/utsname.h>
#include <openssl/md5.h>
/* Import OpenMP header if compiling with -fopenmp */
#if defined(_OPENMP)
#include <omp.h>
#endif
/* You can't compile this on Windows */
#ifdef _WIN32
#error >>> Fatal: It is not possible to compile this program on Windows <<<
#endif
/* Build timestamp */
#define build_time __TIME__
#define build_date __DATE__
/* Calculate log to the base 2 using GCC's bit scan reverse intrinsic */
__inline__ unsigned int clc_log2(const unsigned int num) {
return ((num <= 1) ? 0 : 32 - (__builtin_clz(num - 1)));
}
/* Calculate MD5 checksum for verification */
__inline__ char *clc_md5(const char *string) {
MD5_CTX context;
unsigned char digest[16];
char *checksum = (char*)malloc(33);
int i;
MD5_Init(&context);
MD5_Update(&context, string, strlen(string));
MD5_Final(digest, &context);
for (i = 0; i < 16; ++i) {
snprintf(&(checksum[i*2]), 3, "%02x", (unsigned int)digest[i]);
}
return checksum;
}
/* Calculate pi digits main function */
__inline__ char *clc_pi(unsigned long dgts)
{
/* Variable declaration */
struct timespec start, end;
unsigned long int i, ti, constant1, constant2, constant3;
unsigned long iters = (dgts / 15) + 1;
unsigned long precision;
double bits;
char *oput;
mpz_t v1, v2, v3, v4, v5;
mpf_t V1, V2, V3, total, tmp, res;
mp_exp_t exponent;
/* Initialize */
constant1 = 545140134;
constant2 = 13591409;
constant3 = 640320;
bits = clc_log2(10);
precision = (dgts * bits) + 1;
mpf_set_default_prec(precision);
mpz_inits(v1, v2, v3, v4, v5, NULL);
mpf_inits(res, tmp, V1, V2, V3, total, NULL);
mpf_set_ui(total, 0);
mpf_sqrt_ui(tmp, 10005);
mpf_mul_ui(tmp, tmp, 426880);
/* Get high-res time */
clock_gettime(CLOCK_REALTIME, &start);
/* Print total iterations and start computation of digits */
printf("Total iterations: %lu\n\n", iters - 1);
#if defined(_OPENMP)
#pragma omp parallel for private(v1, v2, v3, v4, v5, V1, V2, V3, ti) reduction(+:total)
#endif
/* Iterate and compute value using Chudnovsky Algorithm */
for (i = 0x0; i < iters; i++) {
ti = i * 3;
mpz_fac_ui(v1, 6 * i);
mpz_set_ui(v2, constant1);
mpz_mul_ui(v2, v2, i);
mpz_add_ui(v2, v2, constant2);
mpz_fac_ui(v3, ti);
mpz_fac_ui(v4, i);
mpz_pow_ui(v4, v4, 3);
mpz_ui_pow_ui(v5, constant3, ti);
if ((1 & ti) == 1) { mpz_neg(v5, v5); }
mpz_mul(v1, v1, v2);
mpf_set_z(V1, v1);
mpz_mul(v3, v3, v4);
mpz_mul(v3, v3, v5);
mpf_set_z(V2, v3);
mpf_div(V3, V1, V2);
mpf_add(total, total, V3);
/* Print interations executed if debugging (I don't like spamming stdout unnecesarily) */
#ifdef DEBUG
printf("Iteration %lu of %lu successfully executed\n", i, iters - 1);
#endif
}
/* Some final computations */
mpf_ui_div(total, 1, total);
mpf_mul(total, total, tmp);
/* Get high-res time */
clock_gettime(CLOCK_REALTIME, &end);
/* Calculate and print time taken */
double time_taken = (double)(end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1E9;
printf("Done!\n\nTime taken (seconds): %lf\n", time_taken);
/* Store output */
oput = mpf_get_str(NULL, &exponent, 10, dgts, total);
/* Free up space consumed by variables */
mpz_clears(v1, v2, v3, v4, v5, NULL);
mpf_clears(res, tmp, V1, V2, V3, total, NULL);
/* Return value */
return oput;
}
/* Entry point of program */
int main(int argc, char *argv[]) {
/* Set number of threads if compiling with -fopenmp */
#if defined(_OPENMP)
omp_set_num_threads(8);
#endif
/* Variable declaration and initialization */
unsigned long how_many_digits = 10000;
unsigned int base = 10;
char *tmp_ptr;
int pd = 0;
int dd = 0;
/* Try setting process priority to highest */
int returnvalue = setpriority(PRIO_PROCESS, (id_t)0, -20);
if (returnvalue == -1) { printf("WARN: Unable to max out priority. Did you not run this app as root?\n"); }
/* Parse command line */
if (argc == 3 && ((strcmp(argv[2], "--printdigits") == 0) || (strcmp(argv[2], "--nodigits") == 0) || (strcmp(argv[2], "--dumpdigits") == 0))) {
how_many_digits = strtol(argv[1], &tmp_ptr, base);
pd = (strcmp(argv[2], "--printdigits") == 0) ? 1 : 0;
dd = (strcmp(argv[2], "--dumpdigits") == 0) ? 1 : 0; }
/* Invalid command line parameters */
else { fprintf(stderr, "Error: Invalid command-line arguments!\nUsage: pibench [digits] [parameter]\nParameter:\n--printdigits : Prints all digits on console\n--nodigits : Suppresses printing of digits on console\n--dumpdigits : Saves all the digits to a text file\n\nUsage example: pibench 50000 --printdigits\n"); exit(1); }
/* Print introductory text */
struct utsname uname_ptr;
uname(&uname_ptr);
printf("\n---------------------------------------------------------------");
printf("\nPi Bench v1.0 beta (%s)\nBuild date: %s %s\n", uname_ptr.machine, build_date, build_time);
printf("---------------------------------------------------------------\n\n");
/* Check if digits isnt zero or below */
if (how_many_digits < 1) { fprintf(stderr, "Error: Digit cannot be lower than 1\n"); exit(1); }
/* Calculate digits of pi */
printf("Computing %lu digits of PI...\n", how_many_digits);
char *digits_of_pi = clc_pi(how_many_digits);
/* Print the digits if user specified the --printdigits flag */
if (pd == 1) {
printf("Here are the digits:\n\n%.1s.%s\n", digits_of_pi, digits_of_pi + 1); }
/* Save digits to text file if user specified the --dumpdigits flag */
if (dd == 1) {
FILE *file;
if ((file = fopen("pidigits.txt", "w")) == NULL) {
fprintf(stderr, "Error while opening file\n"); exit(-1); } else {
fprintf(file, "%.1s.%s\n", digits_of_pi, digits_of_pi + 1);
fclose(file); }
}
/* Print MD5 checksum */
char *md5 = clc_md5(digits_of_pi);
printf("MD5 checksum (for verification): %s\n", md5);
/* Free the memory */
free(digits_of_pi);
/* Time to go! */
printf("Goodbye!\n");
return 0;
}
</code></pre>
<p>The source code is available <a href="https://github.com/theblixguy/CPUBench" rel="nofollow">here</a>.</p>
<p>Any suggestions or tips will be greatly appreciated!</p>
|
[] |
[
{
"body": "<p>For starters, don't use <code>__inline__</code>. It isn't portable. Instead, use the standard C <code>inline</code>.</p>\n\n<p>Next, use more whitespace. Complex calls and almost all conditionals should go into multiple lines, while operations should be spaced. Also, explain what you are doing:</p>\n\n<pre><code>// original\nsnprintf(&(checksum[i*2]), 3, \"%02x\", (unsigned int)digest[i]);\n\n// what it ought to look like\nsnprintf( // Describe\n &(checksum[i * 2]), // what\n 3, // you\n \"%02x\", // are\n (unsigned int)digest[i] // doing\n );\n</code></pre>\n\n<p>and similarly, conditionals:</p>\n\n<pre><code>// original\n dd = (strcmp(argv[2], \"--dumpdigits\") == 0) ? 1 : 0; }\n\n/* Invalid command line parameters */\nelse { fprintf(stderr, \"Error: Invalid command-line arguments!\\nUsage: pibench [digits] [parameter]\\nParameter:\\n--printdigits : Prints all digits on console\\n--nodigits : Suppresses printing of digits on console\\n--dumpdigits : Saves all the digits to a text file\\n\\nUsage example: pibench 50000 --printdigits\\n\"); exit(1); }\n\n\n\n// what it ought to look like\n dd = (strcmp(argv[2], \"--dumpdigits\") == 0) ? 1 : 0;\n} else {\n fputs (\n \"Error: Invalid command-line arguments!\\n\"\n \"Usage: pibench [digits] [parameter]\\n\"\n \"Parameters:\\n\"\n \"\\t--printdigits : Prints all digits on console\\n\"\n \"\\t--nodigits : Suppresses printing of digits on console\\n\"\n \"\\t--dumpdigits : Saves all the digits to a text file\\n\\n\"\n \"Usage example: pibench 50000 --printdigits\\n\",\n stderr\n );\n\n return 1;\n}\n</code></pre>\n\n<p>Now above I did a few more things:</p>\n\n<ul>\n<li>Multiple strings on multiple lines will automatically get joined - use them.</li>\n<li>Use hard tabs when explaining options.</li>\n<li>Don't use <code>printf()</code> unless you need it. Use <code>fputs()</code> instead.</li>\n<li>Don't use exit() unless you are within a function that <strong><em>must</em></strong> return <code>void</code>. Use <code>return 1;</code> instead.</li>\n</ul>\n\n<p>Finally, use <code>char **argv</code>. It doesn't change anything and anyone worth their salt is aware of both, but at least to me, this seems cleaner:</p>\n\n<pre><code>// original\nint main(int argc, char *argv[]) {\n\n// what it should look like\nint main (int argc, char **argv) {\n</code></pre>\n\n<p>Other than that, your code seems pretty clean. Well done!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T13:15:09.530",
"Id": "73875",
"Score": "0",
"body": "Thanks :) Let me make the adjustments! I have updated the code on Git with even more modifications so that I can do both single threaded and multithreaded benchmark, can you take a look at that too maybe (link in Q)?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T01:59:17.330",
"Id": "41927",
"ParentId": "40256",
"Score": "5"
}
},
{
"body": "<p>On top on haneefmubarak's comment, I'd like to point out a couple of things I do not quite like :</p>\n\n<p><strong>Variable names</strong></p>\n\n<p>I think this :</p>\n\n<pre><code>mpz_t v1, v2, v3, v4, v5;\nmpf_t V1, V2, V3, total, tmp, res;\n</code></pre>\n\n<p>says it all. Not only the variables are meaningless names but on top of that, the case does matter. It's hard for everyone to read this without being confused.</p>\n\n<p>Also, <code>unsigned long how_many_digits = 10000;</code> should probably be called something more descriptive like <code>nb_of_digits</code> or <code>digits_number</code>.</p>\n\n<p><strong>Variable declaration</strong></p>\n\n<p>You declare all the variable at the very beginning of the function. Not only this make the function even longer that it should be but on top of that it makes things hard to read without any added value.</p>\n\n<p>One doesn't want to go back and forth dozens of lines in the code to see where this variable finally gets defined/used/declared if everything could be done in just a couple of lines away. </p>\n\n<p>Also, as you try to define variables smaller to where it's useful, you'll notice that you are doing things which are not really useful : for instance, in <code>unsigned long how_many_digits = 10000;</code>, we never ever use the value <code>10000</code> but still, you have to write it, the compiler has to read it and even worth you and I have to read it.</p>\n\n<p><strong>Early return</strong></p>\n\n<p>Instead of doing</p>\n\n<pre><code>if (A) { foo(); } else { bar(); return; } foobar()\n</code></pre>\n\n<p>you could just do:</p>\n\n<pre><code>if (!A) { bar(); return; } foo(); foobar()\n</code></pre>\n\n<p>to make things much more linear.</p>\n\n<p><strong>Automatic evaluation to true/false</strong></p>\n\n<p>You can use the fact that in C, zero evaluates to false and non-zero to true.</p>\n\n<p>Here what it looks like after taking into account these simple comments :</p>\n\n<pre><code>/*\n *\n * Simple PI Benchmarking tool\n * Author: Suyash Srijan\n * Email: suyashsrijan@outlook.com\n *\n * This program calculates how much time your CPU takes to compute n digits of PI using Chudnovsky Algorithm\n * (http://en.wikipedia.org/wiki/Chudnovsky_algorithm) and uses the GNU Multiple Precision Arithmetic Library\n * for computation.\n *\n * For verification of digits, you can download the digits from here: http://piworld.calico.jp/estart.html\n *\n * It's a single threaded program but you can compile it with OpenMP support to enable parallelization.\n * WARN: OpenMP support is experimental\n *\n * Compile using gcc : gcc -O2 -Wall -o pibench pibench.c -lgmp -lssl -lcrypto\n * Compile using gcc (with OpenMP): gcc -O2 -Wall -o pibench pibench.c -lgmp -lssl -lcrypto -fopenmp\n *\n */\n\n#include <gmp.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n#include <sys/resource.h>\n#include <sys/utsname.h>\n#include <openssl/md5.h>\n\n/* Import OpenMP header if compiling with -fopenmp */\n#if defined(_OPENMP)\n#include <omp.h>\n#endif\n\n/* You can't compile this on Windows */\n#ifdef _WIN32\n#error >>> Fatal: It is not possible to compile this program on Windows <<<\n#endif\n\n/* Build timestamp */\n#define build_time __TIME__\n#define build_date __DATE__\n\n/* Calculate log to the base 2 using GCC's bit scan reverse intrinsic */\n__inline__ unsigned int clc_log2(const unsigned int num) {\n return ((num <= 1) ? 0 : 32 - (__builtin_clz(num - 1)));\n}\n\n/* Calculate MD5 checksum for verification */\n__inline__ char *clc_md5(const char *string) {\n MD5_CTX context;\n MD5_Init(&context);\n MD5_Update(&context, string, strlen(string));\n\n unsigned char digest[16];\n MD5_Final(digest, &context);\n\n char *checksum = (char*)malloc(33);\n for (int i = 0; i < 16; ++i) {\n snprintf(&(checksum[i*2]), 3, \"%02x\", (unsigned int)digest[i]);\n }\n return checksum;\n}\n\n/* Calculate pi digits main function */\n__inline__ char *clc_pi(unsigned long dgts)\n{\n double bits = clc_log2(10);\n unsigned long precision = (dgts * bits) + 1;\n mpf_set_default_prec(precision);\n mpz_t v1, v2, v3, v4, v5;\n mpf_t V1, V2, V3, total, tmp, res;\n mpz_inits(v1, v2, v3, v4, v5, NULL);\n mpf_inits(res, tmp, V1, V2, V3, total, NULL);\n mpf_set_ui(total, 0);\n mpf_sqrt_ui(tmp, 10005);\n mpf_mul_ui(tmp, tmp, 426880);\n\n /* Get high-res time */\n struct timespec start;\n clock_gettime(CLOCK_REALTIME, &start);\n\n /* Print total iterations and start computation of digits */\n unsigned long iters = (dgts / 15) + 1;\n printf(\"Total iterations: %lu\\n\\n\", iters - 1);\n\n#if defined(_OPENMP)\n#pragma omp parallel for private(v1, v2, v3, v4, v5, V1, V2, V3, ti) reduction(+:total)\n#endif\n\n /* Iterate and compute value using Chudnovsky Algorithm */\n for (unsigned long int i = 0x0; i < iters; i++) {\n unsigned long int ti = i * 3;\n unsigned long int constant1 = 545140134;\n unsigned long int constant2 = 13591409;\n unsigned long int constant3 = 640320;\n\n mpz_fac_ui(v1, 6 * i);\n mpz_set_ui(v2, constant1);\n mpz_mul_ui(v2, v2, i);\n mpz_add_ui(v2, v2, constant2);\n mpz_fac_ui(v3, ti);\n mpz_fac_ui(v4, i);\n mpz_pow_ui(v4, v4, 3);\n mpz_ui_pow_ui(v5, constant3, ti);\n if ((1 & ti) == 1) { mpz_neg(v5, v5); }\n mpz_mul(v1, v1, v2);\n mpf_set_z(V1, v1);\n mpz_mul(v3, v3, v4);\n mpz_mul(v3, v3, v5);\n mpf_set_z(V2, v3);\n mpf_div(V3, V1, V2);\n mpf_add(total, total, V3);\n\n /* Print interations executed if debugging (I don't like spamming stdout unnecesarily) */\n#ifdef DEBUG\n printf(\"Iteration %lu of %lu successfully executed\\n\", i, iters - 1);\n#endif\n }\n\n /* Some final computations */\n mpf_ui_div(total, 1, total);\n mpf_mul(total, total, tmp);\n\n /* Get high-res time */\n struct timespec end;\n clock_gettime(CLOCK_REALTIME, &end);\n\n /* Calculate and print time taken */\n double time_taken = (double)(end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec) / 1E9;\n printf(\"Done!\\n\\nTime taken (seconds): %lf\\n\", time_taken);\n\n /* Store output */\n mp_exp_t exponent;\n char * oput = mpf_get_str(NULL, &exponent, 10, dgts, total);\n\n /* Free up space consumed by variables */\n mpz_clears(v1, v2, v3, v4, v5, NULL);\n mpf_clears(res, tmp, V1, V2, V3, total, NULL);\n\n /* Return value */\n return oput;\n}\n\n/* Entry point of program */\nint main(int argc, char *argv[]) {\n /* Set number of threads if compiling with -fopenmp */\n#if defined(_OPENMP)\n omp_set_num_threads(8);\n#endif\n\n /* Try setting process priority to highest */\n if (setpriority(PRIO_PROCESS, (id_t)0, -20) == -1) {\n printf(\"WARN: Unable to max out priority. Did you not run this app as root?\\n\");\n }\n\n /* Parse command line */\n if (argc != 3 || (strcmp(argv[2], \"--printdigits\") && strcmp(argv[2], \"--nodigits\") && strcmp(argv[2], \"--dumpdigits\"))) {\n fprintf(stderr, \"Error: Invalid command-line arguments!\\nUsage: pibench [digits] [parameter]\\nParameter:\\n--printdigits : Prints all digits on console\\n--nodigits : Suppresses printing of digits on console\\n--dumpdigits : Saves all the digits to a text file\\n\\nUsage example: pibench 50000 --printdigits\\n\");\n return 1;\n }\n\n char *tmp_ptr;\n unsigned long nb_digits = strtol(argv[1], &tmp_ptr, base);\n int print_digits = strcmp(argv[2], \"--printdigits\");\n int dump_digits = strcmp(argv[2], \"--dumpdigits\");\n\n /* Invalid command line parameters */\n\n /* Print introductory text */\n struct utsname uname_ptr;\n uname(&uname_ptr);\n printf(\"\\n---------------------------------------------------------------\");\n printf(\"\\nPi Bench v1.0 beta (%s)\\nBuild date: %s %s\\n\", uname_ptr.machine, build_date, build_time);\n printf(\"---------------------------------------------------------------\\n\\n\");\n\n /* Check if digits isnt zero or below */\n if (nb_digits < 1) { fprintf(stderr, \"Error: Digit cannot be lower than 1\\n\"); exit(1); }\n\n /* Calculate digits of pi */\n printf(\"Computing %lu digits of PI...\\n\", nb_digits);\n char *digits_of_pi = clc_pi(nb_digits);\n\n /* Print the digits if user specified the --printdigits flag */\n if (print_digits) {\n printf(\"Here are the digits:\\n\\n%.1s.%s\\n\", digits_of_pi, digits_of_pi + 1);\n }\n\n /* Save digits to text file if user specified the --dumpdigits flag */\n if (dump_digits) {\n FILE *file;\n if ((file = fopen(\"pidigits.txt\", \"w\"))) {\n fprintf(file, \"%.1s.%s\\n\", digits_of_pi, digits_of_pi + 1);\n fclose(file);\n } else {\n fprintf(stderr, \"Error while opening file\\n\");\n return -1;\n }\n }\n\n\n /* Print MD5 checksum */\n char *md5 = clc_md5(digits_of_pi);\n printf(\"MD5 checksum (for verification): %s\\n\", md5);\n\n /* Free the memory */\n free(digits_of_pi);\n\n /* Time to go! */\n printf(\"Goodbye!\\n\");\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T13:28:51.737",
"Id": "72276",
"Score": "0",
"body": "A possible solution to the variable `v1, v2, vx, ...` problem may be to simply use `v[x+1]` instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T13:15:26.437",
"Id": "73876",
"Score": "0",
"body": "Thanks :) Let me make the adjustments! I have updated the code on Git with even more modifications so that I can do both single threaded and multithreaded benchmark, can you take a look at that too maybe?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T10:51:06.687",
"Id": "41949",
"ParentId": "40256",
"Score": "5"
}
},
{
"body": "<p>Just a few notes on some things I didn't see mentioned.</p>\n\n<h3>Compilation:</h3>\n\n<ul>\n<li><p>I originally couldn't compile the program with the command in the comments.</p>\n\n<blockquote>\n <p>/tmp/cc2H2h0a.o: In function 'clc_pi': <br/>\n test.c:(.text+0x148): undefined reference to 'clock_gettime' <br/>\n test.c:(.text+0x2f0): undefined referenceto 'clock_gettime' <br/>\n collect2: ld returned 1 exit status</p>\n</blockquote>\n\n<p>Add <code>-lrt</code> to the list of libraries you link to.</p>\n\n<pre><code>// Compile using gcc : gcc -O2 -Wall -o pibench pibench.c -lgmp -lssl -lcrypto -lrt\n</code></pre></li>\n</ul>\n\n<h3>Syntax:</h3>\n\n<ul>\n<li><p>The <code>DEBUG</code> stuff is distracting. Maybe it is temporary, but if you\nwanted to leave it in, I suggest extracting it:</p>\n\n<pre><code>#include <stdarg.h>\n\nstatic inline void debug(const char *format, ...)\n{\n#ifdef DEBUG\n va_list ap;\n va_start(ap, format);\n vfprintf(stdout, format, ap);\n va_end(ap);\n#endif\n}\n</code></pre>\n\n<p>and calling it:</p>\n\n<pre><code>debug(\"Iteration %lu of %lu successfully executed\\n\", i, iters - 1);\n</code></pre>\n\n<p>If <code>DEBUG</code> is undefined, the inline <code>debug</code> function will be empty and will\nbe excluded during compilation - it disappears.</p></li>\n<li><p>Put the <code>else</code> on its own line.</p>\n\n<blockquote>\n<pre><code>if (dd == 1) {\n FILE *file;\n if ((file = fopen(\"pidigits.txt\", \"w\")) == NULL) {\n fprintf(stderr, \"Error while opening file\\n\"); exit(-1); } else {\n fprintf(file, \"%.1s.%s\\n\", digits_of_pi, digits_of_pi + 1);\n fclose(file); }\n}\n</code></pre>\n</blockquote>\n\n<p>When you use it this way, it is very easy to overlook it. I almost glanced over it when examining your code. There isn't really a reason to put it on it's own line, except to save LOC, which you could do better in other places.</p>\n\n<pre><code>if (dd == 1) \n{\n FILE *file;\n if ((file = fopen(\"pidigits.txt\", \"w\")) == NULL) \n {\n fprintf(stderr, \"Error while opening file\\n\"); exit(-1); \n } else {\n fprintf(file, \"%.1s.%s\\n\", digits_of_pi, digits_of_pi + 1);\n fclose(file); \n }\n}\n</code></pre></li>\n<li><p>Put all statements on separate lines. From <em>Code Complete, 2nd Edition</em>, pg. 759:</p>\n\n<blockquote>\n <p>With statements on their own lines, the code reads from top to bottom, instead of top to bottom and left to right. When you’re looking for a specific line of code, your eye should be able to follow the left margin of the code. It shouldn’t have to dip into each and every line just because a single line might contain two statements.</p>\n</blockquote></li>\n<li><p>I would use more comments, especially around your OpenMP <code>#pragma</code>s and function calls.</p></li>\n<li><p>Define <code>i</code> in your <code>for</code> loops.<sup>(C99)</sup></p>\n\n<pre><code>for (int i = 0x0; i < iters; i++)\n</code></pre></li>\n</ul>\n\n<h3>Miscellaneous:</h3>\n\n<ul>\n<li><p><code>fopen()</code>, a widely-used file I/O functions that you are using, got a facelift in C11. It now supports a new exclusive create-and-open mode (<code>“...x“</code>). The new mode behaves like <code>O_CREAT|O_EXCL</code> in POSIX and is commonly used for lock files. The <code>“...x”</code> family of modes includes the following options:</p>\n\n<ul>\n<li><p><code>wx</code> create text file for writing with exclusive access.</p></li>\n<li><p><code>wbx</code> create binary file for writing with exclusive access.</p></li>\n<li><p><code>w+x</code> create text file for update with exclusive access.</p></li>\n<li><p><code>w+bx</code> or <code>wb+x</code> create binary file for update with exclusive access.</p></li>\n</ul>\n\n<p>Opening a file with any of the exclusive modes above fails if the file already exists or cannot be created. Otherwise, the file is created with exclusive (non-shared) access. Additionally, a safer version of <code>fopen()</code> called <code>fopen_s()</code> is also available. That is what I would use in your code if I were you, but I'll leave that up for you to decide and change.</p></li>\n<li><p><code>CLOCK_REALTIME</code> represents the machine's best-guess as to the current wall-clock, time-of-day time. This means that <code>CLOCK_REALTIME</code> can jump forwards and backwards as the system time-of-day clock is changed, including by NTP.</p>\n\n<p><code>CLOCK_MONOTONIC</code> represents the absolute elapsed wall-clock time since some arbitrary, fixed point in the past. It isn't affected by changes in the system time-of-day clock.</p>\n\n<p>If you want to compute the elapsed time between two events observed on the one machine without an intervening reboot, <code>CLOCK_MONOTONIC</code> is the best option.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T13:16:14.813",
"Id": "73877",
"Score": "0",
"body": "-lrt isn't required iirc, it compiles fine on Ubuntu! Anyway, thanks :) Let me make the adjustments! I have updated the code on Git with even more modifications so that I can do both single threaded and multithreaded benchmark, can you take a look at that too maybe (link in Q)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T18:30:58.597",
"Id": "73919",
"Score": "0",
"body": "@noobprohacker Post it as another question later today and I'll take a look at it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T22:01:19.900",
"Id": "42017",
"ParentId": "40256",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "42017",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T11:37:21.990",
"Id": "40256",
"Score": "11",
"Tags": [
"performance",
"c",
"multithreading",
"openmp",
"openssl"
],
"Title": "Pi Benchmarking in C"
}
|
40256
|
<p>Have a look to the following example. Clearly it's very hard to understand the meaning of each parameter passed to the string.Format to be replaced to the numeric sequence of {0}, {1}, ...</p>
<p>I want to improve the software quality: Maintainability\Code readability
<a href="http://en.wikipedia.org/wiki/Software_quality" rel="nofollow">http://en.wikipedia.org/wiki/Software_quality</a></p>
<p>The problem is also bound to the difficulty of associating numbers to the corrisponding values in the template. i.e. at a first glance what is the meaning of {8}?</p>
<pre><code> @"<?xml version='1.0'?>
<RemoteXMLData>
<Username agent_diff_type=""{10}"" usertype=""{5}"" ticket_language=""{6}"" min_slip_stake=""{7}"" max_stake=""{8}"" location=""{9}"">{0}</Username>
<Password>{1}</Password>
<Reseller>{2}</Reseller>
<Function>AutoLogin</Function>
<AppKey>{3}</AppKey>
<Sub>{4}</Sub>
</RemoteXMLData>";
</code></pre>
<p>What should I change?</p>
<pre><code>string autoLoginRequest = String.Format(
AutoLoginRequestTemplate,
username,
password,
Config.Val1,
Config.Val2,
requestSub,
Language,
minValue,
maxValue,
agentDiffType);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T14:58:32.093",
"Id": "67738",
"Score": "2",
"body": "You could simply wrap the string.Format in a method with a proper name and documentation that shows what the output will be like. The IDE will do the rest."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T16:12:46.850",
"Id": "67764",
"Score": "2",
"body": "As a partly flippant answer to *\"What should I change?\"*, perhaps languages! Or at least approaches: consider using templating or XML-specific tools such as Razor, XDocument or XSLT. I would **never** recommend generating XML by methods on String."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T16:58:39.463",
"Id": "67775",
"Score": "0",
"body": "@MichaelUrman: Ok and what about a templating engine? if you have time give me a better explanation by Ansvering so I can decide if mark your answer as accepted. How would you use Razon in a c# application?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T21:06:37.853",
"Id": "67837",
"Score": "0",
"body": "R# mitigates this problem by highlighting format item and argument pairs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T04:03:32.557",
"Id": "67886",
"Score": "1",
"body": "I haven't actually used Razor myself, but [Phil Haack has](http://haacked.com/archive/2011/08/01/text-templating-using-razor-the-easy-way.aspx/). If you're creating XML, stick with the XML-specific tools like meda's XDocument example."
}
] |
[
{
"body": "<p>Like @jesse said you can have a custom method, maybe pass a user object to that method.\nSomething like this:</p>\n\n<pre><code>class User\n{\n public int AutoLoginRequestTemplate { get; set; }\n public string username { get; set; }\n public string password { get; set; }\n public string Val1 { get; set; }\n public string Val2 { get; set; }\n public string requestSub { get; set; }\n public string Language { get; set; }\n public int minValue { get; set; }\n public int maxValue { get; set; }\n public int agentDiffType { get; set; }\n\n\n /// <summary>\n /// Formats the user info.\n /// </summary>\n /// <param name=\"user\">The user object.</param>\n /// <returns>A formated string</returns>\n public string FormatUserInfo(User user)\n {\n\n return String.Format(\"{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}\",\n user.AutoLoginRequestTemplate,\n user.username,\n user.password,\n user.Val1,\n user.Val2,\n user.requestSub,\n user.Language,\n user.minValue,\n user.maxValue,\n user.agentDiffType);\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Your question changed, now I see that you are trying to create an xml string.</p>\n\n<p>For the sake of readabilty, I wouldnt use <code>string.Format()</code>, instead I would just do simple concatenation:</p>\n\n<pre><code>\"<Password>\"+passowrd+\"</Password>\"\n</code></pre>\n\n<p>Now I am not sure about performance, but here we are talking about readability (you probably can spend your time being productive at something else rather than trying to decide which type of concatenation is more efficient/readable)</p>\n\n<p>Now in terms of best practice, I wouldn't create xml manually (just like I wouldnt try to create a JSON or CSV parser) instead I would use .NET framework to do this, which would certainly make it more readble, something like this:</p>\n\n<pre><code> XElement xml = new XElement(\"RemoteXMLData\",\n new XElement(\"Username\",\n new XAttribute(\"agent_diff_type\", agentDiffType),\n new XAttribute(\"agentDiffType\", agentDiffType),\n new XAttribute(\"usertype\", userType),\n new XAttribute(\"ticket_language\", Language),\n new XAttribute(\"min_slip_stake\", minValue),\n new XAttribute(\"max_stake\", maxValue),\n new XAttribute(\"location\", location),\n username),\n new XElement(\"Password\",\n password),\n new XElement(\"Reseller\",\n reseller),\n new XElement(\"Function\",\n function),\n new XElement(\"AppKey\",\n appKey),\n new XElement(\"Sub\",\n sub)\n );\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T16:04:05.110",
"Id": "67759",
"Score": "0",
"body": "I've added some other details. The thing which I don't like is to use the replacement of numbers with parameters. Since at a first glance I can't understand the meaning of {8} for example. In PHP the replacement is very more readable with a simple {$minValue} in the text that will be replaced by the variable minValue"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T17:01:25.997",
"Id": "67778",
"Score": "0",
"body": "@Sam String.Format is one of the basic structures of C#. Maybe you should go and learn the language before you start getting into more difficult problems. BTW, the `{8}` means you are expecting the 8th Parameter in the list after the string. In this case it would be `user.maxValue`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T17:01:52.890",
"Id": "67779",
"Score": "1",
"body": "@Sam I updated my answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T17:03:04.670",
"Id": "67780",
"Score": "0",
"body": "@JeffVanzella: yes, I know it very well, but it's not human readable at first glance. You have to count and it's subject to mistakes.. it's not a good software engineering tecnique I think.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T17:06:40.450",
"Id": "67783",
"Score": "0",
"body": "@meda: Thanks! Just a last question. What do you think about templating engine (like using razor or similar things)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T17:11:54.270",
"Id": "67785",
"Score": "1",
"body": "like @urman said in his comment above use the right tools. In my answer is used Xdocument which is perfect for this. String Builder or format are just bad for such task because one day it will break"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T15:13:23.307",
"Id": "40266",
"ParentId": "40265",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "40266",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T14:53:51.130",
"Id": "40265",
"Score": "2",
"Tags": [
"c#",
"template"
],
"Title": "How to make string.Format template more readable?"
}
|
40265
|
<p>I'm creating a small online multiplayer game in NodeJS and I'm wondering if I'm "doing it right".
Here is a bit of my code: </p>
<pre><code>// app.js
// if I give an id as argument we assume it's an existing player.
var Player = new player();
Player.on('playerLoaded', function (err, result) {
if (result) {
Player.setName('somename');
Player.on('setName', function (err, result) {
console.log('Name changed');
});
} else {
// couldn't load the player
}
});
</code></pre>
<p>This is my player object:</p>
<pre><code>function Player(id) {
// if we don't have a id, this player needs to be created
this.id = (typeof id !== 'number') ? this.createPlayer() : this.setPlayer(id);
this.name = "";
EventEmitter.call(this);
}
</code></pre>
<p>This is the createPlayer method:</p>
<pre><code>Player.prototype.createPlayer = function () {
var self = this;
// we only need a datetime to insert
connection.query("INSERT INTO players SET `created_at` = now()", function (err, result) {
if (result) {
process.nextTick(function () {
if (result.insertId) {
console.log("Successfully found player no. " + result.insertId);
self.id = result.insertId;
// everything was successful
self.emit('playerLoaded', false, true);
} else {
console.log("Trouble inserting a new player");
self.emit('playerLoaded', true, false);
}
});
} else {
process.nextTick(function () {
console.log("Trouble with the mysql while inserting player: " + err);
self.emit('playerLoaded', err, null);
});
}
});
};
</code></pre>
<p>And this is the setName method:</p>
<pre><code>Player.prototype.setName = function (name) {
var self = this;
connection.query("UPDATE players SET ? WHERE ?", [
{ name: name },
{ id: self.id }
], function (err, result) {
if (result) {
process.nextTick(function () {
self.name = name;
console.log("Successfully updated name of player no. " + self.id);
self.emit('setName', false, true);
});
} else {
process.nextTicket(function () {
console.log("Trouble with the mysql while changing player name: " + err);
self.emit('setName', err, false);
});
}
});
};
</code></pre>
<p>Basically my question is if this is the right way to deal with callbacks?</p>
|
[] |
[
{
"body": "<p>Interesting question,</p>\n\n<p>I am assuming you know that usually, in essence, the setting of the name would be written like this:</p>\n\n<pre><code>Player.setName('somename' , function( err, result ) {\n console.log('Name changed'); \n});\n</code></pre>\n\n<p>and in essence <code>setName</code> would be </p>\n\n<pre><code>Player.prototype.setName = function( name, callbackFunction ) {\n\n var self = this;\n\n connection.query(\"UPDATE players SET ? WHERE ?\", [\n { name: name },\n { id: self.id }\n ], function (err, result) {\n\n if (result) {\n process.nextTick(function () {\n self.name = name;\n console.log(\"Successfully updated name of player no. \" + self.id);\n callbackFunction( false, true );\n });\n } else {\n process.nextTicket(function () {\n console.log(\"Trouble with the mysql while changing player name: \" + err);\n callbackFunction( err, false );\n });\n }\n });\n};\n</code></pre>\n\n<p>I like that with your approach you avoid \"callback hell\". Since your project is a small game I would advise you to see how far you can go with this scheme. </p>\n\n<p>Other than that, I hope you are not planning to write a whole function including SQL code for each property. In my mind you should only have 1 function that takes care of updating the whole of the player object.</p>\n\n<p>Finally, easy up on the new lines, it makes your code too hard to read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T07:59:10.127",
"Id": "67907",
"Score": "0",
"body": "I do want to game to theoretically be able to serve hundreds of players at the same time.\n\nA savePlayer method to avoid writing SQL everytime seems a good idea indeed. Thank you. No idea why I haven't thought of that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T01:22:11.307",
"Id": "40319",
"ParentId": "40267",
"Score": "3"
}
},
{
"body": "<p>Very interesting question, here is my opinion.</p>\n\n<p>I don't think EventEmitter as a way to deal or avoid callbacks. There are two main scenarios where I use EventEmitter instead of callbacks:</p>\n\n<ol>\n<li>When I need to execute (in your case <code>setName</code>) in one place and subscribe in another place.</li>\n<li>When the function has more end states or intermediate states that I'm interested on.</li>\n</ol>\n\n<p>So, if you only are interested when the name is changed and you always will call <code>on('setName</code> immediately I consider that EventEmitter doesn't worth for this case and will be better to just pass a function:</p>\n\n<pre><code>Player.setName('newname', function (err) {\n console.log('named changed');\n});\n</code></pre>\n\n<p>Now, a use case where I'd use an emitter can be something like this:</p>\n\n<pre><code>var players = [];\n\napp.post('/player', function (req, res) {\n\n //handle the creation of the player\n //and how to react to different events\n var player = new Player(req.body);\n\n player\n .on('setName', function (oldname, newname) {\n players.forEach(function (p) {\n p.notify(oldname + ' changed name to ' + newname);\n });\n }).on('quit', function () {\n //remove the player from the array of players\n players.remove(players.indexOf(this));\n }).on('other', function () {\n //...\n });\n\n players.push(player);\n\n res.json({ id: player.id });\n});\n\n//trigger the change of the name in another part of the code\napp.put('/player/:id/name', function (req, res) {\n player.setName(req.body.name, function (err) {\n if (err){\n console.log(err);\n return res.send(500);\n }\n res.send(200);\n });\n});\n</code></pre>\n\n<p>In this case the setName function has a callback but also emits an event that I need to handle in another part of the code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T14:05:36.480",
"Id": "41404",
"ParentId": "40267",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T15:28:28.963",
"Id": "40267",
"Score": "6",
"Tags": [
"javascript",
"node.js",
"callback"
],
"Title": "Is this the right way to work with callbacks and the EventEmitter?"
}
|
40267
|
<p>I've written a small library for reading and writing PGM/PPM images. The format is described <a href="http://paulbourke.net/dataformats/ppm/" rel="nofollow">here</a>. I attach the library itself and a small utility to convert binary encoded images to ASCII encoding. Any type of comment will be appriciated. However, these points are most important to me:</p>
<ul>
<li><p><strong>Abusing of the type system</strong> - I fear that I forced my OOP design on the Haskell type system. I wanted to use typeclasses in order to prevent code duplication as much as possible between PGM and PPM images. However, the final result was that I had to duplicate code in several places. The worse thing is that I was forced to add a type signature in the bin2asc utility, so it doesn't support PGM. How can I design this library better to support both types?</p></li>
<li><p><strong>Performance</strong> - Running my bin2asc utility on <a href="http://www.math.umbc.edu/~rouben/2003-09-math625/images/mandrill.ppm" rel="nofollow">this image</a> takes 0.633 seconds. I think it's a bit slow for an image in such size. Since I don't know how to profile code in Haskell I can't tell which function takes most of the time. Is there any bad practice that I have done that hurts performance?</p></li>
<li><p><strong>Branching in mixed IO/Maybe functions</strong> - When using the <code>do</code> notiaion in a function that returns a <code>Maybe</code> I prevent checking for <code>Nothings</code> by chaining monads. However, in bin2asc I have to check explicitly for <code>Nothing</code>, creating an extra branch. Is there anything I can do to prevent this?</p></li>
<li><p><strong>Parsing multiple values in a function</strong> - For <code>parseHeader</code> - I had to use multple <code>r</code> variables to hold the remainders. Is there any less error-prone implementation?</p></li>
</ul>
<p><strong>PNM.hs</strong></p>
<pre><code>module Data.PNM
( Coord
, Image(..)
, ImageType(..)
, Encoding(..)
, PPMImage(..)
, PGMImage(..)
, parseHeader
, Header(..)
) where
import Data.Array
import Data.Char
import Data.List
import qualified Data.ByteString.Lazy as S
import qualified Data.ByteString.Lazy.Char8 as SC
import Data.Word
import Control.Monad
import System.IO
import Control.Applicative
import Debug.Trace
type Coord = (Int,Int)
data GrayscalePixel = GrayscalePixel Int deriving Show
data ColorPixel = ColorPixel Int Int Int deriving Show
data Encoding = ASCII | Binary deriving (Show,Eq)
data ImageType = PPM | PGM deriving (Eq,Show)
data PPMImage = PPMImage (Array Coord ColorPixel) deriving Show
data PGMImage = PGMImage (Array Coord GrayscalePixel)
data Header = Header { imageType :: ImageType
, imageEncoding :: Encoding
, imageCoords :: Coord
, imageBitDepth :: Int }
class Pixel p where
readPixel :: Encoding -> S.ByteString -> Maybe (p,S.ByteString)
encodePixel :: Encoding -> p -> S.ByteString
class Image img where
decode :: S.ByteString -> Maybe img
dimensions :: img -> Coord
encode :: Encoding -> img -> S.ByteString
hLoad :: Handle -> IO (Maybe img)
hLoad h = decode <$> S.hGetContents h
load :: FilePath -> IO (Maybe img)
load fileName = decode <$> S.readFile fileName
dump :: Encoding -> img -> FilePath -> IO ()
dump encoding img fileName = do
let encodedImage = encode encoding img
S.writeFile fileName encodedImage
encodePixels :: (Pixel p) => Encoding -> [p] -> SC.ByteString
encodePixels encoding pixels = SC.concat $ fmap (encodePixel encoding) pixels
encodeHeader :: Header -> S.ByteString
encodeHeader (Header type' encoding (width,height) depth) =
let fields = fmap SC.pack [ magic type' encoding
, show width
, show height
, show depth ]
formattedFields = SC.intercalate (SC.singleton ' ') fields
in formattedFields `SC.append` (SC.singleton '\n')
where
magic PGM ASCII = "P2"
magic PPM ASCII = "P3"
magic PGM Binary = "P5"
magic PPM Binary = "P6"
nextWord :: S.ByteString -> S.ByteString
nextWord s
| SC.null s = SC.empty
| otherwise = let next = SC.dropWhile isSpace s
in if SC.null next then SC.empty
else if SC.head next == '#'
then nextWord $ SC.dropWhile (/= '\n') next
else next
nextLine :: S.ByteString -> S.ByteString
nextLine = SC.drop 1 . SC.dropWhile (/= '\n')
parseMagic :: S.ByteString -> Maybe ((Encoding,ImageType),S.ByteString)
parseMagic s = do
let (word,remainder) = SC.span (\c -> c /= '#' && not (isSpace c)) s
result <- parseMagic' word
return (result, remainder)
where parseMagic' w
| w == SC.pack "P2" = Just (ASCII,PGM)
| w == SC.pack "P3" = Just (ASCII,PPM)
| w == SC.pack "P5" = Just (Binary,PGM)
| w == SC.pack "P6" = Just (Binary,PPM)
| otherwise = Nothing
parseHeader :: S.ByteString -> Maybe (Header,S.ByteString)
parseHeader rawImage = do
((encoding,imageType),r1) <- parseMagic rawImage
(width,r2) <- SC.readInt $ nextWord r1
(height,r3) <- SC.readInt $ nextWord r2
(bitDepth,r4) <- SC.readInt $ nextWord r3
return ((Header imageType encoding (width,height) bitDepth),r4)
readPixels :: (Pixel p) => Encoding -> S.ByteString -> [p]
readPixels encoding s
| SC.null s = []
| otherwise = let result = readPixel encoding (next' s)
in case result of
Nothing -> []
Just (pixel,r) -> pixel:readPixels encoding r
where
next'
| encoding == ASCII = nextWord
| encoding == Binary = id
instance Pixel GrayscalePixel where
readPixel ASCII s = do
(num, r) <- SC.readInt s
return ((GrayscalePixel num),r)
readPixel Binary s = do
(x,xs) <- S.uncons s
let pixelBin = fromIntegral x
return $ ((GrayscalePixel pixelBin),xs)
encodePixel ASCII (GrayscalePixel l) = SC.pack $ (show l) ++ " "
encodePixel Binary (GrayscalePixel l) = SC.singleton $ chr l
instance Pixel ColorPixel where
readPixel ASCII s = do
(red, r1) <- SC.readInt s
(green, r2) <- SC.readInt $ nextWord r1
(blue, r3) <- SC.readInt $ nextWord r2
return ((ColorPixel red green blue),r3)
readPixel Binary s = do
(red,r1) <- S.uncons s
(green,r2) <- S.uncons r1
(blue,r3) <- S.uncons r2
return ((ColorPixel (fromIntegral red) (fromIntegral green) (fromIntegral blue)),r3)
encodePixel ASCII (ColorPixel r g b) = SC.concat $ fmap toAscii [r,g,b]
where toAscii l = SC.pack $ (show l) ++ " "
encodePixel Binary (ColorPixel r g b) = SC.pack $ fmap chr [r,g,b]
instance Image PPMImage where
dimensions (PPMImage pixels) = let (width,height) = snd $ bounds pixels
in (width + 1,height + 1)
decode rawImage = do
(header,r) <- parseHeader rawImage
let imgType = imageType header
unless (imgType == PPM) Nothing
let rawPixels = nextLine r
pixels = readPixels (imageEncoding header) rawPixels
(width,height) = imageCoords header
unless ((length pixels) == (width * height)) Nothing
return (PPMImage $ listArray ((0,0),(width - 1,height - 1)) pixels)
encode encoding img@(PPMImage pixels) =
let pixelList = elems pixels
header = Header PPM encoding (dimensions img) 255
in (encodeHeader header) `S.append` (encodePixels encoding pixelList)
instance Image PGMImage where
dimensions (PGMImage pixels) = let (width,height) = snd $ bounds pixels
in (width + 1,height + 1)
decode rawImage = do
(header,r) <- parseHeader rawImage
let imgType = imageType header
unless (imgType == PGM) Nothing
let rawPixels = nextLine r
pixels = readPixels (imageEncoding header) rawPixels
(width,height) = imageCoords header
unless ((length pixels) == (width * height)) Nothing
return (PGMImage $ listArray ((0,0),(width - 1,height - 1)) pixels)
encode encoding img@(PGMImage pixels) =
let pixelList = elems pixels
header = Header PGM encoding (dimensions img) 255
in (encodeHeader header) `S.append` (encodePixels encoding pixelList)
</code></pre>
<p><strong>Main.hs (pnmbin2asc):</strong></p>
<pre><code>import qualified Data.ByteString.Lazy as S
import System.Environment
import Data.PNM
convertImage :: (Image a) => Maybe a -> String -> IO ()
convertImage Nothing _ = do putStrLn "Bad Source Image"
convertImage (Just img) dest = dump ASCII img dest
main = do
(source:dest:[]) <- getArgs
content <- S.readFile source
let header = parseHeader content
case header of
Nothing -> putStrLn $ source ++ ": Bad image"
Just (header,_) -> case (imageEncoding header) of
ASCII -> putStrLn $ source ++ ": Already an ASCII image"
Binary -> let image = decode content :: Maybe PPMImage
in convertImage image dest
</code></pre>
<p>P.S. I know about Parsec but I have yet to learn how to use it. I wanted to write this library without it for learning purpose</p>
|
[] |
[
{
"body": "<p>A few improvements I notice right off the bat</p>\n\n<p><strong>newtype vs. data</strong>\nreplace single field <code>data</code> declarations with <code>newtype</code>. <code>newtype</code> has no runtime overhead.</p>\n\n<pre><code>data GrayscalePixel = GrayscalePixel Int\n-- becomes\nnewtype GrayscalePixel = GrayscalePixel Int\n</code></pre>\n\n<p><strong>Use StateT</strong></p>\n\n<p>A common pattern in your code (ex. <code>parseHeader</code>) is</p>\n\n<pre><code>foo x = do\n (a, s0) <- doSomething0 x\n (b, s1) <- doSomething1 s0\n ...\n (n, sn) <- doSomethingN sn_1\n return $ (f a b ... n, sn)\n</code></pre>\n\n<p>this is much clearer if you hide the state passing in the <code>State</code> monad, or in this case, the <code>StateT</code> monad transformer. <code>parseHeader</code> becomes </p>\n\n<pre><code>parseHeader :: StateT S.ByteString Maybe Header\nparseHeader = do\n (enc, imgType) <- StateT parseMagic\n width <- readInt\n height <- readInt\n depth <- readInt\n return $ Header imgType enc (width, height) depth\n where readInt = StateT (SC.readInt . nextWord)\n</code></pre>\n\n<p>then you can use <code>runStateT :: StateT s m a -> s -> m (a, s)</code> to evaluate.</p>\n\n<p><strong>Profiling</strong></p>\n\n<p>As far as profiling is concerned, Haskell makes it really easy to get a good idea of where your program is slow. Just compile like <code>ghc -O2 Main.hs -prof -auto-all</code>, then run as <code>./Main src dest +RTS -p</code> and it will produce <code>Main.prof</code> containing profiling information.</p>\n\n<p>Here's the most important bit of the profiling output:</p>\n\n<pre><code>COST CENTRE MODULE %time %alloc\ndump PNM 36.6 44.6\nencodePixel.toAscii PNM 27.2 24.3\nencodePixels PNM 7.2 8.8\nreadPixel PNM 4.3 6.2\n...\n</code></pre>\n\n<p>as you can see, <code>dump</code> and <code>encodePixel.toAscii</code> are taking the majority of time.\nIn particular, <code>encodePixel.toAscii</code> is being very inefficient by <code>show</code>ing an <code>Int</code>, then packing it into a <code>ByteString</code> using <code>SC.pack</code>. Optimizing these two functions should provide a nice speedup to your program.</p>\n\n<p><strong>Next Steps</strong></p>\n\n<p>A further improvement would be to use <code>Data.Binary</code> to parse the binary headers. It's designed for exactly this sort of task and is very fast, although I wouldn't recommend pursuing it unless you fix the two functions mentioned above. Currently the time taken to parse the headers is negligible compared to the cost of encoding to ASCII and dumping.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T18:01:43.943",
"Id": "67803",
"Score": "0",
"body": "Is there any function that converts an `Int` directly to a `ByteString`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T18:07:44.487",
"Id": "67804",
"Score": "2",
"body": "There is `Data.ByteString.Builder.intDec :: Int -> Builder`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T21:27:20.807",
"Id": "67995",
"Score": "0",
"body": "I converted my function to use `Builder` but I still don't think that performance are optimal. Please see my edit in the original message."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T17:56:40.243",
"Id": "40282",
"ParentId": "40269",
"Score": "10"
}
},
{
"body": "<p>Regarding the problem selecting the right image type, you have enough information in your header to select which type of image to create.</p>\n\n<pre><code> case header of\n Nothing -> putStrLn $ source ++ \": Bad image\"\n Just (header,_) -> case (imageEncoding header) of\n ASCII -> putStrLn $ source ++ \": Already an ASCII image\"\n Binary -> let image = decode content :: Maybe PPMImage\n in convertImage image dest\n</code></pre>\n\n<p>Becomes</p>\n\n<pre><code> image <- case header of\n Nothing -> putStrLn $ source ++ \": Bad image\"\n Just (Header _ ASCII _ _) ->\n putStrLn $ source ++ \": Already an ASCII image\"\n Just (Header PPM _ _ _) -> decode content :: Maybe PPMImage\n Just (Header PGM _ _ _) -> decode content :: Maybe PGMImage\n convertImage image dest\n</code></pre>\n\n<p>Besides, this is a check that should really be happening inside your call to decode. Ask yourself what would happen if your user called <code>decode content :: Maybe PGMImage</code> with PPM encoded content.</p>\n\n<p>Perhaps consider leaving the image format at the value level?</p>\n\n<pre><code>newtype Image pix = MkImg (Array Coord pix) deriving Show\n\ndecode PPM content :: Image p\n</code></pre>\n\n<hr>\n\n<p>Following up on cdk's answer: if you are worried about speed, you should take care how you represent your data.</p>\n\n<pre><code>data ColorPixel = ColorPixel Int Int Int deriving Show\n</code></pre>\n\n<p>While this looks like it's cheap, beware that those <code>Int</code>s are boxed values. This means that they can hold either thunks, or pointers to <code>Int</code>s. This extra layer of indirection is potentially harmful to performance, so try unpacking the values directly into the record:</p>\n\n<pre><code>{-# LANGUAGE BangPatterns #-}\ndata ColorPixel = ColorPixel {-# UNPACK #-} !Int {-# UNPACK #-} !Int {-# UNPACK #-} !Int\n deriving Show\n</code></pre>\n\n<blockquote>\n <p><strong>note:</strong> compiling with -funbox-strict-fields allows you to omit the UNPACK pragmas and have the compiler add them for you.</p>\n</blockquote>\n\n<p>You should also do this for all performance sensitive single field datatypes that you don't convert into newtypes.</p>\n\n<p>EDIT: Incorporated cdk's feedback re: UNPACK</p>\n\n<p>REF: <a href=\"http://www.haskell.org/ghc/docs/7.0.2/html/users_guide/pragmas.html#unpack-pragma\" rel=\"nofollow\">http://www.haskell.org/ghc/docs/7.0.2/html/users_guide/pragmas.html#unpack-pragma</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T01:59:34.207",
"Id": "67870",
"Score": "1",
"body": "even better, use an `UNBOX` pragma on strict, primitive fields like `Int`. I don't believe you need `BangPatterns` for strictness annotations on a data constructor."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T02:32:24.517",
"Id": "67873",
"Score": "1",
"body": "@cdk You're right, I was thinking of UNPACK, but BangPatterns is good to know about too."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T23:25:23.153",
"Id": "40309",
"ParentId": "40269",
"Score": "4"
}
},
{
"body": "<p>I have some general design comments. You seem to approach the problem from the OO perspective: you have the Image object with a bunch of virtual methods and the Pixel object with virtual readPixel and encodePixel. These two methods, in turn, internally dispatch based on the type of encoding. </p>\n\n<p>Even in the OO language, I would avoid defining objects that are too smart. Your Image, for instance, knows about file handles. Pixel polymorphism is also strained: readPixel is more like a constructor than a virtual function.</p>\n\n<p>My approach would be more stream based. After reading the header, I would convert the rest of the file to a stream of Ints. For a binary file, that just means mapping fromIntegral over the input. For and ASCII file it means breaking the stream on whitespaces and mapping readInt over it. </p>\n\n<p>Now you have a list of Ints and you either convert it directly to an array for grey scale, or group it into triples and then convert.</p>\n\n<p>This description can be pretty much converted straight to almost self-explanatory code.</p>\n\n<p>As for the encoding, one simple optimization would be to convert bytes to strings using a 256-entry lookup table (Data.Map). (Of course, this won't work if the max value for a pixel component is greater than 255.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T22:24:46.793",
"Id": "40404",
"ParentId": "40269",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "40282",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T15:50:01.287",
"Id": "40269",
"Score": "10",
"Tags": [
"performance",
"haskell",
"image"
],
"Title": "PPM/PGM Image processing library in Haskell"
}
|
40269
|
<p>I like to reuse code as much as possible and keeps things DRY. But I'm afraid that sometimes it creates too many layers of indirection. It then becomes a chore to find where code exists that is relevant to the problem at hand. I'll give a couple of examples.</p>
<p>In the first example, I'm using inheritance on classes that are not directly related, but one class happens to need a lot of functions from the other class.</p>
<p>Here's a portion of the base class:</p>
<pre><code>class GetTimecard < Interactor
def date_range_start
if @request.params[:date_range_start]
Date.parse(@request.params[:date_range_start])
else
pay_period.last_starts_on
end
end
def date_range_end
if @request.params[:date_range_end]
Date.parse(@request.params[:date_range_end]) + 1.day
else
pay_period.last_ends_on
end
end
end
</code></pre>
<p>The inherited class is largely the same as base class but does not need a date range. It is only interested in a single day.</p>
<pre><code>class GetTimecardForShift < GetTimecard
def call
@request.params[:date_range_start] = @request.params[:date]
@request.params[:date_range_end] = @request.params[:date]
end
end
</code></pre>
<p>So in the <code>call</code> method you have a strange assignment of variables that only makes sense if you have a look at the base class.</p>
<p>In the second example, I use modules to share common functionality between many classes.</p>
<p>There is a module like this:</p>
<pre><code>module Timeable
def timesheet_entries_for(shift)
TimesheetEntryRepository.where(account_and_user_ids.merge(assigned_shift_id: shift.id))
end
end
</code></pre>
<p>This function calls a method, <code>account_and_user_ids</code> which is not defined in the module itself. Instead, it's defined in each class that includes the module. But each class may define it differently. For example:</p>
<pre><code>class RecordTime < Interactor
include Timeable
def account_and_user_ids
{ account_id: @request.account_id, user_id: @request.current_user.id }
end
end
class GetTimecard < Interactor
include Timeable
def account_and_user_ids
@account_and_user_ids ||= { account_id: @request.account_id, user_id: get_user_ids }
end
def get_user_ids
if @request.params[:id]
@request.params[:id]
else
if @request.params[:departments]
UserRepository.by_account(@request.account_id).where(department_id: @request.params[:departments]).map(&:id) & managed_users.map(&:id)
else
managed_users.map(&:id)
end
end
end
end
</code></pre>
<p>So it quickly becomes confusing trying to figure out which method is defined where and how changing one method will affect other code.</p>
<p>Are there standard ways of making these dependencies explicit? Hopefully there's a naming convention or a better way to names things. I'm not a fan of too many comments in code because they have a tendency to tell less than the code itself and even to be flat out wrong.</p>
|
[] |
[
{
"body": "<p>These dependencies can't be fixed by naming. They are a symptom of some fundamental design problems. If you're having trouble finding methods, that's\na symptom of an overly coupled design. </p>\n\n<p>You have a class names that really sound like methods in a completely different class. </p>\n\n<p>Without knowing more about the application it's hard to suggest where to go. If you're working in Ruby I highly recommend this book for thinking about class design and re-factoring. </p>\n\n<p><a href=\"http://www.poodr.com/\" rel=\"nofollow\">http://www.poodr.com/</a></p>\n\n<p>You might also look into various code metric tools to help you identify some design problems. There are lot's of these available for Ruby. </p>\n\n<p><a href=\"https://www.ruby-toolbox.com/categories/code_metrics\" rel=\"nofollow\">https://www.ruby-toolbox.com/categories/code_metrics</a></p>\n\n<p>These can seem quite pointless and arbitrary at first, but using SOLID object design principals has been shown to be effective in the long run. </p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)\" rel=\"nofollow\">http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T18:44:05.887",
"Id": "67813",
"Score": "0",
"body": "These classes represent Use Cases from [The Clean Architecture](http://blog.8thlight.com/uncle-bob/2012/08/13/the-clean-architecture.html) style of system design. The coupling is an unintentional side effect of an effort to make code reusable. I'm looking for pointers on how to reduce the coupling _and_ be DRY at the same time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T20:29:40.883",
"Id": "67830",
"Score": "0",
"body": "I'd suggest looking at this article. IMHO, you are being far too literal in mapping Use Cases to objects. http://www.ksc.com/articles/usecases.htm"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T18:30:34.800",
"Id": "40284",
"ParentId": "40270",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "40284",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T15:51:09.983",
"Id": "40270",
"Score": "2",
"Tags": [
"ruby",
"datetime"
],
"Title": "Code reuse while keeping meaning clear and avoiding unforseen consequences"
}
|
40270
|
<p>Is it possible to improve this bit?</p>
<pre><code>def append_nones(length, list_):
"""
Appends Nones to list to get length of list equal to `length`.
If list is too long raise AttributeError
"""
if len(list_) < length:
nones = length - len(list_)
return list_ + [None] * nones
elif len(list_) > length:
raise AttributeError('Length error list is too long.')
else:
return list_
</code></pre>
|
[] |
[
{
"body": "<h3>1. Comments on your code</h3>\n\n<ol>\n<li><p>The documentation does not match the implementation. The docstring says \"append Nones to list\" but it does not append: if the list does not have the required length, it returns a newly allocated list.</p></li>\n<li><p>It seems wrong to return the original list if it was the right length, but return a newly allocated list if it was too short. For consistency, the function should either always return a new list, or always (update and) return the old list.</p></li>\n<li><p>It's a loss of generality to support only the addition of <code>None</code> elements. Why not let the caller pass in their preferred placeholder element.</p></li>\n<li><p>If you run <code>help(AttributeError)</code> you'll see that its description is \"Attribute not found.\" This does not seem appropriate here. <code>ValueError</code> would be a better choice, or better still, create your own.</p></li>\n<li><p>There's no need to name the variable <code>list_</code>: this avoids shadowing the built-in function <code>list</code>, but you don't use that function, so it doesn't matter if you shadow it.</p></li>\n<li><p>You call <code>len(list_)</code> three times. Simpler to call it once and store the value.</p></li>\n<li><p>The case <code>len(list_) == length</code> could be combined with the case <code>len(list_) < length</code> and so simplify the code.</p></li>\n<li><p>The error message \"Length error list is too long\" makes no sense in English.</p></li>\n<li><p>The error message would be more useful if it contained the actual numbers.</p></li>\n<li><p>This kind of function is ideal for <a href=\"http://docs.python.org/3/library/doctest.html\">doctests</a>.</p></li>\n</ol>\n\n<h3>2. Revised code</h3>\n\n<p>I've chosen to make the function always update its argument, and fixed all the problems noted above.</p>\n\n<pre><code>class TooLongError(ValueError):\n pass\n\ndef pad(seq, target_length, padding=None):\n \"\"\"Extend the sequence seq with padding (default: None) so as to make\n its length up to target_length. Return seq. If seq is already\n longer than target_length, raise TooLongError.\n\n >>> pad([], 5, 1)\n [1, 1, 1, 1, 1]\n >>> pad([1, 2, 3], 7)\n [1, 2, 3, None, None, None, None]\n >>> pad([1, 2, 3], 2)\n ... # doctest: +IGNORE_EXCEPTION_DETAIL\n Traceback (most recent call last):\n ...\n TooLongError: sequence too long (3) for target length 2\n\n \"\"\"\n length = len(seq)\n if length > target_length:\n raise TooLongError(\"sequence too long ({}) for target length {}\"\n .format(length, target_length))\n seq.extend([padding] * (target_length - length))\n return seq\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T16:40:24.313",
"Id": "40274",
"ParentId": "40272",
"Score": "11"
}
},
{
"body": "<p>What you've done looks good to me.</p>\n\n<p>However, here's what I would do if I were to write the same function :</p>\n\n<pre><code>def append_nones(length, list_):\n \"\"\"\n Appends Nones to list to get length of list equal to `length`.\n If list is too long raise AttributeError\n \"\"\"\n diff_len = length - len(list_)\n if diff_len < 0:\n raise AttributeError('Length error list is too long.')\n return list_ + [None] * diff_len\n</code></pre>\n\n<p>The main point is to handle a smaller number of cases.</p>\n\n<p>From the <a href=\"http://www.python.org/dev/peps/pep-0020/\" rel=\"nofollow\">Zen of Python</a> :</p>\n\n<blockquote>\n <p>Special cases aren't special enough to break the rules.</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T16:42:05.493",
"Id": "40275",
"ParentId": "40272",
"Score": "3"
}
},
{
"body": "<pre><code>def nones(length,mylist):\n if len(mylist) > length:\n raise AttributeError('Length error list is too long.')\n for i in range(length):\n try: yield mylist[i]\n except IndexError: yield None\n\n\nprint list(nones(20,[1,2,3]))\n</code></pre>\n\n<p>it doesnt exactly match what you described but this is the implementation I would probably use</p>\n\n<p>I would also probably change </p>\n\n<pre><code>if len(mylist) > length:\n raise AttributeError('Length error list is too long.')\n</code></pre>\n\n<p>to</p>\n\n<pre><code>assert len(mylist) <= length,\"list is too long\"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T18:08:43.093",
"Id": "40384",
"ParentId": "40272",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "40274",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T16:15:11.780",
"Id": "40272",
"Score": "7",
"Tags": [
"python"
],
"Title": "Append nones to list if is too short"
}
|
40272
|
<p>The app I'm working on should allows it's users to create tables. I have a view in which users are able to create a table. They should be able to define here the table's columns. The columns that the user adds will be part from some predefined types of columns: BusinessFields, SourceKeys, SourceAttrs,...; At the same time columns should have some other proprieties that define the value they will contain: minlength, minValue, defaultValue,...</p>
<p>These tables have to have a format(at least a column for the SourceKeys and TargetKeys categories), but this format is not so restrictive. The image will help to describe the point:</p>
<p><img src="https://i.stack.imgur.com/FQMHx.png" alt="enter image description here"></p>
<p>I have made it work as you see in the image, but I don't like how I've made the bindings. My code design also reduces the flexibility (For example: It would be much more difficult to add a click binding for a row). </p>
<p><strong>JavaScript:</strong></p>
<pre><code>//column definition
function Column(columnName, minLength, maxLength, minValue, maxValue, reg_ex, role, order, defaultValue) {
var self = {};
self.name = ko.observable(columnName || 'new column');
self.minLength = ko.observable(minLength || null);
self.maxLength = ko.observable(maxLength || null);
self.minValue = ko.observable(minValue || null);
self.maxValue = ko.observable(maxValue || null);
self.reg_exp = ko.observable(reg_ex || null);
self.role = ko.observable(role ? role : 1);
self.order = ko.observable(order || null);
self.defaultValue = ko.observable(defaultValue || null);
return self;
}
//table definition
function Table() {
var self = {};
self.tableName = ko.observable('New table');
self.tableDescription = ko.observable('description');
self.businessFields = ko.observableArray([]);
self.sourceKeys = ko.observableArray([]);
self.sourceAttr = ko.observableArray([]);
self.targetKeys = ko.observableArray([]);
self.targetAttr = ko.observableArray([]);
self.attrFields = ko.observableArray([]);
self.technicalFields = ko.observableArray([]);
return self;
}
//the table
var newTable = ko.observable(Table());
//adding columns to the table
newTable.businessFields.push(Column('col_1'));
</code></pre>
<p><strong>HTML:</strong> (only enough tho get the idea)</p>
<pre><code> <table class="table table-bordered">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Min Length</th>
<th>Max Length</th>
<th>Min Value</th>
<th>Max Value</th>
<th>Regular Expr</th>
<th>Default Value</th>
</tr>
</thead>
<tbody data-bind="with: newTable">
<tr>
<td data-bind="attr: { rowspan: function(){ if(businessFields().length == 0) return 1; else return businessFields().length; }()}">Business fields</td>
<!-- ko if: businessFields().length > 0 -->
<td><strong data-bind="text: businessFields()[0].name"></strong></td>
<td><span data-bind="text: businessFields()[0].minLength"></span></td>
<td><span data-bind="text: businessFields()[0].maxLength"></span></td>
<td><span data-bind="text: businessFields()[0].minValue"></span></td>
<td><span data-bind="text: businessFields()[0].maxValue"></span></td>
<td><span data-bind="text: businessFields()[0].reg_exp"></span></td>
<td><span data-bind="text: businessFields()[0].defaultValue"></span></td>
<!-- /ko -->
</tr>
<!-- ko foreach: businessFields -->
<!-- ko if: $index() !== 0 -->
<tr>
<td><strong data-bind="text: name"></strong></td>
<td><span data-bind="text: minLength"></span></td>
<td><span data-bind="text: maxLength"></span></td>
<td><span data-bind="text: minValue"></span></td>
<td><span data-bind="text: maxValue"></span></td>
<td><span data-bind="text: reg_exp"></span></td>
<td><span data-bind="text: defaultValue"></span></td>
</tr>
<!-- /ko -->
<!-- /ko -->
<tr>
<td data-bind="attr: { rowspan: function(){ if(sourceKeys().length == 0) return 1; else return sourceKeys().length; }()}">Source keys</td>
<!-- ko if: sourceKeys().length > 0 -->
<td><strong data-bind="text: sourceKeys()[0].name"></strong></td>
<td><span data-bind="text: sourceKeys()[0].minLength"></span></td>
<td><span data-bind="text: sourceKeys()[0].maxLength"></span></td>
<td><span data-bind="text: sourceKeys()[0].minValue"></span></td>
<td><span data-bind="text: sourceKeys()[0].maxValue"></span></td>
<td><span data-bind="text: sourceKeys()[0].reg_exp"></span></td>
<td><span data-bind="text: sourceKeys()[0].defaultValue"></span></td>
<!-- /ko -->
</tr>
<!-- ko foreach: sourceKeys -->
<!-- ko if: $index() !== 0 -->
<tr>
<td><strong data-bind="text: name"></strong></td>
<td><span data-bind="text: minLength"></span></td>
<td><span data-bind="text: maxLength"></span></td>
<td><span data-bind="text: minValue"></span></td>
<td><span data-bind="text: maxValue"></span></td>
<td><span data-bind="text: reg_exp"></span></td>
<td><span data-bind="text: defaultValue"></span></td>
</tr>
<!-- /ko -->
<!-- /ko -->
......
......
</code></pre>
<p>Do you have any ideas on how could I bind to represent this 2D table? The JavaScript design is not a restriction, because I was thinking that storing the columns in different arrays is not a good idea for dynamic data. Maybe each column should have a variable that would identify from which category takes part. Therefore, the <code>newTable</code> object should be redesigned.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T17:07:42.753",
"Id": "67784",
"Score": "5",
"body": "Welcome to Code Review. This is a very well formatted question, good to see this in the first-post review queue."
}
] |
[
{
"body": "<p>I would just add a <code>columnGroup</code> attribute to <code>Column</code> and then do a <code>groupBy</code>-type operation on that attribute. That would reduce your <code>Table</code> view-model to just a collection of <code>Row</code>s, which would be nice. Here's what I'm thinking for <code>Column</code></p>\n\n<pre><code>function Column(columnName, columnGroup /* ... all your other attributes ... */) {\n var self = {};\n self.name = ko.observable(columnName || 'new column');\n self.groupName = ko.observable(columnGroup || 'Misc.');\n /* all your other boilerplate setting */\n return self;\n}\n\n// returns a group object, which has a name and an array of items.\n// this will only be created once in the groups array.\nfunction ensureGroup (groups, groupName) {\n var foundGroup;\n groups.some(function (group) {\n if (group.name === groupName) {\n return foundGroup = group;\n }\n });\n if (!foundGroup) {\n foundGroup = {\n name: groupName,\n items: []\n };\n groups.push(foundGroup);\n }\n return foundGroup;\n}\n\nfunction Table() {\n var self = {};\n self.tableName = ko.observable('New table');\n self.tableDescription = ko.observable('description');\n self.columns = ko.observableArray([]);\n self.columnGroups = ko.computed(function () {\n var groups = self.columns().reduce(function (groups, column) {\n var group = ensureGroup(groups, column.fieldGroup();\n group.items.push(column);\n }, []);\n return groups;\n });\n return self;\n}\n</code></pre>\n\n<p>You then just have to iterate over <code>table.columnGroups</code> in your template. Of course, this code is untested, and there are certainly ways to clean it up more, but I wanted to give you an approach to work from.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T18:31:13.567",
"Id": "67981",
"Score": "1",
"body": "I was curious to see how your code worked so I made a jsfiddle: http://jsfiddle.net/b3VWW/"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T16:36:35.167",
"Id": "40377",
"ParentId": "40276",
"Score": "5"
}
},
{
"body": "<p>With the answer using reduce of Nathan, each time you add a column you need to read all the old columns again.</p>\n\n<p>Another approach is to use a ColumnType object and save all the columns in this object.</p>\n\n<pre><code>//column definition\nfunction Column(columnName, minLength, maxLength, minValue, maxValue, reg_ex, role, order, defaultValue) {\n var self = {};\n self.name = ko.observable(columnName || 'new column');\n self.minLength = ko.observable(minLength || null);\n self.maxLength = ko.observable(maxLength || null);\n self.minValue = ko.observable(minValue || null);\n self.maxValue = ko.observable(maxValue || null);\n self.reg_exp = ko.observable(reg_ex || null);\n self.role = ko.observable(role ? role : 1);\n self.order = ko.observable(order || null);\n self.defaultValue = ko.observable(defaultValue || null);\n return self;\n}\n\nfunction ColumnType(name) {\n var self = this;\n self.name = ko.observable(name);\n self.columns = ko.observableArray([]);\n}\n//table definition\nfunction Table() {\n var self = {};\n self.tableName = ko.observable('New table');\n self.tableDescription = ko.observable('description');\n self.columnTypes = ko.observableArray([]);\n\n self.addColumn = function(columnTypeName, column) {\n console.log('adding column of type ' + columnTypeName);\n var columnType = ko.utils.arrayFirst(self.columnTypes(), function(item) {\n return item.name() == columnTypeName;\n });\n\n if(!columnType) {\n console.log('Column type ' + columnTypeName + ' does not exist\\n Creating new ColumnType object');\n columnType = new ColumnType(columnTypeName); \n self.columnTypes.push(columnType);\n }\n\n columnType.columns.push(column);\n }\n\n return self;\n}\n\n// Here's my data model\nvar ViewModel = function() {\n var self = this;\n //the table\n self.newTable = ko.observable(new Table());\n};\n\nvar VM = new ViewModel();\nko.applyBindings(VM); \n\n//adding columns to the table\nVM.newTable().addColumn('businessFields', new Column('col_1'));\nVM.newTable().addColumn('businessFields', new Column('col_2'));\nVM.newTable().addColumn('test', new Column('col_3'));\n</code></pre>\n\n<p>And the html:</p>\n\n<pre><code><table class=\"table table-bordered\">\n <thead>\n <tr>\n <th></th>\n <th>Name</th>\n <th>Min Length</th>\n <th>Max Length</th>\n <th>Min Value</th>\n <th>Max Value</th>\n <th>Regular Expr</th>\n <th>Default Value</th>\n </tr>\n </thead>\n <tbody data-bind=\"with: newTable\">\n <!-- ko foreach: columnTypes -->\n <tr>\n <td data-bind=\"text: name, attr: { rowspan: function(){ if(columns().length == 0) return 1; else return columns().length; }()}\"></td>\n <!-- ko if: columns().length > 0 -->\n <td><strong data-bind=\"text: columns()[0].name\"></strong></td>\n <td><span data-bind=\"text: columns()[0].minLength\"></span></td>\n <td><span data-bind=\"text: columns()[0].maxLength\"></span></td>\n <td><span data-bind=\"text: columns()[0].minValue\"></span></td>\n <td><span data-bind=\"text: columns()[0].maxValue\"></span></td>\n <td><span data-bind=\"text: columns()[0].reg_exp\"></span></td>\n <td><span data-bind=\"text: columns()[0].defaultValue\"></span></td>\n <!-- /ko -->\n </tr>\n <!-- ko foreach: columns -->\n <!-- ko if: $index() !== 0 -->\n <tr>\n <td><strong data-bind=\"text: name\"></strong></td>\n <td><span data-bind=\"text: minLength\"></span></td>\n <td><span data-bind=\"text: maxLength\"></span></td>\n <td><span data-bind=\"text: minValue\"></span></td>\n <td><span data-bind=\"text: maxValue\"></span></td>\n <td><span data-bind=\"text: reg_exp\"></span></td>\n <td><span data-bind=\"text: defaultValue\"></span></td>\n </tr>\n <!-- /ko -->\n <!-- /ko -->\n <!-- /ko -->\n </tbody>\n</table>\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/sU4gh/\" rel=\"nofollow\">See the JSFiddle</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T18:38:18.580",
"Id": "40387",
"ParentId": "40276",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "40377",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T16:45:47.750",
"Id": "40276",
"Score": "11",
"Tags": [
"javascript",
"knockout.js"
],
"Title": "Knockout.js binding 2D table with rowspan"
}
|
40276
|
<p>I have the following method which encrypts a english text, given the plain text and the desired key:</p>
<pre><code>/// <summary>
/// Encrypts english plain text using user defined key. Range for the key is from -25 to 25.
/// </summary>
/// <param name="plainText"></param>
/// <param name="keyValue"></param>
/// <returns></returns>
public static string encryptTextEng(String plainText,int keyValue)
{
string encText = "";
char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
for (int i = 0; i < plainText.Length; i++)
{
if (plainText[i].ToString() == " ")
{
encText += " ";
}
for (int j = 0; j < alphabet.Length; j++)
{
if (String.Equals(alphabet[j].ToString(), plainText[i].ToString(), StringComparison.OrdinalIgnoreCase))
{
try
{
encText += alphabet[j + keyValue];
}
catch (Exception ex)
{
if (j + keyValue > 26)
{
encText += alphabet[j + keyValue - 26];
}
else if (j + keyValue < 0)
{
encText += alphabet[j + keyValue + 26];
}
}
}
}
}
return encText;
}
</code></pre>
<p>What are good programming practices I am missing here? Also I am not sure about the try/catch part I guess there are better ways to do it? Would it be a good idea to add a switch case which checks if the char it is currently reading is a punctuation character?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T17:21:56.560",
"Id": "67789",
"Score": "1",
"body": "Often, when I see a `for-if` or a `foreach-if`, I assume there's a missing `Where`. When I see nested `for`s, I assume there's a missing `SelectMany`."
}
] |
[
{
"body": "<p>You are correct in suspecting that the try/catch is not necessary. Generally speaking, Caesar ciphers are implemented using <a href=\"http://en.wikipedia.org/wiki/Modular_arithmetic\" rel=\"nofollow noreferrer\">modular arithmetic</a>. We can determine if a character is alphabetical by simply checking if <code>alphabet</code> contains that character; anything else (whitespace, digits, punctuation, etc.) can just be copied as-is, so neither the second for loop nor the proposed switch are necessary either. Here's an example of how you could simplify your code:</p>\n\n<pre><code>public static string encryptTextEng(string plainText, int keyValue)\n{\n string encText = \"\";\n char[] alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\".ToCharArray();\n\n foreach (char c in plainText.ToUpper())\n {\n if (alphabet.Contains(c))\n {\n encText += alphabet[Mod((Array.IndexOf(alphabet, c) + keyValue), 26)];\n }\n else\n {\n encText += c;\n }\n }\n\n return encText;\n}\n\nprivate static int Mod(int dividend, int divisor)\n{\n int remainder = dividend % divisor;\n return remainder < 0 ? remainder + divisor : remainder;\n}\n</code></pre>\n\n<p>I threw the Mod method in there because the modulo operator <a href=\"https://stackoverflow.com/questions/1082917/mod-of-negative-number-is-melting-my-brain\">does not work as you might expect with negative numbers</a>.</p>\n\n<hr>\n\n<p>As mentioned by Bruno in the comments below, a more performant way of checking if the current character is in <code>alphabet</code> and getting the index of that character would be:</p>\n\n<pre><code>foreach (char c in plainText.ToUpper())\n{\n int idx = c - 'A';\n if (idx >= 0 && idx < alphabet.Length)\n {\n encText += alphabet[Mod(idx + keyValue, 26)];\n }\n else\n {\n encText += c;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T18:09:47.910",
"Id": "67805",
"Score": "1",
"body": "I believe you could simplify the mod operation by using `return (Dividend + Divisor) % Divisor;`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T18:12:20.703",
"Id": "67806",
"Score": "0",
"body": "Good point. I'll change that now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T18:27:40.657",
"Id": "67809",
"Score": "2",
"body": "You can also substitute your alphabet.Contains O(n) for c - 'A' < alphabet.Length O(1). You can also use that value as a indexer so you don't have to use IndexOf. http://pastebin.com/CPDWh19J"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T18:28:24.500",
"Id": "67810",
"Score": "0",
"body": "@Simon Actually it just occurred to me that `return (Dividend + Divisor) % Divisor;` doesn't work quite the same way as the original implementation and can still end up returning a negative number"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T18:36:05.330",
"Id": "67812",
"Score": "0",
"body": "Crap, you're right! For the general case it can. Although for this specific case, I believe it won't."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T18:50:01.020",
"Id": "67815",
"Score": "0",
"body": "@Bruno yep, that works just as well, if not better. I'm not convinced that there's significant performance impact from using those array methods in this case given how small `alphabet` is but I agree in principle that it's probably a better way of doing things."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T19:43:43.323",
"Id": "67824",
"Score": "2",
"body": "You have a `)` too much in your `Mod` call in the second version - Should be `Mod(idx + keyValue, 26)`. Also if you make `keyValue` an `unsigned int` then you can get rid of the `Mod` method entirely because then you know `idx + keyValue` will never be negative. Also standard naming conventions for method parameters is `camelCase`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T19:50:05.863",
"Id": "67825",
"Score": "0",
"body": "@ChrisWue: fixed the bracket and casing (I just copied Bruno's code so I didn't catch the stray bracket). Using unsigned would also work but the OP's code indicates that he/she wants to be able to input negative values."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T20:18:42.263",
"Id": "67829",
"Score": "0",
"body": "Sorry for that ) <.< ."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T14:16:48.937",
"Id": "68081",
"Score": "0",
"body": "What are the numbers in front of every char in the char array?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T01:46:18.270",
"Id": "68220",
"Score": "0",
"body": "Which part are you talking about, @bodycountPP?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T10:04:29.880",
"Id": "72039",
"Score": "0",
"body": "You should consider using `ToUpperInvariant()` instead of `ToUpper()`. Otherwise, [your code won't work in Turkey](http://www.codinghorror.com/blog/2008/03/whats-wrong-with-turkey.html)."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T17:55:12.630",
"Id": "40281",
"ParentId": "40277",
"Score": "10"
}
},
{
"body": "<p>A simple solution is to have 2 arrays, one with chars to map from and one with chars to map to.</p>\n\n<p>Then a simple look up, something like this, is all that is necessary</p>\n\n<pre><code>char[] mapFrom = \"ABC\".ToCharArray();\nchar[] mapTo = \"LMN\".ToCharArray();\n\nmapTo[Array.IndexOf(mapFrom, ch)] \n</code></pre>\n\n<p>Advantages include a fast look-up, simple easy to understand code, and the fact that the 2 array could be either hard-coded or generated using the desired algorithm (only once).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T07:01:02.673",
"Id": "40335",
"ParentId": "40277",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "40281",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T16:49:31.997",
"Id": "40277",
"Score": "12",
"Tags": [
"c#",
"caesar-cipher"
],
"Title": "How can I improve this Caesar encryption?"
}
|
40277
|
<p>How should I optimize my code for better performance? When I execute the code outside of MySQL stored proc, it is 500% faster. </p>
<p>MySQL stored procedure</p>
<pre><code>SELECT bs.business_id, adr.street, bs.`name`, bs.description, adr.latitude, adr.longitude FROM businesses bs INNER JOIN address adr ON bs.address_id = adr.address_id WHERE bs.business_id = inBusinessid;
//code that fetches the data from the database
public static final String SP_GET_BUSINESS_BY_ID = "call small.tbl_business_get_by_id(?)";
public static final String BUSINESS_ID = "inBusinessid";
Business bs = null;
try
{
SqlStoredProc sproc = new SqlStoredProc(StoredProcs.SP_GET_BUSINESS_BY_ID, getConnection());
sproc.addParameter(businessId, ProcParam.BUSINESS_ID);
ResultSet reader = sproc.executeReader();
if (reader.next())
{
bs = setBusinessData(reader);
}
reader.close();
sproc.dispose();
}
</code></pre>
<p>Here is SQL wrapper I created. </p>
<pre><code>public class SqlStoredProc
{
private CallableStatement mCallableStatement;
private PreparedStatement mPreparedStatement;
private Connection mConnection;
private boolean mConnectionOpen = false;
private boolean mInitConnectionClosed = true;
public enum SqlType
{
Integer, BigInt, TinyInt, Varchar, Char, Date, TimeStamp, Array, Blob, Boolean, Float, Decimal, Double
}
public SqlStoredProc(String storedProcName, Connection connection)
throws SQLException
{
mConnection = connection;
mCallableStatement = mConnection.prepareCall(storedProcName);
mConnectionOpen = true;
}
public SqlStoredProc(Connection connection) throws SQLException
{
mConnection = connection;
mConnectionOpen = true;
}
/* START OF PREPARED STATEMENT CODE */
public void setPreparedStatement(String preparedQuery) throws SQLException
{
mPreparedStatement = mConnection.prepareStatement(preparedQuery);
}
public void addPreparedParamether(int parameterIndex, String value) throws SQLException
{
mPreparedStatement.setString(parameterIndex, value);
}
public void addPreparedParamether(int parameterIndex, int value) throws SQLException
{
mPreparedStatement.setInt(parameterIndex, value);
}
public void addPreparedParamether(int parameterIndex, float value) throws SQLException
{
mPreparedStatement.setFloat(parameterIndex, value);
}
public void addPreparedParamether(int parameterIndex, double value) throws SQLException
{
mPreparedStatement.setDouble(parameterIndex, value);
}
public ResultSet executePreparedQuery() throws SQLException
{
return mPreparedStatement.executeQuery();
}
/* END OF PREPARED STATEMENT */
/* START OF STORED PROC */
public void setStoredProcName(String storedProcName) throws SQLException
{
mCallableStatement = mConnection.prepareCall(storedProcName);
}
public void addParameter(int value, String parameterName)
throws SQLException
{
mCallableStatement.setInt(parameterName, value);
}
public void addParameter(int value, int parameterIndex)
throws SQLException
{
mCallableStatement.setInt(parameterIndex, value);
}
public void addParameter(String value, String parameterName)
throws SQLException
{
if (value != null) mCallableStatement.setString(parameterName, value);
else mCallableStatement.setNull(parameterName, java.sql.Types.VARCHAR);
}
public void addParameter(String value, int parameterIndex)
throws SQLException
{
if (value != null) mCallableStatement.setString(parameterIndex, value);
else mCallableStatement.setNull(parameterIndex, java.sql.Types.VARCHAR);
}
public void addParameter(Date date, String parameterName)
throws SQLException
{
if (date != null)
{
mCallableStatement.setTimestamp(parameterName,
new java.sql.Timestamp(date.getTime()));
}
else
{
mCallableStatement.setNull(parameterName, java.sql.Types.TIMESTAMP);
}
}
public void addParameter(double value, String parameterName)
throws SQLException
{
mCallableStatement.setDouble(parameterName, value);
}
public void addParameter(float value, String parameterName)
throws SQLException
{
mCallableStatement.setFloat(parameterName, value);
}
public void addParameter(float value, int parameterIndex)
throws SQLException
{
mCallableStatement.setFloat(parameterIndex, value);
}
public int getOutParameterTypeInt(String parameterName) throws SQLException
{
return mCallableStatement.getInt(parameterName);
}
public float getOutParameterTypeFloat(String parameterName) throws SQLException
{
return mCallableStatement.getFloat(parameterName);
}
public double getOutParameterTypeDouble(String parameterName) throws SQLException
{
return mCallableStatement.getDouble(parameterName);
}
public void registerOutParameter(String parameterName, SqlType sqlType)
throws SQLException
{
switch (sqlType)
{
case Date:
mCallableStatement.registerOutParameter(parameterName,
java.sql.Types.DATE);
break;
case TimeStamp:
mCallableStatement.registerOutParameter(parameterName,
java.sql.Types.TIMESTAMP);
break;
case Integer:
mCallableStatement.registerOutParameter(parameterName,
java.sql.Types.INTEGER);
break;
case TinyInt:
mCallableStatement.registerOutParameter(parameterName,
java.sql.Types.TINYINT);
break;
case Varchar:
mCallableStatement.registerOutParameter(parameterName,
java.sql.Types.VARCHAR);
break;
case Array:
mCallableStatement.registerOutParameter(parameterName,
java.sql.Types.ARRAY);
break;
case BigInt:
mCallableStatement.registerOutParameter(parameterName,
java.sql.Types.BIGINT);
break;
case Blob:
mCallableStatement.registerOutParameter(parameterName,
java.sql.Types.BLOB);
break;
case Char:
mCallableStatement.registerOutParameter(parameterName,
java.sql.Types.CHAR);
break;
case Boolean:
mCallableStatement.registerOutParameter(parameterName,
java.sql.Types.BOOLEAN);
break;
case Float:
mCallableStatement.registerOutParameter(parameterName,
java.sql.Types.FLOAT);
break;
case Decimal:
mCallableStatement.registerOutParameter(parameterName,
java.sql.Types.DECIMAL);
break;
case Double:
mCallableStatement.registerOutParameter(parameterName,
java.sql.Types.DOUBLE);
break;
default:
break;
}
}
public int executeNonQuery() throws SQLException
{
int rowsAffected = mCallableStatement.executeUpdate();
return rowsAffected;
}
public void addBatch() throws SQLException
{
mCallableStatement.addBatch();
}
public boolean execute() throws SQLException
{
return mCallableStatement.execute();
}
public int[] executeBatch() throws SQLException
{
return mCallableStatement.executeBatch();
}
public ResultSet getResultSet() throws SQLException
{
return mCallableStatement.getResultSet();
}
public boolean getMoreResults() throws SQLException
{
return mCallableStatement.getMoreResults();
}
public ResultSet executeReader() throws SQLException
{
return mCallableStatement.executeQuery();
}
public CallableStatement getCurrentStatement()
{
return mCallableStatement;
}
public void dispose() throws SQLException
{
closeOpenConnections();
}
private void closeOpenConnections() throws SQLException
{
if (mConnectionOpen && mInitConnectionClosed)
{
if (mCallableStatement != null) mCallableStatement.close();
if (mPreparedStatement != null) mPreparedStatement.close();
mInitConnectionClosed = false;
mConnection.close();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T19:18:59.480",
"Id": "67817",
"Score": "2",
"body": "This question appears to be off-topic because it is not really asking for a code review. It is asking for and explanation why two pieces of code do not perform the same. I'm not sure which site this belongs on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T19:31:44.440",
"Id": "67819",
"Score": "0",
"body": "I thought with code reviews you explain why something should be done a certain way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T19:38:58.253",
"Id": "67822",
"Score": "1",
"body": "Please see: [On Topic Questions](http://codereview.stackexchange.com/help/on-topic)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T19:42:16.123",
"Id": "67823",
"Score": "0",
"body": "I just read the on topic and this does fall under Performance. I will rephrase the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T17:53:10.707",
"Id": "67971",
"Score": "0",
"body": "What do you mean by \"outside of MySQL stored proc\"? Is that when you execute the query in MySQL directly without using your code wrapping classes or what is it exactly?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T20:48:09.000",
"Id": "67991",
"Score": "0",
"body": "It is much faster when I use a prepared statement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T22:10:36.910",
"Id": "68002",
"Score": "0",
"body": "@SimonAndréForsberg when I run this query inside a prepared statement the response time is faster by 300-500ms depending on the size of the resultset. I would like to know why is that so when neither is using query cache."
}
] |
[
{
"body": "<p>After three days for research, I discovered that <code>CallableStatements</code> are much slower than prepared statements because there is overhead when setting up the stored procedure. That's why my stored proc takes 300ms+ vs the prepared statement.</p>\n\n<p><a href=\"http://oreilly.com/catalog/jorajdbc/chapter/ch19.html#63495\" rel=\"nofollow\">This</a> explains the issue:</p>\n\n<blockquote>\n <p>As you may recall, CallableStatement objects are used to execute database stored procedures. I've saved CallableStatement objects until last, because they are the slowest performers of all the JDBC SQL execution interfaces. This may sound counterintuitive, because it's commonly believed that calling stored procedures is faster than using SQL, but that's simply not true. Given a simple SQL statement, and a stored procedure call that accomplishes the same task, the simple SQL statement will always execute faster. Why? Because with the stored procedure, you not only have the time needed to execute the SQL statement but also the time needed to deal with the overhead of the procedure call itself.</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T12:29:58.890",
"Id": "40540",
"ParentId": "40285",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "40540",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T18:38:59.217",
"Id": "40285",
"Score": "4",
"Tags": [
"java",
"performance",
"mysql",
"sql"
],
"Title": "Optimize MySQL in a stored procedure"
}
|
40285
|
<p>I am new to c#, and rather new to design-patterns. I want to create a simple and a most elegant solution for loading and validating a xml file and later on extracting its fields.
I've started with a generic <code>IData</code> interface, that gets implemented by a <code>XmlFileData</code> class, but I feel that there is much more to be improved upon, but I lack the knowledge to do it (from design, to naming variables and methods and so on).</p>
<p>So please, have no mercy !!</p>
<pre><code>public interface IData
{
String GetDataString();
}
class XMLValidator
{
private StringBuilder verificationErrorsList = new StringBuilder();
public string ValidationSchema { get; set; }
public String ValidationErrors
{
get { return verificationErrorsList.ToString(); }
}
public bool HasErrors
{
get {return (verificationErrorsList.Length > 0);}
}
public void Validate(IData xmlData)
{
try
{
XmlWriterSettings ws = new XmlWriterSettings();
ws.Indent = true;
XmlReaderSettings rs = new XmlReaderSettings();
rs.ValidationType = ValidationType.Schema;
rs.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(rs_ValidationEventHandler);
rs.Schemas.Add(null, ValidationSchema);
rs.CloseInput = true;
rs.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessIdentityConstraints |
XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ProcessSchemaLocation;
StringReader r = new StringReader(xmlData.GetDataString());
using (XmlReader reader = XmlReader.Create(r, rs))
{
try
{
while (reader.Read()) { }
}
catch (XmlException e)
{
verificationErrorsList.Append(e.Message);
verificationErrorsList.Append(Environment.NewLine);
}
}
}
catch (XmlSchemaValidationException e)
{
verificationErrorsList.Append(e.Message + Environment.NewLine);
}
}
void rs_ValidationEventHandler(object sender, System.Xml.Schema.ValidationEventArgs e)
{
if (e.Severity == XmlSeverityType.Error || e.Severity == XmlSeverityType.Warning)
{
verificationErrorsList.Append(e.Message + Environment.NewLine);
}
}
}
</code></pre>
<p>Usage:</p>
<pre><code> IData data = new XmlFileData(basepathXML + fileNameXML);
XMLValidator validator = new XMLValidator();
validator.ValidationSchema = basepathXML + fileNameXSD;
validator.Validate(data);
if (validator.HasErrors)
{
Console.WriteLine(validator.ValidationErrors);
}
else
{
Console.WriteLine("Success");
}
</code></pre>
|
[] |
[
{
"body": "<p>A few things:</p>\n<ol>\n<li><p><code>IData</code> is not a particularly good name for the interface as it represents a source of data rather than the data itself. Therefor <code>IDataSource</code> seems more appropriate.</p>\n</li>\n<li><p>The interface is a bit ambiguous - which method am I supposed to use <code>GetDataStream</code> or <code>GetDataString</code>? Why use one or the other? Could I call both multiple times and interchangeably?</p>\n<p>As of now it doesn't really provide enough value to warrant it's existence. You'd be better of having <code>XmlValidator</code> accept a <a href=\"http://msdn.microsoft.com/en-us/library/system.io.textreader%28v=vs.110%29.aspx\" rel=\"noreferrer\"><code>TextReader</code></a> and let the calling code deal with how to wrap it around the source.</p>\n</li>\n<li><p>Consider passing the <code>ValidationSchema</code> as part of the constructor for the <code>XmlValidator</code> - it's an integral part of its validation logic.</p>\n</li>\n<li><p>In the validator when the reader throws an exception because there was a problem reading from the stream for example then you catch those as validation errors which I'd consider technically wrong. Your validator should catch validation errors - i.e. anything that has to do with invalid XML. Everything else should not be of its concern. So don't catch <code>Exception</code> - be more specific.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T15:08:00.347",
"Id": "67956",
"Score": "0",
"body": "2. i wanted to generalize the xml data file, for the sake of completeness, maybe some day the data source might be a url, a network stream, an encripted file? Regarding those to methods.. The GetDataStream() method is has no use right now .. 1,3 done. 4. Ok.. So you say I should only catch validation exceptions in the validator.. so does my updated code meet that point?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T06:59:32.253",
"Id": "68043",
"Score": "0",
"body": "@A.K: Re 2) Sure but your interface should hide that. You don't want a call for every possible type of source on your interface. It should have a generic method which supplies data regardless of the source. `TextReader` is not an interface but a generic enough abstract base class which should serve the purpose well."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T19:12:26.787",
"Id": "40288",
"ParentId": "40287",
"Score": "10"
}
},
{
"body": "<p>There is a lot that can be simplified. <code>AppendLine()</code> instead of <code>Append()</code> with <code>Environment.NewLine</code>, object initializer syntax, etc.</p>\n\n<p><code>ws = new XmlWriterSettings</code> is never used.</p>\n\n<p>Also, <code>StringReader</code> is also an <code>IDisposable</code> resource and should therefore be wrapped in <code>using</code>.</p>\n\n<p>I've also put the very short validation event handler method inline with a lambda.</p>\n\n<pre><code>public interface IData\n{\n Stream GetDataStream();\n\n string GetDataString();\n}\n\ninternal class XmlValidator\n{\n private readonly StringBuilder verificationErrorsList = new StringBuilder();\n\n public string ValidationSchema\n {\n get;\n\n set;\n }\n\n public string ValidationErrors\n {\n get\n {\n return this.verificationErrorsList.ToString();\n }\n }\n\n public bool HasErrors\n {\n get\n {\n return this.verificationErrorsList.Length > 0;\n }\n }\n\n public void Validate(IData xmlData)\n {\n try\n {\n ////var ws = new XmlWriterSettings { Indent = true };\n var rs = new XmlReaderSettings\n {\n ValidationType = ValidationType.Schema,\n CloseInput = true,\n ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings\n | XmlSchemaValidationFlags.ProcessIdentityConstraints\n | XmlSchemaValidationFlags.ProcessInlineSchema\n | XmlSchemaValidationFlags.ProcessSchemaLocation\n };\n\n rs.ValidationEventHandler += (sender, e) =>\n {\n if (e.Severity == XmlSeverityType.Error || e.Severity == XmlSeverityType.Warning)\n {\n this.verificationErrorsList.AppendLine(e.Message);\n }\n };\n rs.Schemas.Add(null, this.ValidationSchema);\n using (var r = new StringReader(xmlData.GetDataString()))\n using (var reader = XmlReader.Create(r, rs))\n {\n try\n {\n while (reader.Read())\n {\n }\n }\n catch (Exception ex)\n {\n this.verificationErrorsList.AppendLine(ex.Message);\n }\n }\n }\n catch (Exception ex)\n {\n this.verificationErrorsList.AppendLine(ex.Message);\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T19:44:52.303",
"Id": "40289",
"ParentId": "40287",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "40288",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T18:44:12.580",
"Id": "40287",
"Score": "11",
"Tags": [
"c#",
"design-patterns"
],
"Title": "Simple specific classes design"
}
|
40287
|
<p>I'm working with Codeigniter and I have a jQuery file to add some functionalities. But I think I'm doing it in a wrong way.</p>
<pre><code>$(function() {
var list = '../indoamericana/intranet/employeesList/';
var home = '../indoamericana/administrar/callHome/';
var profile = '../indoamericana/user/';
var addUser = '../indoamericana/user/addUSer';
$(document).on('click', '#documentacion', function(e) {
var head = $('iframe').contents().find('head');
head.append($('<link/>', {
rel: 'stylesheet',
href: '/indoamericana/webroot/css/style.css',
type: 'text/css' }));
head.append($('<link/>', { rel: 'stylesheet',
href: '/indoamericana/webroot/css/custom.css',
type: 'text/css' }));
e.preventDefault();
});
$(document).on('click', 'a[data-target=#ajax]', function(ev){
var target = $(this).attr("href");
$("#ajax").load(target, function() {
$("#ajax").modal("show");
});
ev.preventDefault();
});
var loadPage = function(page){
$(".page-content").load(page);
};
$(".sub-menu .menu-item, .module-item").click(function(event) {
$(".page-content").load($(this).data('target'));
$("title").text( $( this ).text() );
});
$( document ).on( 'click', '.page-sidebar-menu li', function(e) {
$( this ).addClass('active');
$( this ).siblings().removeClass('active');
});
var last_clicked = '';
var order = 'asc';
$(document).on('click', '#admin-support a i', function(e){
var index = $( this ).attr('data-sort');
if( last_clicked == index )
order = ( order == 'asc' ) ? order = 'desc' : order = 'asc';
last_clicked = index;
var page = '../indoamericana/soporte/allSupports/' + index + '/' + order;
$(".page-content").load(page);
});
});
</code></pre>
<p>I'm calling this file (call-functionalities.js) in a script type of my 'head':</p>
<pre><code><script src="webroot/scripts/call-functionalities.js" type="text/javascript"></script>
</code></pre>
<p>I don't want to use anonymous functions. I have seen some pages that use </p>
<pre><code>jQuery(document).ready(function() {
App.init();
Index.init();
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T20:14:51.400",
"Id": "67828",
"Score": "1",
"body": "Why do you think it's the wrong way? It looks like a fairly ok jquery code to me. I'd prefer to use a more specific selector rather than `$(document)` for attaching the event handlers, but that's really a matter of style, I guess. The only thing that definitely can be improved is: `order = ( order == 'asc' ) ? order = 'desc' : order = 'asc';` is better rewritten as `order = ( order == 'asc' ) ? 'desc' : 'asc';`"
}
] |
[
{
"body": "<ol>\n<li><p>Apart from the fact I can't find any use of <code>var loadPage</code> It doesn't need to be an expression.\nInstead try:</p>\n\n<pre><code>function loadPage(page) {\n}\n</code></pre>\n\n<p>It is still accessible only within your code here, it is cleaner and easier to debug.</p></li>\n<li><p>Keep your click events consistent</p>\n\n<pre><code>$(\".sub-menu .menu-item, .module-item\").click(function(event) {\n $(\".page-content\").load($(this).data('target')); \n $(\"title\").text( $( this ).text() );\n});\n</code></pre>\n\n<p>Is the only place you're using <code>.click(</code> I'd stick with the <code>$(parent).on('click', '.selector', function(){</code> style.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T00:18:26.140",
"Id": "40314",
"ParentId": "40290",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T19:45:27.920",
"Id": "40290",
"Score": "5",
"Tags": [
"javascript",
"jquery",
"codeigniter"
],
"Title": "jQuery click handlers"
}
|
40290
|
<p>Here is a method I have in my <code>ApplicationController</code>, but it's "ugly" and needs some cleanup. </p>
<pre><code> def user_root_path
return root_url unless user_signed_in?
return admin_root_url if current_user.admin?
return contributor_dashboard_url if current_user.athlete_contributor? && !current_user.class.name.eql?("Athlete")
return school_admin_athletes_path if current_user.role?("School Admin")
case current_user.class.name
when "Athlete"
if current_user.username.present?
edit_vitals_athlete_profile_path
else
account_finalize_path
end
when "HighSchoolCoach"
school_admin_athletes_path
when "CollegeCoach"
if current_user.sports.blank? || current_user.college_id.blank?
account_finalize_path
else
search_index_path
end
else
root_url
end
end
</code></pre>
|
[] |
[
{
"body": "<p>I would solve this with a combination of inheritance and duck typing. </p>\n\n<ul>\n<li>Use a base method on a <code>User</code> class <code>root_path</code> to be your entry point. </li>\n<li>Pull out that nasty \"signed out\" user concept to a <code>NullUser</code> object, it is safer than passing nils around or constantly calling <code>user_signed_in?</code> everywhere.</li>\n<li>Delegate from the <code>root_path</code> method in the base class to <code>specific_root_path</code> in subclasses once you are past your \"early exit\" logic.</li>\n</ul>\n\n<hr>\n\n<pre><code># application_controller.rb\n\nclass ApplicationController < ActionController::Base\n before_filter :set_current_user\n\n def user_root_path\n @user.root_path\n end\n\n def set_current_user\n @user = current_user\n @user ||= NullUser.new\n end\nend\n</code></pre>\n\n<hr>\n\n<pre><code># user.rb\n\nclass User < ActiveRecord::Base\n include Rails.application.routes.url_helpers\n\n def admin?\n # your admin logic\n end\n\n def root_path\n return admin_root_url if self.admin?\n return school_admin_athletes_path if self.role?(\"School Admin\") \n if self.athlete_contributor? &&\n !self.class.name.eql?(\"Athlete\")\n return contributor_dashboard_url\n end\n\n specific_root_path\n end\n\n def specific_root_path\n root_url\n end\nend\n\nclass NullUser\n include Rails.application.routes.url_helpers\n\n def root_path\n root_url\n end\nend\n</code></pre>\n\n<hr>\n\n<pre><code># athlete.rb\n\nclass Athlete < User\n\n def specific_root_path\n if self.username.present?\n edit_vitals_athlete_profile_path\n else\n account_finalize_path\n end\n end\n\nend\n</code></pre>\n\n<hr>\n\n<pre><code># high_school_coach.rb\n\nclass HighSchoolCoach < User\n\n def specific_root_path\n school_admin_athletes_path\n end\n\nend\n</code></pre>\n\n<hr>\n\n<pre><code># college_coach.rb\n\nclass CollegeCoach < User\n def specific_root_path\n if self.sports.blank? || self.college_id.blank?\n account_finalize_path\n else\n search_index_path\n end\n end\nend\n</code></pre>\n\n<hr>\n\n<p>This logic should be equivalent to your original logic, if it isn't, it is pretty close.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T08:39:22.360",
"Id": "40438",
"ParentId": "40291",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "40438",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T19:51:04.900",
"Id": "40291",
"Score": "1",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Refactoring method in ApplicationController for Rails App"
}
|
40291
|
<pre><code>def getProxiesLstFromDB():
global g_proxies
# insert to status page links table
proxies_list = g_db["proxies_list"]
proxies_list_records = proxies_list.find()
print_to_log("get proxies list from db")
for proxies_list_record in proxies_list_records:
if proxies_list_record is not None:
if len(proxies_list_record["user"]) == 0:
proxies_list_record["user"] = "user"
if len(proxies_list_record["password"]) == 0:
proxies_list_record["password"] = "password"
g_proxies.append(proxies_list_record)
def get_ProxyInfo(proxy_no):
global g_proxies
if len(g_proxies) == 0:
return ""
proxy_no = proxy_no % len(g_proxies)
proxy_info = "%s:%s@%s:%s" % (g_proxies[proxy_no]["user"], g_proxies[proxy_no] ["password"], g_proxies[proxy_no]["ProxyIP"], g_proxies[proxy_no]["ProxyPort"])
return proxy_info
def readHtml_using_proxy(one_url, proxy_no):
global g_proxies
proxy = None
page_text = ""
try:
proxy_info = "%s:%s@%s:%s" % (g_proxies[proxy_no]["user"], g_proxies[proxy_no]["password"], g_proxies[proxy_no]["ProxyIP"], g_proxies[proxy_no]["ProxyPort"])
proxy = urllib2.ProxyHandler({"http": proxy_info,
"https":proxy_info})
except:
print_to_log("Proxy setting error. proxy_no: %d" % proxy_no)
return page_text
try:
opener = urllib2.build_opener(proxy)
req = urllib2.Request(one_url)
r = opener.open(req)
html = r.read()
converter = html2text.HTML2Text()
converter.ignore_links = True
page_text = ""
page_text = html.decode("utf8", "ignore")
page_text = converter.handle(page_text)
except:
print_to_log("Unable to read or decode page html from %s" % one_url)
return page_text
def scrape_one_url(db, one_url, domain_url, domain_url_idx, threadname):
scrape_results = []
threadnamelen = 13
threadname = "(%s)" % threadname
if len(threadname) < threadnamelen:
idx = 0
lenOfthreadname = len(threadname)
while idx < threadnamelen - lenOfthreadname:
idx += 1
threadname = threadname + " "
one_url = urljoin(domain_url, one_url)
if "google.com" in one_url:
#skip for google.com
return
if is_debug:
print_to_log( "%s>>> processing domain_idx: %s, url: %s" % (threadname, domain_url_idx, one_url) )
else:
print_to_log( "%s>>> processing %s" % (threadname, one_url) )
#get page content from url
br = mechanize.Browser()
br.set_handle_equiv(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
try:
response = br.open(one_url)
page_type = response.info()["Content-Type"]
if is_debug:
print response.info()["Content-Type"]
if "image" in page_type:
return
page_html = response.read()
except:
return
converter = html2text.HTML2Text()
converter.ignore_links = True
try:
page_text = page_html.decode("utf8", "ignore")
page_text = converter.handle(page_text)
page_text = re.sub("[^a-zA-Z0-9_!]+[ ,.\?!]", "", page_text)
except:
return
#print page_text
###########################
Site_Cate1 = ""
Site_Cate2 = ""
Site_Cate3 = ""
Google_Page_Rank = "0"
Twitter_share_cnt = ""
Facebook_share_cnt = ""
MAX_LIMIT_CNT_TO_INSERT = 100
#1. Site Categorization
xml = """<?xml version="1.0" encoding="utf-8" ?>
<uclassify xmlns="http://api.uclassify.com/1/RequestSchema" version="1.01">
<texts>
<textBase64 id="TextId">%s</textBase64>
</texts>
<readCalls readApiKey="secret">
<classify id="Clas" username="uClas" classifierName="Topic" textId="TextId"/>
</readCalls>
</uclassify>"""
xml = xml % base64.b64encode(page_text.encode("utf8", "ignore"))
headers = {'Content-Type': 'text/xml; charset=utf-8'} # set what your server accepts
response = requests.post('http://api.uclas.com', data=xml, headers=headers).text
res_xml = BeautifulSoup(response)
Cate_lst = {}
try:
for one_class in res_xml.findAll("class"):
Cate_lst[one_class.attrs["classname"]] = float(one_class.attrs["p"])
except:
pass
idx = 1
for key, value in sorted(Cate_lst.iteritems(), key=lambda (k,v): (v,k), reverse=True):
if idx == 1:
Site_Cate1 = key
elif idx == 2:
Site_Cate2 = key
elif idx == 3:
Site_Cate3 = key
break
idx += 1
global g_proxy_counter
g_queueLock.acquire()
g_proxy_counter += 1
g_queueLock.release()
proxy_info = get_ProxyInfo(g_proxy_counter)
try:
if len(proxy_info) > 0:
Google_Page_Rank = rank_provider.GooglePageRank().get_rank_using_proxy(one_url, proxy_info)
if Google_Page_Rank is None:
Google_Page_Rank = "0"
else:
Google_Page_Rank = str(Google_Page_Rank)
except:
Google_Page_Rank = "0"
if is_debug:
print_to_log( "%sGoogle Page Rank: %s" % (threadname, Google_Page_Rank) )
#8. Social Share Counts
one_url_tw = "http://cdn.api.twitter.com/1/urls/count.json?url=%s" % one_url
try:
response_tw = br.open(one_url_tw)
page_html_tw = response_tw.read()
j = json.loads(page_html_tw)
Twitter_share_cnt = j['count']
except:
pass
one_url_fb = "http://graph.facebook.com/?id=%s" % one_url
try:
response_fb = br.open(one_url_fb)
page_html_fb = response_fb.read()
j = json.loads(page_html_fb)
Facebook_share_cnt = j['shares']
except:
pass
#5. Total Backlinks
t_soup = BeautifulSoup(page_html)
t_as = t_soup.findAll('a')
Total_Incoming_links = 0
Total_Outgoing_links = 0
links_idx = 0
records = []
status_records = []
for t_a in t_as:
if not t_a.has_attr('href') or (not t_a['href'].startswith("http") and not t_a['href'].startswith("/")):
continue
#/#comment, /#readmore, /#respond
if ("/#comment" in t_a['href']) or ("/#readmore" in t_a['href']) or ("/#respond" in t_a['href']):
continue
domain_url_www = domain_url.replace('https://','https://www.').replace('http://','http://www.')
if t_a['href'].startswith(domain_url):
t_a['href'] = t_a['href'][len(domain_url):]
elif t_a['href'].startswith(domain_url_www):
t_a['href'] = t_a['href'][len(domain_url_www):]
InOrOutLink = ""
if t_a['href'].startswith("http"):
Total_Outgoing_links += 1
InOrOutLink = "Outgoing"
else:
Total_Incoming_links += 1
InOrOutLink = "Incoming"
#################################
# insert to status page links table
status_page_links = db["status_page_links"]
status_page_links_record = status_page_links.find_one({"DomainURL": domain_url, "DomainURLIDX": domain_url_idx, "Link": t_a['href']})
if status_page_links_record is None:
status_record = {
"DomainURL": domain_url,
"DomainURLIDX": domain_url_idx,
"Link": t_a['href'],
"Status": 0, #0: not processed, 1: processed
"date": datetime.datetime.utcnow()}
status_page_links_id = status_page_links.insert(status_record)
scrape_results.append(status_record)
links_idx += 1
###################################
# insert to db
record = {
"DomainURL": domain_url,
"DomainURLIDX": domain_url_idx,
"PageURL": one_url,
"Link": t_a['href'],
"InOrOutLink": InOrOutLink,
"date": datetime.datetime.utcnow()}
records.append(record)
if links_idx % MAX_LIMIT_CNT_TO_INSERT == 0:
page_link_info = db["page_link_info"]
page_link_info_ids = page_link_info.insert(records)
records = []
if is_debug:
print_to_log( "%sinserted %s links" % (threadname, links_idx) )
####################################
#calculate total count of incoming / outcoming links
if links_idx % MAX_LIMIT_CNT_TO_INSERT > 0:
page_link_info = db["page_link_info"]
page_link_info_ids = page_link_info.insert(records)
records = []
#2. Keyword Relevance, 3. Key word Sentiment Value
extractor = extract.TermExtractor()
extractor.filter = extract.DefaultFilter(noLimitStrength=2)
kwds = sorted( extractor(page_text) )
total_cntOfWds = len([word for word in page_text.split() if word.isalnum()])
KeywordsCnt = 0
xml_sentiment_templ = """<?xml version="1.0" encoding="utf-8" ?>
<uclassify xmlns="http://api.uclassify.com/1/RequestSchema" version="1.01">
<texts>
<textBase64 id="tweet1">%s</textBase64>
</texts>
<readCalls readApiKey="secret">
<classifyKeywords id="ClassifyKeywords" username="uClassify" classifierName="Sentiment" textId="tweet1"/>
</readCalls>
</uclassify>"""
records = []
for kwd in kwds:
#break # for test
(one_word, occurences, cntOfWd) = kwd
if re.search('[a-zA-Z]+',one_word) == None:
pass
elif len(one_word) < 3:
pass
elif cntOfWd > 3:
pass
else:
Keyword_Density = float(occurences) * cntOfWd / total_cntOfWds
Keyword_Density = "%.6f" % round(float(Keyword_Density),6)
try:
one_word = one_word.decode("utf8", "ignore")
xml_sentiment = xml_sentiment_templ % base64.b64encode(one_word.encode("utf8", "ignore"))
except:
continue
KS_positive = 0
KS_negative = 0
KS_type = "neutral"
#check if kw exists in db already
KeywordsCnt += 1
###################################
# insert to db
record = {
"DomainURL": domain_url,
"DomainURLIDX": domain_url_idx,
"PageURL": one_url,
"Keyword": one_word,
"KWSentiment": KS_type,
"KWSPositive": KS_positive,
"KWSNegative": KS_negative,
"KWDensity": Keyword_Density,
"KWOccurences": occurences,
"KWCntOfWords": cntOfWd,
"date": datetime.datetime.utcnow()}
records.append(record)
if KeywordsCnt % MAX_LIMIT_CNT_TO_INSERT == 0:
page_kw_info = db["page_kw_info"]
page_kw_info_ids = page_kw_info.insert(records)
records = []
####################################
if KeywordsCnt % MAX_LIMIT_CNT_TO_INSERT > 0:
page_kw_info = db["page_kw_info"]
page_kw_info_ids = page_kw_info.insert(records)
records = []
####################################
#6. Kewyword Density
# already got
#7. Domain Age
#8. Calculate Points
Points = 0
try:
int_Google_Page_Rank = int(Google_Page_Rank)
except:
int_Google_Page_Rank = 0
try:
int_Total_Incoming_links = int(Total_Incoming_links)
except:
int_Total_Incoming_links = 0
try:
int_Total_Outgoing_links = int(Total_Outgoing_links)
except:
int_Total_Outgoing_links = 0
try:
int_Twitter_share_cnt = int(Twitter_share_cnt)
except:
int_Twitter_share_cnt = 0
try:
int_Facebook_share_cnt = int(Facebook_share_cnt)
except:
int_Facebook_share_cnt = 0
try:
Points = int_Google_Page_Rank*10 + int_Total_Incoming_links/10 - int_Total_Outgoing_links/5 + ( int_Twitter_share_cnt + int_Facebook_share_cnt )/15
except:
Points = 0
###################################
# insert to db
record = {
"DomainURL": domain_url,
"DomainURLIDX": domain_url_idx,
"PageURL": one_url,
"SiteCate1": Site_Cate1,
"SiteCate2": Site_Cate2,
"SiteCate3": Site_Cate3,
"GooglePageRank": Google_Page_Rank,
"FacebookShareCnt": Facebook_share_cnt,
"TwitterShareCnt": Twitter_share_cnt,
"TotalBacklinks": Total_Incoming_links + Total_Outgoing_links,
"TotalIncomingLinksCnt": Total_Incoming_links,
"TotalOutgoingLinksCnt": Total_Outgoing_links,
"TotalWordsCnt": total_cntOfWds,
"TotalKeywordsCnt": KeywordsCnt,
"Points": Points,
"date": datetime.datetime.utcnow()}
page_main_info = db["page_main_info"]
update_status = page_main_info.update({"PageURL":one_url}, record, upsert=True)
return scrape_results
def scrape_one_domain(domain_url, domain_url_idx, threadname):
global PAGES_CRAWLING_THREADS
one_url = "/"
client = MongoClient('secret', 2422)
db = client['site_analysis']
# insert to status page links table
status_page_links = db["status_page_links"]
status_page_links_record = status_page_links.find_one({"DomainURL": domain_url, "DomainURLIDX": domain_url_idx, "Link": one_url})
if status_page_links_record is None:
status_record = {
"DomainURL": domain_url,
"DomainURLIDX": domain_url_idx,
"Link": one_url,
"Status": 0, #0: not processed, 1: processed
"date": datetime.datetime.utcnow()}
status_page_links_id = status_page_links.insert(status_record)
#process not processed links in separate threads
def process_link_worker(queue, db, domain_url, domain_url_idx, threadname, threadsubname, threads_signals):
global PAGES_CRAWLING_THREADS
while True:
try:
status_page_links_record = queue.get_nowait()
except Queue.Empty:
threads_signals.add(threadsubname)
if len(threads_signals) >= PAGES_CRAWLING_THREADS * 10: # if no job left
return
else:
time.sleep(1)
continue
threads_signals.discard(threadsubname)
one_url = status_page_links_record["Link"]
scrape_results = scrape_one_url(db, one_url, domain_url, domain_url_idx, threadname)
for scrape_result in scrape_results:
queue.put(scrape_result)
db["status_page_links"].update({'_id': ObjectId(status_page_links_record["_id"])},
{'$set': {"Status": 1, "date": datetime.datetime.utcnow()}})
status_page_links = db["status_page_links"]
status_page_links_records = list(status_page_links.find({"DomainURL": domain_url, "DomainURLIDX": domain_url_idx, "Status": 0}))
if status_page_links_records:
links_queue = Queue.Queue()
for status_page_links_record in status_page_links_records:
links_queue.put(status_page_links_record)
link_processing_threads = []
threads_signals = set()
for i in range(PAGES_CRAWLING_THREADS): #start 2 threads
thread = threading.Thread(target=process_link_worker, args=(links_queue,db,domain_url,domain_url_idx,
threadname,'%s_%s' % (threadname, i+1),
threads_signals))
thread.start()
link_processing_threads.append(thread)
#wait for threads return
for thread in link_processing_threads:
thread.join()
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, q):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.q = q
def run(self):
global g_queueLock
global g_workQueue
global g_workingEntry
global g_db
print_to_log( "Starting " + self.name )
while not exitFlag:
g_queueLock.acquire()
if not g_workQueue.empty():
data = g_workQueue.get()
domain_url = data[0]
domain_url_idx = data[1]
g_workingEntry.append(domain_url)
g_queueLock.release()
scrape_one_domain(domain_url, domain_url_idx, self.name)
#updated domain status in db
g_queueLock.acquire()
g_workingEntry.remove(domain_url)
status_domain = g_db["status_domain"]
status_domain.update({"DomainURL": domain_url.strip(), "DomainURLIDX": domain_url_idx,"Status": 0},
{'$set': {"Status": 1, "date": datetime.datetime.utcnow()}})
g_queueLock.release()
else:
g_queueLock.release()
time.sleep(1)
print_to_log( "Exiting " + self.name )
def main():
global g_threads
global g_workQueue
global g_db
global g_workingEntry
global g_queueLock
if len(sys.argv) < 2:
print_to_log("================Crawler newly started==============")
print_to_log("you did not give any arguments.")
threadCnt = 10
else:
print_to_log("================Crawler newly started==============")
threadCnt = int(sys.argv[1])
getProxiesLstFromDB()
print_to_log("Threads Count: %d" % threadCnt)
# Create new threads
threadID = 1
while threadID <= threadCnt:
threadName = "Thread %d" % threadID
thread = myThread(threadID, threadName, g_workQueue)
thread.start()
g_threads.append(thread)
threadID += 1
is_first = True
while True:
# insert to status page links table
status_domain = g_db["status_domain"]
status_domain_records_cnt = status_domain.find({"Status": 0}).count()
if (is_first and status_domain_records_cnt == 0) or (is_first == False):
#read domains
domains_to_crawl = g_db["domains_to_crawl"]
domains_to_crawl_records = domains_to_crawl.find()
for domains_to_crawl_record in domains_to_crawl_records:
max_status_domain_record = status_domain.find_one(sort=[("DomainURLIDX", -1)])
max_DomainURLIDX = 0
if max_status_domain_record is not None:
max_DomainURLIDX = max_status_domain_record["DomainURLIDX"]
status_domain_record = {
"DomainURL": domains_to_crawl_record["DomainURL"],
"DomainURLIDX": max_DomainURLIDX+1,
"Status": 0, #0: not processed, 1: processed
"date": datetime.datetime.utcnow()}
try:
index = g_workingEntry.index(domains_to_crawl_record["DomainURL"])
except:
update_status = status_domain.update({"DomainURL": domains_to_crawl_record["DomainURL"].strip()}, status_domain_record, upsert=True)
print_to_log("domains_to_crawl table content: %s" % domains_to_crawl_record["DomainURL"] )
status_domain_records = status_domain.find({"Status": 0}).sort("DomainURLIDX", 1)
# Fill the queue
g_queueLock.acquire()
while not g_workQueue.empty():
data = g_workQueue.get()
for record in status_domain_records:
try:
index = g_workingEntry.index(record["DomainURL"])
except:
#not exist the url in working list
g_workQueue.put([record["DomainURL"], record["DomainURLIDX"]])
g_queueLock.release()
# Wait for queue to empty
while not g_workQueue.empty():
pass
is_first = False
time.sleep(1)
# Notify threads it's time to exit
exitFlag = 1
# Wait for all threads to complete
for t in g_threads:
t.join()
print_to_log( "Exiting Main Thread" )
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T00:21:00.193",
"Id": "67862",
"Score": "6",
"body": "Could you give some explanation/background to this? Why it was written maybe. What times you are seeing for the amount of data you're processing. etc. etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T12:34:20.560",
"Id": "71620",
"Score": "1",
"body": "I agree with @JamesKhoury. You really need to profile this code to show us what is slow. A simple way on Linux is to use 'time python module.py' so that you know how much time you spend waiting for the API to answer (eg. if the 'cpu' percentage is low). Then you can use Python's profiler to highlight the slow parts."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T03:55:28.627",
"Id": "84097",
"Score": "0",
"body": "Certainly need more detail to point anyone wanting to help in the right direction. That is alot of code there with very little explanation."
}
] |
[
{
"body": "<p>This is just one bit that jumped out at me:</p>\n\n<pre><code> page_text = page_html.decode(\"utf8\", \"ignore\")\n page_text = converter.handle(page_text)\n page_text = re.sub(\"[^a-zA-Z0-9_!]+[ ,.\\?!]\", \"\", page_text)\n</code></pre>\n\n<p>It seems you are converting as utf8, ignoring errors, and then forcing it into ascii with a regex. Why not just decode as ascii and ignore or replace the errors.</p>\n\n<p>There are certainly many other optimizations in a chunk of code that size. You really are doing alot in that chunk of code and there are so many ways to improve on it.</p>\n\n<p>Another observation is the page_html.split() to glean the words out of the document. You have used BeautifulSoup else where in the doc why not use that to get the words. Preferably all in one global parse pass.</p>\n\n<p>Further, you then turn around and submit those words each to an API. It doesn't look like there is any thought that the same word might return the same result each time and as such the results could be stored in some other way so as to avoid needing to request them for each word on each page, which surely will lead to many many redundant queries against the classification. </p>\n\n<p>There is really too much to cover in a single response here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-23T03:54:45.090",
"Id": "47946",
"ParentId": "40296",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T20:41:48.720",
"Id": "40296",
"Score": "2",
"Tags": [
"python",
"performance",
"http"
],
"Title": "How to speed up Python web crawler?"
}
|
40296
|
<p>Here is a method that takes two lists (<code>l1</code> and <code>l2</code>) and pairs up elements that "match". As you can see at the end of the code block these lists consist of matching elements but in different indexes. The method <code>pairUp</code> outputs matching elements paired up, and discards those without a pair.</p>
<p>I spent way too much time writing this method, and it feels clumsy and complex, not scala idiomatic.</p>
<p>How could I have done this simpler? and could I make it faster?</p>
<pre><code>case class A(serial:Int) {
def matches(b:B):Boolean = this.serial == b.serial
}
case class B(serial:Int)
import scala.annotation.tailrec
@tailrec def pairUp(
list1:List[A],
list2:List[B],
i:Int=0,
pairs:List[(A, B)]=List.empty[(A,B)]
):List[(A,B)] = {
if (list1.isEmpty || list2.isEmpty) return pairs
else {
if (i == list2.length) // this list1 element has no match
return pairUp(
list1.tail, // so discard
list2,
0, // reset counter
pairs)
else {
if (list1.head matches list2.head) // these elements match
return pairUp(
list1.tail,
list2.tail,
0,
pairs :+ ((list1.head, list2.head)))
else
return pairUp(
list1,
list2.tail :+ list2.head, // list2 element to back
i + 1,
pairs)
}
}
}
val l1 = List(0, 1, 2, 3, 4, 5).map(A(_))
val l2 = List(1, 3, 0, 2, 4).map(B(_))
val pairs = pairUp(l1, l2)
// List((A(0),B(0)), (A(1),B(1)), (A(2),B(2)), (A(3),B(3)), (A(4),B(4)))
println(pairs)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T21:49:23.237",
"Id": "68174",
"Score": "1",
"body": "Simpler or faster, pick one. :)"
}
] |
[
{
"body": "<p>A version that's probably no faster but slightly less verbose. I'm sure there's a much better way but it's a start:</p>\n\n<pre><code>case class A(serial: Int) {\n def matches(b: B): Boolean = this.serial == b.serial\n}\ncase class B(serial: Int)\n\ndef pairUp2(list1: List[A], list2: List[B]): List[(A,B)] = {\n def pairInc(l1: List[A], l2: List[B], pairs: List[(A,B)]): List[(A,B)] = l1 match {\n case a :: rest => l2.indexWhere(b => a.matches(b)) match {\n case -1 => pairInc(rest, l2, pairs)\n case i => pairInc(rest, l2.patch(i, List.empty[B], 1), pairs :+ (a, l2(i)))\n }\n case Nil => pairs\n }\n pairInc(list1, list2, List.empty)\n}\n\nval l1 = List(0, 1, 2, 3, 4, 5).map(A)\nval l2 = List(1, 3, 0, 2, 4).map(B)\n\nval pairs = pairUp2(l1, l2, matchFn)\n// List((A(0),B(0)), (A(1),B(1)), (A(2),B(2)), (A(3),B(3)), (A(4),B(4)))\nprintln(pairs)\n</code></pre>\n\n<p>This assumes that duplicate values in one list but not the other will only pair once. Otherwise you could use foldLeft, like so:</p>\n\n<pre><code>def pairUp3(list1: List[A], list2: List[B]): List[(A,B)] = {\n list1.foldLeft(List.empty[(A,B)]) { case (p, a) =>\n list2.find(b => a.matches(b)) match {\n case Some(b) => p :+ (a, b)\n case None => p\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T21:45:52.670",
"Id": "40299",
"ParentId": "40297",
"Score": "2"
}
},
{
"body": "<p>I am not an expert at scala, but this works for me</p>\n\n<pre><code>def pairUp2( list1: List[A], list2: List[B]): List[(A, B)] = {\n (for{\n a <- list1\n b <- list2\n if a.serial == b.serial\n } yield (a,b))\n }\n\n val pairs = pairUp2(l1, l2)\n pairs: List[(A, B)] = List((A(0),B(0)), (A(1),B(1)), (A(2),B(2)), (A(3),B(3)), (A(4),B(4)))\n</code></pre>\n\n<p>The for comprehension, takes each element of list1 and an element of list2 and yields a tuple only if the serial values match.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T08:37:28.693",
"Id": "67915",
"Score": "0",
"body": "Simplicity of this is refreshing. However, I'm trying to wrap my head around how to tell which method provides more speed and/or lower footprint."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T22:40:33.817",
"Id": "68193",
"Score": "0",
"body": "@DominykasMostauskis This solution is O(nm), where n and m are the respective sizes of list1 and list2."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T21:58:40.410",
"Id": "40300",
"ParentId": "40297",
"Score": "12"
}
},
{
"body": "<p>Here's a solution that is fairly compact and fast for large lists, but returns the two disordered:</p>\n\n<pre><code>def pairUp(list1: List[A], list2: List[B]): List[(A, B)] = {\n val g1 = list1.groupBy(_.serial).toList\n val g2 = list2.groupBy(_.serial)\n g1.flatMap{ case (k,as) => g2.get(k).toList.flatMap(as zip _) }\n}\n</code></pre>\n\n<p>If you want to keep them ordered, then it's a bit more bookkeeping:</p>\n\n<pre><code>def pairUp2(list1: List[A], list2: List[B]): List[(A, B)] = {\n val g1 = list1.zipWithIndex.groupBy(_._1.serial).toList\n val g2 = list2.groupBy(_.serial)\n val temp = g1.flatMap{ case (k,as) => \n g2.get(k).toList.flatMap(as zip _)\n }\n temp.sortBy(_._1._2).map{ case ((a,_), b) => (a,b) }\n}\n</code></pre>\n\n<p>Note that the direct <code>O(n^2)</code> search will be faster if <code>n</code> is small.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T03:14:18.283",
"Id": "40325",
"ParentId": "40297",
"Score": "3"
}
},
{
"body": "<p>If you first sort the lists, matching only takes a single traversal, making the solution O(n log(n)) (which is the time complexity of the sorts). I've also generalized over the lists' element types, only requiring projection functions <code>proj*</code> that can convert <code>A</code> and <code>B</code> into some common type <code>C</code> that can then be ordered (for sorting) and compared with <code>==</code>.</p>\n\n<pre><code>import scala.annotation.tailrec\n\ndef zipMatching[A, B, C](a: List[A], b: List[B], projA: A => C, projB: B => C)\n (implicit ord: Ordering[C]): List[(A, B)] = {\n import ord._ // Get access to `>`\n\n @tailrec\n def zipSortedMatching(\n aSorted: List[A], bSorted: List[B], accum: List[(A, B)]\n ): List[(A, B)] = {\n (aSorted, bSorted) match {\n case (aHead +: aRest, bHead +: bRest) =>\n val compA = projA(aHead)\n val compB = projB(bHead)\n\n if (compA == compB)\n zipSortedMatching(aRest, bRest, accum :+ (aHead, bHead))\n else if (compA > compB)\n zipSortedMatching(aSorted, bRest, accum)\n else\n zipSortedMatching(aRest, bSorted, accum)\n case _ =>\n accum\n }\n }\n\n zipSortedMatching(a.sortBy(projA), b.sortBy(projB), Nil)\n}\n\n\ncase class AA(serial: Int)\ncase class BB(serial: Int)\n\nval l1 = List(0, 1, 2, 3, 4, 5).map(AA(_))\nval l2 = List(1, 3, 0, 2, 4).map(BB(_))\n\ndef projAA(a: AA) = a.serial\ndef projBB(b: BB) = b.serial\n\nval pairs = zipMatching(l1, l2, projAA, projBB)\n// pairs: List[(AA, BB)] = List((AA(0),BB(0)), (AA(1),BB(1)), (AA(2),BB(2)), (AA(3),BB(3)), (AA(4),BB(4)))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-11T19:31:40.227",
"Id": "172746",
"ParentId": "40297",
"Score": "2"
}
},
{
"body": "<p>A small comment: it's awkward that <code>matches</code> is a member function of <code>A</code> and not <code>B</code>. It would be cleaner to have <code>matches</code> as an individual function. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-13T09:56:31.317",
"Id": "327724",
"Score": "0",
"body": "This may be a valuable comment, but it should be posted as one. I.e. this doesn't qualify as an answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-13T16:45:14.807",
"Id": "327774",
"Score": "0",
"body": "@Dominykas A code review is basically just a list of comments. My list has only one item."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-14T16:52:31.677",
"Id": "328058",
"Score": "0",
"body": "Fair enough, I retract my critique. However, SE doesn't let me retract my downvote, unless the answer is edited."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-12T12:43:41.110",
"Id": "172781",
"ParentId": "40297",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "40300",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T20:52:59.633",
"Id": "40297",
"Score": "10",
"Tags": [
"scala",
"recursion"
],
"Title": "Pair matching elements from two lists"
}
|
40297
|
<p>When the user visits the web page and hovers over an album artwork, the title of the piece and the artist name appears. It leaves when the mouse leaves.
I have achieved this with the following code:
HTML:</p>
<pre><code> <img id="pic1" src=" ">
<div class="info1">
<div class="name">artist</div>
<div class="songname">song title</div>
</div>
<img id="pic2" src=" ">
<div class="info2">
<div class="name">artist</div>
<div class="songname">song2</div>
</div>
</code></pre>
<p>JQuery</p>
<pre><code> $(document).ready(function () {
$("img#pic1").hover(
function () {
$("div.info1").animate({
'opacity': 1
});
},
function () {
$("div.info1").animate({
'opacity': 0
});
});
});
$(document).ready(function () {
$("img#pic2").hover(
function () {
$("div.info2").animate({
'opacity': 1
});
},
function () {
$("div.info2").animate({
'opacity': 0
});
});
});
</code></pre>
<p>The problem is with the javascript; I have to manually add new parts when I add a new image and it takes up a lot of space. Is there a way to condense the code?</p>
<p>CSS:
.info1, .info2 {
opacity:0;
}</p>
<p><a href="http://jsfiddle.net/burntember/22grA/">http://jsfiddle.net/burntember/22grA/</a></p>
|
[] |
[
{
"body": "<p>In your <code>hover</code> method you want to select the next two divs after the img. Assuming that the divs are located (in DOM) immediately after the img, then you can select them using the jQuery <a href=\"http://api.jquery.com/next/\">.next()</a> method, instead of selecting them by name.</p>\n\n<p>ALso instead of selecting each img by id, you could give them all the same class, and then use a single jQuery selector to select every img with that class.</p>\n\n<p>Untested and probably slightly buggy example code:</p>\n\n<pre><code><img id=\"pic1\" class=\"album\" src=\" \">\n<div>\n <div class=\"name\">artist</div>\n <div class=\"songname\">song title</div>\n</div>\n<img id=\"pic2\" class=\"album\" src=\" \">\n<div>\n <div class=\"name\">artist</div>\n <div class=\"songname\">song2</div>\n</div>\n\n$(document).ready(function () {\n\n $(\"img.album\").each().hover(\n\n $div = $(this).next(); // find the next element after this img\n\n function () {\n $div.animate({\n 'opacity': 1\n });\n },\n\n function () {\n $div.animate({\n 'opacity': 0\n });\n });\n });\n</code></pre>\n\n<p>If the div element is not immediately after the img (so you can't use the .next method), you can relate each div to its img by defining <a href=\"http://ejohn.org/blog/html-5-data-attributes/\">a new attribute which begins with <code>data-</code></a>, for example <code>data-img-id</code>:</p>\n\n<pre><code><img id=\"pic1\" class=\"album\" src=\" \">\n<img id=\"pic2\" class=\"album\" src=\" \">\n\n<div data-img-id=\"pic1\">\n <div class=\"name\">artist</div>\n <div class=\"songname\">song title</div>\n</div>\n\n<div data-img-id=\"pic2\">\n <div class=\"name\">artist</div>\n <div class=\"songname\">song2</div>\n</div>\n</code></pre>\n\n<p>Then, in your general-purpose hover method, you can get the id of the this img tag, and use that id value to select the corresponding div using its data-img-id element.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T22:30:17.560",
"Id": "40306",
"ParentId": "40301",
"Score": "5"
}
},
{
"body": "<p>My approach will be like this:</p>\n\n<p>html:</p>\n\n<pre><code><div class=\"gallery\">\n <img src=\" \" />\n <div class=\"info\">\n <div class=\"name\">artist-1</div>\n <div class=\"songname\">song title-1</div>\n </div>\n</div>\n<div class=\"gallery\">\n <img src=\" \" />\n <div class=\"info\">\n <div class=\"name\">artist-2</div>\n <div class=\"songname\">song title-2</div>\n </div>\n</div>\n</code></pre>\n\n<p>js:</p>\n\n<pre><code>$(document).ready(function () {\n $(\".gallery\").each(function () {\n var $gallery = $(this);\n var $info = $gallery.find(\".info\");\n\n $gallery.find(\"img\").hover(function () {\n $info.animate({\n 'opacity': 1\n });\n }, function () {\n $info.animate({\n 'opacity': 0\n });\n });\n });\n\n});\n</code></pre>\n\n<ol>\n<li>make a component(not a loose tag) in HTML</li>\n<li>jQuery defined the behave of component (everything belongs to the component works only under this component).</li>\n</ol>\n\n<p><a href=\"http://jsfiddle.net/22grA/6/\" rel=\"nofollow\">jsfiddle:normal version</a></p>\n\n<hr>\n\n<p>there are plugin version of this code, which could be more genetic:</p>\n\n<pre><code> (function ($) {\n $.fn.gallery = function () {\n return this.each(function () {\n var $gallery = $(this);\n var $info = $gallery.find(\".info\");\n\n $gallery.find(\"img\").hover(function () {\n $info.animate({\n 'opacity': 1\n });\n }, function () {\n $info.animate({\n 'opacity': 0\n });\n });\n });\n\n }\n\n})(jQuery)\n</code></pre>\n\n<p>use this plugin like:</p>\n\n<pre><code>$(document).ready(function () {\n $(\".gallery\").gallery();\n});\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/22grA/8/\" rel=\"nofollow\">jsfiddle: plugin version</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T02:36:11.083",
"Id": "40419",
"ParentId": "40301",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T22:00:07.010",
"Id": "40301",
"Score": "7",
"Tags": [
"javascript",
"jquery"
],
"Title": "Can this code be cleaned? Multiple objects triggering different hover events"
}
|
40301
|
<p>I am new to Java and wrote one small program. It works fine, but it looks like it doesn't meet OOP concepts. Could someone look and give me advice so that I can fine tune?</p>
<pre><code>public class App {
public static void main(String[] arg) {
String str = new String(
"]d010036195815011121123456789]d17YYMMDD1012345678901");
String matchItemAI = new String("01"); //GTIN-14
String matchSNoAI = new String("21"); //Serial Number
String matchExpDtAI = new String("]d17");// Expiry Date
String matchLotNoAI = new String("10"); //Lot Number
//Company Prefix
String matchCompPrefixUS = new String("03"); //US Company Prefix
String matchCompPrefixCork = new String("03"); //US Company Cork
String matchCompPrefixSKorea = new String("03"); //US Company South Korea
String value = str;
String value1 = new String();
String value2 = new String();
String value3 = new String();
char ch;
int pos;
// 1. Need to print ]d0100361958150111 like that 61958-1501-1
// 2. Need to print 21123456789 like that 123456789
// 3. Need to print ]d17YYMMDD like that YYMMDD
// 4. Need to print 1012345678901 like that 12345678901
// GS1 Start with this String....It's a GS1 2d Bar Code, Confirmed Then
// Process the record
if (str.startsWith("]d")) {
System.out.println("GS1 2D Input String :" + str);
ch = str.charAt(2);
switch (ch) {
case '0':
System.out
.println("Calculating Unit of Sale (0) Packaging Indicator digits for GTIN 14's : "
+ str.charAt(2));
pos = str.indexOf(matchItemAI);
System.out.println("GS1 pos:" + value.substring(pos)+" POS Value " +pos);
value = value.substring(pos + 5, value.length());
value1 = value.substring(0, 5);
value2 = value.substring(value1.length(), value1.length() + 4);
value3 = value.substring(value1.length() + value2.length(),
value1.length() + value2.length() + 1);
value3 = value1 + "-" + value2 + "-" + value3;
value = value.trim();
System.out.println("Found string Item : " + value3);
// /GET Serial Number
pos = str.indexOf(matchSNoAI); // AI 21
// System.out.println("Found string SNo : " + pos);
value = str.substring(pos + 2, str.lastIndexOf(matchExpDtAI)); //pos + 2 + 9);
value = value.trim();
System.out.println("Found string SNo : " + value);
pos = str.lastIndexOf(matchExpDtAI);
// System.out.println("Found string Expiry Date " + pos);
value = str.substring(pos + 4, pos + 4 + 6);
value = value.trim();
System.out.println("Found string Expiry Date : " + value);
pos = str.lastIndexOf(matchLotNoAI);
// System.out.println("Found string Lot Number " + pos);
value = str.substring(pos + 2, pos + 2 + 11);
value = value.trim();
System.out.println("Found string Lot Number : " + value);
break;
case '3':
System.out
.println("Calculating Bundle/Multipack 3 Packaging Indicator digits for GTIN 14's : "
+ str.charAt(2));
break;
case '5':
System.out
.println("Calculating Shipper 5 Packaging Indicator digits for GTIN 14's : "
+ str.charAt(2));
break;
default:
System.out
.println("Error - invalid selection entered! for Multipacking ");
break;
}
}
}
}
</code></pre>
<hr>
<p>Here I made change as per your suggestion, can you please review and let me know any other suggestion ?</p>
<pre><code>public class App {
public static void main(String[] arg) {
String str = new String(
"]d010036195815011121123456789]d17YYMMDD1012345678901");
String matchItemAI = "01"; //GTIN-14
String matchSNoAI = "21"; //Serial Number
String matchExpDtAI = "]d17";// ExpiryDate
String matchLotNoAI = "10"; //Lot Number
String WitoutFNC1 = str;
String NDCCode = "";
String itemRef = "";
String itemNo = "";
int pos;
// GS1 Start with this String....It's a GS1 2d Bar Code, Confirmed
if (str.startsWith("]d")) {
System.out.println("GS1 2D Input String :" + str);
switch (str.charAt(2)) {
case '0':
pos = str.indexOf(matchItemAI);
System.out.println("GS1 pos:" + WitoutFNC1.substring(pos)+" POS Value " +pos);
WitoutFNC1 = WitoutFNC1.substring(pos+5, WitoutFNC1.length());
NDCCode = WitoutFNC1.substring(0, 5);
itemRef = WitoutFNC1.substring(NDCCode.length(), NDCCode.length() + 4);
itemNo = WitoutFNC1.substring(NDCCode.length() + itemRef.length(),NDCCode.length() + itemRef.length() + 1);
itemNo = String.format("%s-%s-%s",NDCCode, itemRef ,itemNo);
WitoutFNC1 = WitoutFNC1.trim();
System.out.println("Found string Item : " + itemNo);
// /GET Serial Number
pos = str.indexOf(matchSNoAI); // AI 21
// System.out.println("Found string SNo : " + pos);
WitoutFNC1 = str.substring(pos + 2, str.lastIndexOf(matchExpDtAI)); //pos + 2 + 9);
WitoutFNC1 = WitoutFNC1.trim();
System.out.println("Found string SNo : " + WitoutFNC1);
pos = str.lastIndexOf(matchExpDtAI);
// System.out.println("Found string Expiry Date " + pos);
WitoutFNC1 = str.substring(pos + 4, pos + 4 + 6);
WitoutFNC1 = WitoutFNC1.trim();
System.out.println("Found string Expiry Date : " + WitoutFNC1);
pos = str.lastIndexOf(matchLotNoAI);
// System.out.println("Found string Lot Number " + pos);
WitoutFNC1 = str.substring(pos + 2, pos + 2 + 11);
WitoutFNC1 = WitoutFNC1.trim();
System.out.println("Found string Lot Number : " + WitoutFNC1);
break;
case '3':
System.out
.println("Calculating Bundle/Multipack 3 Packaging Indicator digits for GTIN 14's : "
+ str.charAt(2));
break;
case '5':
System.out
.println("Calculating Shipper 5 Packaging Indicator digits for GTIN 14's : "
+ str.charAt(2));
break;
default:
System.out
.println("Error - invalid selection entered! for Multipacking ");
break;
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T22:20:47.200",
"Id": "67846",
"Score": "0",
"body": "\"but it's not like it should be\" - does this mean that it does not work as intended?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T22:25:10.167",
"Id": "67847",
"Score": "1",
"body": "it' working as it is but looks like it's not meeting OOP concept"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T22:32:20.450",
"Id": "67848",
"Score": "0",
"body": "I see. Would you mind re-wording that phrase in your question? It could confuse some people to believe that your code does not work as intended, and therefore is off-topic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T22:37:06.697",
"Id": "67850",
"Score": "0",
"body": "thanks syb0rg for advice, i made change as you suggested, i am new in this community also."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T00:23:44.250",
"Id": "67863",
"Score": "3",
"body": "Please don't edit the original code, because that would invalidate the existing answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T00:33:06.693",
"Id": "67864",
"Score": "0",
"body": "sorry about that, where i should edit, can you please let me know, I am new to this community"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T01:23:11.513",
"Id": "67865",
"Score": "1",
"body": "@user3246453 I edited your question to add your new code **after** (not instead of) the original code. Or, instead of adding to an existing question, it's also possible to ask a new question: see [How to deal with follow-up questions?](http://meta.codereview.stackexchange.com/a/1066/34757)"
}
] |
[
{
"body": "<ul>\n<li><p>You consistently do <code>String foo = new String(\"some string\")</code>. This is useless, as <code>\"some string\"</code> already is a string. Simplify your code to <code>String foo = \"...\"</code>.</p></li>\n<li><p>You declare some variables far before you use them. Try to declare your variables as close to their point of use as possible, e.g. instead of</p>\n\n<pre><code>char ch;\n...\nch = str.charAt(2);\n</code></pre>\n\n<p>you could just do <code>char ch = str.charAt(2)</code>. The same holds true for <code>pos</code>, <code>value</code>, <code>value1</code>, <code>value2</code>, <code>value3</code>.</p></li>\n<li><p>Actually, you don't even need the <code>ch</code> variable as you could do <code>switch (str.charAt(2)) { ... }</code> directly.</p></li>\n<li><p>Some of your variables have very bad named: <code>value1</code> does not communicate any <em>intent</em> or meaning. Other variables use unecessary abbreviations.</p></li>\n<li><p>You have certain magic numbers that could be replaced. E.g. in <code>str.substring(pos + 4, pos + 4 + 6)</code>, the <code>4</code> is actually <code>matchExpDtAI.length()</code>. I have no idea where the <code>6</code> comes from.</p></li>\n<li><p>This code is pure obfuscation:</p>\n\n<pre><code>value = value.substring(pos + 5, value.length());\n\nvalue1 = value.substring(0, 5);\nvalue2 = value.substring(value1.length(), value1.length() + 4);\nvalue3 = value.substring(value1.length() + value2.length(),\n value1.length() + value2.length() + 1);\nvalue3 = value1 + \"-\" + value2 + \"-\" + value3;\nvalue = value.trim();\nSystem.out.println(\"Found string Item : \" + value3);\n</code></pre>\n\n<p>Note that you don't use the <code>value1</code>, <code>value2</code>, and <code>value3</code> variables outside of this snippet, so they are unecessary. If we count the lengths of those substrings, we can see that this code should be equivalent:</p>\n\n<pre><code>value = value.substring(pos + 5, value.length());\n\nSystem.out.println(\"Found string Item : \" +\n value.substring(0, 5 ) + \"-\" +\n value.substring(5, 5 + 4 ) + \"-\" +\n value.substring(5 + 4, 5 + 4 + 1));\n\nvalue = value.trim();\n</code></pre>\n\n<p>Those constant offsets can be folded, which makes it easier to see that these substrings are actually consecutive:</p>\n\n<pre><code>value = value.substring(pos + 5), value.length());\n\nSystem.out.println(\"Found string Item : \" +\n value.substring(0, 5) + \"-\" +\n value.substring(5, 9) + \"-\" +\n value.substring(9, 10));\n\nvalue = value.trim();\n</code></pre></li>\n<li><p>Actually, let's use <code>String.format</code> for that:</p>\n\n<pre><code>value = value.substring(pos + 5, value.length());\n\nSystem.out.println(String.format(\"Found string Item: %s-%s-%s\",\n value.substring(0, 5),\n value.substring(5, 9),\n value.substring(9, 10)\n));\n\nvalue = value.trim();\n</code></pre></li>\n</ul>\n\n<p>Before thinking about whether an object-oriented approach would be <em>sensible</em> (it isn't), you have other parts of your code to clean up first.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T23:00:07.147",
"Id": "67853",
"Score": "2",
"body": "Amon, Thanks for reviwing the code and your valuable suggestion and feedback, I will make change as you suggested, it's really helpful for me, please keep doing good work"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T22:55:15.507",
"Id": "40308",
"ParentId": "40304",
"Score": "11"
}
},
{
"body": "<ol>\n<li>When you look at the color highlighting of your code, you can see that <code>WithoutFNC1</code> is colored blue like other Java types. This also suggests that in the Java world, it is not recommended for non-static variable names to start with an upper case.</li>\n<li><p>These two blocks are very similar and you can already create a static method for it, for starters:</p>\n\n<pre><code> pos = str.lastIndexOf(matchExpDtAI);\n // System.out.println(\"Found string Expiry Date \" + pos);\n WitoutFNC1 = str.substring(pos + 4, pos + 4 + 6);\n WitoutFNC1 = WitoutFNC1.trim();\n System.out.println(\"Found string Expiry Date : \" + WitoutFNC1);\n\n pos = str.lastIndexOf(matchLotNoAI);\n // System.out.println(\"Found string Lot Number \" + pos);\n WitoutFNC1 = str.substring(pos + 2, pos + 2 + 11);\n WitoutFNC1 = WitoutFNC1.trim();\n System.out.println(\"Found string Lot Number : \" + WitoutFNC1);\n</code></pre></li>\n<li>Also, when you say a substring is \"found\", do you really mean that the string is not empty? Or perhaps you can apply other validation to ensure that the desired substring is really found? You can create a static method to test your \"found\" substrings. Otherwise, I suppose deriving an empty substring and printing <code>Found string Item :</code> is not going to be helpful...</li>\n<li>Just a simple note on most methods for <code>String</code>: If you find yourself repeating variable assignment, you can string one method after another, e.g. <code>\" this is some text \".substring(5).trim()</code>, because they simply return copies of the <code>String</code>.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T03:51:20.940",
"Id": "40327",
"ParentId": "40304",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "40327",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T22:17:33.043",
"Id": "40304",
"Score": "8",
"Tags": [
"java",
"beginner",
"strings"
],
"Title": "Matching program in Java"
}
|
40304
|
<p>I've got a conditional that sets a cookie based on whether a selector exists. There are other places in the code where I do something similar if the selector exists. If the selector exists I either add "nfl" or "nfl-" (notice the dash) to various attributes on the page. I'm trying to remove as much code as I can as there are about five other places I have similar code where I'm adding other attributes. I also feel like there's a better way to approach this without having to write this a ton of times:</p>
<pre><code>if($(".userLocation").length > 0){
</code></pre>
<p>I'm banging my head on how to condense this but can't figure this out. Please include code samples; I learn best that way.</p>
<pre><code>if($(".userLocation").length > 0){
var user_cookie = {
name: 'nfl-user-profile',
options: {
path: '/',
expires: 365
}
};
} else {
var user_cookie = {
name: 'user-profile',
options: {
path: '/',
expires: 365
}
};
}
if($(".userLocation").length > 0){
$('header').attr("href","#nfl-city");
$('header').attr("href","#nfl-state");
} else {
$('header').attr("href","#city");
$('header').attr("href","#state");
}
if($(".userLocation").length > 0){
$('footer').attr("title","#nflcity");
$('footer').attr("title","#nflstate");
} else {
$('footer').attr("title","#city");
$('footer').attr("title","#state");
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T23:44:20.193",
"Id": "67858",
"Score": "0",
"body": "<header> is an html5 element. Sorry the second conditional was suppose to be <footer>"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T23:47:48.503",
"Id": "67861",
"Score": "1",
"body": "When you call `attr(name,value)` twice in a row like that on the same selector, doesn't the second value overwrite the first value?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T02:47:28.223",
"Id": "67877",
"Score": "0",
"body": "I agree with @ChrisW. I also think that setting the `title` attribute to a user-unfriendly string makes little sense. (Wouldn't the browser treat it as a tooltip?) Could you explain the meaning behind `.userLocation` and `nfl-`, and what the motivation for this code is?"
}
] |
[
{
"body": "<p>Increase DRYness. Something like this:</p>\n\n<pre><code>var makeAnchor = function(prefix, suffix) {\n return \"#\" + prefix + suffix;\n}\n\nvar nflPrefix = \"nfl-\";\nif ($(\".userLocation\").length > 0) { nflPrefix = \"nfl\"; }\n$('header').attr(\"href\", makeAnchor(nflPrefix, \"city\");\n</code></pre>\n\n<p>The ternary operator may be suitable too: <code>var nflPrefix = \"nfl\" + ($(\".userLocation\").length > 0 ? \"-\" : \"\";</code> though that makes it a bit less legible.</p>\n\n<p>Also: do you really want to check if anything in the entire DOM has the userLocation class? Perhaps you want something closer to <code>$(yourJqueryLocator).hasClass(\"userLocation\")</code>? This is also a bit more self-documenting.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T23:37:01.930",
"Id": "40310",
"ParentId": "40305",
"Score": "1"
}
},
{
"body": "<p>Only thing I can think of is that wrap the condition:</p>\n\n<pre><code>var hasUserLocation = function (hasFunc, noFunc) {\n if ($(\".userLocation\").size() > 0) {\n hasFunc();\n } else {\n noFunc();\n }\n}\n</code></pre>\n\n<p>then you can call like this:</p>\n\n<pre><code>hasUserLocation(function () {\n alert(\"has\");\n}, function () {\n alert(\"no\")\n})\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/DWgpq/2/\" rel=\"nofollow\">jsfiddle</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T00:10:20.320",
"Id": "40313",
"ParentId": "40305",
"Score": "4"
}
},
{
"body": "<p>You can create a 2-dimensional array of data, which contains the selector plus attribute-name plus the two attribute-values:</p>\n\n<pre><code>var elements = [\n ['header', 'href', '#nfl-city', '#city'],\n ['footer', 'title', '#nflcity', '#city'],\n ... etc ...\n ];\n</code></pre>\n\n<p>Then you can loop through this array, setting the attribute for each element to either the first or second value.</p>\n\n<hr>\n\n<p>Furthermore if you can change the code elsewhere to expect a regular prefix (for example, <code>#nfl-</code> not <code>#nfl</code>) then you only need three elements in each array (one attribute value, e.g. <code>city</code>) and can loop through the array setting the attribute to the value plus the value's appropriate prefix (<code>#</code> or <code>#nfl-</code>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T02:31:12.793",
"Id": "40321",
"ParentId": "40305",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "40313",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T22:18:10.780",
"Id": "40305",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "Setting a cookie based on a selector"
}
|
40305
|
<p>I am new to studying data structures although I have been programming in Java/Android since October. I feel it's time to advance, so I am starting data structures / algorithms this month. Since linked lists are a big topic in interviews and I knew nothing about them (I spent the past 3 days learning about it), hopefully my code is mostly correct, but please let me know if I am missing anything or not catching something, or if there's any way to improve it.</p>
<pre><code>public class MyLinkedList<T> {
private LinkNode<T> head;
private int size;
public MyLinkedList() {
this.head = null;
this.size = 0;
}
public void display() {
if (head == null) {
System.out.println("empty list");
} else {
LinkNode<T> current = head;
while (current != null) {
System.out.println(current.toString());
current = current.getNext();
}
}
}
public void addEnd(T data) {
if (head == null) {
head = new LinkNode<T>(data, head);
} else {
LinkNode<T> current = head;
while (current.getNext() != null) {
current = current.getNext();
}
LinkNode<T> newNode = new LinkNode<T>(data, null);
current.setNext(newNode);
size++;
}
}
public void addFront(T data) {
head = new LinkNode<T>(data, head);
size++;
}
public void removeEnd() {
if (head == null) {
System.out.println("empty list");
} else {
LinkNode<T> current = head;
LinkNode<T> previous = head;
while (current.getNext() != null) {
previous = current;
current = current.getNext();
}
previous.setNext(null);
size--;
}
}
public void removeFront() {
if (head == null) {
System.out.println("empty list");
} else {
head = head.getNext();
}
size--;
}
public void removeNode(T data) {
if (head == null) {
System.out.println("empty list");
} else {
LinkNode<T> current = head;
LinkNode<T> previous = head;
while (current.getData() != data) {
previous = current;
current = current.getNext();
}
if (current == head) {
head = head.getNext();
}
previous.setNext(current.getNext());
}
size--;
}
public LinkNode<T> getNode(T data) {
LinkNode<T> current = head;
if (head == null) {
System.out.println("empty list");
return null;
} else {
while (current.getData() != data) {
if (current.getNext() == null) {
System.out.println("not found");
return null;
}
}
}
return current;
}
private static class LinkNode<T> {
T data;
LinkNode<T> next;
private LinkNode(T data, LinkNode<T> next) {
this.data = data;
this.next = next;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public LinkNode<T> getNext() {
return next;
}
public void setNext(LinkNode<T> node) {
this.next = node;
}
public String toString() {
return ("\nData: " + data);
}
}
public static void main(String[] args) {
MyLinkedList<String> list = new MyLinkedList<String>();
list.addEnd("a");
list.addEnd("aaa");
list.addEnd("aaaaaa");
list.removeNode("aaa");
list.display();
}
}
</code></pre>
<p>My main concern is how differently every one writes these implementations.</p>
|
[] |
[
{
"body": "<p>This is a great first attempt with a consistent coding style and good variable names. Bravo!</p>\n\n<ul>\n<li><p>Consider implementing the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/List.html\" rel=\"nofollow\"><code>java.util.List</code></a> interface so you could use it with existing methods. You already have most of the methods and would just need to change some names. For example, <code>addEnd</code> becomes <code>append</code>, <code>getNode</code> becomes <code>indexOf</code> (with some changes), etc. It defines quite a few more methods entailing more work, but it would make for a great exercise.</p></li>\n<li><p>You can remove the constructor since it has no effect. Unlike C, Java initializes all local variables and fields to default values determined by their types, unless the declaration provides a value. References are initialized to <code>null</code>, numeric types to <code>0</code>, booleans to <code>false</code>, etc.</p></li>\n<li><p>Never expose private inner classes publicly. Instead of returning a <code>LinkNode</code>, <code>getNode</code> should return the index of the found node. If you want to allow clients to change the data held by a node, provide <code>set(int index, T data)</code> and optionally <code>replaceFirst(T data, T replacement)</code> to avoid seeking the node twice.</p></li>\n<li><p>Instead of passing <code>null</code> for <code>next</code> to the <code>LinkNode</code> constructor, create a second constructor that accepts just the <code>data</code> value. Optionally, the existing constructor may pass <code>data</code> to this new constructor so all fields are initialized it at most one place.</p>\n\n<pre><code>private LinkNode(T data) {\n this.data = data;\n}\n\nprivate LinkNode(T data, LinkNode next) {\n this(data);\n this.next = next;\n}\n</code></pre></li>\n</ul>\n\n<p>Finally, you're treating <code>LinkNode</code> as a pure data-holder a la C structs which gives the list class two responsibilities. While this centralizes the logic maintaining the structure in the list, it makes the full list responsible for managing both the list itself (the head) and each node's internal state. Classes that have a <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">single responsibility</a> are much easier to understand, write, and test.</p>\n\n<p>Moving the node-specific logic from the list to the node class would simplify many of the methods, increase DRY, and make each class responsible for one thing. I'll provide one example for <code>addEnd</code> to demonstrate the technique.</p>\n\n<pre><code>public void addEnd(T data) {\n if (head == null) {\n head = new LinkNode(data);\n } else {\n head.addEnd(data);\n }\n}\n\nprivate static class LinkNode<T> {\n ...\n void addEnd(T data) {\n if (next == null) {\n next = new LinkNode(data);\n } else {\n next.addEnd(data);\n }\n }\n}\n</code></pre>\n\n<p>One thing to note is that this turns many of the algorithms into recursive methods which requires more stack space (memory) since Java doesn't have tail recursion.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T04:13:18.497",
"Id": "67887",
"Score": "0",
"body": "Thanks for all the feedback and help. I am wondering about what would I have the MyLinkedList class do if I move all the node methods to the LinkedNode class. Does it just hold a pointer to head and print the list?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T04:44:07.497",
"Id": "67890",
"Score": "1",
"body": "@CatznDogz The list class would have one responsibility: manage the `head` reference. Anything that touches `data` or `next` would move to the node class. Note that this option may not be better for many reasons; the higher memory usage is one example. I would recommend rewriting it this way as an exercise only after you're happy with your list since your primary goal is learning about linked lists."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T09:16:53.583",
"Id": "67917",
"Score": "1",
"body": "I'd suggest using the AbstractSequentialList as a base class, you only need to implement size() and a ListIterator"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T18:51:10.647",
"Id": "67984",
"Score": "0",
"body": "@ratchetfreak If the point was to implement a linked list with minimal effort, I'd agree. But in this case the OP wants to learn how to implement one on their own."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T22:04:05.447",
"Id": "67999",
"Score": "0",
"body": "@DavidHarkness I would use `this(data, null)` in the LinkNode constructor rather than the other way around so all data assignation is in the same place."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T22:27:50.143",
"Id": "68008",
"Score": "0",
"body": "@njzk2 Yes, I usually prefer that as well. Lately, however, I have tried this way so that the two-value constructor can mark the `next` parameter with `@Nonnull`. This way FindBugs will point out when you may have made an error by passing `null` even though technically it's an allowed value. Named factory methods would help with that: `createTailNode(E data)` and `createLinkNode(E data, @Nonnull LinkNode next)`."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T03:58:52.023",
"Id": "40328",
"ParentId": "40311",
"Score": "3"
}
},
{
"body": "<p>Here are a few comments I would make:</p>\n\n<ul>\n<li>You can keep a permanent reference to the tail, which makes appending at the end <code>o(1)</code> operation rather than <code>o(n)</code></li>\n<li>You can make a double-link list, by keeping reference to next and previous links. Deletion of the last link becomes <code>o(1)</code> instead of <code>o(n)</code></li>\n<li>Your <code>removeNode</code> methods crashes if the node is not in the list</li>\n</ul>\n\n<p>Apart from that, I think David Harkness said it all.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T22:39:13.447",
"Id": "40406",
"ParentId": "40311",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "40328",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T23:38:34.000",
"Id": "40311",
"Score": "5",
"Tags": [
"java",
"linked-list"
],
"Title": "Singly linked list implementation"
}
|
40311
|
<p>My <code>Import</code> method takes some <code>data</code> and writes it to a stream. If the <code>CompressedStore</code> property is true, the contents of that stream should be compressed.</p>
<p>This code works, however I just don't like it. For one, I call <code>serializer.Serialize()</code> twice. I feel this code can be made more concise. Any ideas?</p>
<pre><code>public void Import(IProvisionSource source)
{
InitializeStore();
// Call source.Export and populate local data store
var data = source.Export();
var serializer = new XmlSerializer(data.GetType());
var file = CompressedStore ? "KPCData.gz" : "KPCData.xml";
var path = Path.Combine(DataDirectory, file);
using (var fileWriter = new FileStream(path, FileMode.Create))
{
if (CompressedStore)
{
using (var writer = new GZipStream(fileWriter, CompressionLevel.Optimal))
{
serializer.Serialize(writer, data);
}
}
else
{
serializer.Serialize(fileWriter, data);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>By default, <a href=\"http://msdn.microsoft.com/en-us/library/27ck2z1y\" rel=\"nofollow\"><code>GZipStream</code> owns the underlying stream, so it disposes it when it's disposed itself</a>. If you're okay with relying on that, then you could put the right <code>Stream</code> into a variable and then have just one <code>using</code> around it. Something like:</p>\n\n<pre><code>var writer = new FileStream(path, FileMode.Create);\n\nif (CompressedStore)\n writer = new GZipStream(writer, CompressionLevel.Optimal);\n\nusing (writer)\n{\n serializer.Serialize(writer, data);\n}\n</code></pre>\n\n<p>This avoids the duplication and so it's shorter, but it's also less obviously correct (<code>using</code> combined with <code>new</code> is a good pattern, and it's not used here), so I think your original code is actually the better option. If there was more repetition than just one method call, it could make sense to extract that into a separate method, but that's not the case here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T01:39:21.357",
"Id": "67868",
"Score": "0",
"body": "Ah! Yea, that was the issue I couldn't get around; I could rewrite it with various conditionals, but every time something wasn't getting disposed. If disposing of `GZipStream` will also dispose of its `FileStream`, then I'm probably good. I'll keep this solution in mind!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T01:37:29.320",
"Id": "40320",
"ParentId": "40316",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "40320",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T00:46:31.137",
"Id": "40316",
"Score": "4",
"Tags": [
"c#",
".net"
],
"Title": "Conditionally write to a compressed stream"
}
|
40316
|
<p>This is a Python script I made to create a HTML page listing the source files in the current directory. The script creates a syntax highlighted preview of the files and lists some basic attributes.</p>
<p>I would like to know if this is the best method to generate the HTML code? Is there a web development library that would be more efficient for this task? </p>
<p>What are some ways that I could improve my webpage design? </p>
<pre><code># -*- coding: utf-8 -*-
import pygments
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
from pygments.lexers import guess_lexer, get_lexer_for_filename
from os import listdir, mkdir
from os.path import isfile, join, getsize, getctime, isdir, dirname, abspath
from time import ctime
import glob
from math import ceil
# configuration
mypath = "."
maxlines = 30
items_per_page = 10.0
base_path = dirname(abspath(__file__))+"/"
files_to_ignore = ["pgp", "der", "crt", "asc", "key"]
if isdir("pastebin/") == False:
mkdir("pastebin/")
onlyfiles = [ f for f in glob.glob(mypath+"/*.*") if isfile(join(mypath,f)) ]
template = """
<!DOCTYPE html>
<style>
.main-page {
background-color:#C0C0C0;
}
.list-item {
width:90%;
margin-top:10px;
margin-bottom:10px;
margin-right:5%;
margin-left:5%;
background-color:white;
box-shadow: 5px 5px 5px #888888;
}
h3 {
margin-top:10px;
text-align:center;
}
.source {
margin-right:10px;
margin-left:10px;
margin-top:10px;
margin-bottom:10px;
overflow:hidden;
}
footer {
bottom: 0;
position: fixed;
text-align:center;
width: 100%;
margin-top:10px;
background-color:white;
}
</style>
<body class="main-page">
"""
valid_files = []
for name in onlyfiles:
if name.split(".")[1:] in files_to_ignore:
pass
else:
try:
get_lexer_for_filename(name)
valid_files.append(name)
except pygments.util.ClassNotFound:
pass
page_links = ""
for n in range(1, int(ceil(len(valid_files)/items_per_page))):
page_links+="""<a href="page%d.html"> %d </a>"""%(n, n)
count=0
page_count=1
output=template
for name in valid_files:
count+=1.0
name=name.replace("./", "")
code = "".join(open(name, "rb").readlines()[:maxlines])
lexer = get_lexer_for_filename(name)
formatter = HtmlFormatter(linenos=False, cssclass="source", encoding="utf-8")
result = highlight(code, lexer, formatter)
temp="""<div class="list-item">"""
temp+="<style> ccs-color-codes </style>"
temp+="""<h3><a href="file-path">file-name </a></h3><div class="info">"""
temp+=""" Created on: <b>date-created </b>"""
temp+="""Size: <b>file-size </b>"""
temp+="""</div><hr>result</div>"""
temp=temp.replace("ccs-color-codes", HtmlFormatter().get_style_defs('.source'))
temp=temp.replace("file-name", name)
temp=temp.replace("file-path", base_path+name)
temp=temp.replace("file-size", str(getsize(name)))
temp=temp.replace("date-created", ctime(getctime(name)))
temp=temp.replace("result", result)
output+=temp+"\n"
if int(count) == int(items_per_page):
count=0
output+="""<footer><span id="footer">%s</span></footer>"""%(page_links)
output+="</body>"
open("pastebin/page%d.html"%(page_count), "w").write(output)
page_count+=1
</code></pre>
|
[] |
[
{
"body": "<p>There are a <a href=\"https://wiki.python.org/moin/Templating\" rel=\"nofollow\">ton of good template rendering libraries out there</a>, but I'd leave it to you to figure out if they are better suited to your needs than hand rolled code. </p>\n\n<p>Assuming you still want to write this yourself, I'd look for ways to make the code more completely data driven and also to make it more readable. </p>\n\n<p>On the data driven side, you might want save your design as an html file. That way you can use whatever styling or graphic layout tools you want to produce the layout. You merely need to leave template placeholders where you want the data to go and apply the substitutions. <a href=\"http://www.djangobook.com/en/2.0/chapter04.html\" rel=\"nofollow\">Django's templating system</a> offers a great example of what you'd expect: vanilla html data with placeholders where the data's gonna go.</p>\n\n<p>Going data driven will reduce a ton of the code here (since so much of it is just string assembly). You can do some nice syntactic tricks to clean up things like writing html tags, for example</p>\n\n<pre><code> tag = lambda t, c : \"<%s>%s></%s>\" % (t,c,t)\n\n tag('footer','footer goes here')\n > <footer>footer goes here</footer>\n</code></pre>\n\n<p>And you you could also use a context manager for tag nesting (<a href=\"http://docs.python.org/2/library/contextlib.html\" rel=\"nofollow\">example here</a>) to keep things neat</p>\n\n<p>Lastly, use string.Template to allow for keyword or dictionary based replacement you can do things like </p>\n\n<pre><code>header = Template(\"<header><span font=$font>$text</span></header\")\nheader.subsitute(font='sans-serif',text='hello world')\n</code></pre>\n\n<p>that would make it easier to clean up the series of <code>temp = temp.replace...</code> lines. Python is a great language for this sort of thing - it should be easy to cut this down by half or more with built in tools.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T06:01:38.787",
"Id": "40332",
"ParentId": "40317",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T00:56:07.217",
"Id": "40317",
"Score": "2",
"Tags": [
"python",
"html"
],
"Title": "Create HTML listing of source code"
}
|
40317
|
<p>This function is for multiplying two matrices together. It's kind of messed up because the result is actually supposed to overwrite the object that called it, or since it's <code>static</code>, it's supposed to overwrite the <code>left</code> object. Is there any way to make it faster or more readable? </p>
<pre><code>public static Matrix multiply(Matrix left, Matrix right){
int leftRows = left.numRows;
int leftColumns = left.numCols;
int rightRows = right.numRows;
int rightColumns = right.numCols;
if (leftColumns != rightRows)
throw new IllegalArgumentException("Dimensions don't match");
Double[][] result = new Double[leftRows][rightColumns];
for (int i = 0; i < 2 && i < leftRows; i++) {//I found the && i <leftRows to be necessary for handling matrices of 1 row
for (int j = 0; j < 2 && j < rightColumns; j++) {//&& j <rightColumns necessary for matrices with 1 columns
result[i][j] = 0.00000;//ensures no null reference
}
}
for (int i = 0; i < leftRows; i++)
{
for (int j = 0; j < rightColumns; j++)
{
for (int k = 0; k < leftColumns; k++)
{
if(result[i][j] == null)
result[i][j] = 0.0;
result[i][j] += left.getValue(i, k) * right.getValue(k, j);
}
}
}
Matrix product = new Matrix(leftRows, rightColumns);
for(int i = 0; i < leftRows; i++)
{
for(int j = 0; j < rightColumns; j++)
Matrix.setValueAt(product, i, j, result[i][j]);
}
return product;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T03:47:47.460",
"Id": "67885",
"Score": "8",
"body": "Is this code doing what it is supposed to be? It doesn't sound like it is..... in which case you should take this to [so], not here on CodeReview. See the [help/on-topic] for guidance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T14:42:07.583",
"Id": "67952",
"Score": "0",
"body": "when you do get it working we would be happy to review the **working** code."
}
] |
[
{
"body": "<p>For improving readability, you could perhaps replace the for-loop variable names with more descriptive names, such as 'currentColumn' and 'currentRow.'</p>\n\n<p>For performance, you can replace 'x++' with '++x' in every loop. 'x++' actually creates a copy of x, increments x, and returns the copy. It is useful in some situations, but unnecessary in a for-loop.</p>\n\n<p>Now I'll admit that I don't work in Java, and Matrixes are a haze from school, but it seems like 'result' could just be set to a Matrix from the start, instead of a\ndouble[][]. You would cut down a significant portion of your time spent copying from 'result' to 'product' by just using a Matrix in the first place.</p>\n\n<p>I don't see the need for this:</p>\n\n<pre><code>for (int i = 0; i < 2 && i < leftRows; i++) {//I found the && i <leftRows to be necessary for handling matrices of 1 row\n for (int j = 0; j < 2 && j < rightColumns; j++) {//&& j <rightColumns necessary for matrices with 1 columns\n result[i][j] = 0.00000;//ensures no null reference\n }\n</code></pre>\n\n<p>Please explain where a null reference might arise without this code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T05:55:39.010",
"Id": "67892",
"Score": "0",
"body": "The compiler should be able to should be able to know that the result of `x++` is not used and optimize it. Even if it doesn't, I wouldn't make the change unless a profiler said it was a bottle neck. `result` is an array of `Double`, not the primitive `double`, so the array is initialized with `null`s. I agree that the values should be written directly to `product` instead of copying them from `result`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T06:02:48.600",
"Id": "67893",
"Score": "0",
"body": "changing the names of the vars won't help, since the vars are used as column and row indexes in different places. ++x and x++ makes no difference in performance in Java (that can be measured). The array needs to be set non-null because it is an array of `Double`, not `double`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T07:20:02.503",
"Id": "67899",
"Score": "0",
"body": "The doubles are initialised to null, but won't they all be overwritten? I didn't realise x++ was optimised out, I typically use ++x wherever possible as per [link](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Preincrement_and_Predecrement). Just a preference."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T07:20:44.257",
"Id": "67900",
"Score": "1",
"body": "Also, only one downvote on my first answer on Stack Exchange - I think that's not too bad."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T07:29:39.740",
"Id": "67903",
"Score": "0",
"body": "@rolfl Within each for-loop, would it not be more clear using 'currentRow' and 'currentCollumn' than 'i' and 'j'? Using the right index variable in each matrix is a lot easier with more descriptive names."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T10:20:37.037",
"Id": "67923",
"Score": "0",
"body": "@Andrew Just keep answering and you'll get plenty of up-votes soon enough :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T11:27:18.267",
"Id": "67930",
"Score": "1",
"body": "@Andrew In, for example, `cellValue += left.getValue(i, k) * right.getValue(k, j);` would you make the `k` the row, or the column?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T08:02:01.190",
"Id": "68049",
"Score": "0",
"body": "I see. My first instinct would be to set I and k to the values of the left matrix, but you're right - this would probably make it harder, not easier, to read. I'll go hide in my corner now."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T05:26:12.003",
"Id": "40331",
"ParentId": "40318",
"Score": "-1"
}
},
{
"body": "<p>My question would be: Why is it supposed to \"overwrite\" the left value? This seems dubious from a software engineering point of view. The product of two matrices is: A<sub>nm</sub> x B<sub>mp</sub> = C<sub>np</sub> hence you can only \"overwrite\" A with C (re-using the same Matrix object) if <code>m == p</code> or in other words if B is a quadratic matrix.</p>\n\n<p>For now let's clean up the existing code by getting rid of the intermediate array</p>\n\n<pre><code>public static Matrix multiply(Matrix left, Matrix right) {\n int leftRows = left.numRows;\n int leftColumns = left.numCols;\n int rightRows = right.numRows;\n int rightColumns = right.numCols;\n\n if (leftColumns != rightRows)\n throw new IllegalArgumentException(\"Dimensions don't match\");\n\n Matrix product = new Matrix(leftRows, rightColumns);\n for (int i = 0; i < leftRows; i++)\n {\n for (int j = 0; j < rightColumns; j++)\n {\n double cellValue = 0.0;\n for (int k = 0; k < leftColumns; k++)\n {\n cellValue += left.getValue(i, k) * right.getValue(k, j);\n }\n Matrix.setValueAt(product, i, j, cellValue);\n }\n }\n\n return product;\n }\n</code></pre>\n\n<p>You could copy the values back into <code>left</code> - provided <code>right</code> is quadratic and therefore <code>product</code> and <code>left</code> will have the same dimensions. Otherwise if the <code>Matrix</code> class offers a re-sizing option then you could re-size left afterwards and copy <code>product</code> into it. However that is extremely ugly and I would question that requirement.</p>\n\n<p>As a side note: It seems weird that <code>Matrix</code> provides a static method for setting a cell value of a <code>Matrix</code> object. I would have expected that to be an instance method as well like <code>getValue()</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T09:13:21.233",
"Id": "40341",
"ParentId": "40318",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T01:10:59.887",
"Id": "40318",
"Score": "-1",
"Tags": [
"java",
"mathematics",
"matrix"
],
"Title": "Matrix multiplication of arbitrary sizes"
}
|
40318
|
<p>I have created this piece of js purely for learning purposes and I was hoping you could code review to see any mistakes / improvements I can make.</p>
<p>Basically I have a tree structure and I will use the depth variable to work out what level of the menu I will display.</p>
<p>Here is the code example: <a href="http://jsfiddle.net/nqGbw/5/" rel="nofollow">http://jsfiddle.net/nqGbw/5/</a></p>
<p><strong>HTML</strong></p>
<pre><code>The Tree
<ul>
<li> <a href="?1">Root</a>
<ul>
<li> <a href="?2">Folder 1</a>
<ul>
<li><a href="?3">Folder 1.1</a>
</li>
<li><a href="?4">Folder 1.2</a>
</li>
</ul>
</li>
<li> <a href="?5">Folder 2</a>
<ul>
<li><a href="?6">Folder 2.1</a>
</li>
<li> <a href="?7">Folder 2.2</a>
<ul>
<li><a href="?8">Folder 2.2.1</a>
</li>
<li><a href="?8">Folder 2.2.2</a>
</li>
<li><a href="?9">Folder 2.2.3</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</code></pre>
<p><strong>JS</strong></p>
<pre><code>var calcDepth = function (root) {
var $parent = $(root).parents('ul');
var depth = 0;
while ($parent.length > 0) {
$parent = $parent.parents('ul');
depth += 1;
}
return depth;
};
var func = function (rootUL, maxDepth) {
var selectedUL = rootUL;
$(selectedUL.children('li')).each(function () {
var Me = $(this);
if (calcDepth(Me.parent()) == maxDepth) {
Me.hide();
}
if (Me.children('ul').length > 0) {
var selectedUL = Me.children('ul');
func(selectedUL, maxDepth);
}
});
};
var depth = 2; //Change this to set the depth of the menu
var selectedUL = $("ul");
func(selectedUL, depth);
</code></pre>
|
[] |
[
{
"body": "<p>It would be much easier just to let the CSS selector engine select the elements to hide:</p>\n\n<pre><code>var hideDepth = function(root, depth) {\n root.find('ul').show(); // Make sure all sublists are visible \n var selector = Array(depth + 1).join(' > li > ul'); // Repeat string\n root.find(selector).hide();\n}\n\nvar depth = 2; \nvar selectedUL = $(\"#tree\");\n\nhideDepth(selectedUL, depth);\n</code></pre>\n\n<p>NOTE: Add the id <code>tree</code> to the top level <code>ul</code>. Your selector <code>$('ul')</code>selects all lists in the document, not just the top one, so your code was unnecessarily called repeatedly for each sub list.</p>\n\n<p>For the string repeating see: <a href=\"https://stackoverflow.com/questions/1877475/repeat-character-n-times\">https://stackoverflow.com/questions/1877475/repeat-character-n-times</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T14:28:52.527",
"Id": "40368",
"ParentId": "40330",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "40368",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T05:16:49.913",
"Id": "40330",
"Score": "5",
"Tags": [
"javascript",
"jquery",
"tree"
],
"Title": "Hide the tree menu at a certain depth"
}
|
40330
|
<p>I was trying to write a Java program to compare previous records while traversing. It returns true if element exists previously, else false.</p>
<p>e.g.</p>
<ul>
<li>if elements are <code>{"Raj","Jas","Kam","Jas"}</code> then return <code>true</code> (since <code>Jas</code> element available previously)</li>
<li>if elements are <code>{"Raj","Jas","Kam","Tas"}</code> then return <code>false</code></li>
</ul>
<p>I have written the below code, but its complexity is <code>n*n</code>, which is not good. How could I write clean code to improve the performance?</p>
<pre><code>import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CompareList {
private List<String> listNames;
private List<String> listTempName = new ArrayList<>();
public CompareList(String[] vListArray) {
listNames = Arrays.asList(vListArray);
}
public CompareList(List<String> vListName) {
listNames = vListName;
}
public boolean isPreviousNameExist() {
String tempName = null;
for (int i = 0; i < listNames.size(); i++) {
tempName = listNames.get(i);
if (listTempName.contains(tempName)) {
return true;
} else {
listTempName.add(tempName);
}
}
return false;
}
public static void main(String[] args) {
String[] nameArray = {"A", "B", "C", "D", "E", "F"};
CompareList compareList = new CompareList(nameArray);
System.out.println("==>" + compareList.isPreviousNameExist());
}
}
</code></pre>
<p><strong>UPDATED</strong></p>
<p>I have updated the code and tried using a recursive way, same way how we sort using MergeSort and find its performance better for a large number of records, compared to HashSet. I believe its complexity is O(log n).</p>
<pre><code>public class NameComparator {
private String[] listNames;
private String[] listTempNames;
private boolean compareFlag = false;
private int size;
public boolean isNameAlreadyExist(String[] vListNames) {
this.listNames = vListNames;
size = vListNames.length;
this.listTempNames = new String[size];
checkAndSort(0, size - 1);
return compareFlag;
}
private void checkAndSort(int low, int high) {
//Use the merge sort
}
}
..............................
}
</code></pre>
|
[] |
[
{
"body": "<p>You can actually change the performance to <code>O(n)</code> by changing one line of code here (and adding a couple of imports):</p>\n\n<pre><code>import java.util.Set;\nimport java.util.HashSet;\n\n...\n\nprivate Set<String> listTempName = new HashSet<>();\n</code></pre>\n\n<p>Although this works, we can simplify the code a little bit. Effectively, you want to see if the list of elements in the given <code>List</code> are <em>unique</em>. There's a really easy way to do this: add them all to a <code>Set</code>. If the size of the set and the size of the list are equal, then there are no duplicates. If the sizes are different, then there must be 1 or more duplicate elements. With this, we can simplify your code to:</p>\n\n<pre><code>public boolean isPreviousNameExist() \n{\n for(String name : listNames) {\n listTempName.add(name);\n }\n return listNames.size() != listTempName.size();\n}\n</code></pre>\n\n<p>A slight improvement based on comment by @bowmore:</p>\n\n<pre><code>public boolean isPreviousNameExist()\n{\n for(String name : listNames) {\n if(!listTempName.add(name)) {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T07:07:48.370",
"Id": "67896",
"Score": "0",
"body": "thanks Yuushi, Is it any other way without using hashing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T07:11:57.177",
"Id": "67897",
"Score": "1",
"body": "Well, you can use a `TreeSet`, which (by default) uses natural ordering to search for elements (which is `O(log n)` instead of amortized `O(1)`). Is there any real reason you want to avoid hashing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T07:14:47.183",
"Id": "67898",
"Score": "0",
"body": "thanks Yuushi, I only have doubt if it support large datas?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T07:21:18.540",
"Id": "67901",
"Score": "5",
"body": "You can break early from the loop if `Set.add()`returns `false`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T07:29:24.670",
"Id": "67902",
"Score": "0",
"body": "How large a data set are you expecting? This will handle millions of elements quite happily."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T07:51:10.207",
"Id": "67904",
"Score": "0",
"body": "thanks Yuushi and bowmore. Just one more question. Can we do the same kind of solution with O(n) complexity without using collection?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T07:57:48.593",
"Id": "67906",
"Score": "2",
"body": "`O(n)`, not that I can think of. There is an `O(n log n)` solution: sort the original array, and then loop through it, checking adjacent elements. This could potentially be better if memory is an issue."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T06:45:18.310",
"Id": "40334",
"ParentId": "40333",
"Score": "7"
}
},
{
"body": "<p>Your complexity is indeed O<sub>(n<sup>2</sup>)</sub> because you traverse a list bounded by n for each n elements of your list.</p>\n\n<p>You can reduce this list to O<sub>(n * log(n))</sub> quite easily:</p>\n\n<ul>\n<li>Sort your array -> O<sub>(n * log(n))</sub></li>\n<li>Compare each element with the next one <code>listNames.get(i).equals(listNames.get(i+1))</code> -> O<sub>(n)</sub></li>\n</ul>\n\n<p>Total is O<sub>(n * log(n))</sub></p>\n\n<hr>\n\n<h3>Edit:</h3>\n\n<p>If you are really interested on the true/false result, there is a pretty one-liner solution :</p>\n\n<pre><code>return listNames.size() == new HashSet(listNames).size();\n</code></pre>\n\n<p>The <code>HashSet</code> will filter duplicate elements, hence will be smaller if there are any duplicates. It runs in O<sub>(n)</sub>, as insertion in a <code>HashSet</code> is O<sub>(1)</sub></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T07:20:04.170",
"Id": "68046",
"Score": "0",
"body": "thanks njZk2 and sybOrg. I did just small modification in sorting approach. I sort through merge sort(recursive approach) as considering large data and while sorting i compare the element with flag. I updated the code. Please review the same and provide suggestion."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T21:55:24.783",
"Id": "40398",
"ParentId": "40333",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "40334",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T06:21:20.457",
"Id": "40333",
"Score": "3",
"Tags": [
"java",
"performance",
"iteration"
],
"Title": "Improve performance while Traversing List"
}
|
40333
|
<ol>
<li>What is more readable? <code>value / 60 / 60</code>, <code>value / 3600</code>, or <code>Hours{static_cast<Minutes>(*this).value / 60}</code>? Should I use constants, i.e. <code>SECONDS_IN_HOURS</code>.</li>
<li>Should I use the <code>explicit</code> keyword? Would it actually prevent stupid mistakes/silent bugs? Or would it become annoying to have to cast everything?</li>
<li>It is easy to "glaze" over the following code and miss mistakes (for example, mixing up multiplication and dividing, using <code>24</code> instead of <code>60</code> when converting hours to minutes). How should it be refactored? I'm not sure if <code>toSeconds</code>, <code>toMinutes</code> is better than <code>Second::operator Minutes()</code> in terms of clarity.</li>
<li>What happens if I add <code>days</code>, and then <code>week</code>s, and so on? It would require duplicating code and keeping track of what I have already and haven't already implemented. This is basically an extension to number 3 in terms of refactoring: how should I define them in terms of the other to avoid duplication? </li>
</ol>
<p></p>
<blockquote>
<pre><code>#include <iostream>
struct Seconds;
struct Minutes;
struct Hours;
struct Seconds
{
int value;
operator Minutes() const;
operator Hours() const;
};
struct Minutes
{
int value;
operator Seconds() const;
operator Hours() const;
};
struct Hours
{
int value;
operator Minutes() const;
operator Seconds() const;
};
Seconds::operator Minutes() const
{
return Minutes{value / 60};
}
Seconds::operator Hours() const
{
return Hours{static_cast<Minutes>(*this).value / 60};
}
Minutes::operator Seconds() const
{
return Seconds{value * 60};
}
Minutes::operator Hours() const
{
return Hours{value / 60};
}
Hours::operator Minutes() const
{
return Minutes{value * 60};
}
Hours::operator Seconds() const
{
return Seconds{static_cast<Minutes>(*this).value * 60};
}
int main()
{
Minutes m{60};
Seconds s{3600};
Hours h{1};
std::cout << (static_cast<Seconds>(m).value == s.value);
std::cout << (static_cast<Seconds>(h).value == s.value);
std::cout << (static_cast<Minutes>(s).value == m.value);
std::cout << (static_cast<Minutes>(h).value == m.value);
std::cout << (static_cast<Hours>(s).value == h.value);
std::cout << (static_cast<Hours>(m).value == h.value);
return 0;
}
</code></pre>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T10:25:44.927",
"Id": "67925",
"Score": "1",
"body": "[Josay's answer below](http://codereview.stackexchange.com/a/40343/34757) is similar to the answers given for a different but similar question, [Type system for different representations of angle value](http://codereview.stackexchange.com/q/39360/34757), where the OP proposed a different class for each type of unit or dimension, and the answers propose instead a single class with output to different units."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T11:52:18.127",
"Id": "70375",
"Score": "0",
"body": "@remyabel You might be interested by http://nathan.ca/2014/02/type-rich-programming/ ."
}
] |
[
{
"body": "<p>1) For readability, I'd go with explicitly using the single conversion constants instead of lumping them together: </p>\n\n<pre><code>const int uptimeHours = uptimeMSecs / 1000 / 60 / 60;\n</code></pre>\n\n<p>Possibly off-topic, but I would probably do away with all these structs and auto-conversions entirely. If you use well named variables to keep track of the units, the conversion constants (60 secs to a minute etc.) are pretty straightforward.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T09:17:15.287",
"Id": "40342",
"ParentId": "40336",
"Score": "0"
}
},
{
"body": "<p>What you done looks good but I am wondering if it is not a bit over-engineered.</p>\n\n<p>Here's what I would have done (which is probably under-engineered) :</p>\n\n<pre><code>#include <iostream>\n\nenum TimeUnit\n{\n Second = 1,\n Minute = Second*60,\n Hour = Minute*60,\n Day = Hour*24,\n Week = Day*7\n};\n\nclass Time\n{\n public:\n Time(int n = 0, TimeUnit unit = Second) :\n value(n*unit) {};\n\n bool operator==(const Time& other) const {\n return (value==other.value);\n }\n\n int convert(TimeUnit unit = Second) const { return value/unit; }\n\n private:\n const int value; // Assumed to be in seconds.\n};\n\nint main()\n{\n Time s0;\n Time h0(0,Hour);\n std::cout << (s0 == h0);\n\n Time s3600(3600);\n Time s3600bis(3600, Second);\n Time m60(60, Minute);\n Time h1(1, Hour); \n std::cout << (s3600 == s3600bis && s3600bis == m60 && m60 == h1);\n\n return 0;\n}\n</code></pre>\n\n<p>My point is to just take into account the fact that a time is just a value and a unit. We store the value in the easiest format and we convert it on demand. No conversion is actually required for comparison. Adding a new <code>Unit</code> is straightforward (assuming there is a constant factor to multiply - month and year wouldn't work because they do not always last the same time).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T09:28:24.793",
"Id": "40343",
"ParentId": "40336",
"Score": "5"
}
},
{
"body": "<p>I think you are right on track because your code has pretty much the same interface as as the Standard Library header <code><chrono></code>. Just replace all your classes with <code>#include <chrono></code>, your <code>static_cast</code> to <code>duration_cast</code> and <code>.value</code> to <code>count()</code> and you are all set:</p>\n\n<pre><code>#include <iostream>\n#include <chrono>\n\nint main()\n{\n using namespace std::chrono; \n minutes m{60};\n seconds s{3600};\n hours h{1};\n std::cout << (duration_cast<seconds>(m).count() == s.count());\n std::cout << (duration_cast<seconds>(h).count() == s.count());\n std::cout << (duration_cast<minutes>(s).count() == m.count());\n std::cout << (duration_cast<minutes>(h).count() == m.count());\n std::cout << (duration_cast<hours>(s).count() == h.count());\n std::cout << (duration_cast<hours>(m).count() == h.count());\n\n // Bonus\n std::cout << (s == m) << (m == h);\n}\n</code></pre>\n\n<p><a href=\"http://coliru.stacked-crooked.com/a/f2fd4833d5204721\" rel=\"nofollow\"><strong>Live Example</strong></a>.</p>\n\n<p>The <code><chrono></code> implementation is a lot easier than your classes: it consists of a single class template </p>\n\n<pre><code>template<class Rep, class Period> \nclass duration<Rep, Period = std::ratio<1>>;\n</code></pre>\n\n<p>The <code>Rep</code> parameter is a signed integer that contains the <code>count()</code>, and the <code>std::ratio</code> is used to convert without loss of precision. You can also define your own types <code>day</code>, <code>week</code> or <code>year</code> this way. As you can so from my code example, you don't have to convert types to prove equality, just use <code>==</code> directly on the objects. <code>duration_cast</code> is only necessary to print stuff in different units, not for computations.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T21:14:51.863",
"Id": "40577",
"ParentId": "40336",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "40343",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T07:09:20.883",
"Id": "40336",
"Score": "4",
"Tags": [
"c++",
"c++11",
"datetime",
"converting"
],
"Title": "Mutual conversion operators"
}
|
40336
|
<p>I have a nested JSON of multiple levels. The last level has the "series data" that is to be added to the highcharts options to render the chart data of interest.</p>
<p>I am sniffing the JSON and populating the options in each level which is set as a watched model in the controller and modifying the chart data, which is watched inside of the directive and chart updated on the change of these models.</p>
<p>I am looking to structure this as a reusable component and wondering on the best practice to do so. Seems to me, the "JSON selection" part and the "chart rendering" part can be best as their own directives that communicate amongst each other.</p>
<p>Do you concur or suggest an alternative approach?</p>
<p><strong>Controller:</strong></p>
<pre><code>app.controller('MyCtrl',function($scope,Data,ForwardChart){
http.get('scripts/lib/bds2.json').success(function(api_data){
$scope.r_api_data = api_data.res;
var available_options = [];
var chosen_options= [];
var current_json = $scope.r_api_data;
for (var i=0; i<2; i++){
var json_options = _.keys(current_json);
available_options.push(json_options);
chosen_options.push(json_options[0]);
current_json = current_json[json_options[0]];
}
$scope.plot_data = function(){
var bdfs_chart = {
series : Data.get_serieses($scope.r_api_data,$scope.chosen_options)
};
$scope.bdfs_chart = $.extend(true,angular.copy(ForwardChart),bdfs_chart);
};
$scope.chosen_options = [];
$scope.available_options = available_options;
$scope.$watch('chosen_options', function(){
$scope.plot_data();
},true);
$scope.chosen_options = chosen_options;
})
});
</code></pre>
<p><strong>Directive:</strong></p>
<pre><code>app.directive('intchart', function(){
return {
restrict: 'E',
template: '<div class="hc-bars"></div>',
scope: {
chartData: "=chartId"
},
link: function(scope, element, attrs){
var chartsDefaults = {
chart: {
renderTo: element[0],
type: attrs.type || null,
height: attrs.height,
width: attrs.width
},
colors: attrs.color.split(",")
};
var chart = {};
scope.$watch(function() { return scope.chartData; }, function(value){
var chart_json = {};
if (chart.hasOwnProperty('series') && chart.series.length>0){
for (var i = 0; i < value.series.length; i++) {
chart.series[i].setData(value.series[i].data);
}
} else{
$.extend(true, chart_json, chartsDefaults, value);
chart = new Highcharts.Chart(chart_json);
}
}, true);
}
}
})
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T09:29:13.677",
"Id": "68282",
"Score": "0",
"body": "btw, instead of `function() { return scope.chartData; }` as a watcher target, it is valid to just put the string \"chartData\", and of course easier to read."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T09:49:04.773",
"Id": "68284",
"Score": "0",
"body": "Also if I understand correctly what is meant to happen in the controller, It looks like you're relying on the ordering of object keys to get `chosen_options` from the `current_json` object, this might usually work but is not guaranteed to. http://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order"
}
] |
[
{
"body": "<p>It's difficult to tell from these snippets exactly what you're trying to achieve, but I think the questions you have to ask are; how do you anticipate reusing this code? If reusability is the feature, what are the use cases?</p>\n\n<p>If you anticipate needing multiple distinct controllers with a significant and coherent subset of the logic in the get request in the controller, the consider extracting it into a service, to save logic duplication.</p>\n\n<p>Alternatively, if the contents of the controller are only needed for the directive, consider making the controller part of the directive, rather than requiring them to be correctly used in conjunction.</p>\n\n<p>The directive looks good from what I can tell.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T09:50:19.060",
"Id": "40524",
"ParentId": "40337",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T07:22:14.370",
"Id": "40337",
"Score": "3",
"Tags": [
"javascript",
"angular.js"
],
"Title": "Structuring a reusable angular component with multiple communicating directives"
}
|
40337
|
<p>Here is the <a href="http://jsfiddle.net/P7b9S/66/" rel="nofollow">link to fiddle</a>. This is my first app using Dojo. Any comments/feedback is highly appreciated.</p>
<pre><code>dojoConfig = {parseOnLoad: true};
resetStopwatch();
require(["dijit/form/ToggleButton", "dijit/form/Button", "dojo/dom", "dojo/dom-attr", "dojo/domReady!"], function(ToggleButton, Button, dom, domAttr){
var timeUpdate;
var toggleButton = new ToggleButton({
showLabel: true,
checked: false,
label: "Start",
onChange: function() {
if (this.get('label') == "Start") {
this.set('label', 'Stop');
var milliseconds = seconds = minutes = hours = 0;
timeUpdate = updateTime(domAttr, 0, 0, 0, 0);
}
else if (this.get('label') == "Resume") {
this.set('label', 'Stop');
// fetch current time in the stopwatch
prev_milliseconds = parseInt(domAttr.get("milliseconds", "innerHTML"));
prev_seconds = parseInt(domAttr.get("seconds", "innerHTML"));
prev_minutes = parseInt(domAttr.get("minutes", "innerHTML"));
prev_hours = parseInt(domAttr.get("hours", "innerHTML"));
timeUpdate = updateTime(domAttr, prev_hours, prev_minutes, prev_seconds, prev_milliseconds);
}
else if (this.get('label') == "Stop"){
this.set('label', 'Resume');
clearInterval(timeUpdate);
}
}
}, "start_stop_resume");
var resetButton = new Button({
label: "Reset",
onClick: function(){
toggleButton.set('label', "Start");
clearInterval(timeUpdate);
resetStopwatch();
resumeFlag = false;
}
}, "reset");
});
function updateTime(domAttr, prev_hours, prev_minutes, prev_seconds, prev_milliseconds){
var startTime = new Date();
timeUpdate = setInterval(function(){
var timeElapsed = new Date().getTime() - startTime.getTime();
// calculate hours
hours = parseInt(timeElapsed/1000/60/60) + prev_hours;
hours = prependZero(hours);
domAttr.set("hours", "innerHTML", hours + " : ");
// calculate minutes
minutes = parseInt(timeElapsed/1000/60) + prev_minutes;
if(minutes > 60)
minutes = minutes % 60;
minutes = prependZero(minutes);
domAttr.set("minutes", "innerHTML", minutes + " : ");
// calculate seconds
seconds = parseInt(timeElapsed/1000) + prev_seconds;
if(seconds > 60)
seconds = seconds % 60;
seconds = prependZero(seconds);
domAttr.set("seconds", "innerHTML", seconds + " :: ");
// calculate milliseconds
milliseconds = timeElapsed + prev_milliseconds;
milliseconds = prependZero(milliseconds);
if(milliseconds > 1000)
milliseconds = milliseconds % 1000;
if(milliseconds < 10)
milliseconds = "00" + milliseconds.toString();
else if(milliseconds < 100)
milliseconds = "0" + milliseconds.toString();
domAttr.set("milliseconds", "innerHTML", milliseconds);
},25); // update time in stopwatch after every 25ms
return timeUpdate;
}
function resetStopwatch(){
require(["dojo/dom-attr"], function(domAttr){
domAttr.set("hours", "innerHTML", "00 : ");
domAttr.set("minutes", "innerHTML", "00 : ");
domAttr.set("seconds", "innerHTML", "00 :: ");
domAttr.set("milliseconds", "innerHTML", "000");
});
}
function prependZero(time){
if(time < 10){
time = "0" + time.toString();
return time;
}
else
return time;
}
</code></pre>
|
[] |
[
{
"body": "<p>I tinkered a bit with the fiddle, I have the following observations:</p>\n\n<ul>\n<li><p>If you were to place the colons in the HTML, then you would no longer need to concatenate the colons into the time fields:</p>\n\n<blockquote>\n<pre><code><div id=\"stopwatch\"> \n <span id=\"hours\"></span>:\n <span id=\"minutes\"></span>:\n <span id=\"seconds\"></span>::\n <span id=\"milliseconds\"></span>\n</div>\n</code></pre>\n</blockquote></li>\n<li><p>You could generalize <code>prependZero</code> so that it works for both seconds and milliseconds by passing the requested length:</p>\n\n<blockquote>\n<pre><code> function prependZero( time, length ){\n time = time + \"\";\n while( time.length < length ){\n time = '0' + time;\n }\n return time;\n }\n</code></pre>\n</blockquote>\n\n<p>or a more Golfic version which calculates the amount of zeroes that will be required:</p>\n\n<pre><code>function prependZero2( time, length ){\n time = time + \"\";\n return new Array( Math.max( length - time.length + 1 , 0 ) ).join(\"0\") + time;\n}\n</code></pre></li>\n<li><p><code>if(minutes > 60) minutes = minutes % 60;</code> is the same as <code>minutes = minutes % 60;</code> is the same as <code>minutes %= 60;</code>.</p></li>\n<li><p>Your code would be much cleaner if you split out time calculations from prettyfying the numbers.</p>\n\n<p>You could have a function that is dedicated to time calculations:</p>\n\n<pre><code>function updateTime(domAttr, prev_hours, prev_minutes, prev_seconds, prev_milliseconds){\n var startTime = new Date();\n timeUpdate = setInterval(function(){\n var timeElapsed = new Date().getTime() - startTime.getTime();\n\n // calculate hours \n hours = parseInt(timeElapsed/1000/60/60) + prev_hours;\n\n // calculate minutes\n minutes = parseInt(timeElapsed/1000/60) + prev_minutes;\n minutes %= 60;\n\n // calculate seconds\n seconds = parseInt(timeElapsed/1000) + prev_seconds;\n seconds %= 60;\n\n // calculate milliseconds \n milliseconds = timeElapsed + prev_milliseconds;\n milliseconds %= 1000;\n\n setStopwatch( hours , minutes , seconds , milliseconds );\n\n },25); // update time in stopwatch after every 25ms\n\n return timeUpdate;\n}\n</code></pre>\n\n<p>and a function that just updates the DOM:</p>\n\n<pre><code>function setStopwatch( hours , minutes , seconds , milliseconds ){\n require([\"dojo/dom-attr\"], function(domAttr){\n domAttr.set(\"hours\" , \"innerHTML\", prependZero( hours, 2 ) );\n domAttr.set(\"minutes\" , \"innerHTML\", prependZero( minutes, 2 ) );\n domAttr.set(\"seconds\" , \"innerHTML\", prependZero( seconds, 2 ) );\n domAttr.set(\"milliseconds\", \"innerHTML\", prependZero( milliseconds, 3 ) );\n });\n}\n</code></pre>\n\n<p><code>resetStopwatch</code> then becomes as simple as </p>\n\n<pre><code>function resetStopwatch(){\n setStopwatch( 0, 0, 0, 0 );\n}\n</code></pre></li>\n<li><p>A very minor nitpicking, but the <code>require</code> array is hard to read, you should figure out how Dojo proposes you should indent that array.</p></li>\n<li><p>Another nitpicking is that you trust the DOM as your data model (you retrieve the values from the labels when you hit <kbd>Resume</kbd>), that is a bad practice in general, but acceptable for a timer project.</p></li>\n</ul>\n\n<p>You can check the end result <a href=\"http://jsfiddle.net/konijn_gmail_com/P7b9S/70/\" rel=\"nofollow\">here</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T14:18:43.393",
"Id": "40367",
"ParentId": "40339",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "40367",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T08:32:17.997",
"Id": "40339",
"Score": "5",
"Tags": [
"javascript",
"datetime",
"dojo"
],
"Title": "Stopwatch app using Dojo"
}
|
40339
|
<p>Here is an API for using a warehouse:</p>
<pre><code>public static class WarehouseClient
{
event Action<IWarehouse> WarehouseCreated;
}
public interface IWarehouse
{
event Action<IWarehouseSession> NextSession;
IWarehouseSession Session { get; }
WarehouseInfo Info { get; }
}
public interface IWarehouseSession
{
event Action Opened;
event Action Closed;
bool IsOpen { get; }
TariffPolicy TariffPolicy { get; }
IEnumerable<ITerminal> Terminals { get; }
}
public interface ITerminal
{
event Action<double> FreeSpaceUpdated;
string TerminalLetter { get; }
double FreeSpace { get; }
IDeposit Deposit(object item);
}
public interface IDeposit
{
object Item { get; }
event Action ItemAccepted;
event Action<int> ItemDeposited;
event Action ItemWithdrawn;
void Withdraw();
}
</code></pre>
<p>(<code>WarehouseInfo</code> and <code>TariffPolicy</code> are immutable value-like classes)</p>
<p>Also I've got third-party connections to warehouses with interfaces adaptable to mine. But I doubt if I need a mirrored API for connection wrappers, like:</p>
<pre><code>public static class WarehouseProvider
{
IWarehouseBackend CreateWarehouse(WarehouseInfo info);
}
public interface IWarehouseBackend
{
IWarehouseSessionBackend Session { get; }
WarehouseInfo Info { get; }
IWarehouseSessionBackend NextSession(TariffPolicy tp, params string[] terminalLetters);
}
public interface IWarehouseSessionBackend
{
bool IsOpen { get; }
TariffPolicy TariffPolicy { get; }
IEnumerable<ITerminalBackend> Terminals { get; }
void Open();
void Close();
}
public interface ITerminalBackend
{
// ... and so on
</code></pre>
<p>This backend-api can be implemented by library's internal classes.</p>
<p>Removing it means much less code (though it almost written) and harder-to-implement contract for warehouse providers.</p>
<p>So, my question is: do I need backend api?</p>
<p>Also, I would be very grateful for reviewing this API.</p>
|
[] |
[
{
"body": "<ol>\n<li><p>You definitely want to document those interfaces.</p></li>\n<li><p><code>WarehouseClient</code> should probably not be a static class.</p></li>\n<li><p>The name of the <code>NextSession</code> event in <code>IWarehouse</code> doesn't really mean anything to me. Just from reading the interface I don't really know when this event would be raised. Maybe <code>NextSessionCreated</code> or <code>NextSessionOpened</code>?</p></li>\n<li><p><code>CurrentSession</code> would be a better name instead of <code>Session</code>.</p></li>\n<li><p>Also it is not clear if the <code>Session</code> can get opened and closed multiple times. If a session can't be opened and closed multiple time then maybe use <code>Start</code> and <code>Finalize</code> instead? Those imply (at least to me) more of a once only action.</p></li>\n<li><p>In <code>IDeposit</code>: <code>ItemWithdrawed</code> should be <code>ItemWithdrawn</code></p></li>\n<li><p>I'm not 100% sure about the <code>ITerminal</code> and <code>IDeposit</code> relation. The way I read is that a client can deposit an object into a terminal which will then give him some kind of reference to that transaction in form of an <code>IDeposit</code>. Now <code>IDeposit</code> also has a <code>Withdraw()</code> method but it's not clear what the semantics of that is. Can the client who deposited the item basically withdraw that deposit? Or is it mean to be withdrawn by someone else - if yes then shouldn't there be a <code>Withdraw()</code> method on the terminal rather than on the deposit? It's probably not clear to me because I don't know what the workflow is supposed to be but it's hard to deduce from just the interfaces alone.</p></li>\n</ol>\n\n<p>All that being said I'd say: Yes you want that backend API. Apparently the whole system expects a certain kind of workflow and providing a structure which an implementer can fill in will make it much easier for them and probably reduce bugs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T10:05:08.553",
"Id": "67921",
"Score": "0",
"body": "Agree with all documentation and naming issues. What about #2: why it shouldn't be static? What about `public static class WarehouseProvider`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T10:11:09.537",
"Id": "67922",
"Score": "0",
"body": "@astef: That one should not be static either. Static classes make sense for stateless utility or factory classes (like `Tuple`). Classes which own state should not be static. You create implicit, hard to find and unit test dependencies otherwise. Technical debt with little to no benefit."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T09:54:38.173",
"Id": "40346",
"ParentId": "40340",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "40346",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T08:54:51.997",
"Id": "40340",
"Score": "2",
"Tags": [
"c#",
"object-oriented",
"api",
"interface",
"library-design"
],
"Title": "Backend interface VS hard contract"
}
|
40340
|
<p>I want to get the source of these files, but I don't know if I'm efficient.</p>
<p>I get the source of the file, put the source in a <code>list</code>, so I put this in a <code>hashmap</code> with the key is the <code>version</code> of file and the <code>values</code> are the <code>list</code>.</p>
<pre><code>private Map<String, List<String>> loadXmlNodes() {
Map<String, List<String>> mapNodes = new HashMap<>();
List<String> nodes = XmlUtil.loadNodes1_10();
mapNodes.put("1.10", nodes);
nodes = XmlUtil.loadNodes2_00();
mapNodes.put("2.00", nodes);
return mapNodes;
}
public static List<String> loadNodes1_10() {
List<String> node = new ArrayList<>();
try {
InputStream inputStream = XmlUtil.class.getClassLoader().getResourceAsStream("nodes1.10.properties");
Properties properties = new Properties();
properties.load(inputStream);
for (Object value : properties.keySet()) {
node.add((String) value);
}
} catch (IOException e) {
e.printStackTrace();
}
return node;
}
public static List<String> loadNodes2_00() {
List<String> node = new ArrayList<>();
try {
InputStream inputStream = XmlUtil.class.getClassLoader().getResourceAsStream("nodes2.00.properties");
Properties properties = new Properties();
properties.load(inputStream);
for (Object value : properties.keySet()) {
node.add((String) value);
}
} catch (IOException e) {
e.printStackTrace();
}
return node;
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>Instead of <code>Map<String, List<String>></code> you could use Guava's <code>Multimap</code> (<a href=\"https://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap\" rel=\"nofollow noreferrer\">doc</a>, <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html\" rel=\"nofollow noreferrer\">javadoc</a>) which was designed exactly for that.</p></li>\n<li><p>Are you sure that in case of an <code>IOError</code> your clients want an empty list? If that's some optional data it can be fine but it could be possible that instead of this you should propagate the exception to the caller and signal the error to avoid processing invalid data.</p></li>\n<li><p>See also:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/q/10477607/843804\">Avoid printStackTrace(); use a logger call instead</a></li>\n<li><a href=\"https://stackoverflow.com/q/7469316/843804\">Why is exception.printStackTrace() considered bad practice?</a></li>\n</ul></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T10:42:31.887",
"Id": "67926",
"Score": "1",
"body": "I don´t know Guava´s project...I´m going to see"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T17:27:04.907",
"Id": "67968",
"Score": "2",
"body": "The advice in itself is good, but this feels more like a \"quick random note\" (i.e. comment) than an answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T09:31:19.393",
"Id": "68055",
"Score": "1",
"body": "@SimonAndréForsberg thanks for your comment, but it can help me. I´m gonna read."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T10:41:09.240",
"Id": "40350",
"ParentId": "40347",
"Score": "4"
}
},
{
"body": "<p>There are a couple of inefficient things you do, and there's some better-practice items too.</p>\n\n<p>First, let's take one of the methods:</p>\n\n<blockquote>\n<pre><code>public static List<String> loadNodes2_00() {\n\n List<String> node = new ArrayList<>();\n\n try {\n\n InputStream inputStream = XmlUtil.class.getClassLoader().getResourceAsStream(\"nodes2.00.properties\");\n Properties properties = new Properties();\n properties.load(inputStream);\n\n for (Object value : properties.keySet()) {\n node.add((String) value);\n }\n\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n return node;\n}\n</code></pre>\n</blockquote>\n\n<p><code>node</code> is not a great name for something that is a list. It is typical in computer programs for <code>node</code> to point to just a particular element in a list, stack, or whatever, not the whole thing.</p>\n\n<p>Something like <code>result</code>, or <code>names</code> would be better.</p>\n\n<p>Then, you are not closing the InputStream. This is bad practice, and is a bad habit to be in. Java7 allows the try-with-resources statement, which is ideal for this code.</p>\n\n<p>Now, there is the less-commonly-used <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Properties.html#stringPropertyNames%28%29\" rel=\"nofollow\">method stringPropertyNames()</a> available on Properties. It is useful here, instead of iterating on the <code>keyValues()</code>.</p>\n\n<p>Why are the <code>loadNodes1_10()</code> and <code>loadNodes2_00()</code> methods public? Do they need to be? They should be private to the class if they are not used.</p>\n\n<p>Constant values embedded inside code are often <a href=\"http://en.wikipedia.org/wiki/Magic_number_%28programming%29#Unnamed_numerical_constants\" rel=\"nofollow\">called 'Magic values'</a>. In this case, the values are Strings. You should declare a constant for your resource names....</p>\n\n<p>Putting it all together, how about this method:</p>\n\n<pre><code>private static final String RESOURCE_NODES_2_00 = \"nodes2.00.properties\";\nprivate static List<String> loadNodes2_00() {\n\n List<String> names = new ArrayList<>();\n try (InputStream inputStream = XMLUtil.class.getClassLoader()\n .getResourceAsStream(RESOURCE_NODES_2_00)) {\n\n Properties properties = new Properties();\n properties.load(inputStream);\n names.addAll(properties.stringPropertyNames());\n\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n return names;\n}\n</code></pre>\n\n<p>This is neater, and more efficient, and it closes all the streams correctly.... but... apart from the method name, and the file name, your two methods are identical. What you should do is generalize the method:</p>\n\n<pre><code>private static List<String> loadNodes(String resourcename) {\n\n List<String> names = new ArrayList<>();\n try (InputStream inputStream = XMLUtil.class.getClassLoader()\n .getResourceAsStream(resourcename)) {\n\n Properties properties = new Properties();\n properties.load(inputStream);\n names.addAll(properties.stringPropertyNames());\n\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n return names;\n}\n</code></pre>\n\n<p>Now, in your calling method, you can change your code to:</p>\n\n<pre><code>private Map<String, List<String>> loadXmlNodes() {\n\n Map<String, List<String>> mapNodes = new HashMap<>();\n mapNodes.put(\"1.10\", loadNodes(RESOURCE_NODES_1_10);\n mapNodes.put(\"2.00\", loadNodes(RESOURCE_NODES_2_00);\n\n return mapNodes;\n}\n</code></pre>\n\n<p>This should simplify the code a whole lot.</p>\n\n<p>If you need the two methods <code>loadNodes1_10()</code> and <code>loadNodes2_00()</code> to be public, I would make them simply:</p>\n\n<pre><code>public static List<String> loadNodes1_10() {\n return loadNodes(RESOURCE_NODES_1_10);\n}\n</code></pre>\n\n<p>All the best, and enjoy.</p>\n\n<hr>\n\n<h2>EDIT:</h2>\n\n<p>If you want to return a <code>Map<String,Map<String,String>></code> instead, it will look something like:</p>\n\n<pre><code>private static Map<String,String> loadNodes(String resourcename) {\n\n Map<String,String> names = new HashMap<>();\n try (InputStream inputStream = XMLUtil.class.getClassLoader()\n .getResourceAsStream(resourcename)) {\n\n Properties properties = new Properties();\n properties.load(inputStream);\n for (String key : properties.stringPropertyNames()) {\n names.put(key, properties.getProperty(key));\n }\n\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n return names;\n}\n</code></pre>\n\n<p>and then you would have to adjust the other methods that call this respectively.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T16:09:53.503",
"Id": "68100",
"Score": "0",
"body": "I´ve changed my collection to a hashmap, is there any way to put the register like in list?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T16:12:04.863",
"Id": "68102",
"Score": "0",
"body": "@DiegoMacario not sure what you are asking... what's a register?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T16:14:14.980",
"Id": "68103",
"Score": "0",
"body": "I want to put the pair of properties files like this...map<String, Map<String, String>> the key of the map I´m going to put the version...and in the value, I´m going to put properties source file."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T16:18:38.353",
"Id": "68105",
"Score": "1",
"body": "@DiegoMacario See the edit..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T19:54:36.880",
"Id": "68158",
"Score": "0",
"body": "great, I read about try-with resources"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T17:56:37.190",
"Id": "40382",
"ParentId": "40347",
"Score": "8"
}
},
{
"body": "<p>Iterating over the <code>Properties.keySet()</code> should give you keys, not values.\nTherefore, these loops are either buggy or misleading:</p>\n\n<pre><code>for (Object value : properties.keySet()) {\n node.add((String) value);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T03:34:55.263",
"Id": "40506",
"ParentId": "40347",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "40382",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T10:31:43.750",
"Id": "40347",
"Score": "6",
"Tags": [
"java",
"properties",
"hash-map"
],
"Title": "How to refactor this code to get a source from property files?"
}
|
40347
|
<p>Here is a <a href="http://jsfiddle.net/N355H/1/" rel="nofollow">JSFiddle</a> of an accordion menu that i've done. I have used <code>:before</code> to add the icons.</p>
<p>My question is, is there a better way to Add different icon to each <code>li</code> item?</p>
<p>My code is as follows:</p>
<p>HTML Structure:</p>
<pre><code> <ul id="accordion">
<li><div id="profile">Profile</div></li>
<li><div id="messages">Messages</div>
<ul class="submenu">
<li>Inbox</li>
<li>Sent</li>
<li>Drafts</li>
</ul>
</li>
<li><div id="settings">Settings</div></li>
<li><div id="logout">Logout</div></li>
</ul>
</code></pre>
<p>CSS:</p>
<pre><code> body {
background-image: url(http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/tiny_grid.png);
}
ul{
list-style-type:none;
padding:0;
margin:0;
}
#accordion{
margin: 20% auto 80% auto;
width:200px;
height:auto;
background-color:#212830;
border-radius:5px;
color: #BECEDB;
font-family: 'Maven Pro', sans-serif;
border: 1px solid #191E24;
box-shadow: 0px 0px 5px 2px #666666;
}
#accordion > li > div{
background-color:#383C48;
font-weight:700;
-moz-box-shadow:inset 0 1px 1px -1px #A1B3C9;
-webkit-box-shadow:inset 0 1px 1px -1px #A1B3C9;
box-shadow:inset 0 1px 1px -1px #A1B3C9;
border-bottom:1px solid #191E24;
}
#accordion > li > div, #accordion > li > ul > li{
padding:10px 15px;
}
#accordion li{
cursor:pointer;
}
#accordion > li:first-child >div{
border-radius: 5px 5px 0 0;
}
#accordion > li:last-child >div{
border-radius: 0 0 5px 5px;
}
#profile:before,
#messages:before,
#settings:before,
#logout:before,
.submenu>li:before
{
font-family:FontAwesome;
}
#profile:before{
content:"\f007 ";
}
#messages:before{
content:"\f0e0";
}
#settings:before{
content:"\f013";
}
#logout:before{
content:"\f08b";
}
.submenu li:before{
content:"\f0da"
}
#accordion *:before{
margin-right:10px;
}
.submenu li{
margin-left:10px;
}
</code></pre>
<p>JS code: (No problem with this)</p>
<pre><code> $("#accordion > li > div").click(function(){
if(false == $(this).next().is(':visible')){
$('#accordion ul').slideUp(400);
}
$(this).next().slideToggle(300);
});
$('#accordion ul:eq(0)').show();
</code></pre>
<p>Also I would like to know if there are other areas this can be optimized.
<br>Thank you</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T10:42:53.190",
"Id": "67927",
"Score": "1",
"body": "It is good that you linked to a *demo* of the code, but we can only review code that's inside the question itself. Please [edit] your question to include the relevant code."
}
] |
[
{
"body": "<p>First things first: You have a navigation but refuse to use anchor tags. Why? This is potentially harmful. How are you going to <em>navigate</em> if you don't have links? The only possible way would be completely relying on JavaScript. All users with disabled JavaScript have a useless list of words instead.</p>\n\n<p><strong>HTML:</strong></p>\n\n<ul>\n<li>Use <code>a</code> tags instead of the <code>div</code>'s in your HTML (Use <code><a href=\"#\"></code> to test this)</li>\n<li>I'd suggest using classes instead of ID's in this scenario as well. The lower specificity of classes will ease your live later. Overwriting an ID instead could be hard</li>\n</ul>\n\n<p><strong>CSS:</strong></p>\n\n<ul>\n<li>If you use actual links for your navigation, there is no need for <code>cursor: pointer;</code> on list-items.</li>\n<li>If you want the icons to be clickable as well, add the pseudo-elements to the links instead of the list-items</li>\n<li>Don't reset the general styling for lists on the type selector <code>ul</code>. Doing this makes you unable to use lists as regular lists in text etc. You can reset the styles for the navigation on <code>#accordion</code></li>\n<li>Adding a class <code>accordion-item</code> to your list-items could help you. You don't selecting like this: <code>#profile:before, #messages:before, #settings:before...</code></li>\n</ul>\n\n<p>You have some things to consider now. There are more things to improve, but I'd like to see a new question for an updated navigation with the given advice.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T11:32:31.660",
"Id": "67931",
"Score": "0",
"body": "Oops, I forgot to mention, my plan was to wrap Message, Profile ... etc each with anchor tags. Its not that I want to avoid them. Just didn't use here because I was mostly focusing on the looks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T11:34:16.287",
"Id": "67932",
"Score": "4",
"body": "If my advice helped you, it would help to have a new question with the updated markup/CSS. Don't edit the anchors into this question, because this would invalidate my answer and potential others."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T11:29:55.580",
"Id": "40354",
"ParentId": "40349",
"Score": "4"
}
},
{
"body": "<p>I'm going to answer this question:</p>\n\n<blockquote>\n <p>is there a better way to Add different icon to each li item?</p>\n</blockquote>\n\n<p>The short answer is, yes. The better way is to use the classes that FontAwesome provides out of the box, rather than duplicating it in your own css. In this example I would make the following changes to the html:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><ul id=\"accordion\">\n <li><div id=\"profile\"><i class=\"fa fa-user\"></i>Profile</div></li>\n <li><div id=\"messages\"><i class=\"fa fa-envelope\"></i>Messages</div>\n <ul class=\"submenu\">\n <li><i class=\"fa fa-caret-right\"></i>Inbox</li>\n <li><i class=\"fa fa-caret-right\"></i>Sent</li>\n <li><i class=\"fa fa-caret-right\"></i>Drafts</li>\n </ul> \n </li>\n <li><div id=\"settings\"><i class=\"fa fa-cog\"></i>Settings</div></li>\n <li><div id=\"logout\"><i class=\"fa fa-sign-out\"></i>Logout</div></li>\n</ul>\n</code></pre>\n\n<p>See <a href=\"http://jsfiddle.net/3RW8s/1/\" rel=\"nofollow\">this forked fiddle</a>. Note that I had to fix your reference to the fontawesome css, which was giving me a 404 error, and I also deleted the bit of your css that was doing all the \":before\" classes.</p>\n\n<p>As a side note, I totally agree with @kleinfreund on almost all his points.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T13:03:47.070",
"Id": "67942",
"Score": "1",
"body": "Welcome to CodeReview. Nice answer but... please take a moment and copy the relevant code from your forked fiddle back in to this answer as that is a more permanent way to link the suggested changes with the question (and does not rely on an external site to keep your answer valid)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T15:32:15.787",
"Id": "67958",
"Score": "0",
"body": "@rolfl, Well, I think the relevant code IS already in the answer. This is the only code you need to make it work, with the exception of the removal of some code in the css, which I outlined. Should I copy all the css just to remove the bad parts (which are buried at the bottom?)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T15:36:19.910",
"Id": "67959",
"Score": "0",
"body": "you're the expert in this case. If you think the answer stands on it's own without the need for the fiddle (the fiddle is just a nice-to-have), then I'm satisfied."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T17:55:33.287",
"Id": "67973",
"Score": "0",
"body": "Thank you for the answer @ Nathan. My solution lies in both yours as well as @kleinfreund's answer. Which has put me in dilemma as to which one to accept :-|"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T19:09:22.380",
"Id": "67985",
"Score": "1",
"body": "@vineetrok It doesn't need to be the one with the highest votes. Whatever answer is the best in your opinion should be accepted."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T12:38:55.790",
"Id": "40359",
"ParentId": "40349",
"Score": "3"
}
},
{
"body": "<p>Since you have already other answers , I will focus on different issues</p>\n\n<p>This :</p>\n\n<pre><code>#accordion > li:first-child >div{\n border-radius: 5px 5px 0 0;\n}\n\n#accordion > li:last-child >div{\n border-radius: 0 0 5px 5px;\n}\n</code></pre>\n\n<p>Is not needed. You have already border-radius on the container.</p>\n\n<p>And the same for that:</p>\n\n<pre><code>#accordion > li > div{\n background-color:#383C48;\n</code></pre>\n\n<p>Not a big issue, but the duplicity of styles makes your life harder later. \n(When you are changing the border-radius and see that it doesn't change anything) </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T07:03:36.803",
"Id": "68045",
"Score": "0",
"body": "I'd like to point out that, removing the border radius from first and last child has only one minor difference.ie. the subtle inset box-shadow which is at the top around the corners is lost. Not a big deal, but noticeable only if you look closely. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T19:08:01.983",
"Id": "40388",
"ParentId": "40349",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "40354",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T10:35:05.640",
"Id": "40349",
"Score": "2",
"Tags": [
"javascript",
"optimization",
"html",
"css"
],
"Title": "Better way to use pseudo elements"
}
|
40349
|
<p>I'm using the <a href="https://github.com/chuyskywalker/rolling-curl" rel="nofollow">rolling curl</a> library to fire HTTP requests for content-length headers of images (we need to know their size to weed out placeholders and low res images). The image URLs are stored in a database so I need to loop over the data in our products table (approx 1 million rows but will grow bigger, potentially much bigger).</p>
<p>I'm using PHP and the Laravel framework (the artisan CLI component). The operation seems to slow down as time progresses e.g. it starts processing 100 requests in less than a second and later the time to process 100 rows/requests is logged at over 20 seconds. Can anyone explain this and / or offer any performance improvement suggestions? The task is running on an Amazon EC2 micro instance so processing power / memory is limited.</p>
<pre><code>public function fire()
{
$dt = new DateTime();
Log::info("started: ".$dt->format('Y-m-d H:i:s'));
$counter = 1;
Item2::where('img_size', '=', NULL)->chunk(1000, function($items) use ( &$counter)
{
$results = array();
$filePath = storage_path().'/imports/new/new_img_sizes_'.$counter.'.csv';
if (!File::exists($filePath)) {
File::put($filePath, '');
}
$start = microtime(true);
$rollingCurl = new \RollingCurl\RollingCurl();
$rollingCurl->setOptions($this->curlOptions);
foreach ($items as $item)
{
if ($item->img !== '') {
$results[$item->id] = array('url' => $item->img, 'size' => null);
$rollingCurl->get($item->img);
}
}
//callback runs on each curl request
$rollingCurl->setCallback(function(\RollingCurl\Request $request, \RollingCurl\RollingCurl $rollingCurl) use (&$results, $filePath) {
$responseInfo = $request->getResponseInfo();
//var_dump($responseInfo);exit;
$length = $responseInfo['download_content_length'];
foreach ($results as $key => $value) {
if (array_search($request->getURL(),$value)) {
$idKey = $key;
$results[$idKey]['size'] = $length;
File::append($filePath,$idKey.','.$results[$idKey]['size']."\r\n");
break;
}
}
})
->setSimultaneousLimit(10)
->execute();
$counter++;
echo 'done in...'.(microtime(true) - $start).PHP_EOL;
Log::info('1000 records: '.(microtime(true) - $start));
Log::info('Last url was: '.json_encode(end($results)));
exit;
}); // end item chunk
</code></pre>
<p>Some benchmarks:</p>
<blockquote>
<pre><code>done in...3.8803641796112
done in...7.4326379299164
done in...8.1860301494598
done in...8.5088090896606
done in...10.606615781784
done in...10.655412912369
done in...10.804574966431
done in...14.004528045654
done in...10.903785943985
done in...11.905344009399
done in...13.763195991516
done in...14.723680019379
done in...15.823812961578
done in...17.972007989883
done in...31.734715938568
done in...20.509822845459
done in...22.924754858017
done in...34.274693012238
done in...39.217702865601
done in...29.883662939072
done in...24.094554901123
done in...25.726534128189
done in...31.788655996323
done in...24.713880062103
done in...25.855134963989
done in...23.161122083664
done in...32.380167007446
done in...36.53077507019
done in...31.859884023666
done in...71.458341121674
</code></pre>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T16:27:43.630",
"Id": "68111",
"Score": "0",
"body": "Not to nitpick, but you have a very odd, if non-existent, coding style."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T16:44:18.550",
"Id": "68117",
"Score": "1",
"body": "it's a very rough prototype. which has been hacked around while I get something working. Not sure it is 'nitpick'ing but it is certainly not constructive"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T16:50:24.413",
"Id": "68122",
"Score": "0",
"body": "I do apologize for lack of constructiveness, its just my pet peeve :) I actually don't see much you can do here, perhaps someone else can. Have you tried logging or lapping throughout the function to see if you're getting rate limited on the service side? Look up (https://github.com/jsanc623/PHPBenchTime) and use or copy the lapping function there to knock out rate limiting?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T16:54:02.867",
"Id": "68124",
"Score": "0",
"body": "Actually, looking at it again - perhaps lower the concurrency that you set the second time from 100 (setSimultaneousLimit(100)) to 10 or less and see if this gives you better performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T15:03:52.287",
"Id": "70202",
"Score": "0",
"body": "@jsanc623 How would the lapping function 'knock out' rate limiting? You mean rule it out as a source of the performance problem?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T16:11:58.740",
"Id": "70222",
"Score": "0",
"body": "@jsanc623 I also couldn't get your PHPBenchtime working and logged an issue. It wouldn't work in Laravel via composer so I required it manually, then hit that error.https://github.com/jsanc623/PHPBenchTime/issues/4"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T17:26:27.667",
"Id": "70235",
"Score": "0",
"body": "Can PHP suffer from heap fragmentation, memory leaks, etc.? Might it work any better as a series of smaller/separate tasks?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T21:45:45.407",
"Id": "70269",
"Score": "0",
"body": "@codecowboy - yes, meant rule it out as source of the performance problem when I said \"knock out\" rate limiting. I also updated PHPBT to fix the issue you opened ;) I'll have to update the composer.json and structure later on though so it can be imported via composer correctly"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T11:11:10.517",
"Id": "70597",
"Score": "0",
"body": "@jsanc623 cool, will help if I can. I'm getting some duplicates with the updated code above. Can you see what might causing it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T16:27:48.287",
"Id": "70625",
"Score": "0",
"body": "@codecowboy I don't see any duplicates? Also - seeing as there's a large jump of time towards the end, perhaps take ChrisW's recommendation and output memory_get_usage() along with time after each iteration?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T07:26:15.887",
"Id": "71221",
"Score": "0",
"body": "@ChrisW: Damn right PHP can suffer from mem leaks... it manages its memory using simple ref-counts (if a `zval *` has more than 0 ref-counts, its memory isn't freed). If you want to leak memory, just have 2 objects reference each other: `$obj1->prop = $obj2; $obj2->prop = $obj2; unset($obj1, $obj2);` even though I unset both objects, they won't be freed"
}
] |
[
{
"body": "<p>Give this a try and post the results - it integrates PHPBenchTime laps and get_memory_usage() with your script.</p>\n\n<p>\n\n<pre><code>require('PHPBenchTime.php');\nuse PHPBenchTime\\Timer as Timer;\n\npublic function fire(){\n $Benchmark = new Timer;\n $Benchmark->Start();\n\n $dt = new DateTime();\n Log::info(\"started: \".$dt->format('Y-m-d H:i:s'));\n $counter = 1;\n\n Item2::where('img_size', '=', NULL)->chunk(1000, function($items) use ( &$counter){\n $results = array();\n $filePath = storage_path().'/imports/new/new_img_sizes_'.$counter.'.csv';\n\n if (!File::exists($filePath)) {\n File::put($filePath, '');\n }\n $rollingCurl = new \\RollingCurl\\RollingCurl();\n $rollingCurl->setOptions($this->curlOptions);\n\n foreach ($items as $item){\n if ($item->img !== '') {\n $results[$item->id] = array('url' => $item->img, 'size' => null);\n $rollingCurl->get($item->img);\n }\n }\n\n //callback runs on each curl request\n $rollingCurl->setCallback(function(\\RollingCurl\\Request $request, \\RollingCurl\\RollingCurl $rollingCurl) use (&$results, $filePath) {\n $responseInfo = $request->getResponseInfo();\n //var_dump($responseInfo);exit;\n $length = $responseInfo['download_content_length'];\n\n foreach ($results as $key => $value) {\n if (array_search($request->getURL(),$value)) {\n $idKey = $key;\n $results[$idKey]['size'] = $length;\n File::append($filePath,$idKey.','.$results[$idKey]['size'].\"\\r\\n\");\n break;\n }\n }\n })\n\n ->setSimultaneousLimit(10)\n ->execute();\n\n Log::info('Last url was: '.json_encode(end($results)));\n\n $Benchmark->Lap(\"Lap \" . $counter . \" mem \" . memory_get_usage() . \" bytes\");\n\n $counter++;\n\n exit;\n }); // end item chunk\n\n\n $time = $Benchmark->End();\n print_r($time);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T19:02:31.213",
"Id": "70662",
"Score": "0",
"body": "While this is probably a valuable answer, it does not provide a *review* of the OP's code. Please add more details, explain how this solution is different/better than the original code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T19:12:07.070",
"Id": "70664",
"Score": "0",
"body": "@lol.upvote Wasn't really meant as a full answer - rather just integrated memory_get_usage and a timer. I'd rather the code reside here than in a gist or a pastebin."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T19:16:12.023",
"Id": "70667",
"Score": "1",
"body": "*I'd rather the code reside here than in a gist or a pastebin.* - and that's a good call, as a **link-only** answer would have been much worse. However **code-only** answers don't rank much higher. Feel free to edit whenever you have a chance :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T19:22:39.993",
"Id": "70670",
"Score": "0",
"body": "Please see [this meta question/answers](http://meta.codereview.stackexchange.com/questions/1463/short-answers-and-code-only-answers) for more info."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T19:37:23.020",
"Id": "70674",
"Score": "0",
"body": "Not to get in a spitting match here, but do note that I was commenting in codecowboy's question and this edited version of the code is requesting more information as I don't have access to codecowboy's environment. But if you'd like, I can make it a gist and just link it in a comment in their question."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T18:20:25.760",
"Id": "41173",
"ParentId": "40351",
"Score": "2"
}
},
{
"body": "<p>I don't see what could be causing ever-decreasing performance since the only state outside the main loop is a counter, but adding calls to <code>memory_get_usage</code> as @jsanc623 recommends would help with that.</p>\n\n<p>But you can definitely improve the performance by avoiding the loop over <code>$results</code> for every URL returned. Take advantage of PHP's array which is a hash table providing O(1) lookup.</p>\n\n<p>First, make the URL the key for the results array.</p>\n\n<pre><code>foreach ($items as $item) {\n if ($item->img !== '') {\n $url = $item->img;\n $results[$url] = array(\n 'id' => $item->id, \n 'url' => $url,\n 'size' => null\n );\n $rollingCurl->get($url);\n }\n}\n</code></pre>\n\n<p>Next, use <code>isset</code> instead of <code>array_search</code> and looping.</p>\n\n<pre><code>// foreach ($results as $key => $value) { ... } becomes\n\n$url = $request->getURL();\nif (isset($results[$url]) {\n $results[$url]['size'] = $length;\n File::append($filePath, $results[$url]['id'] . ',' . $length . \"\\r\\n\");\n}\n</code></pre>\n\n<p>Since you're placing each URL into the array before making the GET request, the <code>if</code> isn't even necessary.</p>\n\n<p>Separately, you can delay writing to the file until the end of the inner loop so you write one big chunk rather than one thousand tiny chunks. It may be that I/O is more costly, and perhaps you're getting killed by seeking to the end of an ever-growing file? Seems unlikely but maybe after a million writes it adds up.</p>\n\n<p><strong>General Review</strong></p>\n\n<p>There are a few things that could be cleaned up here as well.</p>\n\n<ul>\n<li>Consistent formatting: put your opening brace on the same line or the next, but do it consistently.</li>\n<li>Blank lines before the closing brace seem misplaced to me. Use blank lines to logically group related code, though functions are preferred to whitespace.</li>\n<li><p>Simplify testing if the image URL exists</p>\n\n<pre><code>if ($item->img !== '')\n</code></pre>\n\n<p>can be simplified to</p>\n\n<pre><code>if ($item->img)\n</code></pre>\n\n<p>to skip <code>null</code> values as well. Even if the field cannot be <code>null</code>, it's still easier to read.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T19:53:16.493",
"Id": "41178",
"ParentId": "40351",
"Score": "5"
}
},
{
"body": "<p>Be sure to disable Laravel's query logging and filter all unwanted results directly with your SQL query. Also use a stream to write lots of small chunks of data, it's much more efficient (and what streams where made for).</p>\n\n<p>Here's a possible solution, would love to see the benchmarking results for this one.</p>\n\n<pre><code><?php\n\nclass CodeReview {\n\n /**\n * Keep track of the Laravel chunk we're processing.\n *\n * @var integer\n */\n protected $counter = 1;\n\n /**\n * File handle of the current CSV file (writing only).\n *\n * @var resource\n */\n protected $fh;\n\n /**\n * Array to map image URLs to IDs.\n *\n * @var array\n */\n protected $urlToId = array();\n\n /**\n * Used for caching only.\n *\n * @var string\n */\n protected $storagePath;\n\n /**\n * ...\n *\n * @return this\n */\n public function fire() {\n // Directly format current time and embed variable.\n $date = \\DateTime::format(\"Y-m-d H:i:s\");\n Log::info(\"Started: {$date}\");\n\n // Get storage path once (why is this even a function?).\n $this->storagePath = storage_path();\n\n // Disable Laravel's query log, otherwise it will eat up our RAM.\n //\n // @link http://laravel.com/docs/database#query-logging\n DB::connection()->disableQueryLog();\n\n // Execute the query and filter all unwanted results right away. Don't use closures because they are slower than\n // native methods.\n Item2::whereNotNull(\"img_size\")->where(\"img_size\", \"<>\", \"''\")->chunk(1000, array($this, \"chunkedWhereCallback\"));\n\n return $this;\n }\n\n /**\n * Callback for the Laravel chunked WHERE query method.\n *\n * @internal Must be public in order to be accessible for PHP's call_user_func() function.\n * @param array $results\n * The chunked results from the Laravel WHERE query.\n * @return this\n */\n public function chunkedWhereCallback($results) {\n // Open file handle to CSV file.\n $this->fh = fopen(\"{$this->storagePath}/imports/new/new_img_sizes_{$this->counter}.csv\", \"w\");\n\n // Instantiate new rolling cURL and configure it.\n $rollingCurl = new \\RollingCurl\\RollingCurl();\n $rollingCurl->setOptions($this->curlOptions);\n\n // Micro benchmark\n $start = microtime(true);\n\n /* @var $result \\Namespace\\Of\\Stub\\Class\\ClassName */\n foreach ($results as $result) {\n // Build hash array for easy lookup.\n $this->urlToId[$result->img] = $result->id;\n\n // Add this image to the cURL queue.\n $rollingCurl->get($result->img);\n }\n\n // That's it, we added all images to the array, let's fetch them. Again we use a native method and no closure.\n $rollingCurl->setCallback(array($this, \"rollingCurlCallback\"))->setSimultaneousLimit(10)->execute();\n\n // Finished handling chunk, close CSV handle and increase counter.\n fclose($this->fh);\n ++$this->counter;\n\n $end = microtime(true) - $start;\n Log::info(\"1000 records: {$end}\");\n $last = end($this->urlToId);\n Log::info(\"Last URL was: {$last}\");\n\n return $this;\n }\n\n /**\n * Write image size to CSV file.\n *\n * @param \\RollingCurl\\Request $request\n * The rolling curl request.\n * @return this\n */\n public function rollingCurlCallback($request) {\n $size = $request->getResponseInfo()[\"download_content_length\"];\n $url = $request->getURL();\n\n if (fwrite($this->fh, \"{$this->urlToId[$url]},{$size}\\r\\n\") === false) {\n throw new \\RuntimeException(\"Couldn't write to CSV file!\");\n }\n\n return $this;\n }\n\n}\n</code></pre>\n\n<ul>\n<li>Format your code in a consistent fashion (stick to <a href=\"http://www.php-fig.org/psr/psr-2/\" rel=\"nofollow\">PSR-2</a> rules if you're unsure)</li>\n<li>Try to document your code where it makes sense for you, or for a developer that might have a look at it later</li>\n<li>Closures hurt readability, maintainability and performance (some may disagree with this, but in your case they definitely do because they are too long)</li>\n<li>Return <code>$this</code> by default if you have no return value (like in jQuery) and allow chaining of all your methods by default</li>\n<li>Forget about type checks if performance is all you want (they only add overhead); but don't forget that they are great for public APIs and other stuff (like you get it if you use a framework), it makes things easier for other developers</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T15:12:50.030",
"Id": "76487",
"Score": "0",
"body": "your setCallBack fatals with Catchable fatal error: Argument 1 passed to RollingCurl\\RollingCurl::setCallback() must be an instance of Closure, array given"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T15:48:37.403",
"Id": "76498",
"Score": "0",
"body": "Never actually tried the code, how could I, but this means the RollingCurl has a really, really poor implementation of it's callbacks because it seems like it's checking the instance instead of `is_callable()` and using e.g. `call_user_func()`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T00:52:32.873",
"Id": "41370",
"ParentId": "40351",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T10:44:31.297",
"Id": "40351",
"Score": "7",
"Tags": [
"php",
"performance",
"http",
"networking",
"concurrency"
],
"Title": "Concurrent HTTP request loop"
}
|
40351
|
<p>Obviously, you have to test mapping code somehow, even (or especially) if you use AutoMapper. Is there any way to make it less verbose?</p>
<pre><code>[Test]
public void Map_Always_SetsSimpleProperties()
{
var auctionPlace = fixture.Create<string>();
var submissionCloseDateTime = fixture.Create<DateTime>();
var quotationForm = fixture.Create<string>();
var quotationExaminationDateTime = fixture.Create<DateTime>();
var envelopeOpeningTime = fixture.Create<DateTime>();
var envelopeOpeningPlace = fixture.Create<string>();
var auctionDateTime = fixture.Create<DateTime>();
var applExamPeriodDateTime = fixture.Create<DateTime>();
var considerationSecondPartDate = fixture.Create<DateTime>();
var doc = fixture.Create<Notification223>();
doc.AuctionPlace = auctionPlace;
doc.SubmissionCloseDateTime = submissionCloseDateTime;
doc.QuotationForm = quotationForm;
doc.QuotationExaminationTime = quotationExaminationDateTime;
doc.EnvelopeOpeningTime = envelopeOpeningTime;
doc.EnvelopeOpeningPlace = envelopeOpeningPlace;
doc.AuctionTime = auctionDateTime;
doc.ApplExamPeriodTime = applExamPeriodDateTime;
doc.ConsiderationSecondPartDate = considerationSecondPartDate;
var sut = CreateSut();
var actual = sut.Map(doc);
Assert.That(actual.AuctionPlace, Is.EqualTo(auctionPlace));
Assert.That(actual.SubmissionCloseDateTime, Is.EqualTo(submissionCloseDateTime));
Assert.That(actual.QuotationForm, Is.EqualTo(quotationForm));
Assert.That(actual.QuotationExaminationDateTime, Is.EqualTo(quotationExaminationDateTime));
Assert.That(actual.EnvelopeOpeningTime, Is.EqualTo(envelopeOpeningTime));
Assert.That(actual.EnvelopeOpeningPlace, Is.EqualTo(envelopeOpeningPlace));
Assert.That(actual.AuctionDateTime, Is.EqualTo(auctionDateTime));
Assert.That(actual.ApplExamPeriodDateTime, Is.EqualTo(applExamPeriodDateTime));
Assert.That(actual.ConsiderationSecondPartDate, Is.EqualTo(considerationSecondPartDate));
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T11:34:35.757",
"Id": "68300",
"Score": "1",
"body": "If you put one assertion per test it doesn't look that verbose."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-10-27T08:41:31.413",
"Id": "339662",
"Score": "0",
"body": "I'm new in Unit Testing and I didn't know Automapper. What is `fixture.Create`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-10-28T04:48:47.537",
"Id": "339801",
"Score": "0",
"body": "@VansFannel it's actually from https://github.com/AutoFixture/AutoFixture"
}
] |
[
{
"body": "<p>Unfortunately, I don't think so.</p>\n\n<p>There is <a href=\"http://dozer.sourceforge.net/documentation/faq.html#dozer-unit-tests\" rel=\"nofollow\">a question about this topic on the website of Dozer</a> (which is a similar library for Java) which mentions a trick:</p>\n\n<blockquote>\n <p><strong>Should I write unit tests for data mapping logic that I use Dozer to perform?</strong></p>\n \n <p>[...]</p>\n \n <p>Regardless of whether or not you use Dozer, unit testing data mapping logic is tedious and a necessary evil, but there is a trick that may help. If you have an assembler that supports mapping 2 objects bi-directionally, in your unit test you can do something similar to the following example. This also assumes you have done a good job of implementing the <code>equals()</code> method for your data objects. The idea is that if you map a source object to a destination object and then back again, the original src object should equal the object returned from the last mapping if fields were mapped correctly. [...]</p>\n</blockquote>\n\n<p>I think this trick won't find bugs when, for example, <code>doc.ApplExamPeriodTime</code> is mapped to <code>actual.ConsiderationSecondPartDate</code> and\n<code>doc.ConsiderationSecondPartDate</code> is mapped to <code>actual.ApplExamPeriodTime</code>. I don't know that these kind of bugs are possible with AutoMapper or not.</p>\n\n<p>Furthermore, if you need only one directional mapping, I think the most simple solution is the one that's already in your question, I'd go with that. Adding code for the reverse mapping to the production code would be a test smell (<a href=\"http://xunitpatterns.com/Test%20Logic%20in%20Production.html\" rel=\"nofollow\">Test Logic in Production</a>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T03:36:55.810",
"Id": "68025",
"Score": "0",
"body": "Well, what if I actually need only one direction? I strongly dislike the idea of putting something in a public API just for sake of testing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T21:15:14.570",
"Id": "68170",
"Score": "0",
"body": "@vorou: I think in that case the only solution is that that you showed in your question. What method do you think of as putting it public for only testing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T09:22:59.260",
"Id": "68279",
"Score": "0",
"body": "I'm talking about reverse mapping, I don't have such method right now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T10:20:14.707",
"Id": "68461",
"Score": "0",
"body": "@vorou: I've update the answer a little bit."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T22:24:26.480",
"Id": "40403",
"ParentId": "40352",
"Score": "4"
}
},
{
"body": "<p>Yes, you can make it less verbose.</p>\n\n<p>I assume you are using AutoFixture in you call to Create()?</p>\n\n<p>If so, this will create random values out of the box. No need to specify the content and assign each property. Create the source object for mapping, map it, compare the mapped values with the properties on the source object:</p>\n\n<pre><code> [Test]\n public void Map_Always_SetsSimpleProperties()\n {\n var doc = fixture.Create<Notification223>(); // Autofixture will fill properties with random data.\n var sut = CreateSut();\n\n var actual = sut.Map(doc);\n\n Assert.That(actual.AuctionPlace, Is.EqualTo(doc.AuctionPlace));\n Assert.That(actual.SubmissionCloseDateTime, Is.EqualTo(doc.SubmissionCloseDateTime));\n Assert.That(actual.QuotationForm, Is.EqualTo(doc.QuotationForm));\n Assert.That(actual.QuotationExaminationDateTime, Is.EqualTo(doc.QuotationExaminationDateTime));\n Assert.That(actual.EnvelopeOpeningTime, Is.EqualTo(doc.EnvelopeOpeningTime));\n Assert.That(actual.EnvelopeOpeningPlace, Is.EqualTo(doc.EnvelopeOpeningPlace));\n Assert.That(actual.AuctionDateTime, Is.EqualTo(doc.AuctionDateTime));\n Assert.That(actual.ApplExamPeriodDateTime, Is.EqualTo(doc.ApplExamPeriodDateTime));\n Assert.That(actual.ConsiderationSecondPartDate, Is.EqualTo(doc.ConsiderationSecondPartDate));\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-17T09:49:03.983",
"Id": "224008",
"Score": "0",
"body": "Note that OmitAutoProperties will disable this functionality. It is on by default."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-17T09:29:16.420",
"Id": "120280",
"ParentId": "40352",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "40403",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T10:47:34.913",
"Id": "40352",
"Score": "7",
"Tags": [
"c#",
"unit-testing",
"automapper"
],
"Title": "Testing mapping code"
}
|
40352
|
<p>If have the following code that via an SQL query retrieves data from a database in the form:</p>
<pre class="lang-none prettyprint-override"><code>Id subschemaName locusName
MLST MLST LMO0558
MLST MLST LMO0563
MLVST MLVST LMO1305
MLVST MLVST LMO1089
</code></pre>
<p>And I want to turn this into an XML like:</p>
<pre class="lang-xml prettyprint-override"><code><ResponseSubschemas>
<organism>LMO</organism>
<Subschemas>
<Subschema>
<id>MLST</id>
<name>MLST</name>
<loci>
<locus>LMO0558</locus>
<locus>LMO0563</locus>
</loci>
</Subschema>
<Subschema>
<id>MLVST</id>
<name>MLVST</name>
<loci>
<locus>LMO1305</locus>
<locus>LMO1089</locus>
</loci>
</Subschema>
</Subschemas>
</ResponseSubschemas>
</code></pre>
<p>I do this by using a dictionary but it is the first time I'm using C# and I'm sure there must be a more efficient way of doing this in one go?</p>
<pre><code>string subschemaSQL = "SELECT subschema.Id, subschema.name as subschemaName, locus.Name as locusName " +
"FROM subschema " +
"LEFT JOIN subschemamembers ON subschemamembers.SubSchemaID = subschema.PrimKey " +
"LEFT JOIN locus ON subschemamembers.LocusID = locus.ID " +
"WHERE subschema.OrganismID = ? " +
"ORDER BY subschema.Id, locusName";
XElement rootNode = new XElement("ResponseSubschemas",
new XElement("organism", organismID),
new XElement("Subschemas"));
XElement subschemasNode = rootNode.Element("Subschemas");
DbDataReader subschemaReader = conn.Query(subschemaSQL, organismID);
Dictionary<string, List<string>> dictionary = new Dictionary<string, List<string>>();
while (subschemaReader.Read())
{
string subschemaDbID = (string)subschemaReader["Id"];
XElement subschemaNode = new XElement("Subschema",
new XElement("id", subschemaDbID),
new XElement("name", subschemaReader["subschemaName"])
);
subschemasNode.Add(subschemaNode);
string locusName = (string)subschemaReader["locusName"];
if (dictionary.ContainsKey(subschemaDbID))
{
dictionary[subschemaDbID].Add(locusName);
}
else
{
dictionary.Add(subschemaDbID, new List<string> { locusName });
}
}
IEnumerable<XElement> subschemaNodes = from element in
subschemasNode.Elements("Subschema")
select element;
foreach (XElement subschemaNode in subschemaNodes)
{
string subschemaID = subschemaNode.Element("id").Value;
XElement lociNode = new XElement("loci");
foreach (string locusName in dictionary[subschemaID])
{
XElement locusNode = new XElement("locus", locusName);
lociNode.Add(locusNode);
}
subschemaNode.Add(lociNode);
}
responseXml = rootNode.ToString();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T15:48:13.900",
"Id": "67961",
"Score": "0",
"body": "You could certainly be using Linq-to-Sql rather than hard coding sql strings. The result could then be easily transformed into Linq-to-Xml objects, though I definitely don't understand why you'd want to copy a database to xml."
}
] |
[
{
"body": "<p>Since your data is already sorted you definitely don't need to use a dictionary. You can just accumulate <code>loci</code> and then whenever the <code>id</code> or <code>subschemaId</code> rolls over you write them all out. That wouldn't be a huge change from what you've got. But honestly, what you've got is a bit confusing because you're trying to do several things at once. Namely:</p>\n\n<ul>\n<li>Read from the database and parse the data</li>\n<li>Determine when you've read an entire set of data</li>\n<li>Write it all to XML</li>\n</ul>\n\n<p>It would be easier to figure out what's going on by separating those things out from each other. It might also make your life easier if you ever want to do anything more complex with this data than just dumping it to XML. So let's just do a little rewrite. </p>\n\n<p>To start with, let's create a class to hold each of those <code>Subschema</code> elements. (Honestly <code>Subschema</code> seems like a confusing name to me, it seems like maybe <code>OrganismLocations</code> or <code>OrganismSightings</code> might be more descriptive, but let's just stick with <code>Subschema</code>.)</p>\n\n<pre><code>public class Subschema{\n public string Id {get;set;}\n public string Name {get;set;}\n public List<string> Loci {get;set;}\n\n public Subschema(){\n Loci = new List<string>();\n }\n}\n</code></pre>\n\n<p>Now, let's write a function to parse the database records out into a list of <code>Subschema</code> objects. This is basically doing what I said earlier - tracking <code>loci</code> until we hit a new <code>id</code> or <code>subschemaName</code>. We're using C# iterators (that's the <code>yield return</code> syntax) to make this a little bit cleaner.</p>\n\n<pre><code>private IEnumerable<Subschema> ParseSubschemas(DbDataReader subschemaReader){\n if(!subschemaReader.HasRows){\n yield break;\n }\n\n Subschema subschema = null;\n\n while(subschemaReader.Read()){\n //If we've rolled over to a new ID or SubschemaName, start a new set of sightings\n if(subschema != null && (subschema.Id != (string)subschemaReader[\"id\"] || subschema.Name != (string)subschemaReader[\"subschemaName\"])){\n yield return subschema;\n subschema = null;\n }\n\n if(subschema == null){\n subschema = new Subschema(){\n Id = (string)subschemaReader[\"id\"],\n Name = (string)subschemaReader[\"subschemaName\"]\n };\n }\n\n subschema.Loci.Add((string)subschemaReader[\"locusName\"]);\n }\n\n //yield the last subschema\n yield return subschema;\n}\n</code></pre>\n\n<p>So now we have a nice, clean list of the data you need to output. Basically we've handled the first and second bullets from my list, so all that's left is turning that into XML. There's probably a cleaner way of doing this than using <code>XElement</code>s directly, but let's just stick with it for the moment. But again, let's stick all the logic in a nice clean function.</p>\n\n<pre><code>private XElement SerializeSubSchemasToXml(string organismId, IEnumerable<Subschema> sightings){\n XElement rootNode = new XElement(\"ResponseSubschemas\", \n new XElement(\"organism\", organismId),\n new XElement(\"Subschemas\"));\n XElement subschemasNode = rootNode.Element(\"Subschemas\");\n\n //Turn each Sighting into an XElement, and append to the subschemas\n foreach(var sighting in sightings){\n var subschemaElem = new XElement(\"Subschema\", \n new XElement(\"id\", sighting.Id),\n new XElement(\"name\", sighting.Name),\n new XElement(\"Loci\", sighting.Loci.Select(l => new XElement(\"locus\", l))) \n );\n\n subschemasNode.Add(subschemaElem);\n }\n\n return rootNode;\n}\n</code></pre>\n\n<p>Pretty straightforward here. We could've written this more succinctly, probably even in a (really big) one liner, but this strikes a reasonable balance with clarity, I think. </p>\n\n<p>So, now we just have to put those two together...</p>\n\n<pre><code>private string ReadSubschemasAsXml(){\n string organismId = \"FOO\";\n string subschemaSQL = \"SELECT subschema.Id, subschema.name as subschemaName, locus.Name as locusName \" + \n \"FROM subschema \" +\n \"LEFT JOIN subschemamembers ON subschemamembers.SubSchemaID = subschema.PrimKey \" +\n \"LEFT JOIN locus ON subschemamembers.LocusID = locus.ID \" +\n \"WHERE subschema.OrganismID = ? \" +\n \"ORDER BY subschema.Id, locusName\";\n\n using(DbDataReader subschemaReader = conn.Query(subschemaSQL, organismId)){\n IEnumerable<Subschema> sightings = ParseSubschemas(subschemaReader);\n XElement xelem = SerializeSubSchemasToXml(organismId, sightings);\n return xelem.ToString();\n }\n}\n</code></pre>\n\n<p>That last function isn't really a thing of beauty either - it's got kind of a lot going on. But it's definitely better. I also added a <code>using</code> statement around your <code>DbDataReader</code>, which is just a handy way of making sure that it gets <code>Dispose()</code>d properly. </p>\n\n<p>By the way, I put up a <a href=\"http://dotnetfiddle.net/6m6iIe\" rel=\"nofollow\">DotNetFiddle of the whole thing</a>. It doesn't work because I don't have a database to use, but it might be easier to read there. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T03:36:23.607",
"Id": "68240",
"Score": "0",
"body": "I guess you could use the XmlSerializer class to serialize to XML."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T15:03:05.830",
"Id": "68351",
"Score": "1",
"body": "@dreza, yes you could. You'd have to create another class to handle the wrapper XML structure, but it wouldn't be too hard."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T18:55:59.643",
"Id": "68498",
"Score": "0",
"body": "Your `ParseSubschemas()` will return a sequence containing `null` when the input is empty, I think that's wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-02T16:15:40.443",
"Id": "68593",
"Score": "0",
"body": "@svick - good point. I modified it to return an empty enumerable instead."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T20:01:05.767",
"Id": "40486",
"ParentId": "40353",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "40486",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T11:06:35.520",
"Id": "40353",
"Score": "3",
"Tags": [
"c#"
],
"Title": "Refactor C# code for creating XML to not use intermediate dictionary"
}
|
40353
|
<p>We have a table with calculated data that groups sales by product, year and month, to provide fast querying for statistics.</p>
<p>My colleague argues that the year and month should be two separate fields, because a day is meaningless.</p>
<p>I want it as a date field, because using two separate fields leads to awkward code like this</p>
<pre><code>var lastTwelveMonths = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-11);
var result = data.Where(item =>
(item.Year > lastTwelveMonths.Year
|| (item.Year == lastTwelveMonths.Year && item.Month >= lastTwelveMonths.Month));
</code></pre>
<p>instead of this</p>
<pre><code>var lastTwelveMonths = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-11);
var result = data.Where(item => item.YearAndMonthAsDate >= lastTwelveMonths);
</code></pre>
<p>I understand his argument, but the code is harder to read and there's a higher chance on bugs when doing date/time calculations without using date/time objects. I also can't cast it to a <code>DateTime</code> in the query because I'm using LINQ to Entities.</p>
<p>Which method is the better one?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T12:27:33.107",
"Id": "67938",
"Score": "0",
"body": "Does the information come from a database or where does it come from? If it's a database, which kind of RDMS is it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T12:28:05.200",
"Id": "67939",
"Score": "0",
"body": "@SimonAndréForsberg It comes from a database, SQL Server 2008 R2."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T17:24:23.017",
"Id": "67967",
"Score": "0",
"body": "In the chat you asked for a linq-to-entities tag, would the already existing tag [tag:entity-framework] work?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T22:06:22.507",
"Id": "68001",
"Score": "0",
"body": "@Simon It didn't occur to me to try that tag, I've added it together with [tag:linq]. Feel free to edit the tags though :)"
}
] |
[
{
"body": "<p>In general it really depends on the use cases of your data. If you need to perform queries using just year or just month then you reduce complexity in the code and queries by having separate fields.</p>\n\n<p>However, if you aren't bounding by just a year or just a month then you would want to use a date field.</p>\n\n<p>Professionally I use date or string fields (YYYYMMDD) when representing dates and times because the speedup you get from single year/month fields is small with todays databases (assuming things are correctly indexed).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T12:31:16.883",
"Id": "40358",
"ParentId": "40356",
"Score": "7"
}
},
{
"body": "<p>If you're looking for an argument by authority, consider Microsoft's aversion to <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms724451.aspx\" rel=\"nofollow\">GetVersionEx</a> and in particular misuse of the <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms724833.aspx\" rel=\"nofollow\">OSVERSIONINFOEX structure</a> in calculations that look suprisingly similar. By analogy to the reasons they shim the results from GetVersionEx for program compatibility, it's apparently far to easy to write code that means to say \"After February 2010\" as <code>month > 2 && year > 2010</code>, when the correct code is the more complicated <code>year > 2010 || (year == 2010 && month > 2)</code> as your example shows.</p>\n\n<p>Per a lack of understanding of the limitations of <a href=\"http://msdn.microsoft.com/en-us/library/bb386964.aspx\" rel=\"nofollow\">LINQ to entities</a>, I thought your \nexample was needlessly complex, and exhibited a flawed argument. After all, if you can compare to a <code>DateTime</code> that you've just constructed, and can do the complex logic, why not just encapsulate it back into the <code>DateTime</code> class?</p>\n\n<pre><code>var lastTwelveMonths = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-11);\nvar result = data.Where(item => new DateTime(item.Year, item.Month, 1) >= lastTwelveMonths));\n</code></pre>\n\n<p>However as you clarified in your comments below, L2E does not support creating a <code>DateTime</code> from separate columns inside a <code>Where</code> expression. Instead it's mapping the comparison <code>DateTime lastTwelveMonths</code> date into database queries, and is unable to map from my counterexample to the same queries as generated in your first example.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T14:38:09.913",
"Id": "68083",
"Score": "0",
"body": "I specifically covered that in my question: *I also can't cast it to a DateTime in the query because I'm using LINQ to Entities.* Other than that, good answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T13:21:58.373",
"Id": "68322",
"Score": "0",
"body": "@Stijn There must be a subtlety here that I don't understand (I don't have much experience with LINQ yet), as my counterexample uses the approach of your second example with the data of the first; if my counterexample cannot be done, I don't see how your second example can work either."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T13:42:04.793",
"Id": "68325",
"Score": "0",
"body": "It's a subtle difference indeed. In my second example, `item.YearAndMonthAsDate` is a date field in the database, which translates to a `DateTime` in a L2E query. In your example, `item.Year` and `item.Month` are numeric fields in the database and you try to create a `DateTime` object in the query. This leads to a first problem: *Only parameterless constructors and initializers are supported in LINQ to Entities.*"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T13:43:35.473",
"Id": "68326",
"Score": "0",
"body": "No worries, you might think, I'll just use the parameterless constructor and do something like this: `new DateTime().AddYears(item.Year - 1).AddMonths(item.Month - 1) >= lastTwelveMonths`. This doesn't work either, because it cannot be translated to an SQL query: *LINQ to Entities does not recognize the method 'System.DateTime AddMonths(Int32)' method, and this method cannot be translated into a store expression.* In short, some things possible in L2O are not possible in L2E."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T13:56:14.740",
"Id": "68329",
"Score": "0",
"body": "Thanks for the explanation! I'll update my answer accordingly."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T13:29:32.437",
"Id": "40458",
"ParentId": "40356",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "40358",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T12:19:28.963",
"Id": "40356",
"Score": "8",
"Tags": [
"c#",
"linq",
"sql-server",
"entity-framework",
"datetime"
],
"Title": "Should a year and month be stored as separate fields or as a date?"
}
|
40356
|
<p>In my program(C++), I'm going to use callback functions to process input from the keyboard and mouse and constantly draw a scene. How these functions process information will change depending on the state of the program; like I would have certain functionality assigned to several keys, say the arrow keys move the highlighter in the main screen, but I want their functionality to change in another screen. I'm using OpenGL with GLUT, and it's possible to change the keyboard function for example by assigning a different function pointer to it.</p>
<p>The method I used in the past was to define multiple processing functions, each one for a specific task. For example, I have a keyboard for the main menu, but when a different screen is viewed, the function is changed by assigning the appropriate function pointer:</p>
<pre><code>glutKeyboardFunction(MainMenueKeyboardFuncPtr);
</code></pre>
<p>But now, I'm wondering if using conditional statements within one function is a better approach.</p>
<p><strong>My question</strong> is: are there any performance issues with the conditional functions approach? I'm thinking to define a single function, say for the keyboard, to process keyboard input in all situations:</p>
<pre><code>void KeyInputProcess(int key)
{
select(SCREEN)
{
case MAIN_SCREEN:
select(key)
{
/*process input*/
}
break;
case OPTIONS_SCREEN:
select(key)
{
/*process differently from MAIN_SCREEN*/
}
break;
}
}
</code></pre>
<p>Would the checking that takes place every time the function is called have a significant impact on the performance? Which approach is better if I want to maximize performance?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T13:21:58.550",
"Id": "67947",
"Score": "1",
"body": "It's C++. I changed the tag and I'll add it in the body of the question."
}
] |
[
{
"body": "<blockquote>\n <p>My question is: are there any performance issues with the conditional functions approach?</p>\n</blockquote>\n\n<p>In a word: no.</p>\n\n<p>The additional performance cost is an extra <code>select</code> statement, whose cost probably depends on the number of <code>switch</code> options in the <code>select</code>.</p>\n\n<p>I say \"no\" because I expect that the performance cost for a few extra instructions is measured in nanoseconds: and there aren't enough keystrokes per second for that to make a difference. Also the actual work you do (i.e. calling OpenGL functions) is probably/hopefully more significant than the performance of the code required to get there; it's like, \"Q: Is calling a subroutine expensive? A: Probably not as expensive as executing/running the subroutine.\"</p>\n\n<p>The befit of using \"function pointers\" (or perhaps a different subclass for each screen) is more to do with the code's maintainability and readability: for example, it would let you have different people creating each screen; to be contrasted with having a single KeyInputProcess function, where all handling for every screen is defined in the same function.</p>\n\n<p>Taking the trouble to create an abstract base class for a screen (with concrete subclasses for specific screens, and a virtual KeyInputProcess method) may make more code more maintainable (easier to add new functionality without changing existing functionality, nor requiring previously-simple methods to become too complicated)\nOn the other hand, for a smaller project with one programmer, defining many abstract and concrete classes might be '<a href=\"http://en.wikipedia.org/wiki/Overengineering\" rel=\"nofollow\">over-engineering</a>' (the Wikipedia article for over-engineering says, \"See also: <a href=\"http://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"nofollow\">YAGNI</a>\"). Beware that if you practice YAGNI then, later when you do need it, you ought to be good at refactoring: i.e. adding structure later to previously less-structured code, where I'd regard \"conditional statements within one function\" as 'less structured' and \"abstract base class with subclasses\" as 'more structured'.</p>\n\n<blockquote>\n <p>Which approach is better if I want to maximize performance?</p>\n</blockquote>\n\n<p>Possibly a function pointer: because it's only one or two opcodes to dispatch to the right function, instead of testing several switch statements (assuming that the compiler implements <code>select</code> as \"if else if else if else if\").</p>\n\n<p>It's also possible that a function pointer isn't as fast: it dispatches to a different location i the code, which may cause slowness due to memory pages and CPU caching; whereas instead a monolithic KeyInputProcess function might have all its code located on the same page of memory.</p>\n\n<p>In either case I doubt whether the performance difference is significant in this case (handling keystrokes).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T13:36:46.450",
"Id": "40363",
"ParentId": "40362",
"Score": "2"
}
},
{
"body": "<blockquote>\n <p>are there any performance issues with the conditional functions approach? </p>\n</blockquote>\n\n<p>No.</p>\n\n<blockquote>\n <p>Would the checking that takes place every time the function is called have a significant impact on the performance?</p>\n</blockquote>\n\n<p>No</p>\n\n<blockquote>\n <p>Which approach is better if I want to maximize performance?</p>\n</blockquote>\n\n<p>Insignificant difference.</p>\n\n<p>But neither is the method I would use (not for performance but for maintenance).<br>\nI would either change the callback used by GLUT as the screen changed, or I would pick the function from a vector:</p>\n\n<pre><code>typedef void (*KEYINPUTPROCESS)(int);\nKEYINPUTPROCESS keyboardProcessingFunctions[] = {\n KeyInputProcessMain, \n KeyInputProcessMainOptions\n};\n\nvoid KeyInputProcess(int key)\n{\n KEYINPUTPROCESS procFunc = keyboardProcessingFunctions[SCREEN];\n return procFunc(key);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T22:31:30.800",
"Id": "40405",
"ParentId": "40362",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "40363",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T13:17:00.670",
"Id": "40362",
"Score": "2",
"Tags": [
"c++",
"callback"
],
"Title": "Conditional functions or multiple similar definitions?"
}
|
40362
|
<p>I have learned the question of solving Angular app optimization for search engines, and was frustrated that the most recommended option is <strong>prerendering</strong> HTML.</p>
<p>After some time spent, I suggested to create a directive that will load the bot after rendering templates or update <strong>scope</strong>. </p>
<p><strong>Directive:</strong></p>
<pre><code>angular.module('test', []).directive('seoBot', ['$timeout', function($timeout){
return {
link: function($scope, element, attrs) {
//publish event
$scope.$on('runbot', function(){
//hint for start after render
$timeout(function () {
//find previos google's bot
var googleBot = document.getElementById('googleBot');
//if found - remove
if(googleBot) googleBot.parentNode.removeChild(googleBot);
//this is standard code from GA, but with ID "googleBot"
(function(i,s,o,g,r,a,m){
i['GoogleAnalyticsObject']=r;
i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)
},i[r].l=1*new Date();
a=s.createElement(o),
m=s.getElementsByTagName(o)[0];
a.id="googleBot";
a.async=1;
a.src=g;
m.parentNode.insertBefore(a,m);
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-46685745-1', 'rktdj.com');
ga('send', 'pageview');
//log that bot is loaded
console.log("seo-bot loaded");
//check page to be rendered completely
console.log(document.body.innerHTML);
}, 0, false);
});
}
};
}]);
</code></pre>
<p><strong>In controller:</strong></p>
<pre><code>//get some data from server and update scope
$http.get(GLOBAL.api.SERVER_PATH + GLOBAL.api.facultiesByCourse + s_id)
.success(function (data) {
$scope.courses = data;
console.dir($scope.courses);
//broadcast event to seo-bot
$scope.$broadcast('runbot');
} );
</code></pre>
<p><strong>seo-bot</strong> tag in the bottom of template: </p>
<pre><code> <div class="well" id="courseList">
<!-- some template code -->
</div>
<div seo-bot></div>
</code></pre>
<p>It works, and the bot loads every time when template have update or route changed.
I can check that all elements with data was rendered before.</p>
<p>But... will this solution really work? Will Google bot correctly correlate rendered page with the domain? Can I be banned for this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T20:22:00.303",
"Id": "77931",
"Score": "0",
"body": "Do you make the difference between the google bot and google analytics? The googlebot (search engine) is not executing the javascript (at least most of the time it is not...). This is why you need to pre-render the page if the request comes from the google bot. If you are talking about google analytics then alright your solution will work. Though I would suggest you to take a look at this project http://luisfarzati.github.io/angulartics/. It does exactly what you are trying to do and even more."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-31T13:58:44.713",
"Id": "111913",
"Score": "0",
"body": "Wawaweewa it's a very nice!"
}
] |
[
{
"body": "<p>As you found yourself, this has to work.</p>\n\n<p>I only have 2 minor nitpickings:</p>\n\n<ul>\n<li>Do not use <code>console.log()</code> in production code..</li>\n<li>You are not using <code>element</code> and <code>attrs</code>, you might as well declare <code>function($scope)</code></li>\n</ul>\n\n<p>Very nice code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T21:51:48.307",
"Id": "40396",
"ParentId": "40364",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T13:42:28.943",
"Id": "40364",
"Score": "7",
"Tags": [
"javascript",
"optimization",
"angular.js",
"web-scraping"
],
"Title": "AngularJs and Google Bot experiment"
}
|
40364
|
<p>I wanted to write a small but non-trivial function in OCaml to test my understanding. I have only a basic understanding of the libraries, and no idea at all of what is considered good style. The function computes all combinations of size <code>k</code> from a list, where <code>0 <= k <= length lst</code>.</p>
<p>Would someone mind commenting on</p>
<ol>
<li><p>Whether the function is generally well written (have I covered all cases, are there opportunities for tail recursion that I've missed?)</p></li>
<li><p>Have I made good use of libraries (e.g. I defined <code>is_empty</code> and <code>tails</code> because I couldn't find them in the <code>List</code> module, but maybe they are somewhere else?)</p></li>
<li><p>Is the style okay, particularly the use of <code>let</code> statements and indentation?</p></li>
</ol>
<p>The code is:</p>
<pre><code>let rec tails = function
| [] -> []
| _ :: t as l -> l :: tails t
let is_empty = function
| [] -> true
| _ -> false
let rec combnk k lst =
if k = 0 then [[]]
else let f = function
| [] -> [] (* I think this is unnecessary, but I get a pattern match warning o/w *)
| x :: xs -> List.map (fun z -> x :: z) (combnk (k-1) xs)
in if is_empty lst then []
else List.concat (List.map f (tails lst))
</code></pre>
<hr>
<p>Based on the excellent comments by amon (see below) I have written to what I think is the most readable version of this function, which is the one that inlines the definition of <code>tails</code> and gets rid of <code>is_empty</code> completely, but doesn't go all the way to removing the use of <code>List.concat</code> and <code>List.map</code>, because I believe in using library functions to simplify the code wherever possible.</p>
<p>In particular, the layout guidelines make the structure of the function much clearer, and I think that in this version it is obvious what algorithm is being used, whereas it is somewhat obfuscated in the original. Thanks, amos!</p>
<pre><code>let rec combnk k lst =
if k = 0 then
[[]]
else
let rec inner = function
| [] -> []
| x :: xs -> List.map (fun z -> x :: z) (combnk (k - 1) xs) :: inner xs in
List.concat (inner lst)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-19T10:23:07.113",
"Id": "102715",
"Score": "0",
"body": "Like many, I tend to align the rhs of match arrows, but this style is actually discouraged from the official guidelines: http://caml.inria.fr/resources/doc/guides/guidelines.en.html#idp1191136"
}
] |
[
{
"body": "<p>Your <code>tails</code> is very beatiful, your <code>is_empty</code> useless, and <code>combnk</code> a mess.</p>\n\n<p>In <code>combnk</code>, your indentation obfuscates the actual structure of the code. Here is a better indentation:</p>\n\n<pre><code>let rec combnk k lst =\n if k = 0 then\n [[]]\n else\n let f = function\n | [] -> []\n | x :: xs -> List.map (fun z -> x :: z) (combnk (k - 1) xs)\n in\n if is_empty lst then\n []\n else\n List.concat (List.map f (tails lst))\n</code></pre>\n\n<p>Now there are some interesting observations to be made here: The branch <code>if is_empty lst then []</code> does not access <code>f</code>, so we could move this test outside of the <code>let</code>:</p>\n\n<pre><code>let rec combnk k lst =\n if k = 0 then\n [[]]\n else if is_empty lst then\n []\n else\n let f = function\n | [] -> []\n | x :: xs -> List.map (fun z -> x :: z) (combnk (k - 1) xs)\n in\n List.concat (List.map f (tails lst))\n</code></pre>\n\n<p>But is the <code>is_empty</code> test actually necessary? <code>tails []</code> produces an empty list, <code>List.map f []</code> produces an empty list for any function <code>f</code>, and <code>List.concat []</code> also produces an empty list. We now have:</p>\n\n<pre><code>let rec combnk k lst =\n if k = 0 then\n [[]]\n else\n let f = function\n | [] -> []\n | x :: xs -> List.map (fun z -> x :: z) (combnk (k - 1) xs)\n in\n List.concat (List.map f (tails lst))\n</code></pre>\n\n<p>How can this be improved? We can move the <code>tails</code> definitions inside the else-branch <code>let</code> so that it's restricted to the only scope where it is used:</p>\n\n<pre><code>let rec combnk k lst =\n if k = 0 then\n [[]]\n else\n let rec tails = function\n | [] -> []\n | _ :: t as l -> l :: tails t\n and f = function\n | [] -> []\n | x :: xs -> List.map (fun z -> x :: z) (combnk (k - 1) xs)\n in\n List.concat (List.map f (tails lst))\n</code></pre>\n\n<p>Regarding the question whether the case <code>[] -> []</code> in <code>f</code> is necessary except for the type system: The answer is <em>no</em>, as the list produced by <code>tails</code> cannot contain another empty list – <code>l :: []</code> is <code>l</code> again. This would change when you swap <code>[] -> []</code> in <code>tails</code> for <code>[] -> [[]]</code>, which would be arguably more correct.</p>\n\n<p>Now that <code>f</code> and <code>tails</code> are so close together you may notice some similarities. Indeed, we can combine the two directly, thus getting rid of one <code>map</code>:</p>\n\n<pre><code>let rec combnk k lst =\n if k = 0 then\n [[]]\n else\n let rec inner = function\n | [] -> []\n | x :: xs -> (List.map (fun z -> x :: z) (combnk (k - 1) xs)) :: inner xs\n in\n List.concat (inner lst)\n</code></pre>\n\n<p>Of course, <code>inner</code> could be made partially tail recursive (but this reverses the order of combinations):</p>\n\n<pre><code>let rec combnk k lst =\n if k = 0 then\n [[]]\n else\n let rec inner acc = function\n | [] -> acc\n | x :: xs ->\n let this_length = List.map (fun z -> x :: z) (combnk (k - 1) xs)\n in\n inner (this_length :: acc) xs\n in\n List.concat (inner [] lst)\n</code></pre>\n\n<p>There is still an indirect recursion through <code>combnk</code>, more obvious if we rewrite it like this:</p>\n\n<pre><code>let rec combnk k lst =\n let rec inner acc k lst =\n match k with\n | 0 -> [[]]\n | _ ->\n match lst with\n | [] -> List.flatten acc\n | x :: xs ->\n let this_length = List.map (fun z -> x :: z) (inner [] (k - 1) xs)\n in\n inner (this_length :: acc) k xs\n in\n inner [] k lst\n</code></pre>\n\n<p>Now all that is left to do is to write a <code>map</code> that takes an external accumulator, thus also removing the need for <code>flatten</code> or <code>concat</code>:</p>\n\n<pre><code>let rec combnk k lst =\n let rec inner acc k lst =\n match k with\n | 0 -> [[]]\n | _ ->\n match lst with\n | [] -> acc\n | x :: xs ->\n let rec accmap acc f = function\n | [] -> acc\n | x :: xs -> accmap ((f x) :: acc) f xs\n in\n let newacc = accmap acc (fun z -> x :: z) (inner [] (k - 1) xs)\n in\n inner newacc k xs\n in\n inner [] k lst\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T21:17:46.573",
"Id": "67994",
"Score": "0",
"body": "Thanks a lot. I think your version with `tails` inlined (fifth code block) is clearest."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T17:23:08.833",
"Id": "40380",
"ParentId": "40366",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "40380",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T14:14:40.107",
"Id": "40366",
"Score": "8",
"Tags": [
"recursion",
"functional-programming",
"ocaml"
],
"Title": "Combinations of size k from a list in OCaml"
}
|
40366
|
<p>The intent of this script is to hunt down all <code>"*/testResults/*.xml"</code> files and touch them, so that our build system doesn't issue errors that the files are too old (it's entirely intentional that tests are only re-run when the libraries they change have been modified)</p>
<pre><code>import fnmatch
import os
import time
matches = []
# Find all xml files (1)
for root, dirnames, filenames in os.walk('.'):
for filename in fnmatch.filter(filenames, '*.xml'):
matches.append(os.path.join(root, filename))
# filter to only the ones in a "/testResults/" folder (2)
tests = [k for k in matches if "\\testResults\\" in k]
t = time.time()
# touch them
for test in tests:
os.utime(test,(t,t))
</code></pre>
<p>Is there a simpler way to achieve this? Specifically to perform steps (1) and (2) in a single process, rather than having to filter the matches array? An alternative solution would be to just recursively find all folders called "/testResults/" and list the files within them.</p>
<p>Notes:</p>
<ul>
<li><p>This script would also find "blah/testResults/blah2/result.xml" - I'm not worried about that, as the testResults folders will only contain test result xml files (but not all xml files are test results!)</p></li>
<li><p>This runs on Windows.</p></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T01:22:01.543",
"Id": "68020",
"Score": "0",
"body": "I don't think recursion is a good solution for this problem at all. You're initial solution is better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T09:13:41.710",
"Id": "68054",
"Score": "0",
"body": "I meant recursively in a filesystem sense (i.e. it could be /a/testResults/ or /a/b/testResults/ etc), not in a recursive function sense."
}
] |
[
{
"body": "<p>Python seems like overkill here: this is surely a job for the shell? Depending on exactly which files you want to touch, then use this:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>touch -- */testResults/*.xml\n</code></pre>\n\n<p>or this:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>find . -path '*/testResults/*.xml' -exec touch -- {} \\+\n</code></pre>\n\n<hr>\n\n<p>You indicated that you are using Windows. But even on Windows, surely a PowerShell script (using <a href=\"http://technet.microsoft.com/en-us/library/hh849800.aspx\" rel=\"nofollow\"><code>Get-ChildItem</code></a> instead of <code>find</code> and <a href=\"http://technet.microsoft.com/en-us/library/hh849844.aspx\" rel=\"nofollow\"><code>Set-ItemProperty -Name LastWriteTime</code></a> instead of <code>touch</code>) would be simplest?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T16:06:18.737",
"Id": "67964",
"Score": "0",
"body": "Yes, Windows I'm afraid!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T16:08:03.213",
"Id": "67965",
"Score": "1",
"body": "I've updated your question accordingly."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T16:05:16.547",
"Id": "40374",
"ParentId": "40370",
"Score": "3"
}
},
{
"body": "<pre><code>import os,glob,time\nt = time.time()\ndef touchy(fpath):\n os.utime(fpath,(t,t))\n return fpath\n\ndef findResults(directory = \"/\"):\n results = [] \n search_path = os.path.join(directory,\"testResults/*.xml\")\n for d in filter(os.path.isdir,os.listdir(directory)): \n results.extend( map(touchy,glob.glob(search_path)) if d == \"testResults\" else findResults(os.path.join(directory,d))\n return results\n</code></pre>\n\n<p>is probably about the best you can do if you want python</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T18:09:30.997",
"Id": "67977",
"Score": "0",
"body": "Can you revise this to avoid the long line?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T18:12:46.943",
"Id": "67980",
"Score": "0",
"body": "there its shorter lines ... still probably not quite pep-8"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T18:04:16.400",
"Id": "40383",
"ParentId": "40370",
"Score": "0"
}
},
{
"body": "<p>For combining (1) and (2) you can reverse the sort by only trying if your are under a test directory</p>\n\n<p>Also this is a great use for a generator / map combo to avoid extra loops</p>\n\n<pre><code>import os \nimport re\n\nis_xml = re.compile('xml', re.I)\nis_test = re.compile('testResults', re.I)\n\ndef find_xml_tests(root):\n for current, dirnames, filenames in os.walk(root):\n if is_test.search(current):\n for filename in filter(lambda p: is_xml.search(p), filenames):\n yield os.path.normpath(os.path.join(current, filename))\n\ndef touch(filename ):\n os.utime(test,(time.time(),time.time()))\n\nmap(touch, find_xml_tests('path/to/files'))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T21:23:13.837",
"Id": "40395",
"ParentId": "40370",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T15:35:51.947",
"Id": "40370",
"Score": "3",
"Tags": [
"python",
"recursion",
"file-system",
"windows"
],
"Title": "Python script to touch files of a particular pattern in all folders of a given name"
}
|
40370
|
<p>I'm relatively new to unit testing and having gone through quite a bit of pain I was starting to feel pretty good about my tests. The problem is, now I have a nice set of green ticks I'm also suffering from the nagging doubt that it's just giving me a false sense of security and is in fact just a waste of time. </p>
<p>I have included an example of a method under test and all its accompanying unit tests. My approach was to try and use spies to ensure only the method itself was being tested (the intention being that other methods will be covered in their own tests). So for example my validation methods throw an exception when a value fails validation but these are caught and ignored here, and only the fact the validation is called with the correct parameters is tested.</p>
<p>Writing these tests felt pretty good, but now I can't really see the point of them. The only thing which can break these tests is a change to this specific method and surely if anybody is changing this method they are doing so with good reason, and all I've done is given them an extra job of changing the tests.</p>
<p>I can definitely say that writing these tests caused me to make several improvements to the way I wrote the method under test so there is benefit from that point of view but the unit tests which are left behind feel a bit redundant.</p>
<p>So am I wrong in my approach? Or in my analysis of the value my approach? There are so many evangelists for unit testing - many of whom are far cleverer than me - so I'm pretty sure it's me that's wrong somewhere.</p>
<p>Method under test:</p>
<pre><code>/**
* Calculate the physical centre x co-ordinate for the passed unscaled value
* @param {string} unscaledValue - The logical cx value to be converted to a physical value. It could be a string for category axes or a number for measure axes.
* @param {number} [innerBarCount] - The number of small bars within a bar group. This is only required for multiple category axes.
* @param {number} [offset] - The zero based index of an inner bar within a bar group. This is only required for multiple category axes.
*/
this._getCx = function (unscaledValue, innerBarCount, offset) {
var returnCx = 0;
// Validate the required parameters and properties
dimple.validation._isDefined("x axis", this.x);
dimple.validation._isDefined("unscaledValue", unscaledValue);
// Act based on axis types
if (this.x._hasMeasure() || this.x._hasTimeField()) {
// Measures can return a straight scale
returnCx = this.x._scaleValue(unscaledValue);
}
else if (this.x._hasMultipleCategories()) {
// For multiple categories the second two parameters are required
dimple.validation._isPositiveNumber("innerBarCount", innerBarCount);
dimple.validation._isPositiveNumber("offset", offset);
// Scale to get the left position and then calculate the inner position of the bar based on offset
// plus a half accounting for bar gaps
returnCx = this.x._scaleValue(unscaledValue) + this._xBarGap() + (offset + 0.5) * (this._xBarSize() / innerBarCount);
} else if (this.x._hasCategories()) {
// Scale to get the left position of the bar and add half the bar size to get the centre
returnCx = this.x._scaleValue(unscaledValue) + (this.x._pointSize() / 2);
} else {
throw dimple.exception.unsupportedAxisState("x");
}
return returnCx;
};
</code></pre>
<p>And the tests themselves:</p>
<pre><code>describe("dimple.series._getCx", function() {
var seriesUnderTest = null,
// Mock return values as ascending primes to avoid coincidental passes
unscaledValue = 2,
scaleReturn = 3,
innerBarCount = 7,
offset = 11,
barGap = 13,
pointSize = 17,
barSize = 19;
beforeEach(function () {
// The axis to return mock values while testing
var mockAxis = jasmine.createSpyObj("axis spy", [
"_hasMeasure",
"_hasCategories",
"_hasMultipleCategories",
"_hasTimeField",
"_scaleValue",
"_pointSize"
]);
// These will be individually overridden in tests to mock different axis types
mockAxis._hasMeasure.andReturn(false);
mockAxis._hasCategories.andReturn(false);
mockAxis._hasMultipleCategories.andReturn(false);
mockAxis._hasTimeField.andReturn(false);
// Set the return type dimensions
mockAxis._scaleValue.andReturn(scaleReturn);
mockAxis._pointSize.andReturn(pointSize);
// Instantiate the series to test
seriesUnderTest = new dimple.series();
seriesUnderTest.x = mockAxis;
// Set up series mocks
spyOn(seriesUnderTest, "_xBarGap").andReturn(barGap);
spyOn(seriesUnderTest, "_xBarSize").andReturn(barSize);
// Set up validation spies
spyOn(dimple.validation, "_isDefined").andReturn(true);
spyOn(dimple.validation, "_isNumber").andReturn(true);
spyOn(dimple.validation, "_isPositiveNumber").andReturn(true);
});
it("Validates required members", function () {
try { seriesUnderTest._getCx(unscaledValue); }
catch (ignore) { /* validation is not under test */ }
expect(dimple.validation._isDefined).toHaveBeenCalledWith("x axis", seriesUnderTest.x);
});
it("Validates required parameters", function () {
try { seriesUnderTest._getCx(unscaledValue); }
catch (ignore) { /* validation is not under test */ }
expect(dimple.validation._isDefined).toHaveBeenCalledWith("unscaledValue", unscaledValue);
});
it("Does not validate optional parameters for axes other than multiple category", function() {
try { seriesUnderTest._getCx(unscaledValue, innerBarCount, offset); }
catch (ignore) { /* validation is not under test */ }
expect(dimple.validation._isPositiveNumber).not.toHaveBeenCalled();
expect(dimple.validation._isPositiveNumber).not.toHaveBeenCalled();
});
it("Validates optional parameters for multiple category axes", function() {
seriesUnderTest.x._hasMultipleCategories.andReturn(true);
try { seriesUnderTest._getCx(unscaledValue, innerBarCount, offset); }
catch (ignore) { /* validation is not under test */ }
expect(dimple.validation._isPositiveNumber).toHaveBeenCalledWith("innerBarCount", innerBarCount);
expect(dimple.validation._isPositiveNumber).toHaveBeenCalledWith("offset", offset);
});
it("Throws an exception if axis returns false for all types", function() {
expect(function () { seriesUnderTest._getCx(unscaledValue); })
.toThrow(dimple.exception.unsupportedAxisState("x"));
expect(seriesUnderTest.x._hasMeasure).toHaveBeenCalled();
expect(seriesUnderTest.x._hasCategories).toHaveBeenCalled();
expect(seriesUnderTest.x._hasMultipleCategories).toHaveBeenCalled();
expect(seriesUnderTest.x._hasTimeField).toHaveBeenCalled();
});
it("Uses the x axis scaling for measure axes", function() {
seriesUnderTest.x._hasMeasure.andReturn(true);
expect(seriesUnderTest._getCx(unscaledValue)).toEqual(scaleReturn);
expect(seriesUnderTest.x._hasMeasure).toHaveBeenCalled();
expect(seriesUnderTest.x._scaleValue).toHaveBeenCalledWith(unscaledValue);
});
it("Uses the x axis scaling for time axes", function() {
seriesUnderTest.x._hasTimeField.andReturn(true);
expect(seriesUnderTest._getCx(unscaledValue)).toEqual(scaleReturn);
expect(seriesUnderTest.x._hasTimeField).toHaveBeenCalled();
expect(seriesUnderTest.x._scaleValue).toHaveBeenCalledWith(unscaledValue);
});
it("Calculates middle bar position for multiple categories", function() {
seriesUnderTest.x._hasMultipleCategories.andReturn(true);
expect(seriesUnderTest._getCx(unscaledValue, innerBarCount, offset))
.toEqual(scaleReturn + barGap + (offset + 0.5) * (barSize / innerBarCount));
expect(seriesUnderTest.x._hasMultipleCategories).toHaveBeenCalled();
expect(seriesUnderTest.x._scaleValue).toHaveBeenCalledWith(unscaledValue);
expect(seriesUnderTest._xBarGap).toHaveBeenCalled();
expect(seriesUnderTest._xBarSize).toHaveBeenCalled();
});
it("Calculates middle bar position for single categories", function() {
seriesUnderTest.x._hasCategories.andReturn(true);
expect(seriesUnderTest._getCx(unscaledValue))
.toEqual(scaleReturn + pointSize / 2);
expect(seriesUnderTest.x._hasCategories).toHaveBeenCalled();
expect(seriesUnderTest.x._scaleValue).toHaveBeenCalledWith(unscaledValue);
expect(seriesUnderTest.x._pointSize).toHaveBeenCalled();
});
});
</code></pre>
|
[] |
[
{
"body": "<p>I agree with what you said, i.e.:</p>\n\n<blockquote>\n <ul>\n <li><p>The only thing which can break these tests is a change to this specific method and surely if anybody is changing this method they are\n doing so with good reason, and all I've done is given them an extra\n job of changing the tests.</p></li>\n <li><p>I can definitely say that writing these tests caused me to make several improvements to the way I wrote the method under test so there\n is benefit from that point of view but the unit tests which are left\n behind feel a bit redundant.</p></li>\n </ul>\n</blockquote>\n\n<p>However \"The only thing which can break these tests is a change to this specific method\" isn't quite true: the test could also discover a breaking change to any of the libraries or subroutines called from (used by) the unit-under-test.</p>\n\n<hr>\n\n<p>I do like automated tested (aka \"regression testing\") but I prefer to high-level to low-level tests.</p>\n\n<p>Testing low-level \"units\" is especially useful, in my opinion, if and only if they need to be tested before they're \"integrated\": for example because they will be integrated with code written by other people, and because debugging during integration testing is expensive (because during an integration test it's relatively expensive to discover which of the components to blame).</p>\n\n<p>For further discussion, see this question and the various answers to it: <a href=\"https://stackoverflow.com/q/856115/49942\">Should one test internal implementation, or only test public behaviour?</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T09:31:30.827",
"Id": "68283",
"Score": "0",
"body": "Thanks for the response, I've been thinking on this a while and actually I've started to see the benefit of the tests. I think it comes down to the way that people will modify the code. If somebody needs to alter the functionality described in the test, there seems little value, however it's more likely that people will extend the logic, in which case it's important to test that they haven't disrupted the existing logic flows e.g adding a new condition to the if-else block for a currently unknown axis type. With that in mind I can certainly see benefit in these tests."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T16:10:06.877",
"Id": "40375",
"ParentId": "40371",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "40375",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T15:40:07.143",
"Id": "40371",
"Score": "2",
"Tags": [
"javascript",
"unit-testing",
"physics",
"jasmine"
],
"Title": "Calculate the physical centre"
}
|
40371
|
<blockquote>
<p>As written, getint treats a + or - not followed by a digit as a valid representation of zero. Fix it to push such a charachter back on the input.</p>
</blockquote>
<p>Before the <code>for</code> I check if the charachter after the + or - is a number. If it is, the function will store the representation of that number in *pn. If it is not, it will push back that characther back on the input - such that, everytime the getint is called it will
read that charachter and push it back.</p>
<p>Here is my solution:</p>
<pre><code>int getint(int *pn) {
int c, sign;
while(isspace(c = getch()))
;
if(!isdigit(c) && c != EOF && c != '+' && c != '-') {
ungetch(c);
return 0;
}
sign = (c == '-') ? -1 : 1;
if(c == '+' || c == '-')
c = getch();
if(!isdigit(c)) {
ungetch(c);
return 0;
}
for(*pn = 0; isdigit(c); (c = getch()))
*pn = 10 * *pn + (c - '0');
*pn *= sign;
if(c != EOF)
ungetch(c);
return c;
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>The method modifies the parameter while it is processing input. It should store the processing result locally and then assign it once it is finished.</p></li>\n<li><p>It is unclear what the return value of the method means just by reading the code. If it is supposed to indicate success (return is not 0) or failure (return value is 0) then I think you have subtle bug in there in the case when the last character read from input is '\\0' - in which case you return 0 even though you potentially have parsed a number. You should simply <code>return 1;</code> to indicate the success case.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T21:58:20.080",
"Id": "40399",
"ParentId": "40373",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "40399",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T16:03:04.990",
"Id": "40373",
"Score": "2",
"Tags": [
"c"
],
"Title": "getint that properly handles + or - signs"
}
|
40373
|
<p>I have the following method in Ruby that appears to be just one line too long according to Ruby style guides. (Specifically: Rubocop tells me that my method has too many lines.)</p>
<p>Granted, I'm only one over the apparent allowed "limit" but in the interests of seeing if the style guides are realistic, I'm trying to adhere to them. Here is the method:</p>
<pre><code>def spec_context
spec_repo.map do |path|
files_to_sort = []
if File.directory?(path)
spec_type.each do |type|
files_to_sort << Dir["#{path}/**/*.#{type}"].sort
end
files_to_sort
else
[]
end
end.flatten.uniq
end
</code></pre>
<p>The method essentially looks for any paths passed in, checks if there are files in those paths, and, if so, adds those files to an array (files_to_sort). If the path provided does not exist, an empty array is returned.</p>
<p>This is about as good as I can get this method. What I don't see is any way that I can shorten that to the Ruby style guidelines (10 lines) and still keep the contents nicely expressive.</p>
<p>Responding to a comment below, I wasn't clear at all about what spec_repo and spec_type are. Those are methods that get called which currently just return arrays:</p>
<pre><code>def spec_repo
%w(specs features stories)
end
def spec_type
%w(spec feature story)
end
</code></pre>
<p>(I say "currently" because eventually the logic in those methods will be reading from a configuration setting.)</p>
<p>So the idea is to look over each directory that is listed as a repo and then, for each such directory, loop over each possible file type. (The file extensions being .spec, .feature, or .story.) If any files of the spec_type are found in any of the spec_repo directories, those are stored in the files_to_sort.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T18:00:54.317",
"Id": "67975",
"Score": "0",
"body": "What is `spec_repo` and `spec_type`? If they operate on something external, shouldn't they be parameters? Or are they methods on `self`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T18:02:40.847",
"Id": "67976",
"Score": "0",
"body": "Ah, good point. So the method above is encased in the following structure: module Lucid --> class Setup --> def spec_context. So the spec_repo and spec_type are currently methods in that same class that simply (for the moment) return values like %w(specs features stories) -- for spec_repo -- and %w(spec feature story) -- for spec_type. Eventually those methods will actually be reading values from an Options module. For now I just hard coded the values for demonstration purposes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T20:34:17.590",
"Id": "74113",
"Score": "0",
"body": "f you are satisfied with any of the answers, you should select the one that was most helpful to you."
}
] |
[
{
"body": "<p>Unless I'm misinterpreting your code, you should be able to get by with something like this:</p>\n\n<pre><code>def spec_context\n directories = spec_repo.select { |path| File.directory?(path) }\n files = directories.map do |dir|\n spec_type.map { |type| Dir[\"#{dir}/**/*.#{type}\"].sort }\n end\n files.flatten.uniq\nend\n</code></pre>\n\n<p>That should be well within the line-limit (you could actually write that in <em>one</em> line, but that'd be kinda' annoying to read).</p>\n\n<p>Point is, we filter to get the directories first, rather than in an <code>if...else</code>, and we <code>map</code> rather than push stuff to an array.</p>\n\n<p>By the way, the title of question is a little confusing. Yes, the code \"sorts file names\", but only within their directory structure. Perhaps you want to put that <code>sort</code> at the very end, after the <code>flatten</code>, when you got all the files in a single array?<br>\nAlso, as far as I can tell, the call to <code>uniq</code> isn't actually necessary; the files you'll find will either be in different directories or have different types, so there shouldn't be any repeats. But, if the addition of user configuration might cause repeats, I'd suggest handling that filtering elsewhere, so <code>spec_repo</code> and <code>spec_type</code> are sure to always return arrays with unique items only. Again, you should be able to get rid of the call to <code>uniq</code> here. Perhaps something similar could be done to make sure the <code>spec_repo</code> array only contains directories (assuming that's all it's supposed to contain) so we avoid doing that filtering in the method above.</p>\n\n<p>Speaking of those methods, I'd suggest plural names for those two methods, since they return arrays. Similarly, the name <code>spec_context</code> doesn't quite communicate that the method returns an array of file names. It might be OK within the jargon of your code, but taken out of context, I might prefer something like <code>spec_files</code> as it's slightly more descriptive.</p>\n\n<p>You also seem to be prefixing all your methods (the ones shown here, at least) with <code>spec_</code>. You might consider creating another class for this logic, since prefixing method names is indicative of methods that should be separately encapsulated.</p>\n\n<hr>\n\n<p><em>Responding to the questions posed in the comments:</em></p>\n\n<p>re method names: No, a method name doesn't need to follow any conventions or declare at its return type. In fact, if you overdo it, the code just becomes weirdly stilted. E.g. a method that returns a path ought to just be called <code>path</code>, not <code>path_string</code> - it's just redundant. Besides, Ruby doesn't have strict types, so trying to pseudo-declare types is going against the grain.</p>\n\n<p>But <em>hinting</em> at what something is is very useful, and helps self-document the code. For example, I usually use plural for array variables or methods that return array. Also, somewhat particular to Ruby, a method call without arguments looks like any other variable, since we don't need to add <code>()</code> at the end. For instance, a line like <code>directories.map ...</code> looks the same whether <code>directories</code> is a local variable or a method. So if you were to refactor the code above and extract the first line into a separate method, you might as well call that method <code>directories</code>, since, hey, the name's worked well so far and it's pretty descriptive:</p>\n\n<pre><code>def directories # same name, but now a method\n spec_repo.select { |path| File.directory?(path) }\nend\n\ndef spec_context # besides removing a line, nothing needs to change here. Yay!\n files = directories.map do |dir| # looks just like before\n spec_type.map { |type| Dir[\"#{dir}/**/*.#{type}\"].sort }\n end\n files.flatten.uniq\nend\n</code></pre>\n\n<p>You could go with <code>directory_paths</code> to further indicate that it's <em>paths</em> we're talking about, but... meh, not necessary. The simpler the better in my opinion. That said, it's always a judgment call.</p>\n\n<p>You certainly shouldn't go for something like <code>setup_spec_context</code>; if it's already in a module called <code>Setup</code>, it's totally redundant to repeat that in the individual method names. For instance, the <code>uniq</code> method isn't called <code>array_uniq</code>, because, well, we know it's an array already.</p>\n\n<p>re the word <code>context</code>: From the code and what you're describing, it sounds like a \"context\" in your case is actually more than just a list of files. It's also the directories to search, and the file types to search for (if not more). So you may want something like a <code>Context</code> class. Then you could have two instances of that class, <code>spec</code> and <code>execution</code>, each containing all the relevant stuff (<code>spec.files</code>, <code>spec.types</code>, <code>spec.directories</code>, etc.). Basic OOP encapsulation; modelling the notion of a \"context\".</p>\n\n<p>If you find yourself prefixing the names of a bunch of methods, what you actually want is likely a class to contain those methods, so they're properly encapsulated. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T13:02:37.577",
"Id": "68066",
"Score": "0",
"body": "Quite interesting! Thank you for the time you spent on this. I tried your suggested approach and it certainly seems to work without issue. I agree with you about the removal of .uniq. The more I think about it, it probably has no relevance simply because every file would have to be unique within its own directory. Likewise, I agree with putting .sort along with .flatten. Thank you indeed for your help on this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T13:04:15.383",
"Id": "68068",
"Score": "0",
"body": "I see your point about re-naming the spec_repo and spec_type methods to spec_repos and spec_types. Regarding the naming of spec_context, that's interesting. Does the name of a method have to indicate the type it returns? Is that considered good practice? The reason I call it spec_context is because my app has two different contexts: spec files and execution files. Those files, together, make up a context for other actions. That was why I named the method as I did. I can certainly see your point, however, about that not indicating the kind of context (i.e., files) that is being returned."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T13:06:08.037",
"Id": "68069",
"Score": "0",
"body": "You beat me to it. Very nice answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T13:07:01.440",
"Id": "68070",
"Score": "0",
"body": "Finally, regarding the naming of the methods (with prefix spec_): these methods are all in a module called Lucid, which contains a class called Setup. The reason I put these methods in Setup was because the execution and spec context is first setup when the app starts. Would naming the methods setup_spec_files (or setup_spec_context) be more indicative? It's not really setting up the *files*, though, so much as setting up the context so that it can pass that context (which happens to be a set of files) to a Loader class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T19:49:56.877",
"Id": "68156",
"Score": "0",
"body": "@JeffNyman Firstly, you're welcome. To answer your questions, I added a bunch of stuff to my answer above"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T13:44:32.470",
"Id": "68327",
"Score": "0",
"body": "Interesting stuff. I'm learning a lot. I do fear my code base is probably not very good, based on what I'm reading. By that I mean I don't think I properly situate actions within classes. I seem to have too broad of classes. That said, learning that is a good thing. Plus my code base is relatively small at this point, so it's a good place to course correct."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T20:21:56.643",
"Id": "40392",
"ParentId": "40376",
"Score": "4"
}
},
{
"body": "<p>I believe <code>Dir</code> can do most of the work for you. The trick is to use {} in your glob to find the correct directories. So, </p>\n\n<pre><code>Dir[\"{specs,features,stories}/**/*.{spec,feature,story}\"]\n</code></pre>\n\n<p>will get all files with your extensions in the paths you need.</p>\n\n<p>If none are found then nil is returned. Just added <code>to_a</code> makes it return an empty array when no results are found.</p>\n\n<p>The resulting method is:</p>\n\n<pre><code>def spec_context\n directories = spec_repo.join(',')\n extensions = spec_type.join(',')\n\n Dir[\"{#{directories}}/**/*.{#{extensions}}\"].to_a.sort\nend\n</code></pre>\n\n<p>I am not sure if pulling the variables out is better or worse. It depends on the reuse of a comma delimited list of spec_repo and spec_type.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T00:08:48.057",
"Id": "42630",
"ParentId": "40376",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "40392",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T16:25:35.313",
"Id": "40376",
"Score": "4",
"Tags": [
"ruby",
"file-system"
],
"Title": "Shorten code that gathers files from directories"
}
|
40376
|
<p>I have various types of EF entities, all of them have a navigation property called "Employee". When generating reports the user will have the option to filter the report according to the different employee properties (Cost Center, gender, etc.). </p>
<p>Something like this:</p>
<pre><code>var courses = context.Courses
.Where(c => c.Employee.CostCenterID == ccID
&& c.Employee.Rank == rankID
....
)
.ToList();
</code></pre>
<p>The real filter code is much more longer but this was just a hint. Anyway, I figured out an easier way of doing this filtering with an extension method using an interface:</p>
<pre><code>public interface IFilterable
{
Employee Employee
{
get;
set;
}
}
</code></pre>
<p>Then, I added partial classes to inherit the previous interface for different entities that has the <code>Employee</code> navigation property, for example:</p>
<pre><code>public partial class Course: IFilterable
{
}
</code></pre>
<p>Then created the following generic method:</p>
<pre><code>public static IQueryable<T> Filter<T>(this IQueryable<T> source, SearchCriteria sc)
where T : class, IFilterable
{
var filtered = source.Where(e => e.Employee.CostCenterID == sc.CostCenterID
&& e.Employee.Gender == sc.Gender
.....
);
return filtered;
}
</code></pre>
<p>then simply I can use it like this on any class that inherits <code>IFilterable</code>:</p>
<pre><code>var list = context.Courses.Filter(sc).ToList();
</code></pre>
<p>Note: the <code>SearchCriteria</code> is just a simple class that holds different employee properties.</p>
<p><strong>Q: Is this the way to do it? or is there a more elegant way?</strong></p>
|
[] |
[
{
"body": "<p>I think you might run into some design ugliness with the in the future because you are now coupling the knowledge that an entity could be filtered by a certain property to each entity.</p>\n\n<p>Imagine a requirement comes in to filter by <code>Course</code> - what would that look like in your design?</p>\n\n<p>Are you going to add a <code>Course</code> property to your <code>IFilterable</code> - but then what if an entity currently implementing <code>IFilterable</code> doesn't have a <code>Course</code>? So you then might need to add another <code>IFilterable</code> interface like an <code>ICourseFilterable</code> and another <code>Filter</code> method to go with it. And then if you want to filter on another entity ... seems quite cumbersome and involved to me.</p>\n\n<p>I think the simplest and most flexible way forward is to actually move the matching responsibility into the <code>SearchCriteria</code>. So instead of having a <code>SearchCriteria</code> you rename it to <code>EmployeeSearchCriteria</code> and give it a method to match a particular employee:</p>\n\n<pre><code>public class EmployeeSearchCriteria\n{\n private int _CostCenterId;\n private Gender _Gender;\n ... // other fields to match\n\n public EmployeeSearchCriteria(int costCenterId, Gender gender, ...)\n {\n _CostCenterId = costCenterId;\n _Gender = gender;\n ...\n }\n\n public bool Matches(Employee e)\n {\n return e.CostCenterID == _CostCenterId && e.Gender == _Gender && ... ;\n }\n}\n</code></pre>\n\n<p>Then you can do your filtering via:</p>\n\n<pre><code>var list = context.Courses.Where(c => sc.Matches(c.Employee)).ToList();\n</code></pre>\n\n<p>And in the future if you want to filter entities by <code>Course</code> you create a <code>CourseSearchCriteria</code> with a method <code>bool Matches(Course c)</code> which you then can use as</p>\n\n<pre><code>var list = context.Employees.Where(e => sc.Matches(e.Course)).ToList();\n</code></pre>\n\n<p>The advantage is that the filtering by specific entities is encapsulated into single classes with single responsibilities and you do not have to litter your code with all these filter interfaces. </p>\n\n<p>The concern that an entity can be filtered is now removed from the entity and kept separate which is always a good thing. The more an entity has to know what might happen to it the more complex your code structure will become.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T20:58:26.407",
"Id": "67993",
"Score": "0",
"body": "Good idea, there is one problem I think. I am querying against a database directly, hence the `Matches` method can not be translated to SQL, which will force me to load the whole table to be able to use Linq-to-Objects in order to achieve this style, Am I right here?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T02:21:31.500",
"Id": "68022",
"Score": "0",
"body": "@MIH, hmm yes I think you are correct, have to think about that one"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T20:06:12.530",
"Id": "40391",
"ParentId": "40378",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T16:51:56.870",
"Id": "40378",
"Score": "4",
"Tags": [
"c#",
"linq",
"entity-framework",
"generics",
"extension-methods"
],
"Title": "A genric extension method to filter Linq-EF queries"
}
|
40378
|
<blockquote>
<p>Write getfloat, the floating-point analog of getint. What types does getfloat return as its function value?</p>
</blockquote>
<p><code>gefloat</code> would also return an integer value.
Here is my solution:</p>
<pre><code>int getfloat(double *pf) {
int c, sign;
double power;
while(isspace(c = getch()))
;
if(!isdigit(c) && c != EOF && c != '-' && c != '+' && c != '.') {
ungetch(c); /* push the number back in buffer */
return 0; /* not a valid number */
}
sign = (c == '-') ? -1 : 1;
if(c == '-' || c == '+')
c = getch();
if(!isdigit(c) && c != '.') {
ungetch(c);
return 0; /* not a number */
}
for(*pf = 0.0; isdigit(c); c = getch())
*pf = *pf * 10 + (c - '0');
if(c == '.')
c = getch();
for(power = 1.0; isdigit(c); c = getch()) {
*pf = *pf * 10 + (c - '0');
power *= 10;
}
*pf *= sign;
*pf /= power; /* moving the decimal point */
if(c != EOF)
ungetch(c);
return c; /* it actually returns the value of the charachter that caused the break of the second for */
}
</code></pre>
<p>I have changed the type of the parameter <code>*pf</code> to <code>double</code>, thus it will handle the floating point represenation of a number. The condition of the first <code>if-statement</code> was extended, such that it will not push back in to the buffer a decimal point.
The second <code>for</code> computes the decimal part of the number, storing the number of places that the decimal point should pe moved in the variable <code>power</code>. If there is no decimal part, <code>power</code> will have the value <code>1</code> - thus, nothing will change if I devide <code>*pf</code> by <code>power</code> when <code>power</code> is <code>1</code>. </p>
|
[] |
[
{
"body": "<ol>\n<li><p>It obviously does not handle <code>NAN</code> and <code>INF</code>. Maybe outside code's goals.</p></li>\n<li><p>Surprisingly does not handle exponential notation such as 1.23e+56.</p></li>\n<li><p><code>if(!isdigit(c) && c != '.') {</code> returns a <code>0</code> implying \"not a number\" and ungets the offending <code>c</code>. But a potential <code>+</code> or <code>-</code> was all ready consumed and not available for alternative parsings. Not sure best way to handle, but maybe consider that once a non-white-space <code>char</code> is irrevocable consumed, this function should not return a error signal and should set <code>*pf</code> to _something_like 0 or NAN.</p></li>\n<li><p>Minor: The <code>*pf /= power;</code> approach fails with input such as 123.00000...(300+ zeros) as <code>power</code> or <code>*pf</code> already became INF.</p></li>\n<li><p>This is a pedantic point: Once you get about 17 (depends on <code>double</code>) decimal digits, the addition of <code>(c - '0')</code> to <code>*pf * 10</code> becomes moot. To get a more accurate significand, forming the number right-to-left has precision advantages.</p></li>\n<li><p>The <code>return c;</code> could return <code>0</code> indicating \"not a number\" . Recommend an alternative return value scheme.</p></li>\n<li><p><code>ungetch</code> is not in the C spec. Consider <code>ungetc()</code>.</p></li>\n<li><p>With <code>ungetc()</code> \"If the value of c equals that of the macro EOF, the operation fails and the input stream is unchanged.\" thus negating the need for the <code>if(c != EOF)</code>. Still not bad to have there.</p></li>\n<li><p>The decimal point <code>.</code> is locale sensitive and could be <code>,</code> or something else. Use locale sensitive routines to determine the current decimal point.</p></li>\n<li><p>You are commended for for taking in <code>\"-0\"</code> and rendering <code>-0.0</code> rather than <code>0.0</code>.</p></li>\n<li><p>[Edit] <a href=\"http://en.wikipedia.org/wiki/IEEE_754-2008#Character_representation\" rel=\"nofollow\">IEEE_754-2008 Character_representation</a> discusses the maximum number of non-zero leading digits to use when converting from text to a number. <code>double</code> is often a IEEE_754 binary64, so a maximum number to use is 17+3. This goes into point #3 above. Its a bit deep on how this affects things, but I'll just note it for those who want to delve into a portable robust solution.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T23:54:23.153",
"Id": "41191",
"ParentId": "40379",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "41191",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T17:21:43.983",
"Id": "40379",
"Score": "7",
"Tags": [
"c",
"parsing",
"floating-point"
],
"Title": "getfloat, the floating point analog of getint"
}
|
40379
|
<p>Is the following good design for doing entity framework code first? What am I missing for a production system? I haven't included all my code, just a snapshot...</p>
<p>My application, doesn't update the database; it just reads it. </p>
<pre><code>public class Document
{
[Key, ScaffoldColumn(false)]
public Int32 DocumentID { get; set; }
[ScaffoldColumn(false)]
public Boolean? Status { get; set; }
[Display(Name = "Document Text"), DataType(DataType.MultilineText)]
public String DocumentText { get; set; }
[ScaffoldColumn(false), DataType(DataType.Url)]
public String DocumentFolderPath { get; set; }
[ScaffoldColumn(false), DataType(DataType.Url)]
public String DocumentJSONPath { get; set; }
[ForeignKey("DocumentID")]
public virtual DocumentMetadata Metadata { get; set; }
[ForeignKey("DocumentID")]
public virtual ICollection<Page> Pages { get; set; }
}
public class Page
{
[Key, ScaffoldColumn(false)]
public Int32 PageID { get; set; }
[Required, Display(Name = "Page"), DataType(DataType.Text)]
public Int32 PageNumber { get; set; }
[Required, ScaffoldColumn(false)]
public Int32 DocumentID { get; set; }
[ScaffoldColumn(false), DataType(DataType.ImageUrl)]
public String ImagePath { get; set; }
[Required, Display(Name = "Page Text"), DataType(DataType.MultilineText)]
public String PageText { get; set; }
[NotMapped]
public String HighlightedText { get; set; }
[ForeignKey("PageID")]
public virtual ICollection<Word> Words { get; set; }
}
public class ArchiveDatabaseInitializer : DropCreateDatabaseIfModelChanges<ArchiveContext>
{
protected override void Seed(ArchiveContext context)
{
try
{
GetDocuments().ForEach(d => context.Documents.Add(d));
GetDocumentMetatdata().ForEach(d => context.DocMetadata.Add(d));
GetPages().ForEach(d => context.Pages.Add(d));
GetWords().ForEach(d => context.Words.Add(d));
context.SaveChanges();
}
catch (Exception ex)
{
throw ex;
}
}
private static List<Document> GetDocuments()
{
var documents = new List<Document> {
new Document
{
DocumentID = 1,
DocumentFolderPath = @"Doc1",
DocumentJSONPath = @"Doc1.json",
Status = true
},
new Document
{
DocumentID = 2,
DocumentFolderPath = @"Doc2",
DocumentJSONPath = @"Doc2.json",
Status = true
}
};
return documents;
}
public class ArchiveContext : DbContext
{
public ArchiveContext()
: base("archiveDB")
{
}
public DbSet<Document> Documents { get; set; }
public DbSet<DocumentMetadata> DocMetadata { get; set; }
public DbSet<Page> Pages { get; set; }
public DbSet<Word> Words { get; set; }
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T17:52:01.823",
"Id": "67970",
"Score": "0",
"body": "What makes you think you're missing anything for a production system?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T17:54:21.460",
"Id": "67972",
"Score": "0",
"body": "This is the first time I've used EF so I don't know what I don't know. ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T18:00:10.363",
"Id": "67974",
"Score": "0",
"body": "You got it working?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T18:38:34.773",
"Id": "67982",
"Score": "0",
"body": "I don't think the `ICollection<Page>` navigation property can have a FK attribute AND work. But I could be wrong. It just... looks weird to me. I've favorited this question, I'll get back to it when I have a chance :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T20:33:52.803",
"Id": "67990",
"Score": "1",
"body": "Yes it is working. It looks like it gets the data as expected. I just want to know if this is the correct way of doing this."
}
] |
[
{
"body": "<p>If you chose the code-first approach, I presume you don't have to deal with the constraints of an existing database. If that assumption is correct, then I'd say you've done it the hard way.</p>\n\n<p><strong>Convention Over Configuration</strong></p>\n\n<p>Entity Framework can infer keys (primary and foreign) from the names of your entity members; your code isn't leveraging this formidable capability.</p>\n\n<p>For a <em>greenfield project</em>, I like to start with a base entity type:</p>\n\n<pre><code>public abstract class EntityBase\n{\n public int Id { get; set; } // inferred PK\n public DateTime DateInserted { get; set; }\n public DateTime? DateUpdated { get; set; }\n}\n</code></pre>\n\n<p>Now I can derive, say, <code>Document</code> from that class:</p>\n\n<pre><code>public class Document : EntityBase\n{\n public bool? Status { get; set; }\n public string DocumentText { get; set; }\n // ...\n\n public virtual DocumentMetadata Metadata { get; set; } // inferred FK\n}\n</code></pre>\n\n<p>The PK is inferred from the inherited <code>Id</code> property (or <code>[TypeName]Id</code>), and the mere mention of a <code>virtual</code> property referencing another entity type is enough for EF to understand you want a FK there.</p>\n\n<p>I'll pause here to mention that I was somewhat thrown off by your non-usage of the C# language aliases for <code>System.String</code>, <code>System.Int32</code> and <code>System.Boolean</code>. They're typically written as <code>string</code>, <code>int</code> and <code>bool</code>.</p>\n\n<hr>\n\n<p>You mention you're only <em>reading</em> from the database. This sounds like you're going <em>code-first</em> with an <em>existing</em> database. It's certainly possible, but the best way to do this in my opinion, is to <em><a href=\"http://msdn.microsoft.com/en-us/data/jj200620.aspx\" rel=\"nofollow\">reverse-engineer</a></em> the database into entity classes - then you get the best of both worlds, and the generated code can teach you a lot about how EF works.</p>\n\n<hr>\n\n<p>I think the presence of <code>DisplayAttribute</code> and <code>NotMappedAttribute</code> smells like you're possibly using your entities as both <em>data entities</em> and <em>presentation / ViewModels</em>. I think I would separate these concerns and create separate classes for presentation purposes, where <code>HighlightedText</code> means something relevant.</p>\n\n<p>Also note that relying on a declarative <code>DisplayAttribute</code> will make it quite a pain to localize the application, if you ever need to do that in the future; you'll want these things resolved at run-time, accounting for <code>Thread.CurrentThread.CurrentUICulture</code>.</p>\n\n<hr>\n\n<p>The naming is overall ok, except I don't like the <code>Status</code> column. It's just too vague of a name. What do the <code>null</code>, <code>true</code> and <code>false</code> values mean? The name should convey that meaning. Also I wouldn't prefix most of <code>Document</code>'s members with the word \"Document\", and <code>ID</code> should follow the PascalCasing convention and be <code>Id</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T06:51:36.410",
"Id": "68041",
"Score": "0",
"body": "Thank you for the detailed response. I will be updating my code with your suggestions. About the FK being explicitly set, when I didn't have it there, the database did not create a foreign key in the database. It may be because it wasn't recognizing my id's as keys. I will try it and find out."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T04:18:39.883",
"Id": "40424",
"ParentId": "40381",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "40424",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T17:38:50.413",
"Id": "40381",
"Score": "4",
"Tags": [
"c#",
"sql-server",
"entity-framework"
],
"Title": "Code First Entity Framework"
}
|
40381
|
<p>I'm designing a table cell based map design for a little game I'm building, and I was hoping I could get some cleanup pointers or design tips to "perfect" my engine's design. Basically, in the end result, you'll walk around the map one tile at a time. On any visible tile you can walk to it, but only the tile you're on will have "actions" (randomly generated).</p>
<p>Here is my prototype design:</p>
<pre><code>function Map() {
this.x;
this.y;
}
Map.prototype = {
move:function() {
var new_x = this.x - 1;
var new_y = this.y - 1;
Map.prototype.render(new_x, new_y);
},
render:function(p_x,p_y) {
//check for map boundaries
var max_divs = 2;
if(!p_x) p_x = 1;
if(!p_y) p_y = 1;
if(p_x >= 99) p_x--;
if(p_y >= 99) p_y--;
divs_x = max_divs + p_x;
divs_y = max_divs + p_y;
//create new table
var root = document.createElement("table");
root.id = 'root_table';
//loop coordinates and generate surrounding cells
for (var x = p_x; x <= divs_x; x++) {
var row = document.createElement("tr");
for (var y = p_y; y <= divs_y; y++) {
var cell = document.createElement("td");
if (x <= 0 || y <= 0 || x >= 101 || y >= 101) {
cell.textContent = "";
}
else {
this.x = x; this.y = y;
cell.textContent = "("+this.x+","+this.y+")";
//add event handler for the click event (move)
cell.addEventListener("click", this.move, false);
cell.x = x; cell.y = y;
cell.className = 'map';
}
//add cell to row
row.appendChild(cell);
}
//add row to table
root.appendChild(row);
}
var main = document.getElementById("container");
var old_table = document.getElementById('root_table')
if(old_table) main.removeChild(old_table);
//remove old table, add new one
main.appendChild(root);
}
}
var map = new Map();
map.render();
</code></pre>
<p>And here is a current working link to my map: <a href="http://fooscript.com/zombie" rel="nofollow">zombiesss ahhhh</a></p>
|
[] |
[
{
"body": "<p>I'm afraid your code is very hard to understand. Part of the problem is your variable naming: I'm not sure what exactly <code>p_x</code> is and what distinguishes it from the <code>x</code> that's part of the <code>Map</code> object, for example. It also doesn't help that your comments mostly just describe the behaviour of entirely obvious single lines of code but don't describe any of the unclear aspects of your code, for instance why it is doing what it is doing.</p>\n\n<p>On to more specific comments, this line of code is confusing:</p>\n\n<pre><code>Map.prototype.render(new_x, new_y);\n</code></pre>\n\n<p>Is there a reason you aren't using <code>this.render(new_x, new_y)</code> here, but instead calling the method directly on the prototype object? If so, it would be best to explain it with a comment, as this is quite unusual behaviour. Also, what are <code>new_x</code> and <code>new_y</code>, and why are they calculated in the way they are? As far as I can see, <code>Map.x</code> and <code>Map.y</code> are never set to anything that has any particularly useful meaning.</p>\n\n<p>In your inner loop in the <code>render</code> method, you repeatedly update <code>this.x</code> and <code>this.y</code>, but the values stored here are never read by code outside of the method, because they are overwritten by the next iteration of the loop before anything else can touch it. It is unclear why you are doing this, but generally it would be better to only update them once, and to use local variables when you are calculating values for use only within a single method.</p>\n\n<p>You have a number of values in your code that are seemingly related, i.e. 99 and 101 used in two different places. It may be best to use a variable to store one of these values (I think 100 cells is the size of your map?) and derive one from the other as necessary.</p>\n\n<p><strong>Update after clarification in comments</strong></p>\n\n<p>Having <code>move</code> be part of the <code>Map</code> object when it isn't called in that context is confusing. Also referring to <code>Map.prototype</code> is unlikely to be what you want to do, as it basically prevents you from ever having more than one <code>Map</code>, thus negating a key benefit of using objects at all.</p>\n\n<p>Here's how I would handle it: I wouldn't declare the event handler as a separate function at all, but instead declare it inline when I set the event handler. I would also make sure it had a variable in scope that refers to the <code>Map</code> object, so it doesn't need to access the prototype. Then I'd have it call back to an event-handling function that's actually properly part of the Map object. Here's what that might look like:</p>\n\n<p>in the inner loop of the <code>render</code> function:</p>\n\n<pre><code> var map = this;\n cell.addEventListener(\"click\", function () {\n map.cellClicked (this);\n }, false);\n cell.x = x; cell.y = y;\n</code></pre>\n\n<p>and the new <code>cellClicked</code> function:</p>\n\n<pre><code>Map.prototype = {\n cellClicked: function (cell) {\n this.render (cell.x - 1, cell.y - 1);\n },\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T18:46:01.190",
"Id": "67983",
"Score": "0",
"body": "Inside of `move`, `this` references the element that triggers the click event, not the `Map` object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T19:09:30.687",
"Id": "67986",
"Score": "0",
"body": "Then why is `move` a method of the `Map` object? Either define it inline when you set the event handler, or put it in an object of its own. Declaring it as part of the Map means people will assume that `this` is supposed to refer to the Map when it executes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T19:10:48.300",
"Id": "67987",
"Score": "0",
"body": "Also, you still shouldn't be referring to `Map.prototype` like that: when you execute a method on `Map.prototype` any changes it makes to `this` affect *all instances* of `Map`, not just one. I'll post an update that shows how I would handle this."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T18:37:57.300",
"Id": "40386",
"ParentId": "40385",
"Score": "4"
}
},
{
"body": "<p>I think you are doing it wrong.</p>\n\n<p>It seems massive overkill to re-generate a table and attach listeners every time you move, while you could simply update the <code>textContent</code> of the cells.</p>\n\n<p>If you had an HTML table like this:</p>\n\n<pre><code><table>\n <tr><td id=\"0,0\"></td><td id=\"1,0\"></td><td id=\"2,0\"></td></tr>\n <tr><td id=\"0,1\"></td><td id=\"1,1\"></td><td id=\"2,1\"></td></tr>\n <tr><td id=\"0,1\"></td><td id=\"1,2\"></td><td id=\"2,2\"></td></tr>\n</table>\n</code></pre>\n\n<p>Then your render routine could be as simple as </p>\n\n<pre><code>render:function() {\n var viewRow, viewColumn, element;\n //Loop over view and update text content\n for (viewRow = 0; viewRow < this.viewRows; viewRow++) {\n for (viewColumn = 0; viewColumn < this.viewCols; viewColumn++) {\n element = document.getElementById( viewColumn + ',' + viewRow )\n element.textContent = ( viewColumn + this.col - 1 ) + ',' + ( viewRow + this.row - 1 );\n }\n }\n}\n</code></pre>\n\n<p>Where <code>this.row</code> and <code>this.col</code> represent the center cell the player is on.</p>\n\n<p>I will leave the event handling to you, but I would suggest to add each cell the vector values ( so top left is (-1,-1 ) ) and from there calculate the new <code>this.row</code> and <code>this.col</code> and then re-render the map.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T17:33:23.440",
"Id": "40479",
"ParentId": "40385",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T18:10:45.780",
"Id": "40385",
"Score": "3",
"Tags": [
"javascript",
"game"
],
"Title": "Table cell map engine"
}
|
40385
|
<p>I wanted a hash which lets me reference Japanese syllables by their romanized names. In hindsight I could have searched for an existing one column table, but I wanted to improve my ruby by writing a function which serializes these multi-column tables I found on wikipedia:</p>
<pre><code> katakana:
v_eng: a i u e o
v_jap: ア イ ウ エ オ
K: カ キ ク ケ コ
S: サ シ ス セ ソ
T: タ チ ツ テ ト
N: ナ ニ ヌ ネ ノ
H: ハ ヒ フ ヘ ホ
M: マ ミ ム メ モ
Y: ヤ _ ユ _ ヨ
R: ラ リ ル レ ロ
W: ワ ヰ _ ヱ ヲ
hiragana:
v_eng: a i u e o
v_jap: あ い う え お
k: か き く け こ
s: さ し す せ そ
t: た ち つ て と
n: な に ぬ ね の
h: は ひ ふ へ ほ
m: ま み む め も
y: や _ ゆ _ よ
r: ら り る れ ろ
w: わ ゐ _ ゑ を
nn: ん _ _ _ _
</code></pre>
<p>I was able to create the serializing function, syllabarys():</p>
<pre><code>#!/usr/bin/env ruby
require 'yaml'
def syllabarys
@syllabarys ||= lambda{
raw_data = YAML.load_file 'japanese.dic'
syllabary_names = ['katakana','hiragana']
a = syllabary_names.map{|syllabary|
syllabary_data = raw_data[syllabary]
veng,vjap = syllabary_data['v_eng'].split, syllabary_data['v_jap'].split
vowels = Hash[*veng.zip(vjap).flatten] #zipped flat array => splat
#jp row strings by en consonants:
jrsbec = syllabary_data.select{|con,row|con =~ /^[KSTNHMYRWkstnhmyrwN]$/}
#jp row arrays by en consonants:
jrabec = Hash[*jrsbec.map{|con,row|[con,row.split]}.flatten(1)]
#en vowels with jp row arrays by en consonants:
evwjrabec = Hash[jrabec.map{|con,row|[con,Hash[veng.zip(row)]]}] #array of hashes => no splat
#jp syllables by en syllables:
#outer map provides en consonant to inner map
#inner map creates the dictionary we want in array form, e.g. [#K#[['Ka','カ'],..], #S..]
#flatten(1) removes outer array created by outer map [['Ka','カ'],..] => no splat
jp_by_en = Hash[evwjrabec.map{|con,row|row.map{|vowel,jp_syl| [con+vowel,jp_syl] }}.flatten(1)]
#remove forgotten syllables:
jp_by_en.select{|en_syl,jp_syl|jp_syl != '_'}
}
Hash[*syllabary_names.zip(a).flatten(1)]
}.call
end
</code></pre>
<p>And it returns the desired hash:</p>
<pre><code>{"katakana"=>{"Ka"=>"カ", "Ki"=>"キ", "Ku"=>"ク", "Ke"=>"ケ", "Ko"=>"コ", "Sa"=>"サ", "Si"=>"シ", "Su"=>"ス", "Se"=>"セ", "So"=>"ソ", "Ta"=>"タ", "Ti"=>"チ", "Tu"=>"ツ", "Te"=>"テ", "To"=>"ト", "Na"=>"ナ", "Ni"=>"ニ", "Nu"=>"ヌ", "Ne"=>"ネ", "No"=>"ノ", "Ha"=>"ハ", "Hi"=>"ヒ", "Hu"=>"フ", "He"=>"ヘ", "Ho"=>"ホ", "Ma"=>"マ", "Mi"=>"ミ", "Mu"=>"ム", "Me"=>"メ", "Mo"=>"モ", "Ya"=>"ヤ", "Yu"=>"ユ", "Yo"=>"ヨ", "Ra"=>"ラ", "Ri"=>"リ", "Ru"=>"ル", "Re"=>"レ", "Ro"=>"ロ", "Wa"=>"ワ", "Wi"=>"ヰ", "We"=>"ヱ", "Wo"=>"ヲ"}, "hiragana"=>{"ka"=>"か", "ki"=>"き", "ku"=>"く", "ke"=>"け", "ko"=>"こ", "sa"=>"さ", "si"=>"し", "su"=>"す", "se"=>"せ", "so"=>"そ", "ta"=>"た", "ti"=>"ち", "tu"=>"つ", "te"=>"て", "to"=>"と", "na"=>"な", "ni"=>"に", "nu"=>"ぬ", "ne"=>"ね", "no"=>"の", "ha"=>"は", "hi"=>"ひ", "hu"=>"ふ", "he"=>"へ", "ho"=>"ほ", "ma"=>"ま", "mi"=>"み", "mu"=>"む", "me"=>"め", "mo"=>"も", "ya"=>"や", "yu"=>"ゆ", "yo"=>"よ", "ra"=>"ら", "ri"=>"り", "ru"=>"る", "re"=>"れ", "ro"=>"ろ", "wa"=>"わ", "wi"=>"ゐ", "we"=>"ゑ", "wo"=>"を"}}
</code></pre>
<p>This task was a good exercise in index-free coding, but I notice my code exhibits a recurring pattern of map|zip->flatten->Hash. I'd like to know if this is this a normal pattern in ruby or if there's a better way of serializing tabular data.</p>
|
[] |
[
{
"body": "<p>Feedback:</p>\n\n<ul>\n<li>Instead of <code>||= lambda { ... }.call</code>, you can use <code>||= begin ... end</code></li>\n<li>Instead of <code>Hash[*arr]</code> you can use <code>arr.to_h</code> in Ruby 2.0+</li>\n<li>You don't need to convert everything to a hash if you just want to use it for <code>.map</code> later -- <code>[[1, 2], [3, 4]].map { |k, v| k + v }</code> #=> <code>[3, 7]</code></li>\n<li>Instead of <code>.map { ... }.flatten(1)</code>, you can use <code>.flat_map { ... }</code></li>\n<li>If you won't be using a variable in a block, you can use <code>_</code> instead, like <code>.map { |key, _| key }</code></li>\n</ul>\n\n<p>I rewrote the code to be like what I'd code it today.</p>\n\n<pre><code>require 'yaml'\n\ndef do_it(raw)\n map = raw[\"v_eng\"].split.zip(raw[\"v_jap\"].split)\n\n raw.select do |k, _|\n k.size == 1\n end.flat_map do |pre, japs|\n map.zip(japs.split).map do |(post, _), jap|\n [pre + post, jap] unless jap == '_'\n end.compact\n end.to_h\nend\n\nwant = {\"katakana\"=>{\"Ka\"=>\"カ\", \"Ki\"=>\"キ\", \"Ku\"=>\"ク\", \"Ke\"=>\"ケ\", \"Ko\"=>\"コ\", \"Sa\"=>\"サ\", \"Si\"=>\"シ\", \"Su\"=>\"ス\", \"Se\"=>\"セ\", \"So\"=>\"ソ\", \"Ta\"=>\"タ\", \"Ti\"=>\"チ\", \"Tu\"=>\"ツ\", \"Te\"=>\"テ\", \"To\"=>\"ト\", \"Na\"=>\"ナ\", \"Ni\"=>\"ニ\", \"Nu\"=>\"ヌ\", \"Ne\"=>\"ネ\", \"No\"=>\"ノ\", \"Ha\"=>\"ハ\", \"Hi\"=>\"ヒ\", \"Hu\"=>\"フ\", \"He\"=>\"ヘ\", \"Ho\"=>\"ホ\", \"Ma\"=>\"マ\", \"Mi\"=>\"ミ\", \"Mu\"=>\"ム\", \"Me\"=>\"メ\", \"Mo\"=>\"モ\", \"Ya\"=>\"ヤ\", \"Yu\"=>\"ユ\", \"Yo\"=>\"ヨ\", \"Ra\"=>\"ラ\", \"Ri\"=>\"リ\", \"Ru\"=>\"ル\", \"Re\"=>\"レ\", \"Ro\"=>\"ロ\", \"Wa\"=>\"ワ\", \"Wi\"=>\"ヰ\", \"We\"=>\"ヱ\", \"Wo\"=>\"ヲ\"}, \"hiragana\"=>{\"ka\"=>\"か\", \"ki\"=>\"き\", \"ku\"=>\"く\", \"ke\"=>\"け\", \"ko\"=>\"こ\", \"sa\"=>\"さ\", \"si\"=>\"し\", \"su\"=>\"す\", \"se\"=>\"せ\", \"so\"=>\"そ\", \"ta\"=>\"た\", \"ti\"=>\"ち\", \"tu\"=>\"つ\", \"te\"=>\"て\", \"to\"=>\"と\", \"na\"=>\"な\", \"ni\"=>\"に\", \"nu\"=>\"ぬ\", \"ne\"=>\"ね\", \"no\"=>\"の\", \"ha\"=>\"は\", \"hi\"=>\"ひ\", \"hu\"=>\"ふ\", \"he\"=>\"へ\", \"ho\"=>\"ほ\", \"ma\"=>\"ま\", \"mi\"=>\"み\", \"mu\"=>\"む\", \"me\"=>\"め\", \"mo\"=>\"も\", \"ya\"=>\"や\", \"yu\"=>\"ゆ\", \"yo\"=>\"よ\", \"ra\"=>\"ら\", \"ri\"=>\"り\", \"ru\"=>\"る\", \"re\"=>\"れ\", \"ro\"=>\"ろ\", \"wa\"=>\"わ\", \"wi\"=>\"ゐ\", \"we\"=>\"ゑ\", \"wo\"=>\"を\"}}\n\nraw = YAML.load_file 'japanese.dic'\n\np do_it(raw[\"katakana\"]) == want[\"katakana\"] #=> true\np do_it(raw[\"hiragana\"]) == want[\"hiragana\"] #=> true\n</code></pre>\n\n<p>Hope that helps. Let me know if you want any other clarification(s) in a comment below.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T15:29:35.217",
"Id": "40617",
"ParentId": "40389",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "40617",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T19:16:47.470",
"Id": "40389",
"Score": "3",
"Tags": [
"ruby",
"iterator",
"serialization"
],
"Title": "Serializing tabular data in ruby -- is map, flatten, hash the correct approach?"
}
|
40389
|
<p>I've implemented CTR mode by myself (only decryption for now), using only AES built-in functions from pycrypto. It means that I'm not supposed to use mode=AES.MODE_CTR. However, I know that using AES.MODE_CTR would be more simple, but I'm doing this as a learning experience.</p>
<p>Is it a safe AES CTR??</p>
<p>(non-parallel version)</p>
<pre><code>from Crypto.Cipher import AES
from Crypto.Cipher import AES
ciphers = ["69dda8455c7dd4254bf353b773304eec0ec7702330098ce7f7520d1cbbb20fc3" + \
"88d1b0adb5054dbd7370849dbf0b88d393f252e764f1f5f7ad97ef79d59ce29f5f51eeca32eabedd9afa9329", \
"770b80259ec33beb2561358a9f2dc617e46218c0a53cbeca695ae45faa8952aa" + \
"0e311bde9d4e01726d3184c34451"]
key = "36f18357be4dbd77f050515c73fcf9f2"
class IVCounter(object):
def __init__(self, value):
self.value = value
def increment(self):
# Add the counter value to IV
newIV = hex(int(self.value.encode('hex'), 16) + 1)
# Cut the negligible part of the string
self.value = newIV[2:len(newIV) - 1].decode('hex') # for not L strings remove $ - 1 $
return self.value
def __repr__(self):
self.increment()
return self.value
def string(self):
return self.value
class CTR():
def __init__(self, k):
self.key = k.decode('hex')
def __strxor(self, a, b): # xor two strings of different lengths
if len(a) > len(b):
return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)])
else:
return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b[:len(a)])])
def __split_len(self, seq, lenght):
return [seq[i:i+lenght] for i in range(0, len(seq), lenght)]
def __AESencryptor(self, cipher):
encryptor = AES.new(self.key, AES.MODE_ECB)
return encryptor.encrypt(cipher)
def decrypt(self, cipher):
# Split the CT into blocks of 16 bytes
blocks = self.__split_len(cipher.decode('hex'), 16)
# Takes the initiator vector
self.IV = IVCounter(blocks[0])
blocks.remove(blocks[0])
# Message block
msg = []
# Decrypt
for b in blocks:
aes = self.__AESencryptor(self.IV.string())
msg.append(self.__strxor(b, aes))
self.IV.increment()
return ''.join(msg)
def main():
decryptor = CTR(key)
for c in ciphers:
print 'msg = ' + decryptor.decrypt(c)
if __name__ == '__main__':
main()
</code></pre>
<p>This code was supposed to do the same that the code below:</p>
<pre><code>import Crypto.Util.Counter
ctr_e = Crypto.Util.Counter.new(128, initial_value=long(IV.encode('hex'), 16))
decryptor = AES.new(key.decode('hex'), AES.MODE_CTR, counter=ctr_e)
print decryptor.decrypt(''.join(blocks))
</code></pre>
|
[] |
[
{
"body": "<p>I couldn't spot any problems with your implementations, but caveat lector: I'm not a cryptography expert, so take that with an appropriate pinch of salt.</p>\n\n<p><s>I'm also concerned about the output:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>$ python reinvent.py\nmsg = CTR mode lets yo▒B▒▒▒c▒?▒N▒▒w▒▒ap▒9▒uz▒▒▒3▒▒▒o▒V_M▒▒A\nmsg = Always avoid the▒?A▒▒r ▒ά\n</code></pre>\n\n<p>It looks as if the first block has been decrypted correctly, and then it all falls over. Probably a bug, but I didn't dig into what's causing it.</s></p>\n\n<p><strong>Edit:</strong> Turns out this was an indentation problem – the code as posted had lost some indentation, and I guessed wrong when I tried to add it back.</p>\n\n<p>The biggest problem with this code is the lack of docstrings and comments. Especially when you're dealing with cryptography – it's important to explain <em>why</em> you wrote the code you did, and how it relates to the original problem. This makes code easier to read, review and maintain – and would probably make it much easier to spot the bug above.</p>\n\n<p>A variety of comments below.</p>\n\n<p><br></p>\n\n<h2>IVCounter class</h2>\n\n<p></p></p>\n\n<ul>\n<li><p>There should be a docstring explaining what this class represents, and what sort of values it expects as input. I had lots of <s>fun</s> hassle trying different inputs and hitting a variety of errors before I got it working.</p></li>\n<li><p>Your __repr__ method is mutating the internal state of the object – that seems like a really bad idea. The usual use case for repr() is as a debugging tool; changing the instance you're trying to debug will be a bundle of laughs.</p>\n\n<p>Here's an alternative repr you could use:</p>\n\n<pre><code>def __repr__(self):\n return '%s(%r)' % (self.__class__.__name__, self.value)\n</code></pre>\n\n<p></p></p>\n\n<p>This returns a string that could be eval'd to get something equivalent to the current object, which is a much more conventional use of this function.</p></li>\n<li><p>I'm not sure why you have a string method. It would be better for callers to access self.value directly, and if you want a string representation of an object, you should define __str__ instead.</p></li>\n<li><p>What happens when the counter overflows? You get a nasty TypeError:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> x = IVCounter('\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe')\n>>> x.increment()\n'\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff'\n>>> x.increment()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 8, in increment\n File \"/usr/lib/python2.7/encodings/hex_codec.py\", line 42, in hex_decode\n output = binascii.a2b_hex(input)\nTypeError: Odd-length string\n</code></pre>\n\n<p></p></p>\n\n<p>You should think about how you want to handle an overflow like this – at the very least, you should wrap the exception and provide a more intelligible error message.</p></li>\n</ul>\n\n<p><br></p>\n\n<h3>CTR class.</h3>\n\n<ul>\n<li>Should subclass from object.</li>\n<li>Avoid single letter variable names where possible; try to prefer descriptive and expressive names. For example, <code>__init__(self, key)</code> instead of <code>__init__(self, key)</code>. Or <code>for block in blocks</code>.</li>\n<li>In your <code>__strxor</code> method, you have repeated code – the only thing that changes is the arguments to <code>zip()</code>. Would be good to cut down that repetition.</li>\n<li>The variable name <code>lenght</code> is misspelt in the definition of the <code>__split_len</code> method.</li>\n<li>When I hear the word <code>cipher</code>, I think of things like AES, whereas you seem to be using it to describe a message text. That's a little confusing – docstrings would help.</li>\n<li><p>In the <code>decrypt()</code> method, rather than:</p>\n\n<pre><code>self.IV = IVCounter(blocks[0])\nblocks.remove(blocks[0])\n</code></pre>\n\n<p>you could just use:</p>\n\n<pre><code>self.IV = IVCounter(blocks.pop(0))\n</code></pre>\n\n<p>which will remove the item and extract it.</p></li>\n</ul>\n\n<p><br></p>\n\n<h3>Misc</h3>\n\n<p></p></p>\n\n<ul>\n<li>You appear to be importing Crypto.Cipher.AES twice. Why?</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-08T18:06:53.383",
"Id": "113289",
"ParentId": "40393",
"Score": "2"
}
},
{
"body": "<p>The Pycrpto library has both encrpypt and decrypt functions for the class <code>AES</code>, but you have used the encrypt function for decryption:</p>\n\n<p>For b in blocks:</p>\n\n<pre><code>aes = self.__AESencryptor(self.IV.string())\"\n</code></pre>\n\n<p>It can be corrected by first defining an AES decryptor function as:</p>\n\n<pre><code>def __AESdecryptor(self, cipher):\n dec = AES.new(self.key, AES.MODE_ECB)\n return dec.decrypt(cipher)\n</code></pre>\n\n<p>and calling it inside your CTR decryptor.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-24T17:03:53.053",
"Id": "123774",
"ParentId": "40393",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T20:38:51.593",
"Id": "40393",
"Score": "5",
"Tags": [
"python",
"reinventing-the-wheel",
"cryptography",
"aes"
],
"Title": "AES CTR mode using pycrypto"
}
|
40393
|
<p>It's possible to work out the number of moves required to move from (0, 0) to (A, B) for a knight on an infinite chess board in O(1) time.</p>
<p>This is an attempt at a solution to do it in O(n) time, where n is the number of moves required.</p>
<pre><code>#define ABS(a) ({ typeof (a) _a = (a); _a > 0 ? _a : -_a; })
int movesRequired(int A, int B) {
int X = 0, Y = 0;
int count = 0;
if (!(((A-X) % 2) ^ ((Y-B) % 2)))
return -1;
while (X != A && Y != B) {
int distX = A-X;
int distY = B-Y;
if (ABS(distX) > ABS(distY)) {
X += distX>0?2:-2;
Y += distY>0?1:-1;
} else {
X += distX>0?1:-1;
Y += distY>0?2:-2;
}
count++;
}
return count;
}
</code></pre>
<p>It returns the minimum moves required, or -1 if it's not possible.</p>
<p>What I'm interested in:</p>
<ul>
<li><p>As far as I am aware, this runs in O(n) time. However, I may not be correct. Does it?</p></li>
<li><p>Is there a way to improve my algorithm so it runs in O(n) time?</p></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T22:05:29.030",
"Id": "68000",
"Score": "0",
"body": "We are only considering one knight on this infinite chessboard, right? That's what I'm assuming since collisions with other chess pieces wouldn't be legal."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T22:11:40.503",
"Id": "68003",
"Score": "0",
"body": "@syb0rg Yes, just the knight."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T05:56:32.070",
"Id": "68039",
"Score": "5",
"body": "Under what conditions is it not possible for a Knight to access a square?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T10:23:39.610",
"Id": "68057",
"Score": "0",
"body": "\"It's possible to work out the number of moves required to move from (0, 0) to (A, B) for a knight on an infinite chess board in O(1) time.\" This statement is *false*. The proof is very simple: the output is **not** constant in size. If you choose bigger and bigger `A` and `B` in the infinite chessboard the number of moves increases and thus the size of the output. The time to compute such number of moves `n` is **at least** O(log(n)) otherwise the algorithm wouldn't even have the time to produce output."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T14:42:54.343",
"Id": "68084",
"Score": "2",
"body": "A knight can always move to any square, it's never impossible because no square is unreachable to a knight: see for example [Knight's tour](http://en.wikipedia.org/wiki/Knight's_tour)."
}
] |
[
{
"body": "<p>A few notes (with efficiency aside, as you said):</p>\n\n<ul>\n<li><p>Your defined <code>ABS</code> surrounded by parenthesis is <a href=\"https://stackoverflow.com/q/154136/1937270\">not the usual way that C programmers declare macros</a> so that they aren't problematic.</p>\n\n<pre><code>#define ABS(a) do { typeof (a) _a = (a); _a > 0 ? _a : -_a; } while(0)\n</code></pre>\n\n<p>Also, there is no point of using <code>typeof</code> in this instance. Just use the <code>abs()</code> function from <code><math.h></code>, or define a more simple ABS macro.</p>\n\n<pre><code>#define ABS(x) ((x) > 0 ? x : -x)\n</code></pre>\n\n<p>Note that you will have to use the <code>fabs()</code> for finding the absolute value of floating point numbers using the <code><math.h></code> library.</p></li>\n<li><p>Why are all of your single letter variable names capitalized?</p></li>\n<li><p>You need to let some of your code breathe a bit to make it easier to read (in my opinion).</p>\n\n<pre><code>X += distX > 0 ? 2 : -2;\n</code></pre></li>\n<li><p>Use more comments to say what your code does and why. Don't overdo this though.</p>\n\n<pre><code>if (!(((A-X) % 2) ^ ((Y-B) % 2))) //<insert description here>\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T22:15:48.433",
"Id": "68004",
"Score": "1",
"body": "On that last point, the operands and operators should be separated for readability."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T22:25:44.070",
"Id": "68006",
"Score": "1",
"body": "Thanks for your answer syb0rg. I agree with the first and last suggestions. Using capitalised names was solely because the specification had `A` and `B` capitalised."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T22:26:55.307",
"Id": "68007",
"Score": "1",
"body": "@Alec That's fine. It's just more common for variable names to start with a lowercase letter, so I was wondering why it was uppercase."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T23:19:21.723",
"Id": "68013",
"Score": "0",
"body": "I prefer comments on the previous line, not inline."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T23:20:58.707",
"Id": "68014",
"Score": "0",
"body": "@ChrisW Depending on how long the comments are, yes. If it is a short description that can easily fit on the same line, then I usually put them on the same line."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T21:52:02.147",
"Id": "40397",
"ParentId": "40394",
"Score": "14"
}
},
{
"body": "<p>I have a bit of a bone to pick with this:</p>\n\n<pre><code>#define ABS(a) ({ typeof (a) _a = (a); _a > 0 ? _a : -_a; })\n</code></pre>\n\n<p>Firstly, <code>typeof</code> is a gcc extension, so by using this, you're making your code less portable. To be fair, for something small like this, it's not a big problem, but it's a bit of a bad habit to get into. In this case, it's also not even needed.</p>\n\n<pre><code>#define ABS(x) ((x) > 0 ? x : -x)\n</code></pre>\n\n<p>works just as well.</p>\n\n<p>However, all of this isn't really necessary. <code><math.h></code> defines <code>abs</code> (for integers) and <code>fabs</code> (for floating point values) for you. Use the standard library unless you have very good reason not to.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T06:52:35.833",
"Id": "68042",
"Score": "2",
"body": "On the other hand, if you _are_ using a compiler that supports `typeof`, such as GCC or Clang, this `ABS(x)` macro avoid evaluating its argument twice."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T01:04:57.150",
"Id": "40414",
"ParentId": "40394",
"Score": "9"
}
},
{
"body": "<h2>\\$O(1)\\$ Discussion</h2>\n\n<blockquote>\n <p>Is it possible to calculate the distance in \\$O(1)\\$ time complexity?</p>\n</blockquote>\n\n<p>Yes, it is.</p>\n\n<p>This problem is called the <em>\"Knight's distance\"</em> problem, and googling it find a number of references.</p>\n\n<p>This problem was posed as part of the South African \"Computer Olympiad\" in 2007 for high-school students to solve.... (I know, kids these days.... :) ). The specification was such that some input values for the programs were large enough that \\$O(n)\\$ solutions would fail to compute in the required time limits, so to get full marks you needed to (devise, and) compute the \\$O(1)\\$ system.</p>\n\n<p>The <a href=\"http://olympiad.cs.uct.ac.za/old/saco2007/day1_2007.pdf\" rel=\"noreferrer\">problem description</a>, and enough of the description of <a href=\"http://olympiad.cs.uct.ac.za/old/saco2007/day1_2007_solutions.pdf\" rel=\"noreferrer\">the \\$O(1)\\$ solution are</a> available. In case the .za net goes dead, here's the description of the solution:</p>\n\n<blockquote>\n <p><strong>4 The Knights Who Say Ni</strong></p>\n \n <p>The (x, y)-coordinates in the 50% constraints are small enough to\n generate a full grid of the minimum number of moves required to get\n from any point to (0,0). The grid can be generated by a breadth-first\n search (BFS).</p>\n \n <p>We know that getting to (0,0) requires 0 moves. We therefore know that\n the points (1,2), (2,1) and the other six movements each require 1\n move. From each of those points with a shortest distance of 1, we can\n take another step in each direction for a shortest path of 2. However,\n some moves will bring us back to a point we have already found a\n shorter distance for and we therefore discard such moves. We continue\n this until the grid is full and then use the grid to find the\n distances for each knight.</p>\n \n <p>To get 100%, a lot of scribbling on paper is required to make some key\n observations and work out some formulae. The first thing to note is\n that the grid is symetrical along the x, y axis and the lines <code>y = ±x</code>.\n You can therefore convert all points <code>(x, y)</code> into an equivalent\n point such that the new <code>0 ≤ y ≤ x</code>.</p>\n \n <p>The magic formula is:</p>\n \n <p>$$\nf(x, y) = \\left\\{\n \\begin{array}{ll}\n 2 \\left\\lfloor \\frac{y - \\delta}{3} \\right\\rfloor + \\delta & \\mbox{if } y > \\delta \\\\\n \\delta - 2 \\left\\lfloor \\frac{\\delta - y}{4} \\right\\rfloor & \\mbox{otherwise}\n \\end{array}\n\\right.\n$$</p>\n \n <p>where \\$δ = x − y\\$.</p>\n</blockquote>\n\n<h2>Are there mistakes</h2>\n\n<p>Yes.... All squares are accessible to the knight. Why do you have a restriction?</p>\n\n<p>I put your code in to an Ideone that loops through the 100 targets in positions (0,0) through (9,9).... and <a href=\"http://ideone.com/Akyx2M\" rel=\"noreferrer\">its results are disappointing</a>... Does your code work?</p>\n\n<p>NO. it does not. It produces wildly wrong values.....</p>\n\n<p>Now, the algorithm I referenced above does not seem to be producing good values either (at least a short range....), but seriously? Your code hardly works at all :(</p>\n\n<p>Lots, and lots of -1 distances, and lots and lots of 0.....</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T07:01:09.283",
"Id": "68044",
"Score": "2",
"body": "Found a solution with O(1) time. https://chessprogramming.wikispaces.com/Knight-Distance"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-08T12:29:07.543",
"Id": "215741",
"Score": "0",
"body": "For x=1, and y=0 the formula gives 1, how is this possible?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-12-09T23:56:30.370",
"Id": "281076",
"Score": "1",
"body": "The formulae seemingly works only for larger input, when there is no back-motion necessary. However, I'm still wondering how did they figure it out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-01-18T13:18:44.440",
"Id": "288934",
"Score": "0",
"body": "This formula has a small mistake, for correct one look here http://stackoverflow.com/a/41704071/827753"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T05:51:31.207",
"Id": "40431",
"ParentId": "40394",
"Score": "18"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-01-29T21:14:56.200",
"Id": "40394",
"Score": "23",
"Tags": [
"c",
"pathfinding"
],
"Title": "Calculate the number of moves requires for a knight chess piece"
}
|
40394
|
<ul>
<li>Official site: <a href="http://automapper.org/" rel="nofollow">http://automapper.org/</a></li>
<li>Stack Overflow tag wiki: <a href="http://stackoverflow.com/tags/automapper/info">http://stackoverflow.com/tags/automapper/info</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T22:02:32.840",
"Id": "40400",
"Score": "0",
"Tags": null,
"Title": null
}
|
40400
|
A convention-based object-to-object mapper and transformer for .NET.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T22:02:32.840",
"Id": "40401",
"Score": "0",
"Tags": null,
"Title": null
}
|
40401
|
<p>This is my solution for the <a href="http://projecteuler.net/problem=5" rel="nofollow">5th problem of Project Euler</a>, which asks for the least common multiples of the numbers from 1 to 20 (inclusive). Is there any way to improve the while loop conditional instead of using the sum?</p>
<pre><code>table = range(1, 21)
result = 1
pf = 2
while sum(table) > len(table):
flag = False
for x, y in enumerate(table):
if y % pf == 0:
table[x] = y/pf
flag = True
if flag:
result *= pf
else:
pf += 1
print result
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T13:58:52.110",
"Id": "68080",
"Score": "0",
"body": "are you interested in a functional solution without loops?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T16:53:48.740",
"Id": "68123",
"Score": "1",
"body": "Nah I I know that it's possible to do the same using gcd and reduce, I just want to see how to better optimize this certain algorithm which is basically a pencil and paper algorithm designed for humams. Usually this ends when all elements become 1."
}
] |
[
{
"body": "<p>Use a constant. It's easier to understand when you want to go back and try a different value too.</p>\n\n<p>Copying my answer from stack overflow, also changed things around since this is code review.</p>\n\n<pre><code>MAX_FACTOR = 20 #The largest divisor we want to be able to divide by\n\n#should have a general outline of the algorithm here\ntable = range(1,MAX_FACTOR + 1)\nresult = 1 #final result is stored here\ncurrentFactor = 2 #what we're currently trying to divide by\nwhile currentFactor <= MAX_FACTOR:\n isDivisor = False #is the currentFactor a divisor\n for x,y in enumerate(table):\n if y % currentFactor == 0:\n table[x] = y/currentFactor \n isDivisor = True\n if isDivisor:\n result *= currentFactor\n else:\n currentFactor += 1\nprint result\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T04:42:00.230",
"Id": "40429",
"ParentId": "40402",
"Score": "0"
}
},
{
"body": "<p>Your intent is to terminate the loop when all entries in <code>table</code> become 1. This</p>\n\n<pre><code>while sum(table) > len(table):\n</code></pre>\n\n<p>is a rather obscure way of expressing that intent. I suggest instead</p>\n\n<pre><code>while max(table) > 1:\n</code></pre>\n\n<p>or the more explicit and short-circuiting</p>\n\n<pre><code>while any(x > 1 for x in table):\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T09:29:51.080",
"Id": "40445",
"ParentId": "40402",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "40445",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T22:21:45.123",
"Id": "40402",
"Score": "2",
"Tags": [
"python",
"optimization",
"project-euler"
],
"Title": "Optimizing Python code for Project Euler #5 (LCM of all numbers from 1 to 20)"
}
|
40402
|
<p>I'm curious to see what any of the more experienced programmers would do instead of methods I took as a learning tool. Any tips/tricks/fixes and reasoning is appreciated!!</p>
<p><a href="http://www.jacobweyer.com" rel="nofollow">http://www.jacobweyer.com</a></p>
<p>This is the result of the code so far:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Alpha Tau Omega | Theta Omega</title>
<link rel="stylesheet" type="text/css" href="ATOStyle.css" />
</head>
<body>
<div id="header">
<div id="innerheader">
<div id="banner">
</div>
<div id="title">
<!--<p>Alpha Tau Omega</p>
<p>Theta Omega</p>-->
</div>
<div id="navbar">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="rush.html">Rush</a></li>
<li><a href="history.html">History</a></li>
<li><a href="alumni.html">Alumni</a></li>
<li><a href="calendar.html">Calendar</a></li>
<li><a href="media.html">Media</a></li>
</ul>
</div>
</div>
</div>
<div id="pagecenter">
</div>
<div id="footer">
<div id="footercontent">
<div id="footerbanner">
</div>
</div>
</div>
</body>
</html>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>html, body, div, span, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
abbr, address, cite, code,
del, dfn, em, img, ins, kbd, q, samp,
small, strong, sub, sup, var,
b, i,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, figure, footer, header,&nbsp;hgroup, menu, nav, section, menu,
time, mark, audio, video {
margin:0px;
padding:0px;
border:0px;
outline:0px;
font-size:100%;
vertical-align:baseline;
background:transparent;
}
#navbar ul {
list-style-type: none;
margin: 0px;
padding: 0px;
}
#navbar ul li a {
text-decoration: none;
color: black;
}
#navbar ul li a:hover {
color: white;
}
#navbar ul li {
font-family: Arial, Helvetica, sans-serif;
text-decoration: none;
color: #000000;
display: inline-block;
width: 70px;
height: 40px;
margin: 10px;
}
#banner {
background:url(./pieces/banner.png);
position: absolute;
margin-left: 0px;
min-height: 193px;
min-width: 183px;
background-repeat: no-repeat
}
#title {
position: absolute;
background: url(./pieces/name.png);
margin-left: 190px;
min-height: 75px;
min-width: 285px;
}
#navbar {
position: relative;
top: 80px;
left: 210px;
margin-left: inherit;
}
#social ul li{
display: inline-block;
width: 35px;
height: 35px;
margin: 5px;
}
#social {
position: absolute;
float: left;
right: 180px;
top: -5px;
}
#social ul {
list-style-type: none;
}
#innerheader {
height: 139px;
width: 750px;
margin-right: auto;
margin-left: auto;
position: relative;
}
#header {
background:url(./pieces/headerBar.png);
position: static;
width:100%;
height:139px;
padding:0;
border:0;
z-index: 10000;
}
#pagecenter {
position: static;
margin-right: auto;
margin-left: auto;
height: 50px;
width: 750px;
min-height: 1000px;
background:url(./pieces/mainBG.png);
background-position: center;
background-repeat: no-repeat;
background-attachment: fixed;
margin-top: -19px;
z-index:50
}
body {
width: 100%;
margin: 0px 0px 0px 0px;
background-color: #808080
}
#footer {
margin-top: 20px;
padding-top: 30px;
background: url(./pieces/footerbar.png);
height: 77px;
width: 100%;
margin-right: auto;
margin-left: auto;
clear: both;
bottom: 0px;
position: static;
}
#footerbanner {
background: url(./pieces/footerbanner.png);
position: absolute;
min-height: 95px;
min-width: 90px;
background-repeat: no-repeat;
margin-top: -30px;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T23:53:18.470",
"Id": "68015",
"Score": "0",
"body": "[I think your code looks fine.](http://meta.codereview.stackexchange.com/a/96/34757)"
}
] |
[
{
"body": "<p>I see no problems with it. However, at the HTML section, try adding maybe 2 lines of blank space in between the all of the divs. An example lies below.</p>\n\n<pre><code><div id=\"pagecenter\">\n\n\n</div>\n\n\n<div id=\"footer\">\n\n\n<div id=\"footercontent\">\n\n\n<div id=\"footerbanner\">\n\n\n</div>\n\n\n</div>\n\n\n</div>\n\n\n</body>\n\n\n</html> \n</code></pre>\n\n<p>This could help your code look more clean, separate, and easier to maintain over time. I hope I helped!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T22:49:40.107",
"Id": "68011",
"Score": "4",
"body": "For me this feels like too much whitespace."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T22:51:40.827",
"Id": "68012",
"Score": "0",
"body": "For some it could be, but to be honest, if you wanted, you could leave it at one enter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T03:40:00.177",
"Id": "68026",
"Score": "0",
"body": "Your sample should be at least indented ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T03:46:50.060",
"Id": "68032",
"Score": "0",
"body": "konjin, I was going to do it but I thought that OP would do that already, I was just leaving some room for op."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T22:48:03.030",
"Id": "40408",
"ParentId": "40407",
"Score": "-7"
}
},
{
"body": "<p>I don't care for all that whitespace myself. I prefer to leave empty divs on a single line like so:</p>\n\n<pre><code><div id=\"footer\"></div>\n</code></pre>\n\n<p>I put the closing tag on a separate line only where there is content, and in either case, of course, indent as appropriate for ease of reading.</p>\n\n<p>You can reduce your CSS reset chunk by using a more universal selector. Instead of this:</p>\n\n<pre><code>html, body, div, span, object, iframe,\nh1, h2, h3, h4, h5, h6, p, blockquote, pre,\nabbr, address, cite, code,\ndel, dfn, em, img, ins, kbd, q, samp,\nsmall, strong, sub, sup, var,\nb, i,\ndl, dt, dd, ol, ul, li,\nfieldset, form, label, legend,\ntable, caption, tbody, tfoot, thead, tr, th, td,\narticle, aside, figure, footer, header,&nbsp;hgroup, menu, nav, section, menu,\ntime, mark, audio, video {\nmargin:0px;\npadding:0px;\nborder:0px;\noutline:0px;\nfont-size:100%;\nvertical-align:baseline;\nbackground:transparent;\n}\n</code></pre>\n\n<p>Try this with your selectors, and put all your CSS on one line per declaration:</p>\n\n<pre><code>html, html * { padding:0px; border:0px; margin:0px; outline:0px; font-size:100%; vertical-align:baseline; background:transparent; }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T00:57:09.890",
"Id": "68017",
"Score": "0",
"body": "It is also a good idea to have a set order in which you do your stylesheet declarations, too. That way you always know where to look to find the exact style you wish to modify. I generally start with the display and positioning, then the box model elements from width/height moving outward (padding, border, margin), then font declarations if any, then color, then background, roughly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-26T17:28:56.587",
"Id": "370835",
"Score": "0",
"body": "Since writing the above comment I have shifted my approach to alphabetizing the style attributes instead. Much easier and universal than having a private organization scheme. Just FYI."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T23:48:37.850",
"Id": "40409",
"ParentId": "40407",
"Score": "4"
}
},
{
"body": "<p>A lot of this type of stuff is just personal style, or if you're working on a team, the layout is defined ahead of the project.</p>\n\n<p>The use of classes vs id's is also personal. I've seen people say that they ALWAYS use classes. I've tried both classes and id's on many pages, and I find that I get into fewer problems with mostly classes, reserving id's for truly individual elements.</p>\n\n<p>I've read that the stuff at the top of your CSS can slow things down quite a bit and may not be necessary in many cases.</p>\n\n<p>I formatted the last two parts of your CSS a bit differently. I do that a lot with PHP, but have seen in recently in CSS, and I think it might work nicely in some situations.</p>\n\n<p>But for fun...</p>\n\n<pre><code><!DOCTYPE html>\n<html>\n<head>\n <title>Alpha Tau Omega | Theta Omega</title>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"ATOStyle.css\" />\n</head>\n\n<body>\n<div id=\"header\">\n <div id=\"innerheader\">\n <div id=\"banner\"></div>\n <div id=\"title\"><!--<p>Alpha Tau Omega</p> <p>Theta Omega</p>--></div>\n <div id=\"navbar\">\n <ul>\n <li><a href=\"index.html\">Home</a></li>\n <li><a href=\"rush.html\">Rush</a></li>\n <li><a href=\"history.html\">History</a></li>\n <li><a href=\"alumni.html\">Alumni</a></li>\n <li><a href=\"calendar.html\">Calendar</a></li>\n <li><a href=\"media.html\">Media</a></li>\n </ul>\n </div><!--end navbar-->\n </div><!--end banner-->\n </div><!--end innerheader-->\n</div><!--end header-->\n\n<div id=\"pagecenter\"></div>\n\n<div id=\"footer\">\n <div id=\"footercontent\">\n <div id=\"footerbanner\"></div>\n </div>\n</div><!--end footer-->\n\n</body>\n</html>\n</code></pre>\n\n<p>CSS</p>\n\n<pre><code>html, body, div, span, object, iframe,\nh1, h2, h3, h4, h5, h6, p, blockquote, pre,\nabbr, address, cite, code,\ndel, dfn, em, img, ins, kbd, q, samp,\nsmall, strong, sub, sup, var,\nb, i, dl, dt, dd, ol, ul, li,\nfieldset, form, label, legend,\ntable, caption, tbody, tfoot, thead, tr, th, td,\narticle, aside, figure, footer, header,&nbsp;hgroup, menu, nav, section, menu,\ntime, mark, audio, video {\n margin: 0px;\n padding: 0px;\n border: 0px;\n outline: 0px;\n font-size: 100%;\n vertical-align: baseline;\n background: transparent;\n}\n#navbar ul {\n list-style-type: none;\n margin: 0px;\n padding: 0px;\n}\n#navbar ul li a {\n text-decoration: none;\n color: black; \n}\n#navbar ul li a:hover {\n color: white;\n}\n#navbar ul li {\n font-family: Arial, Helvetica, sans-serif; \n text-decoration: none;\n color: #000000;\n display: inline-block;\n width: 70px;\n height: 40px;\n margin: 10px;\n}\n#banner {\n background:url(./pieces/banner.png);\n position: absolute;\n margin-left: 0px;\n min-height: 193px;\n min-width: 183px;\n background-repeat: no-repeat\n}\n\n#title {\n position: absolute;\n background: url(./pieces/name.png);\n margin-left: 190px;\n min-height: 75px;\n min-width: 285px;\n}\n#navbar {\n position: relative;\n top: 80px;\n left: 210px;\n margin-left: inherit;\n}\n#social ul li{\n display: inline-block;\n width: 35px;\n height: 35px;\n margin: 5px;\n}\n#social {\n position: absolute;\n float: left;\n right: 180px;\n top: -5px;\n}\n#social ul {\n list-style-type: none;\n}\n\n#innerheader {\n height: 139px;\n width: 750px;\n margin-right: auto;\n margin-left: auto;\n position: relative;\n}\n\n#header {\n background:url(./pieces/headerBar.png);\n position: static; \n width:100%;\n height:139px;\n z-index: 10000;\n}\n\n#pagecenter {\n position: static;\n margin-right: auto;\n margin-left: auto;\n height: 50px;\n width: 750px;\n min-height: 1000px;\n background: url(./pieces/mainBG.png);\n background-position: center;\n background-repeat: no-repeat;\n background-attachment: fixed;\n margin-top: -19px;\n z-index:50\n}\nbody {\n width: 100%;\n margin: 0px 0px 0px 0px;\n background-color: #808080\n}\n#footer {\n margin-top: 20px;\n padding-top: 30px;\n background: url(./pieces/footerbar.png);\n height: 77px;\n width: 100%;\n margin-right: auto;\n margin-left: auto;\n clear: both;\n bottom: 0px;\n position: static;\n}\n#footerbanner {\n background: url(./pieces/footerbanner.png);\n position: absolute;\n min-height: 95px;\n min-width: 90px;\n background-repeat: no-repeat;\n margin-top: -30px;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T10:13:51.003",
"Id": "68287",
"Score": "1",
"body": "IDs identify an element, classes identify a type of element: several elements can have the same class, but an ID value must be unique to a single element."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T23:50:55.900",
"Id": "40410",
"ParentId": "40407",
"Score": "6"
}
},
{
"body": "<p>Your HTML is good. Your CSS is good. Once you start coding more you will find out the way you like to style your CSS and HTML and then other languages. However, if you're working with other people or for a company, then you all likely would agree on certain coding styles.</p>\n\n<p>This is how I prefer to do my CSS.</p>\n\n<p>It doesn't show exactly visually correct on here since the width is limited. But if you copy paste it to a full notepad, you will see a better visual of how it really is pretty organized.</p>\n\n<p>The reset is just one line at the top.</p>\n\n<p>Similiar items don't have any line spacing between them. Like navbar ul, li, li a, li a:hover.</p>\n\n<p>If a elements styling is going to be wider than the notedpad view, then I just hit enter and start a new line. An example of this is #pagecenter.</p>\n\n<p>The benefit to this coding style is that you don't have to scroll up and down so much.</p>\n\n<p>I actually fit all your CSS on the screen, so I don't have to scroll up or down at all. I don't have to scroll right , since the only thing to the right is the reset.</p>\n\n<pre><code>html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; } body { line-height: 1; } ol, ul { list-style: none; } blockquote, q { quotes: none; } blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; } table { border-collapse: collapse; border-spacing: 0; }\n\n#navbar { position: relative;top: 80px;left: 210px; margin-left: inherit; }\n#navbar ul { list-style-type: none; margin: 0px; padding: 0px; }\n#navbar ul li { font-family: Arial, Helvetica, sans-serif; text-decoration: none; color: #000000; display: inline-block; width: 70px; height: 40px; margin: 10px; }\n#navbar ul li a { text-decoration: none; color: black; }\n#navbar ul li a:hover { color: white; }\n\n#banner { background:url(./pieces/banner.png);position: absolute; margin-left: 0px; min-height: 193px; min-width: 183px; background-repeat: no-repeat; }\n\n#title { position: absolute; background: url(./pieces/name.png); margin-left: 190px; min-height: 75px; min-width: 285px; }\n\n#social { position: absolute; float: left; right: 180px; top: -5px; }\n#social ul { list-style-type: none; }\n#social ul li{ display: inline-block;width: 35px; height: 35px;margin: 5px; }\n\n#innerheader { height: 139px; width: 750px; margin-right: auto; margin-left: auto; position: relative; }\n\n#header { background:url(./pieces/headerBar.png); position: static; width:100%; height:139px; padding:0; border:0; z-index: 10000; }\n\n#pagecenter {position: static; margin-right: auto; margin-left: auto; height: 50px; width: 750px; min-height: 1000px; \n background:url(./pieces/mainBG.png); background-position: center; background-repeat: no-repeat; background-attachment: fixed;\n margin-top: -19px; z-index:50; }\n\nbody { width: 100%;margin: 0px 0px 0px 0px;background-color: #808080}\n\n#footer { margin-top: 20px; padding-top: 30px; background: url(./pieces/footerbar.png); height: 77px; width: 100%; margin-right: auto; margin-left: auto; \n clear: both; bottom: 0px; position: static; }\n\n#footerbanner { background: url(./pieces/footerbanner.png); position: absolute; min-height: 95px; min-width: 90px; background-repeat: no-repeat; margin-top: -30px; }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T00:19:13.113",
"Id": "40412",
"ParentId": "40407",
"Score": "5"
}
},
{
"body": "<p><strong>HTML:</strong></p>\n\n<ul>\n<li>With the HTML5 doctype being set, you don't need the <code>type</code> attribute on your link, style and script tags anymore. You can safely ommit them.</li>\n<li>Just a note: It's possible to ommit the <code>/</code> on self-closing html tags like <code>link</code> or <code>img</code> as well.</li>\n<li><p>You should add the meta charset and viewport tags. The first one ensures your site uses the correct character encoding and the second one is relevant for mobile devices.</p>\n\n<pre><code><meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n</code></pre></li>\n<li><p>You're using an ID for everything. You may think these things will only occur once on my page and a ID is perfectly fine. In my opinion, it's not. There may be multiple header and footers on a page.</p>\n\n<p>Also an ID has a higher CSS specificity value and overwriting it with a class is <em>almost</em> impossible. I don't use ID's as styling hooks at all and completely rely on classes.</p>\n\n<p>Some of your ID names also have a bad naming. Your header is your site wide header, it should have a name like <code>site-header</code> or <code>site-head</code>. Otherwise it's not clear from your markup what you're actually looking at.</p></li>\n</ul>\n\n<p><strong>CSS:</strong></p>\n\n<ul>\n<li><p>I for my part would avoid these exzessive CSS resets. It just makes your work harder setting the necessary values for all those elements again. Removing the default <code>margin</code> and <code>padding</code> from some block-level elements is enough in almost all cases:</p>\n\n<pre><code>h1, h2, h3, h4, h5, h6,\np, blockquote, pre,\ndl, dd, ol, ul,\nform, fieldset, legend,\ntable, th, td, caption,\nhr {\n margin: 0;\n padding: 0;\n}\n</code></pre></li>\n<li><p>If you're setting a property value to zero, you don't need to add the unit. Zero is zero. <code>margin: 0;</code> is enough easier to write</p></li>\n<li>Selecting a list-item inside a list is unnecessary. A list-item is always part of a list, you usually only need <code>#navbar li</code> or <code>#navbar a</code></li>\n<li>Also (again opinionated) I intend the declarations inside a CSS rule (see above), because it's easier to distinct between the seperate blocks.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T18:02:24.317",
"Id": "68134",
"Score": "1",
"body": "I disagree about omitting the `/` on self-closing tags as that wouldn't be valid XHTML. (And it's never wrong to have valid XHTML)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T18:08:41.040",
"Id": "68136",
"Score": "0",
"body": "@Simon If one uses the HTML5 doctype, why would you care for you document to be valid __X__HTML? The meta charset rule isn't valid XHTML either."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T18:11:24.227",
"Id": "68137",
"Score": "0",
"body": "I'm not a HTML-guy so I might be the wrong person to ask :) But I just want to answer that with: \"Why wouldn't you?\". To me, it's good practice to close your tags either way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T18:14:31.117",
"Id": "68138",
"Score": "0",
"body": "@Simon Simply because you don't need to. These tags are really just for holding the attributes and their values. There won't be scenario where you need `<link ...><!--content--></link>`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T18:30:30.410",
"Id": "68139",
"Score": "2",
"body": "After reading up on the subject a bit, it seems like you're right. +1. I will still probably use `<link ... />` though as that is also valid in HTML5, and to me it looks better :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T18:38:29.507",
"Id": "68141",
"Score": "2",
"body": "@Simon Valid XHTML is also valid HTML5. ;)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T17:22:40.540",
"Id": "40478",
"ParentId": "40407",
"Score": "6"
}
},
{
"body": "<p>There's an error message if check this against the <strong><a href=\"http://validator.w3.org/\" rel=\"nofollow noreferrer\">The W3C Markup Validation Service</a></strong>. It suggests you add an element such as,</p>\n\n<pre><code><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" >\n</code></pre>\n\n<p>Or, <a href=\"https://stackoverflow.com/a/4696517/49942\">for HTML5</a>, simply:</p>\n\n<pre><code><meta charset=\"utf-8\">\n</code></pre>\n\n<p>Maybe this particular 'error' isn't an important error at this stage.</p>\n\n<p>But I did want to mention it because I want you to know that <a href=\"http://validator.w3.org/\" rel=\"nofollow noreferrer\">http://validator.w3.org/</a> exists -- I recommend you use this to 'validate' your finished HTML before you publish it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T19:22:05.580",
"Id": "68150",
"Score": "0",
"body": "@kleinfreund That looks like cleaner syntax than [the `<meta>` element which I suggested](http://www.w3.org/International/O-charset). In my answer I mostly wanted to tell the OP that the W3C validator exists."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T19:24:59.000",
"Id": "68153",
"Score": "0",
"body": "The charset meta tag you suggested is the one for XHTML and/or HTML4. HTML5 uses the shorter syntax. Validating an HTML document to check for issues is always a good idea, especially if one is new to this stuff."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T19:11:49.960",
"Id": "40484",
"ParentId": "40407",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "40410",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-29T22:41:12.147",
"Id": "40407",
"Score": "6",
"Tags": [
"html",
"css"
],
"Title": "How would you better organize/code this basic HTML and CSS?"
}
|
40407
|
<p>I'm building an installer package for our software using Inno Setup. As a part of this, I'm also building a few different DLL's in Delphi XE2 to accommodate for some of the common tasks required by the installer. One of those is querying and manipulating settings on these instances. I intend to support SQL versions 2005 and above.</p>
<p>The things I need to query are:</p>
<ul>
<li>List of all installed instances</li>
<li>Versions of all installed instances</li>
<li>Settings which I need to change (explained next)</li>
</ul>
<p>The settings I need to change are:</p>
<ul>
<li>Enable/Disable TCP/IP Protocol</li>
<li>Enable/Disable Named Pipes Protocol</li>
<li>Change Dynamic Ports of TCP/IP</li>
<li>Change Port Number of TCP/IP</li>
</ul>
<p>What I understand is that this is all found in the registry, for example</p>
<p><img src="https://i.stack.imgur.com/6M7PS.png" alt="SQL Server Config in Registry"></p>
<p>I do know this can be done using WMI as well, but I'd rather avoid WMI if at all possible. I also know that I need to restart the instance to apply any changes.</p>
<p><strong>SQLHelper.dll</strong></p>
<pre><code>library SQLHelper;
uses
System.SysUtils,
System.Classes,
System.Win.Registry,
WinApi.Windows;
{$R *.res}
const
SQL_INSTANCES_KEY = 'Software\Microsoft\Microsoft SQL Server\Instance Names\SQL\';
SQL_INST_ROOT_KEY = 'Software\Microsoft\Microsoft SQL Server\%s\MSSQLServer\';
type
TStringArray = array of String;
function Is64BitOS: Bool; stdcall;
type
TIsWow64Process = function(Handle:THandle; var IsWow64 : BOOL) : BOOL; stdcall;
var
hKernel32 : Integer;
IsWow64Process : TIsWow64Process;
IsWow64 : BOOL;
begin
Result := False;
hKernel32 := LoadLibrary('kernel32.dll');
try
if (hKernel32 = 0) then RaiseLastOSError;
@IsWow64Process := GetProcAddress(hkernel32, 'IsWow64Process');
if Assigned(IsWow64Process) then begin
IsWow64 := False;
if (IsWow64Process(GetCurrentProcess, IsWow64)) then begin
Result := IsWow64;
end else RaiseLastOSError;
end;
finally
FreeLibrary(hKernel32);
end;
end;
function RegAccess: Cardinal; stdcall;
begin
Result:= KEY_READ or KEY_WRITE;
if Is64BitOS then
Result:= Result or KEY_WOW64_64KEY;
end;
function GetSQLInstanceList(var A: TStringArray): Bool; stdcall;
var
R: TRegistry;
L: TStringList;
X: Integer;
begin
Result:= False;
SetLength(A, 0);
R:= TRegistry.Create(RegAccess);
try
R.RootKey:= HKEY_LOCAL_MACHINE;
if R.KeyExists(SQL_INSTANCES_KEY) then begin
if R.OpenKey(SQL_INSTANCES_KEY, False) then begin
L:= TStringList.Create;
try
R.GetValueNames(L);
SetLength(A, L.Count);
for X := 0 to L.Count - 1 do begin
A[X]:= L[X];
end;
Result:= True;
finally
L.Free;
end;
R.CloseKey
end;
end;
finally
R.Free;
end;
end;
function GetSQLInstanceID(const Instance: WideString): WideString; stdcall;
var
R: TRegistry;
begin
Result:= '';
R:= TRegistry.Create(RegAccess);
try
R.RootKey:= HKEY_LOCAL_MACHINE;
if R.KeyExists(SQL_INSTANCES_KEY) then begin
if R.OpenKey(SQL_INSTANCES_KEY, False) then begin
if R.ValueExists(Instance) then begin
Result:= R.ReadString(Instance);
end;
R.CloseKey
end;
end;
finally
R.Free;
end;
end;
function GetSQLInstanceExists(const Instance: WideString): Bool; stdcall;
begin
Result:= GetSQLInstanceID(Instance) <> '';
end;
function GetSQLInstanceRootKey(const Instance: WideString): WideString; stdcall;
begin
Result:= Format(SQL_INST_ROOT_KEY, [GetSQLInstanceID(Instance)]);
end;
function GetSQLInstanceVerKey(const Instance: WideString): WideString; stdcall;
begin
Result:= GetSQLInstanceRootKey(Instance)+'CurrentVersion\';
end;
function GetSQLInstanceConfigKey(const Instance: WideString): WideString; stdcall;
begin
Result:= GetSQLInstanceRootKey(Instance)+'SuperSocketNetLib\';
end;
function GetSQLInstanceVer(const Instance: WideString): WideString; stdcall;
var
R: TRegistry;
begin
Result:= '';
R:= TRegistry.Create(RegAccess);
try
R.RootKey:= HKEY_LOCAL_MACHINE;
if R.KeyExists(GetSQLInstanceVerKey(Instance)) then begin
if R.OpenKey(GetSQLInstanceVerKey(Instance), False) then begin
if R.ValueExists('CurrentVersion') then begin
Result:= R.ReadString('CurrentVersion');
end;
R.CloseKey;
end;
end;
finally
R.Free;
end;
end;
function GetSQLInstanceProtocolEnabled(const Instance, Protocol: WideString): Bool; stdcall;
var
R: TRegistry;
begin
Result:= False;
R:= TRegistry.Create(RegAccess);
try
R.RootKey:= HKEY_LOCAL_MACHINE;
if R.KeyExists(GetSQLInstanceConfigKey(Instance)+Protocol) then begin
if R.OpenKey(GetSQLInstanceConfigKey(Instance)+Protocol, False) then begin
if R.ValueExists('Enabled') then begin
Result:= R.ReadInteger('Enabled') = 1;
end;
R.CloseKey;
end;
end;
finally
R.Free;
end;
end;
function SetSQLInstanceProtocolEnabled(const Instance, Protocol: WideString;
const Enabled: Bool): Bool; stdcall;
var
R: TRegistry;
V: Integer;
begin
Result:= False;
R:= TRegistry.Create(RegAccess);
try
R.RootKey:= HKEY_LOCAL_MACHINE;
if R.KeyExists(GetSQLInstanceConfigKey(Instance)+Protocol) then begin
if R.OpenKey(GetSQLInstanceConfigKey(Instance)+Protocol, False) then begin
if R.ValueExists('Enabled') then begin
if Enabled then V:= 1 else V:= 0;
R.WriteInteger('Enabled', V);
Result:= True;
end;
R.CloseKey;
end;
end;
finally
R.Free;
end;
end;
function GetSQLInstanceTCPPort(const Instance: WideString): Integer; stdcall;
var
R: TRegistry;
begin
Result:= 0;
R:= TRegistry.Create(RegAccess);
try
R.RootKey:= HKEY_LOCAL_MACHINE;
if R.KeyExists(GetSQLInstanceConfigKey(Instance)+'Tcp\IPAll\') then begin
if R.OpenKey(GetSQLInstanceConfigKey(Instance)+'Tcp\IPAll\', False) then begin
if R.ValueExists('TcpPort') then begin
Result:= R.ReadInteger('TcpPort');
end;
R.CloseKey;
end;
end;
finally
R.Free;
end;
end;
function SetSQLInstanceTCPPort(const Instance: WideString; const Port: Integer): Bool; stdcall;
var
R: TRegistry;
begin
Result:= False;
R:= TRegistry.Create(RegAccess);
try
R.RootKey:= HKEY_LOCAL_MACHINE;
if R.KeyExists(GetSQLInstanceConfigKey(Instance)+'Tcp\IPAll\') then begin
if R.OpenKey(GetSQLInstanceConfigKey(Instance)+'Tcp\IPAll\', False) then begin
if R.ValueExists('TcpPort') then begin
R.WriteInteger('TcpPort', Port);
Result:= True;
end;
R.CloseKey;
end;
end;
finally
R.Free;
end;
end;
function GetSQLInstanceTCPDynamicPorts(const Instance: WideString): Integer; stdcall;
var
R: TRegistry;
begin
Result:= 0;
R:= TRegistry.Create(RegAccess);
try
R.RootKey:= HKEY_LOCAL_MACHINE;
if R.KeyExists(GetSQLInstanceConfigKey(Instance)+'Tcp\IPAll\') then begin
if R.OpenKey(GetSQLInstanceConfigKey(Instance)+'Tcp\IPAll\', False) then begin
if R.ValueExists('TcpDynamicPorts') then begin
Result:= R.ReadInteger('TcpDynamicPorts');
end;
R.CloseKey;
end;
end;
finally
R.Free;
end;
end;
function SetSQLInstanceTCPDynamicPorts(const Instance: WideString; const Port: Integer): Bool; stdcall;
var
R: TRegistry;
begin
Result:= False;
R:= TRegistry.Create(RegAccess);
try
R.RootKey:= HKEY_LOCAL_MACHINE;
if R.KeyExists(GetSQLInstanceConfigKey(Instance)+'Tcp\IPAll\') then begin
if R.OpenKey(GetSQLInstanceConfigKey(Instance)+'Tcp\IPAll\', False) then begin
if R.ValueExists('TcpDynamicPorts') then begin
R.WriteInteger('TcpDynamicPorts', Port);
Result:= True;
end;
R.CloseKey;
end;
end;
finally
R.Free;
end;
end;
exports
Is64BitOS,
RegAccess,
GetSQLInstanceList,
GetSQLInstanceID,
GetSQLInstanceExists,
GetSQLInstanceRootKey,
GetSQLInstanceVerKey,
GetSQLInstanceConfigKey,
GetSQLInstanceVer,
GetSQLInstanceProtocolEnabled,
SetSQLInstanceProtocolEnabled,
GetSQLInstanceTCPPort,
SetSQLInstanceTCPPort,
GetSQLInstanceTCPDynamicPorts,
SetSQLInstanceTCPDynamicPorts;
begin
end.
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T20:40:22.807",
"Id": "70872",
"Score": "0",
"body": "<Review>Although registry are tasty piece of cake, I would strongly recommend you to use [`WMI`](http://msdn.microsoft.com/en-us/library/ms180499.aspx) for your task. That's many times recommended suggestion.</Review> :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T20:45:38.873",
"Id": "70873",
"Score": "0",
"body": "<response>@TLama Indeed :-)</response>"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T21:08:30.330",
"Id": "70874",
"Score": "0",
"body": "@TLama I've seen awkward occasions where clients disable WMI, IT people can enforce some strange rules"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T21:15:32.980",
"Id": "70875",
"Score": "0",
"body": "It's upon you. You may continue relying on registy keys which may be suddenly changed with some SQL Server update. I wouldn't do that. Hence my short review..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-11T04:16:51.720",
"Id": "101002",
"Score": "0",
"body": "I think we should migrate this to dba.stackexchange.com"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-11T08:11:35.103",
"Id": "101019",
"Score": "0",
"body": "@Phrancis Migration is not possible for such an old question. Furthermore, the question is mainly about reviewing registry manipulation code, and is therefore on-topic for Code Review."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T00:48:55.767",
"Id": "40413",
"Score": "2",
"Tags": [
"sql-server",
"windows",
"delphi"
],
"Title": "Installer package using Inno Setup"
}
|
40413
|
<p>I need help cleaning up this piece of code.</p>
<pre><code>if is_complete == true
#If there are time stamps get between time stamps
if start_date && end_date
tasks = Task.find(:all, :include => [:task_observer, :job, :contact], :conditions => ["contact_id = ? and completed_date IS NOT NULL and DATE(completed_date) between ? and ?", contact_id, start_date, end_date])
else
tasks = Task.find(:all, :include => [:task_observer, :job, :contact], :conditions => ["contact_id = ? and completed_date IS NOT NULL", contact_id])
end
else
#If there are time stamps get between time stamps
if start_date && end_date
tasks = Task.find(:all, :include => [:task_observer, :job, :contact], :conditions => ["contact_id = ? and completed_date IS NULL and DATE(completed_date) between ? and ?", contact_id, start_date, end_date])
else
tasks = Task.find(:all, :include => [:task_observer, :job, :contact], :conditions => ["contact_id = ? and completed_date IS NULL", contact_id])
end
end
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li>you can replace <code>if is_complete == true</code> with <code>if is_complete</code></li>\n<li>the only thing that changes is <code>:conditions</code>, <code>tasks = ...</code> should not be inside the if/else</li>\n<li>the 3rd case is invalid: <code>completed_date</code> can't be <code>NULL</code> and within a certain range at the same time</li>\n<li>use one conditional for the <code>NOT</code> in <code>completed_date IS (NOT) NULL</code> and one for the <code>and DATE ...</code>, and concatenate the sql string then. Then the nested if/else is gone.</li>\n<li>the extra query arguments <code>start_date</code> and <code>end_date</code> depend only on <code>start_date && end_date</code>, so the distinctions should not be in the <code>is_completed</code> conditional.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T09:26:25.130",
"Id": "40443",
"ParentId": "40415",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "40443",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T01:12:24.653",
"Id": "40415",
"Score": "2",
"Tags": [
"ruby",
"datetime",
"ruby-on-rails",
"active-record"
],
"Title": "Task observer implementation"
}
|
40415
|
<p>I'm writing a small guessing game. I'm writing a points calculation algorithm.</p>
<p>I wrote the following, and it works. But I feel like I'm bringing over procedural background into Ruby, or not leveraging Ruby properly.</p>
<p>How would an experienced Ruby programmer approach the problem? You can test the code on <a href="http://tryruby.org/levels/1/challenges/0">TryRuby.com</a> (copy and paste code in the browser interpreter).</p>
<pre><code># g = guesses
g = [{ id: 1, elmer: 5, roger: 7, outcome: "Roger Win" },{ id: 2, elmer: 5, roger: 1, outcome: "Elmer Win" },{ id: 3, elmer: 4, roger: 8, outcome: "Roger Win" }]
# r = actual results
r = [{ id: 1, elmer: 3, roger: 9, outcome: "Roger Win" },{ id: 2, elmer: 7, roger: 9, outcome: "Roger Win" },{ id: 3, elmer: 4, roger: 8, outcome: "Roger Win" }]
# points table
p = []
# rules: correct outcome = 1 point, perfect match = 5 points.
# Loop over results.
r.each do |result|
# Loop over guesses.
g.each do |guess|
# Make sure we compare corresponding ids.
# So, compare result 1 to guess 1, r2 to g2, etc....
if result[:id] == guess[:id]
# Init a hash to store score
score = {}
# Did they guess the correct outcome?
if result[:outcome] == guess[:outcome]
# Correct outcome guessed! Make a score hash, give'em a point.
score[:id] = result[:id] # game id
score[:points] = 1 # point
# Was it a perfect match?
if result[:elmer] == guess[:elmer] && result[:roger] == guess[:roger]
# Perfect match! Give them 4 points.
# They already got 1 point for guessing the correct outcome.
score[:points] += 4
end
end
# Add the score to the points table
p.push(score) unless score.empty?
end
end
end
</code></pre>
|
[] |
[
{
"body": "<p>Assuming your lists are already sorted by the ID and contain results/guesses for exactly the same ID you can do:</p>\n\n<pre><code>r.zip(g).each do |result, guess|\n score = {}\n #...\nend\n</code></pre>\n\n<p>This dramatically reduces runtime from quadratic to linear time. If they are not already sorted, but contain exactly the same IDs you can do the following to sort them.</p>\n\n<pre><code>r.sort_by! {|e| e[:id]}\ng.sort_by! {|e| e[:id]}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T05:54:31.963",
"Id": "40433",
"ParentId": "40416",
"Score": "1"
}
},
{
"body": "<p>I first propose how to improve your algorithm without changing the data structures.</p>\n\n<p>Your algorithm is quadratic (two nested loops over all the entries). This can be easily avoided because you don't need to loop over all the <code>g</code> array to find the item you need. </p>\n\n<p>If they are not, sort the arrays by the <code>id</code> key, using <a href=\"http://ruby-doc.org/core-2.1.0/Enumerable.html#method-i-sort_by\" rel=\"nofollow\">sort_by</a>:</p>\n\n<pre><code>r.sort_by! { |e| e[:id] }\ng.sort_by! { |e| e[:id] }\n</code></pre>\n\n<p>Then you can use <a href=\"http://ruby-doc.org/core-2.1.0/Enumerable.html#method-i-each_with_index\" rel=\"nofollow\">each_with_index</a>:</p>\n\n<pre><code>r.each_with_index { |result, i|\n guess = g[i]\n\n # compute the score here\n}\n</code></pre>\n\n<p>or, if speed is not an issue (and this does not seem to be the case), you can also <a href=\"http://www.ruby-doc.org/core-2.1.0/Array.html#method-i-zip\" rel=\"nofollow\">zip</a> the arrays together <code>r.zip(g)</code> and iterate on that:</p>\n\n<pre><code>r.zip(g).each { |result, guess|\n # compute the score here\n}\n</code></pre>\n\n<hr>\n\n<p>If you can modify the data structure I propose some alternatives.</p>\n\n<p>Often when you have a set of objects with an id you use a hash.</p>\n\n<pre><code># g = guesses\ng = {1 => { elmer: 5, roger: 7, outcome: \"Roger Win\" }, 2 => {elmer: 5, roger: 1, outcome: \"Elmer Win\" }, 3 => { elmer: 4, roger: 8, outcome: \"Roger Win\" }}\n# r = actual results\nr = {1 => { elmer: 3, roger: 9, outcome: \"Roger Win\" }, 2 => {elmer: 7, roger: 9, outcome: \"Roger Win\" }, 3 => { elmer: 4, roger: 8, outcome: \"Roger Win\" }}\n# points table\np = {}\n\n# Loop over results.\nr.each { |id, result|\n guess = g[id]\n\n # Init a hash to store score\n score = {}\n\n # compute the score here\n # ...\n\n p[id] = score unless score.empty?\n}\n</code></pre>\n\n<hr>\n\n<p>If the id is a simple incremental integer and you add the entries in <code>r</code> and <code>g</code> in the same order, you can avoid the id at all and use the array indices instead:</p>\n\n<pre><code># g = guesses\ng = [{ elmer: 5, roger: 7, outcome: \"Roger Win\" }, {elmer: 5, roger: 1, outcome: \"Elmer Win\" }, { elmer: 4, roger: 8, outcome: \"Roger Win\" }]\n# r = actual results\nr = [{ elmer: 3, roger: 9, outcome: \"Roger Win\" }, {elmer: 7, roger: 9, outcome: \"Roger Win\" }, { elmer: 4, roger: 8, outcome: \"Roger Win\" }]\n# points table\np = {}\n\n# Loop over results.\nr.each_with_index { |result, id|\n guess = g[id]\n\n # Init a hash to store score\n score = {}\n\n # compute the score here\n # ...\n\n p[id] = score unless score.empty?\n}\n</code></pre>\n\n<hr>\n\n<p>You can create a class to represent each entry of the array (let's call each entry a Match) and then implement the scoring algorithm as a method:</p>\n\n<pre><code>class Match\n attr_accessor :elmer, :roger, :outcome\n\n def initialize(elmer, roger, outcome)\n @elmer = elmer\n @roger = roger\n @outcome = outcome\n end\n\n def compare(m)\n score = 0\n\n score = score + 1 if @outcome == m.outcome\n score = score + 4 if @elmer == m.elmer and @roger == m.roger\n\n score\n end\nend\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>guess = Match.new(5, 7, \"Roger Win\")\nresult = Match.new(3, 9, \"Roger Win\")\nputs guess.compare(result) # => 1\n\nguess = Match.new(5, 1, \"Elmer Win\")\nresult = Match.new(7, 9, \"Roger Win\")\nputs guess.compare(result) # => 0\n\nguess = Match.new(5, 7, \"Roger Win\")\nresult = Match.new(5, 7, \"Roger Win\")\nputs guess.compare(result) # => 5\n\nputs guess.compare(guess) # => 5\n</code></pre>\n\n<hr>\n\n<p>If the string argument just says who is the winner based on the numbers, you can compute it:</p>\n\n<pre><code>class Match\n attr_accessor :elmer, :roger\n\n def initialize(elmer, roger)\n @elmer = elmer\n @roger = roger\n end\n\n def outcome\n if @elmer > @roger\n :elmer\n elsif @roger > @elmer\n :roger\n else\n :tie\n end\n end\n\n def compare(m)\n if @elmer == m.elmer and @roger == m.roger\n 5\n elsif outcome == m.outcome\n 1\n else\n 0\n end\n end\nend\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>guess = Match.new(5, 7)\nresult = Match.new(3, 9)\nputs guess.compare(result) # => 1\n\nguess = Match.new(5, 1)\nresult = Match.new(7, 9)\nputs guess.compare(result) # => 0\n\nguess = Match.new(5, 7)\nresult = Match.new(5, 7)\nputs guess.compare(result) # => 5\n\nputs guess.compare(guess) # => 5\n\nguess = Match.new(2, 2)\nresult = Match.new(3, 3)\nputs guess.compare(result) # => 1\n\nguess = Match.new(2, 2)\nresult = Match.new(2, 2)\nputs guess.compare(result) # => 5\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T10:11:16.457",
"Id": "68056",
"Score": "1",
"body": "Wow. This is superb. I learnt so much from your answer. Thank you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T11:17:43.167",
"Id": "68059",
"Score": "0",
"body": "I'm not sure about the id. I'm going to use MongoDB to store the guesses. So they will all have an `id`, only the MongoDB id not numeric like RDBS, so it has no value for sorting. The other thing is, given I'm using a document database, I can just add the score to the guess document."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T07:03:28.680",
"Id": "68258",
"Score": "1",
"body": "Very good answer. Any reason to have `:outcome`, considering that it is easily determined from the score?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T07:33:30.260",
"Id": "68264",
"Score": "0",
"body": "@CarySwoveland, I can't see any reason indeed. That's why I dropped it in the last example"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T02:08:08.927",
"Id": "68429",
"Score": "1",
"body": "I missed that. In `compare()`, perhaps `if @elmer == m.elmer && @roger == m.roger; 5; elsif outcome == m.outcome; 1; else; 0; end`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T07:48:23.400",
"Id": "68456",
"Score": "0",
"body": "@CarySwoveland You are right, good catch. That's definitely better. I'm updating my answer"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T08:56:00.153",
"Id": "40441",
"ParentId": "40416",
"Score": "5"
}
},
{
"body": "<p>How does this look to you?</p>\n\n<pre><code>g.zip(r).collect do |guess, result|\n points = (guess == result) ? 5 : guess[:outcome] == result[:outcome] ? 1 : 0 \n {:id => guess[:id], :points => points} \nend\n</code></pre>\n\n<p>Note: This assumes g and r are sorted by :id; if not, you can sort prior to doing this =)\nAlso, I would define: <code>FULL_SCORE = 5</code> and <code>CORRECT_OUTCOME_SCORE = 1</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T10:24:22.243",
"Id": "40448",
"ParentId": "40416",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "40441",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T01:13:21.307",
"Id": "40416",
"Score": "5",
"Tags": [
"algorithm",
"ruby",
"game"
],
"Title": "Small guessing game in Ruby"
}
|
40416
|
<p>This takes a width specified by user and prints a diamond of that width. It uses only three <code>for</code> loops, but could I reduce that further? Is there a more elegant solution?</p>
<pre><code>public class Diamond {
static boolean cont = true;
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
while (cont) {
System.out.print("Width: ");
int width = input.nextInt();
int lines = width;
System.out.println();
for (int line = 0; line < lines; line++) {
for (int spaces = 0; spaces < Math.abs(line - (lines / 2)); spaces++) {
System.out.print(" ");
}
for (int marks = 0; marks < width - 2 * (Math.abs(line - (lines / 2))); marks++) {
System.out.print("x");
}
System.out.println();
}
System.out.println();
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>There are a few things that we can do to clean this up.</p>\n\n<ul>\n<li><p>This is something I would extract to its own method. Handle getting the user input in the <code>main()</code> method, and then pass that on to the <code>drawDiamond()</code> method.</p></li>\n<li><p>Your <code>for</code> loops are divided into iterating over lines, spaces, and\nmarks. We can simplify that down to just rows and columns where we can iterate over each individual unit at a time. This will also eliminate one of your <code>System.out.println()</code>s in the final method.</p></li>\n<li><p>We can simplify down the math of where to print a piece of the diamond.</p>\n\n<pre><code>if ((column == Math.abs(row - half)) || (column == (row + half)) || (column == (sqr - row + half - 1)))\n</code></pre></li>\n</ul>\n\n<h2>Final Method:</h2>\n\n<pre><code>void drawDiamond(int sqr)\n{\n int half = sqr/2;\n for (int row=0; row<sqr; row++)\n {\n for (int column=0; column<sqr; column++)\n {\n if ((column == Math.abs(row - half)) || (column == (row + half)) || (column == (sqr - row + half - 1)))\n {\n System.out.print(\"*\");\n }\n else System.out.print(\" \");\n }\n System.out.println();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T02:19:46.453",
"Id": "40418",
"ParentId": "40417",
"Score": "27"
}
},
{
"body": "<p>You know, it's nice to see code that does what it says, and a nice simple task that still requires some head scratching.... but I'll assume you're a Java beginner.</p>\n\n<h2>Basics</h2>\n\n<p>Going through some of the basic stuff...</p>\n\n<ul>\n<li>you have the <code>cont</code> variable declared as a static variable outside the method, but the only place it is used is inside the method. In this case, you should move the declaration inside the <code>main</code> method. Also, nothing changes that state, so the program just runs, and runs, which is OK (as a beginner).</li>\n<li>you do not close the <code>input</code> Scanner. Again, this is probably because the program never completes, but there are nice ways in Java7 to make sure it happens neatly, and without much effort.</li>\n<li>you should probably validate the user input. If the user enters negative integers, it's actually OK (the program does nothing). More concerning is if the user enters 2000000000. You should set an upper bound.</li>\n<li>you call this shape a 'diamond' but it is actually a square. The width and height are the same number of characters. You only need one variable, <code>lines</code> or <code>width</code>, not both.</li>\n<li>it is confusing that you have both <code>line</code> and <code>lines</code> variable. There is no need for <code>lines</code> if you use <code>width</code> instead, so get rid of it (also since the user prompt is \"Width:\").</li>\n</ul>\n\n<p>OK, that's some relatively simple stuff. Messing your code around using the above suggestions I get:</p>\n\n<pre><code>public static void main (String[] args) {\n boolean cont = true;\n\n try (Scanner input = new Scanner(System.in)) {\n while (cont) {\n System.out.print(\"Width: \");\n int width = input.nextInt();\n System.out.println();\n\n if (width > 100) {\n System.out.println(\"Width too wide, reducing to 100\");\n width = 100;\n }\n\n for (int line = 0; line < width; line++) {\n for (int spaces = 0; spaces < Math.abs(line - (width / 2)); spaces++) {\n System.out.print(\" \");\n }\n for (int marks = 0; marks < width - 2 * (Math.abs(line - (width / 2))); marks++) {\n System.out.print(\"x\");\n } \n System.out.println();\n }\n System.out.println();\n }\n }\n}\n</code></pre>\n\n<h2>Algorithm</h2>\n\n<p>OK, now, some algorithmic things:</p>\n\n<ul>\n<li><code>System.out.print(...)</code> and the <code>println</code> variants, are actually really slow. Calling them from inside loops is a real problem for performance, and is a bad habit to learn. These methods lock the console output, and are not nice to other threads either. Where possible, you should always batch up the character printing in to a larger statement.</li>\n<li>Sometimes, taking stuff away is easier than adding it .... (cryptic hint).</li>\n</ul>\n\n<p>We can solve a lot of the complexity in your loops by doing a couple of tricks. Here's a suggestion:</p>\n\n<ol>\n<li>Build up two Strings, one of spaces and the other of 'x' characters. Each should be at least as long as the longest value we will need.</li>\n<li>loop through the rows and use parts of each of the two above strings.</li>\n</ol>\n\n<p>The logic is the exact same as yours <strong>except</strong> I have big things I use a part of, whereas you build it up bit by bit. The important part is the Math.abs(...) statements are identical to the previous version.... they are the limit to the values we build.</p>\n\n<p>Here's a way to do it:</p>\n\n<pre><code>public static void main (String[] args) {\n boolean cont = true;\n\n try (Scanner input = new Scanner(System.in)) {\n while (cont) {\n System.out.print(\"Width: \");\n int width = input.nextInt();\n System.out.println();\n\n if (width > 100) {\n System.out.println(\"Width too wide, reducing to 100\");\n width = 100;\n }\n\n char[] spaces = new char[width / 2];\n char[] exes = new char[width];\n Arrays.fill(spaces, ' '); // now an array of spaces\n Arrays.fill(exes, 'x'); // now an array of 'x'\n\n for (int line = 0; line < width; line++) {\n String pad = new String(spaces, 0, Math.abs(line - (width / 2)));\n String fill = new String(exes, 0, width - 2 * (Math.abs(line - (width / 2))));\n System.out.println(pad + fill);\n }\n System.out.println();\n }\n }\n}\n</code></pre>\n\n<p>That's just something for you to think about.....</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T08:39:24.493",
"Id": "68052",
"Score": "0",
"body": "Agreed with first sentence. It took me 2 hours on a bus to solve `draw diamond problem` years ago, and I'm really happy about the results now that I've solved it myself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T12:43:00.807",
"Id": "68064",
"Score": "2",
"body": "Calling this a \"diamond\" is [not inaccurate](http://en.wikipedia.org/wiki/Rhombus). In fact, squares as diamonds are [new and exciting](http://meanwhile.wordpress.com/2007/07/12/diamond-shreddies/)!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T00:00:31.580",
"Id": "68205",
"Score": "0",
"body": "If you replace the char arrays by String literals of the maximum length, you can avoid the `Arrays.fill()` call, and just take substrings, which saves the underlying array copy of `new String(char[])`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T02:40:29.030",
"Id": "40420",
"ParentId": "40417",
"Score": "20"
}
},
{
"body": "<p>You can indeed do it in one loop.\nAs I don't speak Java, so I'll use C# syntax.</p>\n\n<pre><code>public static void Main()\n{\n string valueString;\n int width;\n do\n {\n Console.Write(\"Width:\");\n valueString = Console.ReadLine();\n } while (!int.TryParse(valueString, NumberStyles.Integer, CultureInfo.InvariantCulture, out width) && width > 0 && width <= 100);\n int half = (int)((double)width/2+0.5);\n string pattern = new string(' ',width)+new string('*',width);\n for (int row = 1; row <= width; row++)\n { \n int spaces = width-Math.Abs(half - row);\n Console.WriteLine(pattern.Substring(spaces, spaces));\n }\n}\n</code></pre>\n\n<hr>\n\n<p><em>Translated to Java for your convenience</em> ....</p>\n\n<pre><code>public static void main (String[] args) {\n\n try (Scanner scanner = new Scanner(System.in)) {\n int width;\n do\n {\n System.out.print(\"Width:\");\n width = scanner.nextInt();\n } while (width < 0 || width > 100);\n\n char[] blanks = new char[width];\n char[] exes = new char[width];\n Arrays.fill(blanks, ' ');\n Arrays.fill(exes, 'x');\n String pattern = new String(blanks) + new String(exes);\n\n int half = (int)((double)width / 2 + 0.5);\n for (int row = 1; row <= width; row++)\n {\n int spaces = width - Math.abs(half - row);\n // Java substring has arguments (first, last), not (first, length).\n System.out.println(pattern.substring(spaces, spaces + spaces));\n } \n\n System.out.println();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T15:26:07.397",
"Id": "68090",
"Score": "1",
"body": "Yes I tested this and the output is what you'd expect, try it for yourself. The value of spaces is calculated inside the loop, and is different for each iteration. The trick is to construct a string that contains X leading spaces and X diamond characters and with every loop we take a different part out of it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T15:37:21.333",
"Id": "68094",
"Score": "1",
"body": "Oh.... (... penny drops ...) That's quite clever (I have stepped through your code in debug....). ;-) Thanks for that. Would +2 if I could."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T12:21:45.790",
"Id": "40454",
"ParentId": "40417",
"Score": "10"
}
},
{
"body": "<p>It's bad practice to put all of your code into <code>main()</code>. Here, you have the additional problem that <code>main()</code> does three things: prompt for input, print the diamond, and loop. (By the way, you offer no error-free way to exit from the infinite loop.) Mixing these tasks into one function would make it impossible, for example, to reuse your diamond-printing routine in some other way (such as making a continuous vertical string of several diamonds).</p>\n\n<p>@syb0rg offered one way to split the input routine from the printing routine. I would go further and suggest that an object-oriented interface would be a good habit to build in Java. Here's one way:</p>\n\n<pre><code>private static int promptWidth(Scanner input) {\n System.out.print(\"Width: \");\n return input.hasNextInt() ? input.nextInt() : 0;\n}\n\npublic static void main(String[] args) {\n Scanner input = new Scanner(System.in);\n int width;\n // Exit cleanly on EOF, or if anything other than a positive\n // integer is entered.\n while ((width = promptWidth(input)) > 0) {\n System.out.println();\n new Diamond(width).draw(System.out);\n System.out.println();\n }\n input.close();\n}\n</code></pre>\n\n<p>In other words, a <code>Diamond</code> knows how to draw itself to <code>System.out</code>.</p>\n\n<p>Here's another approach:</p>\n\n<pre><code>public static void main(String[] args) {\n Scanner input = new Scanner(System.in);\n int width;\n // Exit cleanly on EOF, or if anything other than a positive\n // integer is entered.\n while ((width = promptWidth(input)) > 0) {\n int width = input.nextInt();\n System.out.println();\n System.out.println(new Diamond(width));\n System.out.println();\n }\n input.close();\n}\n</code></pre>\n\n<p>That relies on <code>Diamond</code>'s <code>.toString()</code> method, which you would have to implement using a <code>StringBuilder</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T12:23:44.447",
"Id": "40455",
"ParentId": "40417",
"Score": "10"
}
},
{
"body": "<p>People have gone into lots of important things about syntax, program structure, etc. But I think that you could make your loops much simpler and easier to understand:</p>\n\n<pre><code>int halfheight = (width + 1) / 2;\nint spaces = halfheight;\nint exes = width - 2 * spaces;\n\nfor (int i = 0; i < halfheight; i++)\n{\n spaces--;\n exes += 2;\n\n // You could use the approaches suggested by other folk here instead of inner loops\n for (int s = 0; s < spaces; s++)\n System.out.print(\" \");\n for (int x = 0; x < exes; x++)\n System.out.print(\"X\");\n System.out.print(\"\\n\");\n}\n\nfor (int i = 0; i < halfheight - 1; i++)\n{\n spaces++;\n exes -= 2;\n\n for (int s = 0; s < spaces; s++)\n System.out.print(\" \");\n for (int x = 0; x < exes; x++)\n System.out.print(\"X\");\n System.out.print(\"\\n\");\n}\n</code></pre>\n\n<p>(I believe that this handles odd and even widths exactly the same as yours, except that it doesn't output an initial blank line in the case of even width. I assumed this was an artefact rather than part of the spec.)</p>\n\n<p>The only 'math' I do is in the initialization, then I loop by amounts which are completely clear without any calculation, and change the number of exes and spaces in each iteration in a way that is completely obvious. It may seem that the various calculations with <code>abs</code> and integer division are not complex, however when you are debugging or trying to slightly modify your code, you will waste time on thinking through different cases (positive, negative, odd, even, first iteration, last iteration), and will probably find yourself just testing different values <code>something</code>, <code>something + 1</code>, <code>something - 1</code> etc, rather than being able to see the precise interaction of each variable at the edge cases.</p>\n\n<p>Note that I have <strong>6</strong> for loops and the code is much longer than the corresponding parts of yours or anyone else's. It's not reducing these that makes the code clear. It's the fact that it is easy to grasp what each does without referring to (much) stuff outside of the loop that helps the maintainer. IMHO (and I know some would disagree), repetition used sparingly and symmetrically as it is here is more elegant than it would be if I factored it out.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T13:13:32.047",
"Id": "40457",
"ParentId": "40417",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T01:58:30.037",
"Id": "40417",
"Score": "31",
"Tags": [
"java",
"console"
],
"Title": "Print an ASCII diamond"
}
|
40417
|
<p>I need a review on this. This code will read a 2D matrix bar code, which I hard-coded as a string <code>str</code>. It has "]d" starting string, which is a GS1 International body Bar Code spec. after that. It has information about Item Number, Serial Number, Locator Information. This code will read the entire string, split and validate fields as per US, SK or Ireland country specs.</p>
<pre><code>public class App {
public static int pos;
public static String getLotNo;
public static String getExpDt;
public static String getItemNo;
public static String getTrimItemNo(String itemNo) {
return itemNo.trim();
}
public static String getItemNumber(String str) {
String matchItemAI = "01";
pos = str.indexOf(matchItemAI);
// Company Prefix for US
if (str.substring(5, 7).equals("03")) {
System.out.println("US Company Prefix :");
String itemStr = str.substring(pos + 5, str.length());
System.out.println(itemStr);
String itemNo = String.format("%s-%s-%s", itemStr.substring(0, 5),
itemStr.substring(5, 9), itemStr.substring(9, 10));
return itemNo = itemNo.trim();
}// For Ireland
else if (str.substring(5, 7).equals("53")) {
System.out.println("Cork Company Prefix :");// 539150714
System.out.println("Cork Company Prefix ----POS:" + pos);
System.out.println("Cork Company Prefix ----STR:" + str);
String itemStr = str.substring(pos + 8, str.length());
System.out.println("Cork Company Prefix ----:" + itemStr);
String itemNo = String.format("%s-%s-%s", itemStr.substring(0, 5),
itemStr.substring(5, 9), itemStr.substring(9, 10));
return itemNo = itemNo.trim();
}// For South Korea
else if (str.substring(5, 7).equals("88")) {
System.out.println("South Korea Company Prefix :");
String itemStr = str.substring(pos + 8, str.length());
System.out.println(itemStr);
String itemNo = String.format("%s-%s-%s", itemStr.substring(0, 5),
itemStr.substring(5, 9), itemStr.substring(9, 10));
return itemNo = itemNo.trim();
} else {
System.out.println("Not Found Company Prefix");
return null;
}
}
public static String getSNo(String str) {
String matchSNoAI = "21"; // AI Serial Number 21
pos = str.indexOf(matchSNoAI);
String matchExpDtAI = "]d17";// ExpiryDate Group Seprator
String getSNo = str.substring(pos + 2, str.lastIndexOf(matchExpDtAI));
return getSNo = getSNo.trim();
}
public static String getExpDt(String str, String matchExpDtAI) {
pos = str.lastIndexOf(matchExpDtAI);
getExpDt = str.substring(pos + 4, pos + 4 + 6);
return getExpDt = getExpDt.trim();
}
public static String getLotNo(String str) {
String matchLotNoAI = "10"; // AI Lot Number
pos = str.lastIndexOf(matchLotNoAI);
getLotNo = str.substring(pos + 2, pos + 2 + 11);
return getLotNo = getLotNo.trim();
}
public static void main(String[] arg) {
// US GS1 String
// 01 AI
// 0 Packing Indicator
// 03 GS1 US Code
// 61958 FDA Code
// 07011 Assigned Product Code
// 1 Asigned Packinging Code
// 9 Check Digit Code
String str = new String(
"]d010036195815011121123456789]d17YYMMDD1012345678901");
// South Korea String
// String str = new String(
// "]d010880625915011821123456789]d17YYMMDD1012345678901");
// Ireland String
// String str = new String(
// "]d010539150714011821123456789]d17YYMMDD1012345678901");
String withoutFunctionKey = str;
if (str.startsWith("]d")) {
System.out.println("GS1 2D Input String :" + str);
switch (str.charAt(2)) { // Scan UNIT 0
case '0':
// Get Item Number
withoutFunctionKey = getItemNumber(str);
System.out.println("Found Item Number : "
+ withoutFunctionKey);
// Get Serial Number
String matchExpDtAI = "]d17";// ExpiryDate
withoutFunctionKey = getSNo(str);
System.out.println("Found string Serial Number : "
+ withoutFunctionKey);
// Get Expiry Date
withoutFunctionKey = getExpDt(str, matchExpDtAI);
System.out.println("Found string Expiry Date : "
+ withoutFunctionKey);
// Get Lot Number
withoutFunctionKey = getLotNo(str);
System.out.println("Found string Lot Number : "
+ withoutFunctionKey);
break;
case '3':
// BUNDLE 3
System.out
.println("Bundle/Multipack 3 Packaging Indicator digits for GTIN 14's : "
+ str.charAt(2));
break;
// SHIPPER 5
case '5':
System.out
.println("Shipper 5 Packaging Indicator digits for GTIN 14's : "
+ str.charAt(2));
break;
default:
System.out
.println("Error - invalid selection entered! for Multipacking ");
break;
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T08:54:54.230",
"Id": "68053",
"Score": "3",
"body": "I looked at [@amon's answer to your previous question](http://codereview.stackexchange.com/a/40308/20251). You haven't followed that advice nearly enough. And a new review to be too repetitive."
}
] |
[
{
"body": "<p>Either your interpretation of the specification is incorrect, or I'm looking at the wrong specs. <a href=\"http://www.gs1.org/barcodes/support/prefix_list\" rel=\"nofollow\">GS1 country codes</a> are three digits, not two. Indeed, you disregard the character after your \"two digit\" country code, but it's not obvious that you skipped that character since you take some substrings with fixed offsets and some substrings relative to the position of the <code>\"01\"</code> string. <code>\"03\"</code> is just one of the many possible strings for the US. <code>\"53\"</code> could be <code>\"539\"</code> for Ireland, but also possibly <code>\"530\"</code> for Albania or <code>\"535\"</code> for Malta. <code>\"88\"</code> could be <code>\"880\"</code> for South Korea, but also possibly <code>\"884\"</code> for Cambodia, <code>\"885\"</code> for Thailand, or <code>\"888</code>\" for Singapore.</p>\n\n<p>In any case, this is a kind of problem where a programmer who is maintaining the code (which could be you yourself in three months!) cannot rely on intuition at all. Therefore, it pays to embed generous amounts of comments, justifying the interpretation of <em>every</em> field by citing the relevant section of the specification document. GS1 publishes its specifications freely online, so there's no excuse for lack of citations, especially if you're asking other people to review your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T13:03:46.883",
"Id": "68067",
"Score": "0",
"body": "I removed all the comments from my source code before posting it so that i should source code only for review but i am keeping comments in the original code but thanks for good suggestion, GS1 has three digit range but as per GTIN-14,\"03\" goes for US in GTIN-14 starts with Application Identifier // 01 AI\n // 0 Packing Indicator\n // 03 GS1 US Code\n // XXXXX FDA Code\n // 15011 Product Code\n // 1 Asigned Packinging Code Unit,Packet etc\n // 9 Check Digit Code"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T09:34:38.687",
"Id": "40446",
"ParentId": "40421",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T02:52:30.957",
"Id": "40421",
"Score": "3",
"Tags": [
"java",
"strings",
"parsing",
"validation"
],
"Title": "Reading and validating 2D matrix bar code"
}
|
40421
|
<p>This is my tentative solution to:</p>
<p><a href="https://codereview.meta.stackexchange.com/questions/1376/how-can-i-prepare-my-code-so-that-i-can-paste-it-formatted">How can I prepare my code so that I can paste it formatted?</a></p>
<p>If you need to copy and paste code into the question or answer textarea when solving someone's problem, describing your own, or fixing someone else's formatting, this tool will correct the indentation of the code and prepare it as a code block as understood by the Stack Exchange formatter. Pending CR's improvements, it will some day hatch into a bookmarklet, and none of us will hit the space bar repeatedly or alt-tab between browser and IDE ever again.</p>
<p>In the interest of having a great thing that can make all of our CRing easier, I invite you to review this without mercy. Readability, usefulness, you prefer <code>.concat</code> to <code>+</code>, you just stubbed your toe - you have a gripe, let's hear it.</p>
<p>The following were my concerns while writing this, upon which I would specifically request comment:</p>
<ul>
<li>I'm pretty sure the way I'm counting delimiters is not the most obvious route, but it works in what I think is linear time. Is it difficult to follow? I kept tossing out comments thinking I wasn't getting the whole strategy across right.</li>
<li>Am I overdoing <code>map</code>, <code>filter</code>, <code>reduce</code>, etc? To me, it's easier to see the <em>intent</em> of an iterative process and to analyze its performance characteristics when I use those methods than using <code>while</code> and <code>for</code> for everything. But I don't see a lot of code that uses them as much as I do.</li>
<li>Clearly there was some iterative factoring going on, and not all methods have been neatly bundled into classes, so I invite comment on a more organized set of abstractions, or just how you would have factored it differently.</li>
</ul>
<p>There are also some features which are just not going to fit into what I've got right now, so I would like input on how you think their absence impacts the effectiveness of the tool and how you might go about implementing them without a total re-write and/or moving on to a grammar-based solution. These are:</p>
<ul>
<li>Can't enforce token parity (e.g. doesn't care if it sees <code>{)</code>). It's not impossible to do with what I have, but I think it would affect performance (requiring a stack or recursion instead of just counting) and not generally be worth it.</li>
<li>Doesn't see any difference between grammatical contexts, e.g. <code>"{"</code> and <code>/*{*/</code> will both cause indent. I think it would be stupid to try to do this without a grammar, but it would need a separate grammar <em>for every language it would support</em>. It's already one monster of a bookmarklet.</li>
<li>It isn't going to do hanging indents for <code>case</code>s, <code>public:</code>, <code>private:</code>, or anything else where a single token dedents the line it's on but indents the next line. It would have to be split up into two tokens, and would probably need to be tweaked per-language. Or I would need to do grammars.</li>
<li>It isn't going to do hanging indents for statements missing a semicolon. A regex can't determine what statements need a semicolon and which don't.</li>
</ul>
<p>It was originally going to have a "just turn the tabs into spaces" mode, which is why you see it messing with tab/space alignment. Is this a feature that would be useful? It would take trivial effort to implement.</p>
<p>Finally, I want to hear what additional features you might want, and what languages you want added (optimally along with a token set as described by the code).</p>
<p>Fiddle with it <a href="http://jsfiddle.net/Lay9k/13/" rel="nofollow noreferrer">here</a>.</p>
<p>In the fiddle, the "bookmarklet" runs on page load, adding the toolbar beneath the <code>textarea</code>.</p>
<pre><code>(function ($, config) {
"use strict";
var // this regex digests a string into leading whitespace,
// content text, and trailing whitespace.
lineRegex = /^(\s*)(\S.*\S|\S)?(\s*)$/g,
spacesPerTab = config.spacesPerTab,
// digests a string in which sequences of spaces equivalent
// to a tab have all been replaced with actual tabs.
// remaining spaces that are not trailing all tabs have no
// effect on alignment.
aligningTabRegex = /^(\s*)([^\t]*)$/g,
adp = Array.prototype,
predefinedLanguages = {},
MicroToolbar,
repeatSpaces;
repeatSpaces = (function () {
// we'll be repeating spaces a lot, so memoize and generate new repetitions
// in O(log n) allocations.
var spacesByRepeatCount = ["", " "];
return function repeatSpaces(n) {
var result = spacesByRepeatCount[n];
if (n && !result) {
result = repeatSpaces(n >> 1);
result += result;
if (n & 1) {
result += " ";
}
spacesByRepeatCount[n] = result;
}
return result;
};
})();
/**
* POD class to be manipulated by indentation fixers
* @param {String} [rawText] original line text including
* leading and trailing white space as tabs & spaces, but
* NO line breaks.
* @param {String} [text] content text with no leading or
* trailing white space
* @param {Number} [originalSpaces] indentation level with
* tabs counted as multiple spaces.
* @constructor
*/
function Line(rawText, text, originalSpaces) {
this.rawText = rawText || "";
this.text = text || "";
this.originalSpaces = originalSpaces || 0;
this.spaces = originalSpaces || 0;
}
function splitLines(rawText) {
var oneTabWorthOfSpaces = repeatSpaces(config.spacesPerTab);
return rawText.split(/\r\n|\r|\n/g).map(function (lineTxt) {
lineRegex.lastIndex = 0;
aligningTabRegex.lastIndex = 0;
var sections = lineRegex.exec(lineTxt),
rawLeadingWs = sections[1] || "",
contentText = sections[2] || "",
importantTabs = rawLeadingWs.replace(
oneTabWorthOfSpaces, "\t"
),
tabsAndAligningSpaces =
aligningTabRegex.exec(importantTabs),
// I don't like this as much as Lint does.
importantWsLength =
(tabsAndAligningSpaces[1] || "").replace(/[^\t]/g, "")
.length * spacesPerTab +
(tabsAndAligningSpaces[2] || "").length;
return new Line(lineTxt, contentText, importantWsLength);
});
}
/**
* Splits a string at occurrences of any of an array of separators.
* @param {String} text
* @param {Array<String|RegExp>} separators
* @return {Array<String>}
*/
function splitOnArray(text, separators) {
var result = [text];
separators.forEach(function (sep) {
result = adp.concat.apply([], result.map(
function (segment) {
return segment.split(sep);
}
));
});
return result;
}
// for now, don't enforce token parity, tag parity, etc. etc.
// (if I did, I would clearly want a grammar rather than a
// regex-based system)
// BUT I am abstracting the analyzer to take a paired token
// input in case demand arises for that feature.
/**
* Class that encapsulates indentation rules based on paired
* or regular tokens. The tokenSet parameter may be an object
* {open: Array<String|RegExp> | String | RegExp,
* close: Array<String|RegExp> | String | RegExp}
* or an array of the same structures where open defines
* tokens that demand an indent and close defines tokens that
* demand a dedent.
* @param {Object|Array<Object>} tokenSet
* @constructor
*/
function IndentationAnalyzer(tokenSet) {
var normalizedTokenSet = this.normalizedTokenSet = {
open: [],
close: []
};
(function normalize(defn) {
var open, close;
if (defn instanceof Array) {
defn.forEach(normalize);
} else {
open = defn.open;
close = defn.close;
if (open) {
if (open instanceof Array) {
normalizedTokenSet.open =
normalizedTokenSet.open.concat(open);
} else if (open) {
normalizedTokenSet.open.push(open);
}
}
if (close) {
if (close instanceof Array) {
normalizedTokenSet.close =
normalizedTokenSet.close.concat(close);
} else {
normalizedTokenSet.close.push(close);
}
}
}
})(tokenSet);
}
/**
* Returns an analysis of the given string's indentation
* properties: indent (total opening tokens present that
* should affect the indentation of the next line), dedent
* (total closing tokens that should affect indentation of
* the next line), and prededent (closing tokens present that
* should affect the indentation of the current line)
* @param {String} text
* @return {Object}
*/
IndentationAnalyzer.prototype.analyze = function (text) {
var result = {
prededent: 0,
indent: 0,
dedent: 0
},
openings,
closings;
openings = splitOnArray(text, this.normalizedTokenSet.open);
result.indent = openings.length - 1;
// now split those segments by the closing tokens
// similarly, but keep the opening segments split up
// so that pre-dedent can be calculated.
closings = openings.map(function (segment) {
return splitOnArray(
segment, this.normalizedTokenSet.close
);
}, this);
// Each element of each array beyond one element is
// due to 1 closing token
result.dedent = closings.reduce(function (n, closing) {
return n + closing.length - 1;
}, 0);
// only closing tokens that don't correspond to an opening
// token on the same line affect the indentation of that
// line. state is {opens, prededent} where opens is the
// number of unclosed open tokens (each closing array is 1)
// and prededent is the number of closing tokens without
// a corresponding opening token.
result.prededent = closings.reduce(function (state, closing) {
var closedCount = closing.length - 1;
if (closedCount > state.opens) {
closedCount -= state.opens;
state.opens = 0;
state.prededent += closedCount;
} else {
state.opens -= closedCount;
}
state.opens++;
return state;
}, {prededent: 0, opens: 0}).prededent;
return result;
};
/**
* Analyzes an array of Line objects assigning each of them
* a 'spaces' property based on the balance of opening and
* closing tokens found on each line and previous lines.
* Mutates the Line objects - returns nothing.
* @param {Array<Line>} lines
*/
IndentationAnalyzer.prototype.fix = function (lines) {
var levelStack = [],
level = 0,
me = this;
// Extend the line objects with indentation data from
// analyzer.
lines.forEach(function (line) {
var analysis = me.analyze(line.text),
pre = level - analysis.prededent,
post = level + analysis.indent - analysis.dedent,
parentDepth = levelStack.length;
// Find the indentation of the level corresponding
// to the last unopened closed token - that's this
// line's indent.
while (pre < level && parentDepth--) {
level = levelStack.pop();
}
line.spaces = levelStack.length * config.spacesPerTab;
// If there was a net reduction in level, return to
// the indentation that had the new level for the
// next line.
while (levelStack.length && level > post) {
level = levelStack.pop();
}
// If there wasn't an exact match searching down
// or there was a net increase in level, push the old
// level on the stack and let the new level be post.
if (post !== level) {
levelStack.push(level);
level = post;
}
});
};
// populate the predefined language list with some common ones
// that share a set of indentation rules
// not sure where this will end up, so I use self-invoking lambda
// to keep it cut-pasta-safe in case it leaves this scope.
(function setupPredefinedLanguages(langs) {
var htmlXml,
curly,
lisp;
htmlXml = [
{
// comments come first so the opening tag
// doesn't match them
open: /<!--/g,
close: /-->/g
},
{
// <open tag> but not <self closing tag/>
open:
/<(?:"(?:\\"|[^"])*"|'(?:\\'|[^'])*'|[^>])*[^\/]>/g,
// </closing tag>
close: /<\/[^>]*>/g
},
{
// single tag split among lines
open: "<",
close: ">"
}
];
// generic curly bracket language
curly = [
{open: "{", close: "}"},
{open: "(", close: ")"},
{open: "[", close: "]"}
];
// curly would work for lisp, but performance is O(NM),
// and lisp just needs M = 1.
lisp = [{open: "(", close: ")"}];
langs.html = htmlXml;
langs.xml = htmlXml;
langs.c = curly;
langs.cpp = curly;
langs.cplusplus = curly;
langs.js = curly;
langs.javascript = curly;
langs.ecmascript = curly;
langs.java = curly;
langs.lisp = lisp;
})(predefinedLanguages);
function renderLinesToString(lines) {
return lines.map(function (line) {
return repeatSpaces(line.spaces) + line.text;
}).join("\r\n");
}
function escapeForPreCode(text) {
// as long as all of the '<' are escaped, the '>' seem to be fine.
return text.replace("&", "&amp;").replace("<", "&lt;");
}
function noTagCodeBlock(text) {
return text.split(/\r\n|\r|\n/g).map(function (line) {
return " " + line;
}).join("\r\n");
}
MicroToolbar = (function () {
var templ = $("<div>").addClass("fix-indent-toolbar"),
noMoBtn =
$("<button>").appendTo(templ)
.text("X").addClass("fix-indent-no-more"),
doItBtn =
$("<button>").appendTo(templ)
.text("fix indent").addClass("fix-indent-do-it"),
langSel =
$("<select><option>language</option></select>")
.appendTo(templ)
.addClass("fix-indent-language"),
sptLbl =
$("<label>").appendTo(templ)
.text("spaces per tab"),
sptIn =
$("<input>").appendTo(templ)
.attr("type", "number")
.attr("min", "1")
.attr("step", "1")
.addClass("fix-indent-spaces-per-tab"),
preCodeChk =
$("<input>").appendTo(templ)
.attr("type", "checkbox")
.addClass("fix-indent-use-pre-code"),
preCodeLbl =
$("<label>").appendTo(templ)
.text("use <pre><code>");
Object.keys(predefinedLanguages).forEach(function (key) {
$("<option>").text(key).attr("value", key)
.appendTo(langSel);
});
function getUid(baseId) {
baseId = "fix-indent-" + baseId;
while ($("#" + baseId + "-unique-id").length) {
baseId += "-very";
}
return baseId + "-unique-id";
}
function uniqueIds() {
// can't be too careful with document scope IDs
var sptId = getUid("spaces-per-tab"),
preCodeId = getUid("use-pre-code");
sptIn.attr("id", sptId);
sptLbl.attr("for", sptId);
preCodeChk.attr("id", preCodeId);
preCodeLbl.attr("for", preCodeId);
}
// Delegating events to the document element means that
// pretty much everything in this module will be kept alive
// until unload. In case it's running in an elevator
// controller =D, remove the event handlers that have
// references to this closure scope and let GC do its thing
// when no more toolbars remain.
function helpGc() {
if (MicroToolbar.all().toolbarElement().length === 0) {
$(document).off(".fixIndent");
}
}
// If the bookmarklet is run a second time, no need to re-hook
// all the events.
if ($(".fix-indent-toolbar").length === 0) {
$(document)
.on("click.fixIndent",
".fix-indent-toolbar .fix-indent-no-more",
function () {
new MicroToolbar(this).die();
}
).on("change.fixIndent",
".fix-indent-toolbar .fix-indent-spaces-per-tab",
function () {
var my = new MicroToolbar(this);
my.spacesPerTab(my.spacesElement().val());
}
).on("change.fixIndent",
".fix-indent-toolbar .fix-indent-language",
function () {
var my = new MicroToolbar(this);
my.language(my.languageElement().val());
}
).on("change.fixIndent",
".fix-indent-toolbar .fix-indent-use-pre-code",
function () {
var my = new MicroToolbar(this);
my.usePreCode(my.preCodeElement().prop("checked"));
}
).on("click.fixIndent",
".fix-indent-toolbar .fix-indent-do-it",
function () {
var my = new MicroToolbar(this),
textEl = my.textElement().get(0),
selStart = textEl.selectionStart || 0,
selEnd = textEl.selectionEnd,
selText = textEl.value,
lines,
langObj = predefinedLanguages[config.language],
out;
if (!selEnd || selStart === selEnd) {
selEnd = textEl.textLength;
}
spacesPerTab = config.spacesPerTab;
selText = selText.slice(selStart, selEnd);
// pre & code tags could be part of the selection
if (/^<pre><code>/.test(selText)) {
selText = selText.slice(11);
}
if (/<\/pre><\/code>$/.test(selText)) {
selText = selText.slice(0, -13);
}
lines = splitLines(selText);
new IndentationAnalyzer(langObj).fix(lines);
out = renderLinesToString(lines);
if (config.usePreCode) {
out = "<pre><code>\r\n" +
escapeForPreCode(out) +
"\r\n</pre></code>";
} else {
out = noTagCodeBlock(out);
}
if (textEl.setRangeText) {
textEl.setRangeText(out, selStart, selEnd);
} else {
textEl.value = textEl.value.slice(0, selStart) +
out + textEl.value.slice(selEnd);
}
}
);
}
function MicroToolbar(el) {
if (!(el instanceof $)) {
el = $(el || "body");
}
if (!(this instanceof MicroToolbar)) {
// used with no new gets an object referencing all toolbars
// already constructed (it doesn't make any new toolbars)
// (lint likes MicroToolbar.all() better, though)
return new MicroToolbar(el.find(".fix-indent-toolbar"));
}
// it's fine to have an object referencing multiple toolbars
// (since the config object is shared between all of them)
// but there will be confusion if el is an ancestor with multiple
// textareas some of which have the html toolbar and others don't.
// So I have to narrow the query's selection, install a toolbar
// on the textareas that need it, and make sure the element
// referenced by the object has all of the toolbars, new & used.
el = el.closest(":has(textarea)").find("textarea");
var tb = el.next(".fix-indent-toolbar");
if (tb.length !== el.length) {
// update the template to reflect config before it's cloned
sptIn.val(config.spacesPerTab);
preCodeChk.prop("checked", config.usePreCode);
el.filter(function () {
return $(this).next(".fix-indent-toolbar").length === 0;
}).each(function () {
var oneEl = $(this),
oneTb;
uniqueIds();
oneTb = templ.clone();
oneEl.after(oneTb);
tb.add(oneTb);
});
}
this.toolbarElement = function () { return tb; };
}
MicroToolbar.prototype.spacesElement = function () {
return this.toolbarElement().find(".fix-indent-spaces-per-tab");
};
MicroToolbar.prototype.languageElement = function () {
return this.toolbarElement().find(".fix-indent-language");
};
MicroToolbar.prototype.preCodeElement = function () {
return this.toolbarElement().find(".fix-indent-use-pre-code");
};
MicroToolbar.prototype.textElement = function () {
return this.toolbarElement().prev("textarea");
};
MicroToolbar.prototype.spacesPerTab = function (n) {
if (n !== undefined) {
if (typeof n === "string") n = parseInt(n, 10);
config.spacesPerTab = n;
MicroToolbar.all().spacesElement().val(n);
return this;
} else {
return config.spacesPerTab;
}
};
MicroToolbar.prototype.language = function (s) {
if (s !== undefined) {
if (predefinedLanguages.hasOwnProperty(s)) {
config.language = s;
MicroToolbar.all().languageElement().val(s);
}
return this;
} else {
return config.language;
}
};
MicroToolbar.prototype.usePreCode = function (b) {
if (b !== undefined) {
config.usePreCode = b;
MicroToolbar.all().preCodeElement().prop("checked", b);
return this;
} else {
return config.usePreCode;
}
};
MicroToolbar.prototype.die = function () {
this.toolbarElement().remove();
helpGc();
};
MicroToolbar.all = function (inEl) {
inEl = inEl instanceof $ ? inEl : $(inEl || document);
return new MicroToolbar(inEl.find(".fix-indent-toolbar"));
};
return MicroToolbar;
})();
new MicroToolbar($("textarea"));
})(jQuery, {language: "java", spacesPerTab: 4, usePreCode: true});
</code></pre>
<p><a href="http://jsfiddle.net/Lay9k/14/" rel="nofollow noreferrer">Revision 14</a> adds the option to not do any language analysis and just prepare the selection as a markdown code block. This encompasses the "tabs to spaces only" mode that was originally planned and requested. The language selection control was split into a <code><select></code> and <code><label></code> like the other inputs. The default selection (previously "language" to indicate the purpose of the select box) was renamed to reflect its purpose. The list of predefined languages was prepended with generic language descriptions for the existing options.</p>
<p>There were changes in the IIFE <code>setupPredefinedLanguages</code> and in the IIFE whose result is <code>MicroToolbar</code>, but adding them here puts this post over the length limit, so see the fiddle for details.</p>
<p>I am now also specifically looking for feedback of the form "X feature is useless!" so that I can shorten the code.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T15:41:13.247",
"Id": "68095",
"Score": "0",
"body": "Hmm, your code is 20K+ characters, IE9 will only accept up to 5K."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T21:06:14.143",
"Id": "68167",
"Score": "0",
"body": "@konijn minification will cut all the spaces and line breaks, should be able to take all the variable and function names down to a single character, might make it down to 5k. Will have to try it & get back to you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T22:25:57.510",
"Id": "68192",
"Score": "0",
"body": "@konijn got it down to -8k- 5.8k. will try fiddling with options, then start cutting stuff."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T22:42:45.237",
"Id": "68194",
"Score": "0",
"body": "In order to be rid of that last 800 characters, I'll have to shorten a bunch of property names, or add annotations for closure compiler and let it mangle them. Will look into it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T23:04:48.020",
"Id": "68198",
"Score": "0",
"body": "Perhaps you will have to Golf it ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T03:20:41.797",
"Id": "68239",
"Score": "0",
"body": "@konijn A lot of my property names are ridiculous long, but if reducing those doesn't work, I'll let Golf re-write it in befunge."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T23:45:50.690",
"Id": "68521",
"Score": "0",
"body": "@konijn Can't I just host the script somewhere else and the bookmarklet can consist of `$(\"<script src='elsewhere.com/fix-indent.js'></script>\").appendTo(\"body\")`? It seems like I shouldn't be able to do that (XSS risk?) but then there's http://stackoverflow.com/questions/106425/load-external-js-from-bookmarklet"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T23:49:59.693",
"Id": "68523",
"Score": "0",
"body": "I am pretty sure you can do that. If you have a github account, I can probably add you to the https://github.com/CodeReviewCommunity/CodeReviewBookmarklet repository, and then you can load the .js from github.io"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T23:57:14.817",
"Id": "68525",
"Score": "0",
"body": "@konijn Sweet. That will be way easier than implementing a Befunge interpreter."
}
] |
[
{
"body": "<blockquote>\n <p>It was originally going to have a \"just turn the tabs into spaces\" mode, which is why you see it messing with tab/space alignment. Is this a feature that would be useful? It would take trivial effort to implement.</p>\n</blockquote>\n\n<p>That feature might be useful on this site (Code Review):</p>\n\n<ul>\n<li>Reviewing the format of the code in the OP is on-topic; if the format is bad we should review that in an answer, <a href=\"https://codereview.meta.stackexchange.com/a/763/34757\">not correct it in the OP's question</a>.</li>\n<li>Occasionally, however, the formatting is messed up because the OP pasted-in code which contains tabs. In that case (formatting was messed up by the process of converting to markdown) it would be appropriate for someone else to edit the question to fix only that (tabs to spaces).</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T23:22:42.163",
"Id": "68518",
"Score": "0",
"body": "This answer is **community wiki** because it really belongs on meta: it's not a code review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T23:37:34.217",
"Id": "68519",
"Score": "0",
"body": "I absolutely agree that sensible indentation is an issue to address in the review if the code appears as the OP intended. I think it's mangled simply by copy/paste more often than it would first appear because @Jamal (bless him!) runs around tidying up new posts. The sample in the fiddle, for example, is an original post, verbatim, that he fixed manually, obtaining the same result that my tool does automatically. I was thinking simple tabs->spaces might be good for Python, too, but I don't really know."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T01:58:49.060",
"Id": "68851",
"Score": "0",
"body": "added the \"markdown prep only\" mode, which replaces tabs with spaces and adds 4 spaces or `<pre><code>`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T04:01:20.970",
"Id": "68882",
"Score": "0",
"body": "Honestly, I think indentation should be fixed in an edit to encourage other reviewers. Leave a comment with the edit to this effect. But I digress."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T23:17:28.453",
"Id": "40643",
"ParentId": "40422",
"Score": "5"
}
},
{
"body": "<p>The <code>repeatSpaces</code> function: I must have missed something.</p>\n\n<p>Could you not use a built-in like <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat\" rel=\"nofollow noreferrer\">String.repeat</a> ? <em>(works in Chrome 31)</em></p>\n\n<p>If it is not available a shim like:<br>\n<a href=\"https://stackoverflow.com/a/202627/684890\">https://stackoverflow.com/a/202627/684890</a></p>\n\n<pre><code>String.prototype.repeat = function repeat(repeatTimes)\n{\n return new Array(repeatTimes+ 1).join(this);\n};\n</code></pre>\n\n<p>would be sufficient?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T02:37:44.863",
"Id": "68855",
"Score": "0",
"body": "Doesn't look like it's in the standard, so I hesitate to use it regardless of adoption among common browsers. I think the shim you provide is about as straightforward as the way I've written it; if CR at large disagrees or if I test the performance and mine is inferior, I'll switch."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T02:41:02.060",
"Id": "68857",
"Score": "0",
"body": "@sqykly Thats an interesting idea. jsperf.com?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T03:16:34.590",
"Id": "68865",
"Score": "0",
"body": "Now I'm struggling to come up with a fair set of test cases since mine is using memoization; obviously I can't time generation of the same repeat count over and over, but I also can't use a set contrived to be devoid of repetitions. Thoughts?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T03:36:05.880",
"Id": "68872",
"Score": "0",
"body": "On my machine *with memoization* for both. It makes little difference. So I'd label my one as no real improvement. http://jsperf.com/code-review-40422"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T04:09:22.937",
"Id": "68885",
"Score": "0",
"body": "good call. I'm seeing 0 difference, too, except that firefox or my machine sucks =D."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T04:17:09.507",
"Id": "68887",
"Score": "0",
"body": "I added a few more browsers. Results are still inconclusive"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T11:49:43.163",
"Id": "69925",
"Score": "0",
"body": "Starting to look like the shim version is better than or equal to mine, even when I add the asm.js `n | 0` optimization hint & increase sample size to really ridiculous numbers of spaces. So let this be a lesson to all future JS bit-twiddlers =D."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T02:26:31.050",
"Id": "40819",
"ParentId": "40422",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T03:44:48.880",
"Id": "40422",
"Score": "10",
"Tags": [
"javascript",
"jquery",
"formatting",
"stackexchange",
"bookmarklet"
],
"Title": "Tool for automatically correcting indentation and formatting of CR & SO code"
}
|
40422
|
<p>Below is the method that I have written for reading from a text file. While reading, I need to match a line string to a given regex, and if it matches, I need to add the line string to a collection.</p>
<pre><code>private static void GetOrigionalRGBColours(string txtFile)
{
string tempLineValue;
Regex regex = new Regex(@"^\d+.?\d* \d+.?\d* \d+.?\d* SRGB$");
using (StreamReader inputReader = new StreamReader(txtFile))
{
while (null != (tempLineValue = inputReader.ReadLine()))
{
if (regex.Match(tempLineValue).Success
&& tempLineValue != "1 1 1 SRGB"
&& tempLineValue != "0 0 0 SRGB")
{
string[] rgbArray = tempLineValue.Split(' ');
RGBColour rgbColour = new RGBColour() { Red = Convert.ToDecimal(rgbArray[0]), Green = Convert.ToDecimal(rgbArray[1]), Blue = Convert.ToDecimal(rgbArray[2]) };
originalColourList.Add(rgbColour);
}
}
}
}
</code></pre>
<p>When this method is run for a text file of 4MB having 28653 lines, it takes around <strong>3 minutes</strong> just to finish the above method. Also, as a result of the above run, <code>originalColourList</code> is populated with 582 items.</p>
<p>How can I improve the performance of this method? I had truncated the original text file for testing purpose. The actually text file size may go up to 60MB.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T13:15:43.557",
"Id": "68072",
"Score": "0",
"body": "It might be useful to profile the difference between matching the Regex then calling split vs. matching a capturing Regex, and converting its capture groups."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T18:37:37.377",
"Id": "68140",
"Score": "2",
"body": "Also, don't forget to pre-compile the regex."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T07:08:41.170",
"Id": "68262",
"Score": "0",
"body": "@JeffVanzella Great tip! This increase the execution time of the regex ctor from 169ms to 375ms but reduced the execution time of `Match` to about half! Definitely worth doing if you plan to use the same regexp a lot."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T07:11:35.323",
"Id": "68263",
"Score": "1",
"body": "@JeffVanzella After my rough estimates `RegexOptions.Compiled` payed for itself after about 10000 `Match`es."
}
] |
[
{
"body": "<p>First, a sample of the input data would be helpful for testing. That said:</p>\n\n<ul>\n<li>If you're using .NET 4 or greater you can use the\n<a href=\"http://msdn.microsoft.com/en-us/library/dd383503%28v=vs.110%29.aspx\">File.ReadLines()</a> method to read all the lines at once which may speed things up. </li>\n<li>Try to narrow the complexity of the regex pattern. Usages of * and + are going to be slower than other options. Or find a way to avoid regex all together.</li>\n<li>It looks like you're trying to match decimal numbers with the <code>\\d+.?\\d*</code> pattern, but the <code>.</code> character matches all characters. You may want the pattern <code>\\d+\\.?\\d*</code>.</li>\n<li>Are you sure the input data is in the form of decimal colors? RGB implementations are almost always either bytes or integers.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T13:17:30.877",
"Id": "68073",
"Score": "2",
"body": "+1 especially for catching `\\.`; this could easily lead to much backtracking assuming no literal `.` and only single spaces between numbers."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T04:26:12.170",
"Id": "40425",
"ParentId": "40423",
"Score": "6"
}
},
{
"body": "<p>I have run your code but it finishes for me for an input file of 290000 lines of 8MB under a second. Could you provide a sample of the file?</p>\n\n<p><strong>Update:</strong>\nMy guess at this point is that the non matching lines which appear to be very long consume the most time. You could try to exclude them by checking for something simple like if the first character is a digit or if their length is below some threshold.</p>\n\n<p>Can you provided some details on the implementation of <code>RGBColour</code> and what kind of collection <code>originalColourList</code> is. For my test I have assumed <code>originalColourList</code> is <code>List<RGBColour></code> and <code>RGBColour</code> is a PODS like:</p>\n\n<pre><code>class RGBColour {\n public decimal Red { get; set; }\n public decimal Green {get; set;}\n public decimal Blue {get; set;}\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T07:53:13.783",
"Id": "40437",
"ParentId": "40423",
"Score": "2"
}
},
{
"body": "<p>I would imagine your while loop is slowing things down,</p>\n\n<p>If you read in the complete file using <code>File.ReadAllLines()</code> then call <code>Regex.Matches()</code>, foreache'd through each match,\nit should be faster. </p>\n\n<p>on a side note I personally like to store my large sql and regex filters/queries as a private const , obviously only if they ARE constant. though in this case it seems so.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T10:25:18.637",
"Id": "40449",
"ParentId": "40423",
"Score": "1"
}
},
{
"body": "<p>One option is to not perform any regular expression check at all. You can perform a quick match by checking if the line ends with <code>SRGB</code> and the try the split and convert and simply continue if it fails. Something along these lines:</p>\n\n<pre><code>private static void GetOrigionalRGBColours(string txtFile)\n{\n using (StreamReader inputReader = new StreamReader(txtFile))\n {\n while (!inputReader.EndOfStream) \n {\n var line = inputReader.ReadLine();\n\n if (line.EndsWith(\" SRGB\")\n && line != \"1 1 1 SRGB\"\n && line != \"0 0 0 SRGB\")\n {\n try \n {\n string[] rgbArray = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n if (rgbArray.Length == 4)\n {\n RGBColour rgbColour = new RGBColour() { Red = Convert.ToDecimal(rgbArray[0]), Green = Convert.ToDecimal(rgbArray[1]), Blue = Convert.ToDecimal(rgbArray[2]) };\n originalColourList.Add(rgbColour);\n }\n }\n catch (FormatException) {}\n catch (OverflowException) {}\n }\n }\n }\n} \n</code></pre>\n\n<p>Alternatively to the <code>try-catch</code> you can use <code>decimal.TryParse()</code> and ignore the line if it returns <code>false</code> for any of the 3 entries.</p>\n\n<p><strong>Update</strong>: Version with <code>decimal.TryParse</code>.</p>\n\n<pre><code>private static void GetOrigionalRGBColours(string txtFile)\n{\n using (StreamReader inputReader = new StreamReader(txtFile))\n {\n while (!inputReader.EndOfStream) \n {\n var line = inputReader.ReadLine();\n\n if (line.EndsWith(\" SRGB\")\n && line != \"1 1 1 SRGB\"\n && line != \"0 0 0 SRGB\")\n {\n string[] rgbArray = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n if (rgbArray.Length != 4) { continue; }\n\n decimal red;\n var hasRed = decimal.TryParse(rgbArray[0], out red);\n decimal green;\n var hasGreen = decimal.TryParse(rgbArray[1], out green);\n decimal blue;\n var hasBlue = decimal.TryParse(rgbArray[2], out blue);\n\n if (hasRed && hasGreen && hasBlue)\n {\n RGBColour rgbColour = new RGBColour() { Red = red, Green = green, Blue = blue };\n originalColourList.Add(rgbColour);\n }\n }\n }\n }\n} \n</code></pre>\n\n<p>I like that one better because I find <code>try {} catch {}</code> block always a bit ugly . It also conveys the intend of the code better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T06:52:38.337",
"Id": "68254",
"Score": "0",
"body": "In my test case reduced execution time by 90%! Nice!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T07:03:54.290",
"Id": "68259",
"Score": "0",
"body": "Also change the two `tempLineValue`s to `line` for the code to compile!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T07:06:56.960",
"Id": "68261",
"Score": "0",
"body": "@Andris good catch, missed those, fixed"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T08:01:11.137",
"Id": "68267",
"Score": "0",
"body": "@Andris: You already seem to have a benchmark around. Do you mind running the `TryParse` version? I'd be interested to see if it makes a difference."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T08:22:02.090",
"Id": "68269",
"Score": "0",
"body": "The `TryParse` variant look a little bit faster but I feel the difference is close to the margin of error of my ad-hoc test so I would say the difference is insignificant."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T08:23:04.843",
"Id": "68270",
"Score": "0",
"body": "Also you wrote `decimalTryParse` instead of `decimal.TryParse`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T08:25:09.853",
"Id": "68271",
"Score": "0",
"body": "AND there is a bug in both code samples: instead of `rgbArray.Length == 3` you should write `rgbArray.Length == 4` because the `Split` creates 4 elements. The fourth being the text \"SRGB\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T08:34:08.597",
"Id": "68272",
"Score": "0",
"body": "@Andris, thanks fixed, I shouldn't write code when I'm tired."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T08:52:16.827",
"Id": "68275",
"Score": "0",
"body": "Some minor speed improvements to avoid repeated queries for the current culture inside `decimal.TryParse`: `decimal.TryParse(rgbArray[0], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out red);` and also `line.EndsWith(\" SRGB\", false, CultureInfo.InvariantCulture)`. Shaves off about 10% in my testcase compared to your previous code."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T10:44:12.727",
"Id": "40452",
"ParentId": "40423",
"Score": "12"
}
},
{
"body": "<p>One significant performance problem here is that you are doing <strong>two</strong> String operations on every line (well, almost every one). First, the line match, second the split. The second operation is also creating new String instances....</p>\n\n<p>(included JoeClarks <a href=\"https://codereview.stackexchange.com/a/40425/31503\">fix for the decimal point in the regex</a>)</p>\n\n<p>it is actually quite simple to bring this down to a single operation:</p>\n\n<pre><code>private static void GetOrigionalRGBColours(string txtFile)\n{\n string tempLineValue;\n Regex regex = new Regex(@\"^(\\d+\\.?\\d*) (\\d+\\.?\\d*) (\\d+\\.?\\d*) SRGB$\", RegexOptions.Compiled);\n\n using (StreamReader inputReader = new StreamReader(txtFile))\n {\n while (null != (tempLineValue = inputReader.ReadLine())) \n {\n Match match = regex.Match(tempLineValue);\n if (match.Success)\n {\n Decimal red = Convert.ToDecimal(match.Groups[1].Value);\n Decimal green = Convert.ToDecimal(match.Groups[2].Value);\n Decimal blue = Convert.ToDecimal(match.Groups[3].Value);\n if ( !(red == 1 && green == 1 && blue == 1)\n && !(red == 0 && green == 0 && blue == 0))\n {\n originalColourList.Add(new RGBColour(red, green, blue));\n } \n }\n }\n }\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T07:00:06.900",
"Id": "68255",
"Score": "0",
"body": "I have run your code through a profiler and it looks to me that due to your regex being more complex with the inclusion of groups the execution time got longer. I have even observed a slight increase in runtime. Around +10% in execution time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T07:01:37.547",
"Id": "68256",
"Score": "0",
"body": "If I add the `RegexOptions.Compiled` to the ctor of regex I get a speed improvement of 40% in your code of the total execution time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T07:02:14.533",
"Id": "68257",
"Score": "0",
"body": "Also note that you have to write `Convert.ToDecimal(match.Groups[1].Value);` in order for your code to compile."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T11:15:53.033",
"Id": "68296",
"Score": "0",
"body": "@Andris . of course, and of course. Thanks for running things through, I have u[dated the answer with your suggestions."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T14:30:07.450",
"Id": "40461",
"ParentId": "40423",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "40452",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T03:45:24.383",
"Id": "40423",
"Score": "10",
"Tags": [
"c#",
"performance",
".net",
"parsing",
"regex"
],
"Title": "Reading from text file with RegexMatch"
}
|
40423
|
<p>Is this a correct method of Fibonacci with recursion?</p>
<pre><code>function fibb($limit,$first_numer=0,$second_number=1){
echo $first_numer."\n";
echo $second_number."\n";
if($limit > 0){
fibb($limit-2,$first_numer+$second_number,($first_numer+$second_number+$second_number));
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I think that programmers can write code with their own logic. You should get the correct output (with less code, which is great).</p>\n\n<p>There are many ways to do the same, such as:</p>\n\n<pre><code><?php\nfunction fibonacci ($n)\n{\n if ($n == 0) {\n return 0;\n }\n else if ($n == 1)\n {\n return 1;\n } else {\n return fibonacci( $n - 1 ) + fibonacci( $n - 2 );\n }\n}\n?>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T14:26:40.067",
"Id": "68339",
"Score": "0",
"body": "Hi and welcome to CodeReview. [Code-only](http://meta.codereview.stackexchange.com/questions/1463/short-answers-and-code-only-answers) answers are not the best format for a code review. How is your code different? Why is it better? See [how to answer](http://codereview.stackexchange.com/help/how-to-answer) and add these details to your answer and you will have a much higher quality result"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T04:33:31.530",
"Id": "40427",
"ParentId": "40426",
"Score": "1"
}
},
{
"body": "<p>In a sense, your function does produce the right numbers. However, the termination condition is not quite right. For example, <code>fibb(3)</code> and <code>fibb(4)</code> produce identical output: each prints six numbers. Why six? The most natural interpretation of the parameters would be that <code>$limit</code> should specify the number of items in the sequence to be printed.</p>\n\n<p>The root of the problem is that each call to <code>fibb()</code> prints two lines, which means that output will always be printed in pairs. Normally, you would want to print just one number per call.</p>\n\n<p>In addition, your naming is unconventional. Why <code>fibb()</code> with two <code>b</code>s? Also, <code>$first_numer</code> is misspelled.</p>\n\n<pre><code>function fibonacci($limit, $first_number=0, $second_number=1) {\n if ($limit <= 0) {\n return;\n }\n echo \"$first_number\\n\";\n fibonacci($limit - 1, $second_number, $first_number + $second_number);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T05:33:42.107",
"Id": "40511",
"ParentId": "40426",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T04:30:14.347",
"Id": "40426",
"Score": "5",
"Tags": [
"php",
"fibonacci-sequence"
],
"Title": "Is this Fibonacci function right?"
}
|
40426
|
<p>This code will accept user input from the command line.</p>
<p>The first user can enter the limit of series.</p>
<p>e.g: user may enter 5</p>
<p>After that, the user will be prompted for 5 numbers of a series.</p>
<p>e.g:</p>
<p>2
4
8
10
12</p>
<p>Here in this series, 6 is missing, so I am going to find the missing series from common difference series.</p>
<p>I got the correct output from this code. Is it the correct way? Is there any other simple code to do the same?</p>
<pre><code><?php
fscanf(STDIN, "%d\n", $count);
$series = array();
$common_diff = array();
$prev_element = null;
for($i=0;$i<$count;$i++){
fscanf(STDIN, "%d\n", $series[$i]);
if($prev_element != null){
$common_diff[] = $series[$i] - $prev_element;
}
$prev_element = $series[$i];
}
$c = array_count_values($common_diff);
asort($c);
end($c);
$common_d = key($c);
$prev_element = $series[0];
$missed_no = 0;
for($i=1;$i<$count;$i++){
$diff = $series[$i] - $prev_element;
if($diff != $common_d){
$missed_no = $prev_element + $common_d;
}
$prev_element = $series[$i];
}
echo $missed_no;
exit;
?>
</code></pre>
<p>example input</p>
<p>5
2
4
8
10
12</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T10:27:55.743",
"Id": "68289",
"Score": "0",
"body": "is it possible for more than 1 values to be missing? are series of 1 allowed? Are you considering negatives/invalid input?"
}
] |
[
{
"body": "<p>Right, I'd fill in the missing values like so:</p>\n\n<pre><code>//assume\n$series = array(2,4,8,10,12);\n$count = 5;\n//get step-size:\n$step = floor((max($series) - min($series))/$count);\n//then check/complete series:\n$complete = array($series[0]);//first element is valid\nfor($i=1, $j=count($series);$i<$j;++$i)\n{\n while(end($complete) + $step < $series[$i]\n {//while the complete series + step, add missing value\n $complete[] = end($complete) + $step;\n }\n $complete = $series[$i];\n}\n</code></pre>\n\n<p>Now this is far from perfect, but it's a start</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T10:40:34.953",
"Id": "40529",
"ParentId": "40428",
"Score": "1"
}
},
{
"body": "<h2>Functions</h2>\n\n<p>The code can be more readable if it is broken into functions. This also <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow\">separates the concern</a> of reading in the series and calculating the missing element(s).</p>\n\n<pre><code>function readSeries($fileHandle)\n{\n $series = array();\n fscanf($fileHandle, \"%d\\n\", $count);\n\n for ($i = 0; $i < $count; ++$i)\n {\n fscanf($fileHandle, \"%d\\n\", $series[$i]);\n }\n\n return $series;\n}\n\nfunction findMissing(Array $series)\n{\n sort($series);\n $start = reset($series);\n $finish = end($series);\n $step = ($finish - $start) / count($series); \n\n return array_diff(range($start, $finish, $step),\n $series);\n}\n\n$series = readSeries(STDIN);\n$missing = findMissing($series);\necho reset($missing);\n</code></pre>\n\n<p>The use of functions also help to make the code more reusable. The <code>readSeries</code> function can easily be used to read from standard input or another source.</p>\n\n<p>The <code>findMissing</code> function takes advantage of some assumptions that can be made when a series is sorted:</p>\n\n<ul>\n<li>It would be impossible to notice whether the beginning or end elements were missed, so they must both be present.</li>\n<li>One the beginning and end values are known then every step along this range must be present.</li>\n</ul>\n\n<p>It then uses the difference of the expected series calculated using the PHP <a href=\"http://php.net/manual/en/function.range.php\" rel=\"nofollow\">range</a> function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T12:40:11.983",
"Id": "40543",
"ParentId": "40428",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T04:41:28.543",
"Id": "40428",
"Score": "5",
"Tags": [
"php"
],
"Title": "Finding missing number from series"
}
|
40428
|
<p>My code snippet is like this:</p>
<pre><code>public static string EventId
{
get { return HttpContext.Current.Request["eventId"]; }
}
</code></pre>
<p>And I will call this property <code>EventId</code> whenever I need it. Is it a good practice?</p>
|
[] |
[
{
"body": "<p>Can you guarantee that <code>eventId</code> will never change? If so it might not be a bad idea, but this comes down to a few things</p>\n\n<ul>\n<li><code>eventId</code> never changes;</li>\n<li>how and where you're using it. It might be somewhat difficult for a new programmer in the project to locate and realize what it actually does (it returns the <code>eventId</code> for the current Http Request), solely based on the property name; and</li>\n<li>Are you sure that both <code>HttpContext.Current</code> and <code>Current.Request</code> are initialized before retrieving <code>eventId</code>. There is a change these will throw a null reference exception. It might be a very good idea to do a simple <code>if != null</code> check before invoking the Request property.</li>\n</ul>\n\n<p>If your code can accommodate for these points I don't see any inherently wrong with doing this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T07:52:09.040",
"Id": "40436",
"ParentId": "40430",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "40436",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T05:41:16.467",
"Id": "40430",
"Score": "2",
"Tags": [
"c#",
"asp.net"
],
"Title": "Is it a good idea to keep Request querystring as a property?"
}
|
40430
|
<p>The configuration file of my app is similar to,</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<Items>
<Item Name="Coffee"
Cost="10"
Image="itemCoffee.png" />
<Item Name="Tea"
Cost="10"
Image="itemTea.png" />
<Item Name="Vada"
Cost="10"
Image="itemVada.png" />
</Items>
</code></pre>
<p>Just trying to read the above small configuration file and I wrote this method.</p>
<pre><code>public static class Configuration
{
public static T DeSerialize<T>(string filePath)
{
if (!System.IO.File.Exists(filePath))
{
throw new System.IO.FileNotFoundException(filePath);
}
var serializer = new System.Xml.Serialization.XmlSerializer(T);
return (T)serializer.Deserialize(new FileStream(filePath, FileMode.Open));
}
}
</code></pre>
<ol>
<li><p>Where should I use <code>using</code> in this code? (Because, I never ever dispose the <code>new FileStream</code> that I wrote in this method)</p></li>
<li><p>Is this an overkill for reading this simple xml file?</p></li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T01:46:41.463",
"Id": "68223",
"Score": "5",
"body": "If that XML is really the *configuration file of your app*, I think you've missed an opportunity to leverage [*.net application settings*](http://msdn.microsoft.com/en-us/library/k4s6c3a0(v=vs.110).aspx)."
}
] |
[
{
"body": "<ol>\n<li><p>I would definitely wrap the FileStream object into a using clause like this:</p>\n\n<pre><code>using (Stream reader = new FileStream(filePath, FileMode.Open))\n{\n var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));\n return (T)serializer.Deserialize(reader);\n}\n</code></pre>\n\n<p>This way the Dispose method of the <code>FileStream</code> gets called immediately. Otherwise it will be delayed until the <code>FileStream</code> object gets garbage collected. This may not be a big problem in practice in simple applications where you read the configuration only once but is good practice to do it anyway.\nAlso note that you have to use <code>XmlSerializer(typeof(T))</code> instead of <code>XmlSerializer(T)</code>.</p></li>\n<li><p>My opinion is that it is overkill to create a generic method if you have only one kind of configuration file in your app. This method might be hard to read for a maintainer who is not sufficiently comfortable with generics and it has no benefit in making your code DRY-er if you have only one type of configuration file. </p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T07:43:04.047",
"Id": "68047",
"Score": "5",
"body": "I agree on your first point, but not on your second. I do not think it's overkill to create a generic method for this. If there are any programmers in the wild that do not understand generics they shouldn't be working as programmers. And by making a generic method he will be able to reuse his method whenever he needs it - whether its today or tomorrow or months from now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T08:07:34.320",
"Id": "68050",
"Score": "0",
"body": "@Andris: Thank you. `I prefer Answer for point 1` and go with @Max's comment for `Point 2`. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T08:11:14.017",
"Id": "68051",
"Score": "1",
"body": "@nowhewhomustnotbenamed. Point 2 is a judgement call. It is quite readable but it still feels like YAGNI to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T16:19:28.100",
"Id": "68107",
"Score": "1",
"body": "YAGNI and DRY are sometimes at odds. Particularly here where the required effort to create the generic is almost nothing, and the chances of reusing the method are high."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T07:24:13.333",
"Id": "40435",
"ParentId": "40434",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "40435",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T07:00:04.647",
"Id": "40434",
"Score": "5",
"Tags": [
"c#",
".net"
],
"Title": "Reading a configuration file in c#"
}
|
40434
|
<p>I'm writing an application that will be managed by my team, it uses Mustache.php as template engine.</p>
<p>I have a PHP file that makes an array of variables and functions that is passed to the Mustache parser to populate the template.</p>
<p>I even provide a system to override partials of my template to edit the aspect of the application for specific users.</p>
<p>Now I'd like to add a way to allow my team to add custom variables to the array passed to Mustache.php without have to hack the core of my application.</p>
<p>I thought about a little function that checks if a .php file with the name of the user exists and if so, include it after I've generated the array and before I pass it to mustache.</p>
<p>It should looks like:</p>
<p><strong>contents.php</strong>:</p>
<pre><code>// my queries
$variables = Array(1,2,3,bla,foo,bar);
if (file_exists($_SERVER['BASE_DIR'] . '/customcontents/'. $username . '.php')) {
include($_SERVER['BASE_DIR'] . '/customcontents/'. $username . '.php');
}
// Call mustache and pass $variables to it
</code></pre>
<p><strong><username>.php</strong>:</p>
<pre><code>// custom queries
$variables = array_merge($variables, $customvariables)
</code></pre>
<p>I'm not sure if this can be a nice solution or if you guys have some better idea.</p>
|
[] |
[
{
"body": "<p>I don't know anything about Mustache, so just a note about the code: <code>$_SERVER['BASE_DIR'] . '/customcontents/'. $username . '.php'</code> is duplicated, it could be extracted out to a local variable:</p>\n\n<pre><code>$userFile = $_SERVER['BASE_DIR'] . '/customcontents/' . $username . '.php'\nif (file_exists($userFile)) {\n include($userFile);\n}\n</code></pre>\n\n<p>(You might have ideas for a better name.)</p>\n\n<p>Reference: <em>Chapter 6. Composing Methods</em>, <em>Introduce Explaining Variable</em> in <em>Refactoring: Improving the Design of Existing Code</em> by Martin Fowler:</p>\n\n<blockquote>\n <p>Put the result of the expression, or parts of the expression, \n in a temporary variable with a name that explains the purpose.</p>\n</blockquote>\n\n<p>And <em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G19: Use Explanatory Variables</em>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T09:24:27.790",
"Id": "40442",
"ParentId": "40439",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T08:39:34.207",
"Id": "40439",
"Score": "1",
"Tags": [
"php",
"mustache"
],
"Title": "Allow users to add custom queries to Mustache variables"
}
|
40439
|
<p>The full question description is found <a href="http://www.geeksforgeeks.org/a-linked-list-with-next-and-arbit-pointer/" rel="nofollow">http://www.geeksforgeeks.org/a-linked-list-with-next-and-arbit-pointer/</a>.
Looking for code review, optimization, clean code etc.</p>
<pre><code>public class CopyArbit<T> {
private Node<T> first;
private Node<T> last;
private int size;
public CopyArbit() {}
private static class Node<T> {
T item;
Node<T> next;
Node<T> arbit;
Node(T item, Node<T> next, Node<T> arbit) {
this.item = item;
this.next = next;
this.arbit = arbit;
}
}
public void add(T item) {
final Node<T> l = last;
final Node<T> newNode = new Node<T>(item, null, null);
last = newNode;
if (first == null) {
first = newNode;
} else {
l.next = newNode;
}
size++;
}
public void makeArbitrary (int srcPos, int destPos) {
if (first == null) throw new NoSuchElementException("Linkedlist is empty.");
if (srcPos > size || srcPos < 1) {
throw new IllegalArgumentException("The srcPos " + srcPos + " is out of bound");
}
if (destPos > size || destPos < 1) {
throw new IllegalArgumentException("The destPos " + destPos + " is out of bound");
}
Node<T> source = getNodeAtPos(srcPos);
Node<T> destination = getNodeAtPos(destPos);
source.arbit = destination;
}
private Node<T> getNodeAtPos(int posFromStart) {
assert posFromStart > 0 && posFromStart <= size;
/*
* We need (posFromStart - 1) hops to reach the node at that pos.
*/
int hops = posFromStart - 1;
int counter = 0;
Node<T> temp = first;
while (counter < hops) {
temp = temp.next;
counter++;
}
return temp;
}
public CopyArbit<T> getCopy() {
Node<T> temp = first;
// interject nodes in between each other.
// ie convert A->B->C->D into A->A->B->B->C->C->D->D
while (temp != null) {
Node<T> tempAux = new Node<T>(temp.item, temp.next, null);
temp.next = tempAux;
temp = temp.next.next;
}
// fill in the arbit pointer
temp = first;
while (temp != null) {
Node<T> tempAux = temp.next;
tempAux.arbit = temp.arbit.next;
temp = temp.next.next;
}
return split();
}
private CopyArbit<T> split () {
Node<T> temp = first;
Node<T> first = null;
Node<T> firstHead = null;
Node<T> second = null;
Node<T> secondHead = null;
int counter = 0;
while (temp != null) {
if (counter % 2 == 0) {
if (firstHead == null) {
firstHead = temp;
} else {
first.next = temp;
}
first = temp;
} else {
if (secondHead == null) {
secondHead = temp;
} else {
second.next = temp;
}
second = temp;
}
temp = temp.next;
counter++;
}
first.next = null; // note this step.
CopyArbit<T> copyArbit = new CopyArbit<T>();
copyArbit.first = secondHead;
copyArbit.last = second;
copyArbit.size = size;
return copyArbit;
}
public Iterator<T> iterator() {
return new LinkedListIterator();
}
private class LinkedListIterator implements Iterator<T> {
int currentSize;
Node<T> node;
LinkedListIterator() {
currentSize = 0;
node = first;
}
public boolean hasNext() {
return currentSize < size;
}
public T next() {
T item = node.item;
node = node.next;
currentSize++;
return item;
}
@Override
public void remove() {
// TODO Auto-generated method stub
}
}
public Iterator<T> arbitIterator() {
return new LinkedListArbitIterator();
}
private class LinkedListArbitIterator implements Iterator<T> {
int currentSize;
Node<T> node;
LinkedListArbitIterator() {
currentSize = 0;
node = first;
}
public boolean hasNext() {
return currentSize < size;
}
public T next() {
T item = node.arbit.item;
node = node.next;
currentSize++;
return item;
}
@Override
public void remove() {
// TODO Auto-generated method stub
}
}
public static void main(String[] args) {
CopyArbit<Integer> source = new CopyArbit<Integer>();
source.add(10);
source.add(20);
source.add(30);
source.add(40);
source.makeArbitrary(1, 4);
source.makeArbitrary(2, 1);
source.makeArbitrary(3, 4);
source.makeArbitrary(4, 2);
CopyArbit<Integer> target = source.getCopy();
System.out.println("Expected: 40 10 40 20");
System.out.print("Actual: ");
Iterator<Integer> iterator = target.arbitIterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>I'd move the <code>main</code> method to a separate class. (For example, <code>CopyArbitMain</code>.) It's usually a good idea to separate a class from its clients.</p></li>\n<li><p><code>Iterator.remove()</code> should throw <code>UnsupportedOperationException</code> if remove is not supported (<a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html#remove%28%29\" rel=\"nofollow\">according to the javadoc</a>). Anyway, <code>// TODO Auto-generated method stub</code> comments usually a bad smell, don't leave them in the code.</p></li>\n<li><p>Instead of </p>\n\n<pre><code>if (srcPos > size || srcPos < 1) {\n throw new IllegalArgumentException(\"The srcPos \" + srcPos + \" is out of bound\");\n}\n</code></pre>\n\n<p>you could use <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Preconditions.html#checkArgument%28boolean,%20java.lang.String,%20java.lang.Object...%29\" rel=\"nofollow\">Guava's <code>checkArgument</code></a> (or just create a similar method, if you don't want to include an external library):</p>\n\n<pre><code>checkArgument(srcPos > size || srcPos < 1, \"The srcPos %s is out of bound\", srcPos);\n</code></pre>\n\n<p>It's a little bit simpler and easier to read.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T12:30:02.463",
"Id": "40610",
"ParentId": "40444",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T09:27:43.237",
"Id": "40444",
"Score": "2",
"Tags": [
"java",
"linked-list"
],
"Title": "Copy a linkedlist with an arbitrary pointer"
}
|
40444
|
<p>Is it right? any improvements? different approach...?</p>
<pre><code>import java.util.Properties;
import javax.ejb.EJBException;
import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class CalculatorImpl implements MessageDrivenBean,MessageListener {
private static Properties properties;
private static Context jndiContext;
private static final String
//JNDI_PROVIDER_CONTEXT_FACT = "weblogic.jndi.WLInitialContextFactory" //weblogic specific value
JNDI_PROVIDER_CONTEXT_FACT = "org.jnp.interfaces.NamingContextFactory";
;
private static final String
//JNDI_PROVIDER_URL = "t3://localhost:7003"//weblogic specific value
JNDI_PROVIDER_URL = "jnp://localhost:7003"//Mention valid provider url
;
private static final String
JNDI_SECURITY_PRINCIPAL = "weblogic"//Mention valid principal value
;
private static final String
JNDI_SECURITY_CREDENTIALS = "weblogic12"//Mention valid credential value
;
private String splitMsg,expr1,expr2 = null;
private double trigVal = 0.0;
private boolean negPostNum = false;
private int subIdx,addIdx,postIdx,preIdx = 0;
//----------------------------------------------------------------------------------------
public CalculatorImpl(){
properties = new Properties();
properties.put (Context.PROVIDER_URL, JNDI_PROVIDER_URL);
properties.put(Context.INITIAL_CONTEXT_FACTORY,JNDI_PROVIDER_CONTEXT_FACT);
properties.put(Context.SECURITY_PRINCIPAL, JNDI_SECURITY_PRINCIPAL);
properties.put(Context.SECURITY_CREDENTIALS, JNDI_SECURITY_CREDENTIALS);
}
//----------------------------------------------------------------------------------------
public void onMessage(Message p_message){
Message l_message = p_message;
String l_requestStr = null,
l_correlationID = null,
l_result = null;
try {
l_correlationID = l_message.getJMSCorrelationID();
if(l_correlationID == null){
l_correlationID = l_message.getJMSMessageID();
}
if (l_message instanceof TextMessage) {
l_requestStr = ((TextMessage) l_message).getText ();
} else {
throw new Exception (
"Message Type Not Supported : "
+ l_message.getClass ().getName ()
);
}
l_result = calculate(l_requestStr);
writeResponse(l_result,l_correlationID);
} catch (EJBException e){
e.printStackTrace();
throw new EJBException();
} catch(JMSException jex){
jex.printStackTrace();
throw new EJBException();
} catch(Exception ex){
ex.printStackTrace();
try{
writeResponse(ex.getMessage(),l_correlationID);
} catch(Exception e1){
e1.printStackTrace();
}
}
}
//----------------------------------------------------------------------------------------
/*The calculate function takes a string parameter,fetches the constant, operator
and function & returns the calculated value.*/
public synchronized String calculate(String p_msg) throws Exception {
String l_message = p_msg;
try
{
l_message=l_message.replace(" ", "");
System.out.println("CalculatorTest.calculate() "+l_message.intern());
while(l_message.indexOf("sin(") != -1){
l_message = getSin(l_message);
//System.out.println("CalculatorTest.calculate() aftersin "+l_message);
}
while(l_message.indexOf("cos(") != -1){
l_message = getCos(l_message);
//System.out.println("CalculatorTest.calculate() aftercos "+l_message);
}
while(l_message.indexOf("(") != -1){
l_message = getBrac(l_message);
//System.out.println("CalculatorTest.calculate()afterbrac "+l_message);
}
while(l_message.indexOf("/") != -1){
l_message = getDiv(l_message);
//System.out.println("CalculatorTest.calculate()afterdiv "+l_message);
}
while(l_message.indexOf("*") != -1){
l_message = getMult(l_message);
//System.out.println("CalculatorTest.calculate()aftermult "+l_message);
}
while(l_message.indexOf("+") != -1){
l_message = getAdd(l_message);
//System.out.println("CalculatorTest.calculate()afteradd "+l_message);
}
while(l_message.indexOf("-") != -1 && l_message.indexOf("Terminate")==-1){
l_message = getSub(l_message);
//System.out.println("CalculatorTest.calculate()aftersub "+l_message);
}
if(l_message.indexOf("Terminate")!=-1){
l_message = l_message.substring(0, l_message.indexOf("Terminate"));
}
System.out.println("CalculatorTest.calculate() result "+l_message);
} catch (Exception e){
e.printStackTrace();
throw new Exception("Error Occured During Calculation for "+p_msg);
} finally {
splitMsg= null; expr1= null;expr2= null;
trigVal = 0.0;
negPostNum = false;
subIdx = 0;addIdx = 0;postIdx = 0;preIdx = 0;
}
return l_message;
}
//----------------------------------------------------------------------------------------
//This method returns the sin value for the double parameter passed
public String getSin(String p_message) throws Exception
{
splitMsg=expr1=expr2 = null;
trigVal = 0.0;
splitMsg=p_message.substring(p_message.indexOf("sin("),p_message.length());
splitMsg=splitMsg.substring(0,splitMsg.indexOf(")")+1);
trigVal=Double.parseDouble(splitMsg.substring(splitMsg.indexOf("(")+1,splitMsg.indexOf(")")));
p_message = p_message.replace(splitMsg,String.valueOf(Math.sin(trigVal)));
return p_message;
}
//----------------------------------------------------------------------------------------
//This method returns the cos value for the double parameter passed
public String getCos(String p_message) throws Exception
{
splitMsg=expr1=expr2 = null;
trigVal = 0.0;
splitMsg=p_message.substring(p_message.indexOf("cos("),p_message.length());
splitMsg=splitMsg.substring(0,splitMsg.indexOf(")")+1);
trigVal=Double.parseDouble(splitMsg.substring(splitMsg.indexOf("(")+1,splitMsg.indexOf(")")));
p_message = p_message.replace(splitMsg,String.valueOf(Math.cos(trigVal)));
return p_message;
}
//----------------------------------------------------------------------------------------
//This method returns the value of expression within brackets
public String getBrac(String p_message) throws Exception
{
String l_bracMsg = null;
splitMsg=expr1=expr2 = null;
splitMsg=p_message.substring(p_message.indexOf("("),p_message.length());
l_bracMsg=splitMsg.substring(splitMsg.indexOf("("),splitMsg.indexOf(")")+1);;
splitMsg=splitMsg.substring(1,splitMsg.indexOf(")"));
while(splitMsg.indexOf("/") != -1){
splitMsg = getDiv(splitMsg);
}
while(splitMsg.indexOf("*") != -1){
splitMsg = getMult(splitMsg);
}
while(splitMsg.indexOf("+") != -1){
splitMsg = getAdd(splitMsg);
}
while(splitMsg.indexOf("-") != -1){
splitMsg = getSub(splitMsg);
}
p_message = p_message.replace(l_bracMsg,splitMsg);
return p_message;
}
//----------------------------------------------------------------------------------------
//This method returns the value of addition between two expressions
public String getAdd(String p_message) throws Exception
{
splitMsg=expr1=expr2 = null;
subIdx=addIdx=postIdx=preIdx = 0;
negPostNum =false;
double addVal =0.0;
expr2=p_message.substring(p_message.indexOf("+")+1,p_message.length()).trim();
expr1=p_message.substring(0,p_message.indexOf("+")).trim();
while(expr2.indexOf("-")!=-1 || expr2.indexOf("+")!=-1){
subIdx=expr2.indexOf("-");
addIdx =expr2.indexOf("+");
postIdx=Math.min(addIdx==-1?99999999:addIdx, subIdx==-1?99999999:subIdx);
if(postIdx ==0){
negPostNum = true;
expr2=expr2.substring(1,expr2.length()).trim();
continue;
}
if(postIdx == -1){
negPostNum = true;
expr2=expr2.substring(1,expr2.length()).trim();
} else{
expr2=expr2.substring(0,postIdx).trim();
}
}
if(expr1.indexOf("-")!=-1 || expr1.indexOf("+")!=-1){
subIdx=expr1.lastIndexOf("-");
addIdx =expr1.lastIndexOf("+");
preIdx=Math.max(addIdx, subIdx);
expr1=expr1.substring(preIdx+1,expr1.length()).trim();
}
if(negPostNum){
splitMsg=expr1+"+-"+expr2;
addVal = Double.parseDouble(expr1) + Double.parseDouble("-"+expr2);
} else{
splitMsg=expr1+"+"+expr2;
addVal = Double.parseDouble(expr1) + Double.parseDouble(expr2);
}
return p_message = p_message.replace(splitMsg,String.valueOf(addVal));
}
//----------------------------------------------------------------------------------------
//This method returns the value of substraction between two expressions
public String getSub(String p_message) throws Exception
{
splitMsg= expr1=expr2 = null;
subIdx=addIdx=postIdx=preIdx = 0;
negPostNum = false;
double subVal = 0.0;
expr2=p_message.substring(p_message.indexOf("-")+1,p_message.length()).trim();
expr1=p_message.substring(0,p_message.indexOf("-")).trim();
while(expr2.indexOf("-")!=-1){
postIdx=expr2.indexOf("-");
if(postIdx ==0){
negPostNum = true;
expr2=expr2.substring(1,expr2.length()).trim();
continue;
}
if(postIdx == -1){
negPostNum = true;
expr2=expr2.substring(1,expr2.length()).trim();
} else{
expr2=expr2.substring(0,postIdx).trim();
}
}
if(expr1.indexOf("-")!=-1 || expr1.indexOf("+")!=-1){
subIdx=expr2.lastIndexOf("-");
addIdx =expr2.lastIndexOf("+");
preIdx=Math.max(addIdx, subIdx);
expr1=expr1.substring(preIdx+1,expr1.length()).trim();
}
if(expr1 !=null && expr1.length()>0 && expr2 !=null && expr2.length()>0){
if(negPostNum){
splitMsg=expr1+"--"+expr2;
subVal = Double.parseDouble(expr1) - Double.parseDouble("-"+expr2);
} else{
splitMsg=expr1+"-"+expr2;
subVal = Double.parseDouble(expr1) - Double.parseDouble(expr2);
}
return p_message = p_message.replace(splitMsg,String.valueOf(subVal));
} else {
return p_message+"Terminate";
}
}
//----------------------------------------------------------------------------------------
//This method returns the value of division between two expressions
public String getDiv(String p_message) throws Exception
{
splitMsg= expr1=expr2 = null;
subIdx=addIdx=postIdx=preIdx = 0;
int multiPres,addPres,subPres = 0;
int postIdxChk,preIdxChk = 0;
double divVal = 0.0;
expr2=p_message.substring(p_message.indexOf("/")+1,p_message.length()).trim();
expr1=p_message.substring(0,p_message.indexOf("/")).trim();
if(expr2.indexOf("*")!=-1 || expr2.indexOf("+")!=-1 || expr2.indexOf("-")!=-1){
multiPres=expr2.indexOf("*");
addPres=expr2.indexOf("+");
subPres=expr2.indexOf("-");
postIdxChk=Math.min(multiPres==-1?99999999:multiPres, addPres==-1?99999999:addPres);
postIdx = Math.min(postIdxChk, subPres==-1?99999999:subPres);
expr2=expr2.substring(0,postIdx).trim();
}
if(expr1.indexOf("*")!=-1|| expr1.indexOf("+")!=-1 || expr1.indexOf("-")!=-1){
multiPres=expr1.lastIndexOf("*");
addPres=expr1.lastIndexOf("+");
subPres=expr1.lastIndexOf("-");
preIdxChk=Math.max(multiPres, addPres);
preIdx = Math.max(preIdxChk, subPres);
expr1=expr1.substring(preIdx+1,expr1.length()).trim();
}
splitMsg=expr1+"/"+expr2;
divVal = Double.parseDouble(expr1) / Double.parseDouble(expr2);
return p_message = p_message.replace(splitMsg,String.valueOf(divVal));
}
//----------------------------------------------------------------------------------------
//This method returns the value of multiplication between two expressions
public String getMult(String p_message) throws Exception
{
splitMsg=expr1=expr2 = null;
subIdx=addIdx=postIdx=preIdx = 0;
int addPres,subPres,multiPres= 0;
int postIdxChk,preIdxChk = 0;
double multiVal = 0.0;
expr2=p_message.substring(p_message.indexOf("*")+1,p_message.length()).trim();
expr1=p_message.substring(0,p_message.indexOf("*")).trim();
if(expr2.indexOf("+") !=-1 || expr2.indexOf("-")!=-1 || expr2.indexOf("*")!=-1){
addPres=expr2.indexOf("+");
subPres=expr2.indexOf("-");
multiPres=expr2.indexOf("*");
postIdxChk=Math.min(multiPres==-1?99999999:multiPres, addPres==-1?99999999:addPres);
postIdx=Math.min(subPres==-1?99999999:subPres, postIdxChk);
expr2=expr2.substring(0,postIdx).trim();
}
if(expr1.indexOf("+")!=-1 || expr1.indexOf("-")!=-1){
addPres=expr1.lastIndexOf("+");
subPres=expr1.lastIndexOf("-");
multiPres=expr2.indexOf("*");
preIdxChk=Math.max(multiPres, addPres);
preIdx = Math.max(preIdxChk, subPres);
expr1=expr1.substring(preIdx+1,expr1.length()).trim();
}
splitMsg=expr1+"*"+expr2;
multiVal = Double.parseDouble(expr1) * Double.parseDouble(expr2);
return p_message = p_message.replace(splitMsg,String.valueOf(multiVal));
}
//----------------------------------------------------------------------------------------
//This method writes the result of calculation to response queue
public void writeResponse(String p_response,String p_l_correlationID) throws Exception{
QueueConnectionFactory queueConnectionFactory = null;
QueueConnection queueConnection = null;
QueueSession queueSession = null;
Queue queue = null;
QueueSender queueSender = null;
TextMessage message = null;
String l_txtMessage = "";
String l_corr_id = "";
try {
jndiContext = new InitialContext(properties);
queueConnectionFactory = (QueueConnectionFactory)
jndiContext.lookup("jms/connFactory");//Mention actual connection factory name
queue = (Queue) jndiContext.lookup(new String("jms/respQueue")); //Mention actual connection queue name
} catch (NamingException e) {
e.printStackTrace();
throw e;
}
l_corr_id = p_l_correlationID;
l_txtMessage= p_response;
try {
queueConnection = queueConnectionFactory.createQueueConnection();
queueSession = queueConnection.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);
queueConnection.start();
queueSender = queueSession.createSender(queue);
message = queueSession.createTextMessage();
message.setJMSCorrelationID (l_corr_id != null?l_corr_id:"");
message.setText(l_txtMessage);
queueSender.send(message);
} catch (JMSException e) {
e.printStackTrace ();
throw e;
} finally {
if (queueConnection != null) {
try {
queueConnection.close();
} catch (JMSException e) {}
}
if (queueSession != null) {
try {
queueSession.close();
} catch (JMSException e) {}
}
if (queueSender != null) {
try {
queueSender.close();
} catch (JMSException e) {}
}
}
}
//----------------------------------------------------------------------------------------
public void ejbRemove ()
throws EJBException {
}
//----------------------------------------------------------------------------------------
public void ejbCreate ()
throws EJBException {
}
//----------------------------------------------------------------------------------------
public void setMessageDrivenContext (
MessageDrivenContext p_context
) throws EJBException {
}
//----------------------------------------------------------------------------------------
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T18:05:35.097",
"Id": "68135",
"Score": "2",
"body": "Tiny thing, but probably you should use whitespaces consistently: in some places, you have unnecessary indentations, and missing spaces (before and after \"=\" and \",\")."
}
] |
[
{
"body": "<p>Some notes:</p>\n\n<ol>\n<li><p>The <code>get*</code> methods do not look too easy to understand. I bet that there is some library which could do the calculations for you (<a href=\"https://stackoverflow.com/q/3422673/843804\">here a question about it on Stack Overflow</a>), so using one would improve both readability and maintainability of your code (since you need less code) and save you a few days too. </p>\n\n<p>See also: <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em> (The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)</p></li>\n<li><p>From <em>Code Complete, 2nd Edition</em>, p761:</p>\n\n<blockquote>\n <p><strong>Use only one data declaration per line</strong></p>\n \n <p>[...] \n It’s easier to modify declarations because each declaration is self-contained.</p>\n \n <p>[...]</p>\n \n <p>It’s easier to find specific variables because you can scan a single\n column rather than reading each line. It’s easier to find and fix\n syntax errors because the line number the compiler gives you has \n only one declaration on it.</p>\n</blockquote></li>\n<li>\n\n<pre><code> } catch (final EJBException e) {\n e.printStackTrace();\n throw new EJBException();\n } ...\n</code></pre>\n\n<p>Logging and rethrowing an exception usally leads to logging it twice (application servers logs system output too) which means harder maintenance (two stacktrace for every error). Furthermore, if you rethrow an exception set its cause:</p>\n\n<pre><code>} catch (final EJBException e) {\n throw new EJBException(e);\n} ...\n</code></pre>\n\n<p>It helps debugging a lot.</p>\n\n<p>Other references:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/q/10477607/843804\">Avoid printStackTrace(); use a logger call instead</a></li>\n<li><a href=\"https://stackoverflow.com/q/7469316/843804\">Why is exception.printStackTrace() considered bad practice?</a></li>\n</ul></li>\n<li><p><code>l_message</code> is unnecessary, you could use <code>p_message</code> instead of it.</p></li>\n<li><p>The declaration of <code>l_result</code> could be inside the <code>try</code> block. Try to minimize the scope of local variables. It's not necessary to declare them at the beginning of the method, declare them where they are first used. (<em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>)</p>\n\n<pre><code>final String result = calculate(requestStr);\nwriteResponse(result, correlationID);\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T23:30:10.130",
"Id": "40644",
"ParentId": "40453",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T11:31:57.023",
"Id": "40453",
"Score": "3",
"Tags": [
"java",
"calculator",
"jms"
],
"Title": "Calculator implemented in a MessageDrivenBean"
}
|
40453
|
<p>I would like to connect this "JS" to Bugzilla (example: bugzilla.mozilla.org or landfill.bugzilla.org). </p>
<p>I started to learn JS language today and I would like to ask you:</p>
<ol>
<li>How can I not do bad things in global scope? </li>
<li>How should I use functions (in <code>var</code> or not)?</li>
</ol>
<p></p>
<pre><code>quicksearch = document.getElementById('quicksearch_top');
comment = document.getElementById('comment');
severity = document.getElementById('bug_severity');
priority = document.getElementById('priority');
commit_top = document.getElementById('commit_top');
commit = document.getElementById('commit');
function focusonload() {
// may be it should be
// in next function?
function cursorfocus(s) {
x = window.scrollX;
y = window.scrollY;
s.focus();
window.scrollTo(x, y);
}
if (comment !== null) {
cursorfocus(comment)
} else {
quicksearch.focus();
}
}
function navigation(keypressed) {
keypressed = keypressed || window.event;
function selectelement(w, select) {
w.value = select;
}
keyCode = keypressed.keyCode || keypressed.which,
kn = {
enter: 13,
save: 83,
down: 40,
up: 38,
p1: 49,
p2: 50,
p3: 51,
p4: 52,
p5: 53,
};
if (keypressed.altKey) {
if (keyCode == nk.save && commit_top!==null){
commit_top.click();
}
var key_str;
if (priority!==null){
switch (keyCode) {
case kn.p1: key_str = "P1"; break;
case kn.p2: key_str = "P2"; break;
case kn.p3: key_str = "P3"; break;
case kn.p4: key_str = "P4"; break;
case kn.p5: key_str = "P5"; break;
}
}
selectelement(priority, key_str);
severity.focus();
} else if (keypressed.ctrlKey) {
switch (keyCode) {
case kn.enter:
if (commit!==null&&comment.value!=="") {
commit.click();
}
break;
case kn.up:
if (quicksearch!==null) {
quicksearch.focus();
}
break;
case kn.down:
if (comment!==null) {
comment.focus();
}
break;
}
}
}
focusonload();
document.onkeydown = navigation;
// how to call this functions when page
// would be loaded at all (with window.onload)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T01:29:51.113",
"Id": "68850",
"Score": "0",
"body": "typo: `if (keyCode == nk.save && commit_top!==null){` should be `kn.save` not `nk.save`?"
}
] |
[
{
"body": "<blockquote>\n <p>How can I not mess up the global scope?</p>\n</blockquote>\n\n<p>You can use an IIFE ( Immediately Invoked Function Expression ) to surround your code and then assign all your variables with <code>var</code> <- Very important.</p>\n\n<pre><code>(function(){\n\n var quicksearch = document.getElementById('quicksearch_top');\n var comment = document.getElementById('comment');\n\n var severity = document.getElementById('bug_severity');\n var priority = document.getElementById('priority');\n\n var commit_top = document.getElementById('commit_top');\n var commit = document.getElementById('commit'); \n\n //the rest of your code here\n\n}()); \n</code></pre>\n\n<blockquote>\n <p>How should I use functions (in <code>var</code> or not)?</p>\n</blockquote>\n\n<p>It really is up to you, at this point I prefer <code>function</code>.</p>\n\n<p><em>Other than that:</em></p>\n\n<p>You should use lowerCamelCasing, so</p>\n\n<ul>\n<li>commit_top -> commitTop</li>\n<li>quicksearch -> quickSearch</li>\n<li>selectelement -> selectElement</li>\n</ul>\n\n<p>etc.etc</p>\n\n<p>Your keycode map is very nice, keep it that way!</p>\n\n<p>One last comment is that you should not use <code>document.onkeydown = navigation;</code>, there is a good chance that you will break something this way.</p>\n\n<p>Try <code>document.addEventListener(\"keydown\", navigation, true);</code> instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T11:27:44.363",
"Id": "68299",
"Score": "0",
"body": "Thank you very much for your advices and for being answered."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T15:00:55.650",
"Id": "40464",
"ParentId": "40462",
"Score": "10"
}
},
{
"body": "<p>To add a couple of points to konijns answer;</p>\n\n<p>You can remove the need for verbose switch statements with a <code>dict</code>:</p>\n\n<pre><code>var kn = {\n 49: 'P1', \n 50: 'P2', \n 51: 'P3', \n 52: 'P4', \n 53: 'P5', \n};\n\n...\n\nvar keyStr = kn[keyCode];\n</code></pre>\n\n<p>You can call a function when the page loads using the <code>onload</code> event:</p>\n\n<pre><code>window.onload = focusOnLoad;\n</code></pre>\n\n<p>Since it's only executed once <code>function cursorfocus(s)</code> may as well be inline, rather than a function declaration. The same with <code>selectElement()</code>.</p>\n\n<p>I also like to put the larger block of code in my else statement. This makes it easier to read, and the flow feels better. Also avoid unnecessary variables, it's quite clear what this code means without <code>x</code> and <code>y</code>.</p>\n\n<pre><code>if (!comment) {\n quicksearch.focus();\n} else {\n s.focus();\n window.scrollTo(window.scrollX, window.scrollY);\n}\n</code></pre>\n\n<p>Finally, don't forget those <code>var</code> statements!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T01:06:36.943",
"Id": "68845",
"Score": "0",
"body": "Why would you use an anon function`window.onload = function() {` for onload when you're just calling a single function? Also I on't think the `focusOnLoad()` function was specified as on load of window but rather on load of the script. Also the difference between your `kn` object and the OP's is that yours is in reverse. *(numbers to names rather than names to numbers)*"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T01:19:21.293",
"Id": "68847",
"Score": "0",
"body": "@JamesKhoury Whoops, good point. I got the `onload` requirement from the comments at the bottom. Quite true about the `kn` object, but since he's not really using the names for anything I deemed the object mapping more effective."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T01:29:28.453",
"Id": "68849",
"Score": "0",
"body": "the `kn` object is used in detirmining the `keyCode`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T14:21:20.267",
"Id": "69942",
"Score": "0",
"body": "@JamesKhoury Yes, but the **keys** in the `kn` object aren't used for anything, so they don't need to be words like `enter`, `save` and `down`, it's simple enough to understand without."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T23:29:30.340",
"Id": "40797",
"ParentId": "40462",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "40464",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T14:35:02.183",
"Id": "40462",
"Score": "8",
"Tags": [
"javascript",
"scope"
],
"Title": "Advice needed for scopes in JavaScript"
}
|
40462
|
<p>I'm calling a view into a view. Am I doing correctly, or is this a bad practice?</p>
<pre><code><div class="tab-pane" id="tab_1_2">
<div class="portlet ">
<div class="portlet-title">
<div class="caption">
<i class="icon-reorder"></i> Nuevo Usuario
</div>
</div>
<?php $this->load->view('modules/user/form_add_user'); ?>
</div>
</div>
</code></pre>
|
[] |
[
{
"body": "<p>For your controller, a method like this would be best to call all your variables:</p>\n\n<pre><code>$data = array(\n \"add_user\" => $this->load->view('form_add_user'),\n \"username\" => $username,\n \"admin\" => $admin\n);\n</code></pre>\n\n<p>(Variables are made up just for example)</p>\n\n<p>Then, within your code, do this:</p>\n\n<pre><code><div class=\"tab-pane\" id=\"tab_1_2\">\n <div class=\"portlet \">\n <div class=\"portlet-title\">\n <div class=\"caption\">\n <i class=\"icon-reorder\"></i> Nuevo Usuario\n </div>\n </div>\n <?=$add_user;?> <!-- looks cleaner -->\n </div>\n</div>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T16:07:11.787",
"Id": "68099",
"Score": "0",
"body": "form_add_user is a large html form and I placed in another view for that reason."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T16:11:10.887",
"Id": "68101",
"Score": "0",
"body": "Completely re-wrote answer after some research + your comment @AndreFontaine"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T15:54:00.600",
"Id": "40469",
"ParentId": "40465",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "40469",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T15:17:22.290",
"Id": "40465",
"Score": "2",
"Tags": [
"php",
"html",
"mvc",
"codeigniter"
],
"Title": "Codeigniter view within a view"
}
|
40465
|
<p>I am writing a Tornado app in which a user can maintain his products wishlist. There are two collections, <code>users</code> and <code>products</code>. As the names imply, the <code>users</code> collections will contain users info and the <code>products</code> collections will contain the URLs. </p>
<p>Typically a <code>user</code> document in <code>users</code> collection will contain the following fields:</p>
<ul>
<li><code>email_id</code></li>
<li><code>name</code></li>
<li><code>tracked_products</code></li>
</ul>
<p>The <code>tracked_products</code> here is a list which maintains the wishlist. It contains the <code>ObjectId</code> mapped to URLs in <code>products</code> collection. To make it clear, when two users add the same product URL, in their respective user documents instead of containing the URL, they will have the <code>ObjectId</code> of this URL, which is the ID of the URL in the <code>products</code> collection.</p>
<p>To find tracked_products of a specific user:</p>
<pre><code> search_user = user_db.find_one({'email_id': user_email})
search_user['tracked_products']
</code></pre>
<p>above will return to me list of <code>ObjectId</code>s.</p>
<p>To add a product URL to the user's wishlist:</p>
<pre><code>product_doc = product_db.find_one({'url': url})
if not product_doc:
# code needs to be added here to get product name from url
product_id = str(product_db.insert({'product_name': 'iPad', 'url': url})
else:
product_id = product_doc['_id']
user_db.update({'email_id': user_email}, {'$addToSet': {'tracked_products': ObjectId(product_id)}})
</code></pre>
<p>The following is the code when user wants to remove a URL from his wishlist. Do note that he will send the <code>ObjectId</code> instead of the URL, he intends to remove. This may seem less intuitive. The user will actually never know the <code>ObjectId</code>s, but the page rendered to him which displays the wishlist, will make call when user wants to delete the URL (am I clear here?):</p>
<pre><code>user_db.update({'email_id': user_email}, {'$pull': {'tracked_products': ObjectId(product_id)}})
</code></pre>
<p>And here is my actual Tornado app code. I am not using any templating as of now, will add that later. Also ignore the repeated <code>user_db = self.application.db.users</code> statement which is present in all handlers (which should not, may app can have this variable). And one more thing: I access the current logged in user's email ID every time by a cookie.</p>
<p>Is there any way to avoid this? Can I have some global variable which stores user email ID every time the user is logged in?</p>
<pre><code>class ProductsDisplayHandler(BaseHandler):
@tornado.web.authenticated
def get(self):
user_email = self.get_secure_cookie('trakr')
user_db = self.application.db.users
search_user = user_db.find_one({'email_id': user_email})
self.write(str(search_user.get('tracked_products', None)))
class ProductAddHandler(BaseHandler):
@tornado.web.authenticated
def get(self, url):
user_email = self.get_secure_cookie('trakr')
user_db = self.application.db.users
product_db = self.application.db.products
product_doc = product_db.find_one({'url': url})
if not product_doc:
product_id = str(product_db.insert({'product_name': 'iPad', 'url': url}))
else:
product_id = product_doc['_id']
user_db.update({'email_id': user_email}, {'$addToSet': {'tracked_products': ObjectId(product_id)}})
class ProductDelHandler(BaseHandler):
@tornado.web.authenticated
def get(self, product_id):
user_email = self.get_secure_cookie('trakr')
user_db = self.application.db.users
user_db.update({'email_id': user_email}, {'$pull': {'tracked_products': ObjectId(product_id)}})
self.redirect('/products')
return
</code></pre>
|
[] |
[
{
"body": "<p>You can try editing your BaseHandler like this</p>\n\n<pre><code>class BaseHandler(tornado.web.RequestHandler):\n def prepare(self):\n self.user_email = self.get_secure_cookie('trakr')\n self.user_db = self.application.db.users\n</code></pre>\n\n<p>and then call the following in your other Handlers </p>\n\n<pre><code>self.userdb.update({'email_id': self.user_email},\n</code></pre>\n\n<p>Basically the prepare function is called right at the beginning of the request\nfor more information you can look at the <a href=\"http://tornado.readthedocs.org/en/latest/web.html#tornado.web.RequestHandler.prepare\" rel=\"nofollow\">tornado docs</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-24T11:18:25.003",
"Id": "78485",
"ParentId": "40466",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T15:38:17.203",
"Id": "40466",
"Score": "3",
"Tags": [
"python",
"mongodb",
"tornado"
],
"Title": "Tornado PyMongo product wishlist"
}
|
40466
|
<p>I've been building a system for inputting and monitoring shifts for casual staff, who work across multiple sites with the ability to generate accounting information.</p>
<p>I've had some help from Stack Overflow in building this project, as I had no prior knowledge of PHP or MySQL, and each time I posted some of my code I had comments about the lack of security. </p>
<p>In my system, sensitive information like salaries, work hours and things are protected by having different levels of user accounts. The code below is a snippet of code from my Admin Area allowing me to edit an account's userLevel and password.</p>
<pre><code>if(isset($_POST['submit'])) {
$editid = htmlentities($_POST['id'], ENT_QUOTES, 'UTF-8');
$userLevel = htmlentities($_POST['userLevel'], ENT_QUOTES, 'UTF-8');
if(!empty($_POST['password'])) {
$password = password_hash("$_POST['password']", PASSWORD_DEFAULT)
$sql = "UPDATE users SET userLevel = ?, password = ?, salt = ? WHERE id = ?";
$stmt = $connection->prepare($sql);
$stmt->bind_param('ssss', $userLevel, $password, $salt, $editid);
} else {
$sql = "UPDATE users SET userLevel = ? WHERE id = ?";
$stmt = $connection->prepare($sql);
$stmt->bind_param('ss', $userLevel, $editid);
}
$stmt->execute();
}
</code></pre>
<p>I specify UTF-8 charset at the top of my php files, and all raw output variables, posts, gets and sessions are wrapped in htmlentities tags. My account passwords are hashed and salted. </p>
<p>My system is only used locally and will never be used on the web (unless I post the code somewhere, which I could do to help other new people learn), but as I'm learning I was told I should get in the habit of writing secure code. So finally we get to the question.. Is the above code of a secure enough level for the web? If not, please offer suggestions.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T15:55:29.637",
"Id": "68098",
"Score": "1",
"body": "You could add `$stmt->execute();` outside the `if` statement so it doesn't have to be there twice. Although that's just being extremely nitpicky."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T16:48:03.870",
"Id": "68121",
"Score": "0",
"body": "@BeatAlex, that is a very good point, I would upvote that review(answer) you should post with a little more explanation on it, even though it doesn't need one really."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T17:01:18.097",
"Id": "68125",
"Score": "0",
"body": "Thanks for pointing it out, I've probably missed a bunch of little things like that as I've done a complete overhaul of code. Average reduction in lines of code per page is about 50% to give you some idea of how poor it was :p (many of it written in my first day(s) of php)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T09:05:54.980",
"Id": "68276",
"Score": "0",
"body": "@MrLore I followed a tutorial and some stackoverflow posts, that said iterating hashes and injecting the password in each iteration was a good method of increasing the strength of the hash. http://stackoverflow.com/a/348140/3169285"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T17:43:29.460",
"Id": "72812",
"Score": "0",
"body": "Do not invent your own hashing scheme"
}
] |
[
{
"body": "<p>One thing to improve on (if your PHP version allows it), is to consider using PHP's built in <code>password_hash()</code> function. Coupled with <code>password_verify()</code>, it eliminates the need to salt and hash passwords manually. More information can be found <a href=\"http://us2.php.net/manual/en/ref.password.php\" rel=\"nofollow\">in the documentation</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T13:27:43.547",
"Id": "72745",
"Score": "0",
"body": "Thanks, didn't know this function existed. Have a +1 :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T17:41:27.800",
"Id": "72811",
"Score": "0",
"body": "If your not one a new enough version, you can use this great resource. https://github.com/ircmaxell/password_compat"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T04:32:09.860",
"Id": "42260",
"ParentId": "40467",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T15:51:19.020",
"Id": "40467",
"Score": "5",
"Tags": [
"php",
"mysql",
"sql",
"security"
],
"Title": "System for inputting and monitoring worker shifts"
}
|
40467
|
<p>I am creating a Monopoly board game using HTML, CSS, PHP, JS and jQuery. I am doing this to develop my web development skills. I have cut the project into sections, so this question will only deal with creating the board.</p>
<p><a href="http://jsfiddle.net/eltonfrederik/XyL48/" rel="nofollow">JSFiddle</a></p>
<p>The board size is determined by the sizes of the 40 Monopoly positions <code>class name .box</code>. The problem is in deciding the optimum size for these positions.</p>
<p>This is the current makeup:</p>
<ul>
<li>Title</li>
<li>Runway : When a player lands on that position a 12x12px star will be displayed.</li>
<li>Body: This a 32px area where icons are placed if icons are used</li>
<li>Price: This displays the purchase price in case unowned, or rent if owned, or taxes.</li>
</ul>
<p>I don't want the user to scroll at all. Users with a screen size lower than 1024x768 are not supported in this case. How would you size the 40 positions for users with a 1024x768 screen size?</p>
<p>Note: Don't worry about the lack of iteration with PHP that can come later. We first need to know what the HTML should look like then we can automate it later.</p>
<p><a href="http://i.dailymail.co.uk/i/pix/2011/06/03/article-1393521-0C6047E600000578-120_964x966.jpg" rel="nofollow">Image of a real Monopoly board</a></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-css lang-css prettyprint-override"><code>/*******************************
Elements
********************************/
span{
display: block;
font: bold 10px "Arial", "Helvetica", sans-serif;
color: #000;
text-align: center;
}
/*******************************
Board Structure
********************************/
.board {
background: #EBEBE0;
width: 808px;
}
.row{
background: #fff;
float: left;
margin-bottom: 2px;
}
#row1, #row3 {
height: 82px;
width: 788px;
}
#row2 {
width: 788px;
}
.col1{
float: left;
width: 75px;
}
.col3{
float: right;
margin-right: 2px;
width: 75px;
}
/*******************************
Board positions - Box
********************************/
.box {
background: #fff;
border: 1px solid #000;
float: left;
height: 80px;
width: 75px;
}
div #box-x:last-child {
margin-right: 0;
}
#box-x{
margin-right: 2px;
}
#box-y{
margin-bottom: 2px;
}
div #box-y:last-child {
margin-bottom: 0;
}
/*******************************
Board positions - Title
********************************/
.title{
background: black;
border-bottom: 1px solid #000;
line-height: 16px;
}
#blanktitle{
background: none;
border-color: #fff;
}
#pink{
background: #ff4f72;
}
/*******************************
Board positions - Runway
********************************/
.runway{
background: aliceblue;
height: 12px;
margin: 2px 0 2px 0;
}
.piece{
background-image:url('../img/piece2.png');
float: left;
height:12px;
margin-left: 2px;
width: 12px;
}
/*******************************
Board positions - Body
********************************/
.cardbody{
background: beige;
height:32px;
}
.icons{
background-repeat: no-repeat;
width: 32px;
height: 32px;
margin: 0 auto 0 auto;
}
#airport{
}
#chest{
}
/*******************************
Board positions - Price
********************************/
.price{
line-height: 12px;
margin: 2px 0 2px 0;
text-align: center;
width: 100%;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<div class="board">
<div class="row" id="row1">
<div class="box" id="box-x">
<span class="title" id="pink">Amsterdam</span>
<div class="runway">
</div>
<div class="cardbody">
</div>
<span class="price"></span>
</div>
<div class="box" id="box-x">
<span class="title" id="blanktitle"> Schiphol</span>
<div class="runway">
</div>
<div class="cardbody">
<span class="icons" id="airport"></span>
</div>
<span class="price"> </span>
</div>
<div class="box" id="box-x"></div>
<div class="box" id="box-x"></div>
<div class="box" id="box-x"></div>
<div class="box" id="box-x"></div>
<div class="box" id="box-x"></div>
<div class="box" id="box-x"></div>
<div class="box" id="box-x"></div>
<div class="box" id="box-x"></div>
</div>
<div class="row" id="row2">
<div class="col1">
<div class="box" id="box-y"></div>
<div class="box" id="box-y"></div>
<div class="box" id="box-y"></div>
<div class="box" id="box-y"></div>
<div class="box" id="box-y"></div>
<div class="box" id="box-y"></div>
<div class="box" id="box-y"></div>
<div class="box" id="box-y"></div>
</div>
<div class="col3">
<div class="box" id="box-y"></div>
<div class="box" id="box-y"></div>
<div class="box" id="box-y"></div>
<div class="box" id="box-y"></div>
<div class="box" id="box-y"></div>
<div class="box" id="box-y"></div>
<div class="box" id="box-y"></div>
<div class="box" id="box-y"></div>
</div>
</div>
<div class="row" id="row3">
<div class="box" id="box-x">
<span class="title" id="pink">Amsterdam</span>
<div class="runway">
</div>
<div class="cardbody">
</div>
<span class="price"></span>
</div>
<div class="box" id="box-x">
<span class="title" id="blanktitle"> Schiphol</span>
<div class="runway">
</div>
<div class="cardbody">
<span class="icons" id="airport"></span>
</div>
<span class="price"> </span>
</div>
<div class="box" id="box-x"></div>
<div class="box" id="box-x"></div>
<div class="box" id="box-x"></div>
<div class="box" id="box-x"></div>
<div class="box" id="box-x"></div>
<div class="box" id="box-x"></div>
<div class="box" id="box-x"></div>
<div class="box" id="box-x"></div>
</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T17:37:17.043",
"Id": "68130",
"Score": "4",
"body": "Greetings and welcome to Code Review. Since there is no JavaScript or PHP in this question, I removed these tags. The only thing then to review is the HTML which we all know is not going to make the final cut ( you will generate this ) and the CSS. Honestly, I think you jumped the gun on this, you should advance your project a bit more and then come back."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T17:53:35.623",
"Id": "68133",
"Score": "3",
"body": "Questions about \"How would you guys implement this feature that I haven't implemented?\" (i.e. \"So how would you guys size the 40 positions for users with a 1024x768 screen size?\") is off-topic for Code Review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T22:51:34.640",
"Id": "68197",
"Score": "0",
"body": "This is very imaginative. Much of the game of Monopoly is just the beauty of the board, so I wonder if it would be worth taking the time to make the spaces rectangular and adding the colored bars and some of the images in your divs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T04:13:41.953",
"Id": "68243",
"Score": "0",
"body": "@SimonAndréForsberg I have replicated the Monopoly board in my code for a 1024x768 screen. I was not sure my code (HTML) was efficient and my question was how you would replicate it."
}
] |
[
{
"body": "<p>As mentioned in the comments the question that you are asking is actually off topic as you have not implemented it yet and there are many solutions (you could for example do everything as percentage or <a href=\"http://css-tricks.com/viewport-sized-typography/\">vh/vw units</a> rather than pixels). What you're asking for is a concept known as <a href=\"https://shop.smashingmagazine.com/responsive-design.html\">responsive design</a>. I will however review the code that you have.</p>\n\n<p>First problem I see</p>\n\n<pre><code> <div class=\"box\" id=\"box-x\"></div>\n <div class=\"box\" id=\"box-x\"></div>\n</code></pre>\n\n<p>you have non-unique ids! This is <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element.id\">against spec</a> and you will find that many tools and libraries have problems when using non-unique ids. Instead you should use </p>\n\n<pre><code> <div class=\"box box-x\"></div>\n <div class=\"box box-x\"></div>\n</code></pre>\n\n<p>Speaking of which, the <code>.box</code> class is probably not the best named. you could imagine making a diesel-punk version of this where you use border-radius to have round (not boxy) spaces. Instead name it for what it is. My recommendation would be <code>.place</code></p>\n\n<p>I'll stop short of saying that you should avoid ids altogether but only use them when you're really really sure that the element is the only one on the page with that name (including any other components built from composite uis).</p>\n\n<p>Next - this is a bit of personal preference but I think you're overusing divs. proper html elements can give good semantics to your document. I would probably structure the <code>.column>div</code> stuff as <code>ul.column>li</code> since these are part of a series. Other valid possibilities might be <code><article></code> (as in article of clothing NOT a blog post article) or <code><section></code> elements.</p>\n\n<p>I would also say you can make this significantly more lightweight by using a javascript templating framework like <a href=\"http://handlebarsjs.com/\">Handlebars</a> or a an MVVM framework like <a href=\"http://knockoutjs.com\">Knockout</a> or a full javascript framework like <a href=\"http://angularjs.org/\">Angular</a>. Your mounds and mounds of html will then collapse down to just a single definition.</p>\n\n<p>Runway probably doesn't need to be an element at all. You can probably just tag the <code>.box</code> the appropriate class (like <code>.orange</code>) and use <a href=\"http://www.colorzilla.com/gradient-editor/\">css3 gradients</a> to create that stripe.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T04:07:59.317",
"Id": "68241",
"Score": "0",
"body": "I have implemented the board structure and asked this question with the aim of improving my base structure. If it wasn't for your answer, I would have continued with non-unique ids! Also naming it `.place` instead of `.box` is a good suggestion, perhaps the best word is `.position`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T04:10:37.203",
"Id": "68242",
"Score": "0",
"body": "`.runway` is to contain the monopoly pieces when the player lands there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T04:29:30.873",
"Id": "68244",
"Score": "0",
"body": "I see, then `.runway` does make sense, yes. Also you can benefit a lot from using a css precompiler. Either LESS or SASS (my preference) - either one works and either one is 1000000 times nicer than raw css."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T05:16:41.753",
"Id": "68247",
"Score": "0",
"body": "Yes. I will use them, also like sass. I like to first do raw HTML just to get good idea and then automate it. I know CR is really for improving code but I needed to review the base structure first."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T05:20:55.023",
"Id": "68248",
"Score": "0",
"body": "Here is an image of some the issue I have to think about [link](http://snag.gy/sAlq4.jpg). It seems that 75x75 is necessary, that way I can add all the necessary data. The background colors are just for illustration purposes."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T23:05:16.893",
"Id": "40495",
"ParentId": "40468",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T15:53:24.703",
"Id": "40468",
"Score": "1",
"Tags": [
"html",
"game",
"css"
],
"Title": "Creating a Monopoly board"
}
|
40468
|
<p>In my CodeIgniter project I have a Login controller that load this view:</p>
<pre><code><ul class="sub-menu">
<li>
<a href="javascript:;" class = "menu-item" data-target="../indoamericana/soporte/callSupport/"> Mis solicitudes </a>
</li>
</ul>
</code></pre>
<p>The controller: <code>soporte</code>, function: <code>callSupport</code></p>
<pre><code>public function callSupport($index = null, $order = null){
$session_data = $this->session->userdata('session_user');
$data['solicitud'] = $this->helpdesk_model->getRequest($session_data['usuario'], $index, $order);
$data['categories'] = $this->helpdesk_model->getCategories();
$this->load->view('modules/help_desk/supports', $data);
}
</code></pre>
<p>With jQuery I call the controller and render in a page content that is a <code><div></code> element:</p>
<pre><code>$(".sub-menu .menu-item, .module-item").click(function(event) {
$(".page-content").load($(this).data('target'));
$("title").text( $( this ).text() );
});
</code></pre>
<p>In the view 'modules/help_desk/supports':</p>
<pre><code><table class="table table-striped table-hover" id="admin-support" data-target="soporte/callSupport/">
<thead>
<tr>
<th>Estado <a href="javascript:;"><i class="icon-sort" data-sort="status"></i></a></th>
<th>Prioridad <a href="javascript:;"><i class="icon-sort" data-sort="priority"></i></a></th>
<th>Responsable <a href="javascript:;"><i class="icon-sort" data-sort="id_responsible"></i></a></th>
</tr>
</thead>
<tbody>
<?php foreach ($solicitud as $key => $value) { ?>
<tr>
<td><span class="label label-sm <?= $value['label']?> "><?= ucfirst($value['status']) ?></span></td>
<td><span class="badge <?= $value['class']?> "><?= $value['priority'] ?></span></td>
<td><?= $value['name'].' '.$value['last_name'] ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</code></pre>
<p>As you can see, in the first <code><td></code> a put an anchor tag calls another controller with jQuery similar than before. Please be critical, very severe with me.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-02T06:08:08.723",
"Id": "414963",
"Score": "0",
"body": "If you are lucky, you'll never have a help desk employee called `<script>alert(123)</script>`. I wouldn't count on that, though. Better protect your code against cross-site scripting."
}
] |
[
{
"body": "<h1>General comments</h1>\n<p>I don't see much wrong with the code. The biggest concern I might have is that PHP code is mixed in with the HTML - an alternative to this would be using a template system. CodeIgniter has the <a href=\"https://www.codeigniter.com/userguide3/libraries/parser.html\" rel=\"nofollow noreferrer\">template parser class</a> which should allow you to do this.</p>\n<blockquote>\n<p><em>Please be critical, very severe with me.</em></p>\n</blockquote>\n<p>Okay - I am not typically this critical but you asked for it! The next section has a couple other review points</p>\n<h1>Minor nitpicks</h1>\n<p>In the PHP code, <code>$data</code> is not declared before values are assigned to specific keys:</p>\n<blockquote>\n<pre><code>$data['solicitud'] = $this->helpdesk_model->getRequest($session_data['usuario'], $index, $order); \n</code></pre>\n</blockquote>\n<p>I don't see a problem with this practice but <a href=\"http://php.net/manual/en/language.types.array.php#language.types.array.syntax.modifying\" rel=\"nofollow noreferrer\">the PHP documentation</a> advises against it:</p>\n<blockquote>\n<p>If <code>$arr</code> doesn't exist yet, it will be created, so this is also an alternative way to create an <a href=\"http://php.net/manual/en/language.types.array.php\" rel=\"nofollow noreferrer\">array</a>. This practice is however discouraged because if <code>$arr</code> already contains some value (e.g. <a href=\"http://php.net/manual/en/language.types.string.php\" rel=\"nofollow noreferrer\">string</a> from request variable) then this value will stay in the place and <code>[]</code> may actually stand for <a href=\"http://php.net/manual/en/language.types.string.php#language.types.string.substr\" rel=\"nofollow noreferrer\">string access operator</a>. It is always better to initialize a variable by a direct assignment.</p>\n</blockquote>\n<hr />\n<p>I tried running the jQuery callback through <a href=\"https://eslint.org/demo/#eyJ0ZXh0IjoiZnVuY3Rpb24gYShldmVudCkge1xyXG4gICAgJChcIi5wYWdlLWNvbnRlbnRcIikubG9hZCgkKHRoaXMpLmRhdGEoJ3RhcmdldCcpKTsgIFxyXG4gICAgJChcInRpdGxlXCIpLnRleHQoICQoIHRoaXMgKS50ZXh0KCkgKTtcclxufVxyXG5mdW5jdGlvbiAkKCkge1xyXG5cclxufVxyXG5hKCk7Iiwib3B0aW9ucyI6eyJwYXJzZXJPcHRpb25zIjp7ImVjbWFWZXJzaW9uIjo2LCJzb3VyY2VUeXBlIjoic2NyaXB0IiwiZWNtYUZlYXR1cmVzIjp7fX0sInJ1bGVzIjp7ImNvbnN0cnVjdG9yLXN1cGVyIjoyLCJuby1jYXNlLWRlY2xhcmF0aW9ucyI6Miwibm8tY2xhc3MtYXNzaWduIjoyLCJuby1jb21wYXJlLW5lZy16ZXJvIjoyLCJuby1jb25kLWFzc2lnbiI6Miwibm8tY29uc29sZSI6Miwibm8tY29uc3QtYXNzaWduIjoyLCJuby1jb25zdGFudC1jb25kaXRpb24iOjIsIm5vLWNvbnRyb2wtcmVnZXgiOjIsIm5vLWRlYnVnZ2VyIjoyLCJuby1kZWxldGUtdmFyIjoyLCJuby1kdXBlLWFyZ3MiOjIsIm5vLWR1cGUtY2xhc3MtbWVtYmVycyI6Miwibm8tZHVwZS1rZXlzIjoyLCJuby1kdXBsaWNhdGUtY2FzZSI6Miwibm8tZW1wdHktY2hhcmFjdGVyLWNsYXNzIjoyLCJuby1lbXB0eS1wYXR0ZXJuIjoyLCJuby1lbXB0eSI6Miwibm8tZXgtYXNzaWduIjoyLCJuby1leHRyYS1ib29sZWFuLWNhc3QiOjIsIm5vLWV4dHJhLXNlbWkiOjIsIm5vLWZhbGx0aHJvdWdoIjoyLCJuby1mdW5jLWFzc2lnbiI6Miwibm8tZ2xvYmFsLWFzc2lnbiI6Miwibm8taW5uZXItZGVjbGFyYXRpb25zIjoyLCJuby1pbnZhbGlkLXJlZ2V4cCI6Miwibm8taXJyZWd1bGFyLXdoaXRlc3BhY2UiOjIsIm5vLW1peGVkLXNwYWNlcy1hbmQtdGFicyI6Miwibm8tbmV3LXN5bWJvbCI6Miwibm8tb2JqLWNhbGxzIjoyLCJuby1vY3RhbCI6Miwibm8tcmVkZWNsYXJlIjoyLCJuby1yZWdleC1zcGFjZXMiOjIsIm5vLXNlbGYtYXNzaWduIjoyLCJuby1zcGFyc2UtYXJyYXlzIjoyLCJuby10aGlzLWJlZm9yZS1zdXBlciI6Miwibm8tdW5kZWYiOjIsIm5vLXVuZXhwZWN0ZWQtbXVsdGlsaW5lIjoyLCJuby11bnJlYWNoYWJsZSI6Miwibm8tdW5zYWZlLWZpbmFsbHkiOjIsIm5vLXVuc2FmZS1uZWdhdGlvbiI6Miwibm8tdW51c2VkLWxhYmVscyI6Miwibm8tdW51c2VkLXZhcnMiOjIsIm5vLXVzZWxlc3MtZXNjYXBlIjoyLCJyZXF1aXJlLXlpZWxkIjoyLCJ1c2UtaXNuYW4iOjIsInZhbGlkLXR5cGVvZiI6Mn0sImVudiI6e319fQ==\" rel=\"nofollow noreferrer\">the demo page on eslint.org</a>. It showed this warning:</p>\n<blockquote>\n<p>'event' is defined but never used.</p>\n</blockquote>\n<p>For this line:</p>\n<blockquote>\n<pre><code>$(".sub-menu .menu-item, .module-item").click(function(event) {\n</code></pre>\n</blockquote>\n<p>While <code>event</code> could be used if necessary, it isn't needed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-02T01:17:22.197",
"Id": "214579",
"ParentId": "40470",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-01-30T16:03:36.817",
"Id": "40470",
"Score": "3",
"Tags": [
"javascript",
"php",
"jquery",
"html",
"codeigniter"
],
"Title": "Correct MVC in CodeIgniter"
}
|
40470
|
<p>I'm a novice programmer learning Objective-C in my spare time. I would greatly appreciate any help or advice with my code. I want to follow best practices whenever possible. I know that I am missing some foundational stuff with my code, so please point that out where you see it. Things like when to make variables instance variables versus properties, when to define things like (strong) for properties, when and where to instantiate variables, etc.</p>
<p>I'm building a simple game to practice and to learn Sprite-Kit. I've been working on it for a few days, and it does function mostly as I want it to. The game model is pure objective-c and generates a map of tiles as well as handles inserting tiles into the map. This is done with an NSDictionary with the keys being the coordinates of the tiles. That code is not included below, but I can post it if need be. My SKScene renders those tiles based on their type, and tells the model to insert new tiles where the screen is tapped. It also manages the touch controls.</p>
<p>The main problems are that the panning around the world and the pinching to zoom move much faster than I would like. I can't figure out how to slow them down, and I'm wondering if I am doing something wrong. </p>
<p>Please let me know if you need to see more code to review it. And please don't hesitate to point out any flaws that you see, both in style and in substance.</p>
<p>Here is the header:</p>
<pre><code>// TPGameSceneSO.h
#import <SpriteKit/SpriteKit.h>
#import "TPGame.h"
//set up for 60 frames per second
#define kMinTimeInterval (1.0f / 60.0f)
//seems to run better with the delegate enabled
@interface TPGameSceneSO : SKScene <UIGestureRecognizerDelegate>
@property TPGame *theGame;
@property SKSpriteNode *tileMapNode;
@property SKSpriteNode *movableSprites;
@property UIPinchGestureRecognizer *pinchRecognizer;
@property UIPanGestureRecognizer *panRecognizer;
@end
</code></pre>
<p>And now the implementation:</p>
<pre><code>enter code here
// TPGameSceneSO.m
#import "TPGameSceneSO.h"
#define TILE_SIZE CGSizeMake(128,128)
#define TILE_DIMENSION 128
static NSString * const kMovableNodeName = @"movable";
@interface TPGameSceneSO ()
@property (nonatomic) NSTimeInterval lastUpdateTimeInterval;
@end
@implementation TPGameSceneSO {
CGFloat _tempScale;
CGPoint *_tempPosition;
BOOL _contentCreated;
NSArray *_tilesFromAtlas;
BOOL _tileHasBeenInserted;
SKSpriteNode *_selectedNode;
SKNode *_world;
CGPoint _tempWorldLocation;
BOOL _worldMovedForUpdate;
CGPoint _activeTilePos;
BOOL _activeTilePosChanged;
}
#pragma mark - Utility Methods
////////////The following are utility methods////////////////////////////////
//first two are for randomness
//not sure if i need it in every class that uses it
static inline CGFloat skRandf() {
return rand() / (CGFloat) RAND_MAX;
}
static inline CGFloat skRand(CGFloat low, CGFloat high) {
return skRandf() * (high - low) + low;
}
float degToRad(float degree) {
return degree / 180.0f * M_PI;
}
#pragma mark - Initialization
/////////////////Initialization methods//////////////////////////
-(void)didMoveToView:(SKView *)view {
if(!_contentCreated) {
[self createSceneContents];
_contentCreated = YES;
}
}
-(void)createSceneContents{
self.scaleMode = SKSceneScaleModeAspectFit;
//Set up the gesture recognizers
_panRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePanFrom:)];
[[self view] addGestureRecognizer:_panRecognizer];
_pinchRecognizer = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(handlePinch:)];
[[self view] addGestureRecognizer:_pinchRecognizer];
//Set up the texture atlas
[self buildTileTextureAtlas];
//Set up the world, used for the camera
_world = [[SKNode alloc] init];
[_world setName:@"world"];
[self addChild:_world];
//Initialize the game object
self.theGame = [[TPGame alloc]init];
//Build the tile map
[self.theGame startGame];
//Set up the tile map used for rendering and render the initial map
//self.tileMapNode = [[[SKSpriteNode alloc]init] initWithColor:[SKColor whiteColor] size:self.frame.size];
self.tileMapNode = [[[SKSpriteNode alloc]init] initWithColor:[SKColor whiteColor] size:CGSizeMake(1024,1024)];
[self.tileMapNode setName:@"background"];
self.tileMapNode = [self renderTileMap:self.tileMapNode];
[_world addChild:self.tileMapNode];
//Set up the movable sprites
_movableSprites = [[SKSpriteNode alloc] init];
[self setUpMovableSprites];
[_movableSprites setName:@"sprites"];
[_world addChild:_movableSprites];
}
-(void) setUpMovableSprites {
NSArray *imageNames = @[@"tile1", @"tile2", @"tile3", @"tile4"];
for (int i = 0; i < [imageNames count]; i++) {
SKTexture *temp = _tilesFromAtlas[i];
SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithTexture:temp];
sprite.size = CGSizeMake(TILE_DIMENSION, TILE_DIMENSION);
[sprite setName:kMovableNodeName];
float offsetFraction = ((float)(i + 1)) / ([imageNames count] + 1);
[sprite setPosition:CGPointMake(self.size.width * offsetFraction, self.size.height - self.size.height/3)];
[_movableSprites addChild:sprite];
}
}
-(void)buildTileTextureAtlas {
int numFormats = 3;
NSMutableArray *tileImages = [NSMutableArray array];
SKTextureAtlas *tileAtlas = [SKTextureAtlas atlasNamed:@"tileimages"];
int numImages = tileAtlas.textureNames.count;
for (int i = 1; i <= numImages/numFormats; i++) {
NSString *textureName = [NSString stringWithFormat:@"tile%d", i];
SKTexture *temp = [tileAtlas textureNamed:textureName];
[tileImages addObject:temp];
}
_tilesFromAtlas = tileImages;
}
#pragma mark - Update loop
/////////////Here are the updaters/////////////////////
- (void)update:(NSTimeInterval)currentTime {
// Handle time delta.
// If we drop below 60fps, we still want everything to move the same distance.
CFTimeInterval timeSinceLast = currentTime - self.lastUpdateTimeInterval;
self.lastUpdateTimeInterval = currentTime;
if (timeSinceLast > 1) { // more than a second since last update
timeSinceLast = kMinTimeInterval;
self.lastUpdateTimeInterval = currentTime;
//doing this here seems to slow down the pan and zoom rate
_worldMovedForUpdate = YES;
}
[self updateWithTimeSinceLastUpdate:timeSinceLast];
}
- (void)updateWithTimeSinceLastUpdate:(NSTimeInterval)timeSinceLast {
//will build tiles slowly and randomly out from the center
//[self insertTileInRandomPlace];
if (_worldMovedForUpdate) {
[self moveWorldView];
[self clearActiveTilePosChanged];
}
if (_activeTilePosChanged){
[self addTile];
}
if (_tileHasBeenInserted == YES){
[_movableSprites removeFromParent];
[self.tileMapNode removeFromParent];
[self.tileMapNode removeAllChildren];
self.tileMapNode = [self renderTileMap:self.tileMapNode];
[_world addChild:self.tileMapNode];
[_world addChild:_movableSprites];
}
}
#pragma mark - Camera Movement
///////////////Methods for moving the world (camera)/////////////////////
-(void) moveWorldView {
_world.position = _tempWorldLocation;
[self clearWorldMoved];
}
- (void)clearWorldMoved {
_worldMovedForUpdate = NO;
}
#pragma mark - Rendering Methods
/////////////////Rendering methods//////////////////
-(SKSpriteNode *) renderTileMap: (SKSpriteNode *)tileMapForRender {
for (id key in self.theGame.gameTileMap.tileMapDict) {
TPTile *tempTile = [self.theGame.gameTileMap.tileMapDict objectForKey:key];
int tileXPos = tempTile.position.x*TILE_DIMENSION;
int tileYPos = tempTile.position.y*TILE_DIMENSION;
if (tempTile.revealed == YES) {
SKSpriteNode *tile = [self renderTile:tempTile.terrainType];
tile.position = CGPointMake(tileXPos,tileYPos);
[tileMapForRender addChild:tile];
[tile setName:@"tile"];
}
}
_tileHasBeenInserted = NO;
return tileMapForRender;
}
-(SKSpriteNode *)renderTile: (int)tileType {
switch (tileType) {
case 0:
{
SKSpriteNode *renderedTile = [SKSpriteNode spriteNodeWithColor: [SKColor blackColor] size:TILE_SIZE];
return renderedTile;
}
case 1:
{
SKTexture *temp = _tilesFromAtlas[0];
SKSpriteNode *renderedTile = [SKSpriteNode spriteNodeWithTexture:temp size:TILE_SIZE];
return renderedTile;
}
case 2:
{
SKTexture *temp = _tilesFromAtlas[1];
SKSpriteNode *renderedTile = [SKSpriteNode spriteNodeWithTexture:temp size:TILE_SIZE];
return renderedTile;
}
case 3:
{
SKTexture *temp = _tilesFromAtlas[2];
SKSpriteNode *renderedTile = [SKSpriteNode spriteNodeWithTexture:temp size:TILE_SIZE];
return renderedTile;
}
case 4:
{
SKTexture *temp = _tilesFromAtlas[3];
SKSpriteNode *renderedTile = [SKSpriteNode spriteNodeWithTexture:temp size:TILE_SIZE];
return renderedTile;
}
case 5:
{
SKTexture *temp = _tilesFromAtlas[4];
SKSpriteNode *renderedTile = [SKSpriteNode spriteNodeWithTexture:temp size:TILE_SIZE];
return renderedTile;
}
case 6:
{
SKTexture *temp = _tilesFromAtlas[5];
SKSpriteNode *renderedTile = [SKSpriteNode spriteNodeWithTexture:temp size:TILE_SIZE];
return renderedTile;
}
default:
{
SKSpriteNode *renderedTile = [SKSpriteNode spriteNodeWithColor: [SKColor grayColor] size:TILE_SIZE];
return renderedTile;
}
}
}
#pragma mark - Interaction with other classes
//////////////Methods for inserting tiles into the model///////////////////
-(void) addTile {
_tileHasBeenInserted = YES;
//have to round these here before inserting them because just doing an int will drop the decimal
CGFloat tileFloatX = _activeTilePos.x/TILE_DIMENSION;
CGFloat tileFloatY = _activeTilePos.y/TILE_DIMENSION;
int tilePosX = roundf(tileFloatX);
int tilePosY = roundf(tileFloatY);
CGPoint pointForInsertion = CGPointMake(tilePosX, tilePosY);
[self.theGame.gameTileMap insertTileToTheMap:pointForInsertion];
[self clearActiveTilePosChanged];
}
-(void) updateActiveTilePos:(CGPoint)location {
_activeTilePos = location;
_activeTilePosChanged = YES;
}
-(void)clearActiveTilePosChanged {
_activeTilePosChanged = NO;
}
-(void) insertTileInRandomPlace {
CGPoint tempPosition = CGPointMake(skRand(-5000, 5000), skRand(-5000, 5000));
_activeTilePos = tempPosition;
_activeTilePosChanged = YES;
}
#pragma mark - Touch controls
///////////////This is the touch engine///////////////////////////////
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
for (UITouch *touch in touches) {
UITouch *touch = [touches anyObject];
if(touch.tapCount == 1) {
CGPoint positionInScene = [touch locationInNode:self];
[self selectNodeForTouch:positionInScene];
}
}
}
-(void) handlePanFrom:(UIGestureRecognizer *)recognizer {
if (recognizer.state == UIGestureRecognizerStateChanged) {
if (![[_selectedNode name] isEqualToString:kMovableNodeName]) {
CGPoint translation = [_panRecognizer translationInView:recognizer.view];
translation = CGPointMake(translation.x, -translation.y);
[self panForTranslation:translation];
} else if ([[_selectedNode name] isEqualToString:kMovableNodeName]) {
//this is the code that moves the sprites around
CGPoint translation = [_panRecognizer translationInView:recognizer.view];
translation = CGPointMake(translation.x, -translation.y);
CGPoint pos = [_selectedNode position];
CGPoint newPos = CGPointMake(pos.x + translation.x, pos.y + translation.y);
SKAction *moveTo = [SKAction moveTo:newPos duration:0.2];
//[moveTo setTimingMode:SKActionTimingEaseOut];
[_selectedNode runAction:moveTo];
}
}
}
-(void)panForTranslation:(CGPoint)translation {
CGPoint position = _world.position;
CGPoint newPos = CGPointMake(position.x + translation.x, position.y + translation.y);
//manual control of the world position (not spritekit movement)
_tempWorldLocation = newPos;
_worldMovedForUpdate = YES;
//this would use spritekit to move the world instead of doing it in the update method
//[_world removeAllActions];
//SKAction *moveTo = [SKAction moveTo:newPos duration:0.1];
//[moveTo setTimingMode:SKActionTimingEaseOut];
//[_world runAction:moveTo];
}
-(void) handlePinch:(UIPinchGestureRecognizer *)sender {
if (sender.state == UIGestureRecognizerStateBegan) {
_tempScale = [sender scale];
}
if (sender.state == UIGestureRecognizerStateChanged) {
//for some reason adding .1 slows the rate of movement
//probably because most of the scale values being outputted are between -2 and 2
CGFloat zoomOutAmount = (_tempScale / [sender scale]) + .1;
CGFloat zoomInAmount = ([sender scale] / _tempScale) + .1;
if([sender scale] < _tempScale) {
self.size = CGSizeMake(self.size.width*zoomInAmount, self.size.height*zoomInAmount);
} else if ([sender scale] > _tempScale) {
self.size = CGSizeMake(self.size.width/zoomOutAmount, self.size.height/zoomOutAmount);
}
_tempWorldLocation = CGPointMake(0+self.frame.size.width/2, 0+self.frame.size.height/2);
_worldMovedForUpdate = YES;
}
}
-(void)selectNodeForTouch:(CGPoint)touchLocation {
SKSpriteNode *touchedNode = (SKSpriteNode *)[self nodeAtPoint:touchLocation];
//this inserts the tile at the location in world node
CGPoint locationInWorld = [self.scene convertPoint:touchLocation toNode:_world];
[self updateActiveTilePos:locationInWorld];
//this is code for selecting the sprites
if(![_selectedNode isEqual:touchedNode]) {
[_selectedNode removeAllActions];
[_selectedNode runAction:[SKAction rotateToAngle:0.0f duration:0.1]];
_selectedNode = touchedNode;
if([[touchedNode name] isEqualToString:kMovableNodeName]) {
SKAction *sequence = [SKAction sequence:@[[SKAction rotateByAngle:degToRad(-4.0f) duration:0.1],
[SKAction rotateByAngle:0.0 duration: 0.1],
[SKAction rotateByAngle:degToRad(4.0f) duration:0.1]]];
[_selectedNode runAction: [SKAction repeatActionForever:sequence]];
}
}
}
@end
</code></pre>
|
[] |
[
{
"body": "<p>I must say that I'm not an expert in Objective-C. I have used it though so I will review what I can and hope that others will fill in for the rest.</p>\n\n<p>First of all, to address your questions about variables and properties. Here's how I think about it: </p>\n\n<ul>\n<li>If you need a variable only in one method make it a local variable inside that method.</li>\n<li>If you need a variable within multiple methods in the same class, make it an instance variable.</li>\n<li>If you need a variable in many different classes, make it a property. </li>\n</ul>\n\n<p>While you are doing this, try to remember to <a href=\"http://pragprog.com/articles/tell-dont-ask\">Tell, don't ask</a>. What this means, simplified, is that you shouldn't do something like this: <code>this.getSomeObject().getOtherObject().doSomething();</code> (sorry for the Java-syntax there, I hope you understand it). I think your current code handles this quite good, just remember to keep it that way :)</p>\n\n<p>It is also important that you understand how Objective-C deals with, and how you should deal with, <a href=\"http://rypress.com/tutorials/objective-c/memory-management.html\">memory management</a>. (Objective-C handles this a bit differently from other languages that I am more used to)</p>\n\n<p>The utility methods that you are mentioning, if you are copying those methods to each class that is using them, then you are doing it wrong. Instead put them in one file and use <code>#include</code> for that file in the other files where you are going to need it.</p>\n\n<p>Your indentation of the code is mostly good, but in the end of the <code>renderTileMap</code> method, things seem to go wrong. This seems to continue to the entire <code>renderTile</code> method which is indented one step too much.</p>\n\n<p>Speaking of the renderTile method, it can be improved quite significantly since there's a strong pattern for cases 1 to 6. It's been a while since I wrote Objective-C code but I think this should work, and if not I hope you get the idea of how it should work:</p>\n\n<pre><code>-(SKSpriteNode *)renderTile: (int)tileType {\n if (tileType == 0) {\n SKSpriteNode *renderedTile = [SKSpriteNode spriteNodeWithColor: [SKColor blackColor] size:TILE_SIZE];\n return renderedTile;\n }\n else if (tileType >= 1 && tileType <= 6) {\n SKTexture *temp = _tilesFromAtlas[tileType - 1];\n SKSpriteNode *renderedTile = [SKSpriteNode spriteNodeWithTexture:temp size:TILE_SIZE];\n return renderedTile;\n }\n else {\n SKSpriteNode *renderedTile = [SKSpriteNode spriteNodeWithColor: [SKColor grayColor] size:TILE_SIZE];\n return renderedTile;\n }\n}\n</code></pre>\n\n<p>Generally I must say that your code looks very good. Very well done for being a beginner!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T05:08:08.703",
"Id": "70704",
"Score": "0",
"body": "`#import`, not `#include`. You can `#include`, but you should definitely be `#import`ing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T17:42:56.963",
"Id": "71140",
"Score": "0",
"body": "Thanks for the compliment and for replying on this. I am having a problem with #imports and #includes. I made a header called maths.h and put the randomization functions in there. Then I tried to do #import \"maths.h\" into multiple other files, but it crashes if I import it into more than one. Not sure what I'm doing wrong?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T00:11:19.110",
"Id": "77305",
"Score": "0",
"body": "@bazola In Xcode for Objective-C code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T16:01:17.770",
"Id": "77361",
"Score": "0",
"body": "@nhgrif In Xcode"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T21:35:27.710",
"Id": "77463",
"Score": "0",
"body": "@bazola Can you put your project on github so I can take a look at see if I get the errors?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T16:42:46.990",
"Id": "79781",
"Score": "0",
"body": "Marking this one as the answer since I'm using the pattern suggested in my code. Thanks for the help!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T18:30:49.383",
"Id": "40570",
"ParentId": "40471",
"Score": "7"
}
},
{
"body": "<p><strong>Instance Variables and Properties</strong></p>\n\n<p>Understanding exactly what a <code>@property</code> is is absolutely crucial to being a good Objective-C programmer. Here's my crash course.</p>\n\n<p>An instance variable is just that. An instance variable. It's pretty straight forward. It's just a variable in that can be accessed by all the methods in your class. And if it's a public variable, it can be accessed outside the class as well.</p>\n\n<p>A <code>@property</code>, however, is different. A <code>@property</code> doesn't even necessarily have an instance variable behind it. It does by default, but a <code>@property</code> is much more than just an instance variable. Moreover, you can have public AND private <code>@property</code> variables. Simon's comments on properties versus variables are inaccurate.</p>\n\n<p>Consider</p>\n\n<pre><code>@interface Person : NSObject\n@property (nonatomic, strong) NSString *name;\n@end\n</code></pre>\n\n<p>What have we actually done? As it turns out, this is the equivalent of doing this:</p>\n\n<pre><code>@interface Person : NSObject {\n @private\n NSString *name;\n}\n- (void)setName:(NSString*)aName;\n- (NSString*)name;\n@end\n\n@implementation Person\n- (void)setName:(NSString*)aName {\n name = aName;\n}\n- (NSString*)name {\n return name;\n}\n</code></pre>\n\n<p>So by default, a <code>@property</code> creates three things: an instance variable, a setter, and a getter.</p>\n\n<p>But consider this case:</p>\n\n<pre><code>@interface Person : NSObject\n@property NSString *firstName;\n@property NSString *lastName;\n@property (readonly) NSString *fullName;\n@end\n\n@implementation Person\n- (NSString*)fullName {\n return [NSString stringWithFormat:\"%@ %@\", self.firstName, self.lastName];\n}\n@end\n</code></pre>\n\n<p>By declaring <code>fullName</code> as a <code>readonly</code> property, we've prevented the creation of a setter method. But in the <code>@implementation</code>, what we've also done is overridden the getter method. But something very important happened in this method. We made no reference to <code>_fullName</code>, which would be the instance variable that a <code>@property</code> called <code>fullName</code> would create. As such, we've also prevented the creation of an instance variable.</p>\n\n<p>So, the other thing left is that a <code>@property</code> allows you to use the dot-syntax to access the setters and getters (though you don't have to use it).</p>\n\n<p>Now then, when should you use an <code>@property</code> and when should you use an instance variable?</p>\n\n<p>Well, it really doesn't matter too terribly much. If you need a variable to be visible outside the class, you can still use an instance variable and still give it a getter and setter. The only difference between writing a getter, setter, creating an instance variable and just using a <code>@property</code>? Dot-syntax, that's it.</p>\n\n<p>And the cool thing is, you don't have to limit yourself to the traditional idea of a setter, getter, and instance variable. You can create dot-syntax methods any time you need a method that takes no arguments and returns a value.</p>\n\n<p>Please let me know if you would like some more information about properties/instance variables.</p>\n\n<hr>\n\n<p>Simon's answer does make a good recommendation about condensing your <code>renderTile:</code> method. Although, I'd do it in a different way. Personally, I like <code>switch</code> statements. You can keep the <code>switch</code> and still condense the code:</p>\n\n<pre><code>-(SKSpriteNode *)renderTile: (int)tileType {\n switch(tileType) {\n case 1:\n // do stuff\n break;\n case 2:\n case 3:\n case 4:\n case 5:\n case 6:\n // do stuff\n break;\n default:\n // do stuff\n break;\n }\n}\n</code></pre>\n\n<p>BUT... if you're doing this, let's use an <code>enum</code>, shall we? </p>\n\n<pre><code>typedef NS_ENUM(unsigned short, MyTileTypeEnum) {\n BlackTile = 1,\n TileTextureA = 2,\n TileTextureB = 3,\n TileTextureC = 4,\n TileTextureD = 5,\n TileTextureE = 6\n};\n</code></pre>\n\n<p>So now our switch can look like this:</p>\n\n<pre><code>switch(tileType) {\n case BlackTile:\n // do stuff\n break;\n// ... etc\n</code></pre>\n\n<p>Of course, the names should be chosen for something that's appropriately descriptive in your case. The point here is we've made our code more self-documenting.</p>\n\n<p>It's important for our code to be easy to read. Code is written for humans and no one likes writing comments, so let's make our code more readable by using good variable names as well as using enums.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T17:44:07.887",
"Id": "71141",
"Score": "0",
"body": "Extremely helpful! Definitely points me in the right direction as far as understanding the differences. Thank you!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-04T09:00:05.917",
"Id": "106091",
"Score": "0",
"body": "As in all things in Objective-C, it's better to prefix your enums and enum members to avoid name collisions with other variables out there."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T05:43:32.987",
"Id": "41206",
"ParentId": "40471",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "40570",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T16:04:49.060",
"Id": "40471",
"Score": "10",
"Tags": [
"beginner",
"game",
"objective-c",
"ios"
],
"Title": "Game with tile map - Sprite-Kit"
}
|
40471
|
<p><em>Note: I have posted a <a href="https://codereview.stackexchange.com/questions/127552/portable-periodic-one-shot-timer-thread-improvements?lq=1">follow-up question</a> for a significantly updated version of this code.</em></p>
<p>I have implemented a class that provides portable one-shot or periodic timers.</p>
<p>The API provides a way to schedule one or more timer callbacks to fire some number of milliseconds in the future, and optionally fire again every so many milliseconds.</p>
<p>The API returns an ID which can be used later to see if the timer still exists, or destroy it.</p>
<p>The implementation assigns increasing IDs to the timers, starting at one. The timer IDs use a 64-bit unsigned integer, to avoid dealing with wraparound.</p>
<p>The implementation stores the context of each timer <code>Instance</code> in an <code>unordered_map</code> called <code>active</code>, keyed by ID. Each instance has a <code>next</code> member, which is a <code>time_point</code> that indicates when it needs to fire next.</p>
<p>The implementation uses a <code>multiset</code> called <code>queue</code> to sort the timers by the <code>next</code> member, using a functor.</p>
<p>The queue multiset stores <code>reference_wrapper</code> objects that refer directly to the <code>Instance</code> objects. This allows the queue's comparator to refer directly to the instances.</p>
<p>A worker thread is created to service the timer queue. A <code>mutex</code> and <code>condition_variable</code> are used for synchronization. The condition variable is used to notify the worker thread when a timer is created or destroyed, and to request worker thread shutdown.</p>
<p>The worker thread uses <code>wait</code> to wait for notification when there are no timers, and uses <code>wait_for</code> to wait until earliest notification needs to fire, or until awakened.</p>
<p>The lock is released during the callback when a timer fires.</p>
<p>The destructor sets the <code>done</code> flag to true, notifies the condition variable, releases the lock, then joins with the worker to wait for it to exit.</p>
<p><strong>EDIT</strong>: I realized that there was a race condition that occurs if a timer is destroyed while its callback is in progress. I solved that by having a <code>running</code> flag on each instance. The worker thread checks it when a callback returns to see if that <code>Instance</code> needs to be destroyed. This avoids dereferencing an <code>Instance</code> that was destroyed while the lock was not held during the callback. The <code>destroy</code> method was also updated to see if the callback is running, and set <code>running</code> to false if so, to indicate to the worker that it needs to be destroyed. If the callback for that timer is not running, <code>destroy</code> destroys the <code>Instance</code> itself.</p>
<p><strong>timer.h</strong></p>
<pre><code>#ifndef TIMER_H
#define TIMER_H
#include <thread>
#include <mutex>
#include <condition_variable>
#include <algorithm>
#include <functional>
#include <chrono>
#include <unordered_map>
#include <set>
#include <cstdint>
class Timer
{
public:
typedef uint64_t timer_id;
typedef std::function<void()> handler_type;
private:
std::mutex sync;
typedef std::unique_lock<std::mutex> ScopedLock;
std::condition_variable wakeUp;
private:
typedef std::chrono::steady_clock Clock;
typedef std::chrono::time_point<Clock> Timestamp;
typedef std::chrono::milliseconds Duration;
struct Instance
{
Instance(timer_id id = 0)
: id(id)
, running(false)
{
}
template<typename Tfunction>
Instance(timer_id id, Timestamp next, Duration period, Tfunction&& handler) noexcept
: id(id)
, next(next)
, period(period)
, handler(std::forward<Tfunction>(handler))
, running(false)
{
}
Instance(Instance const& r) = delete;
Instance(Instance&& r) noexcept
: id(r.id)
, next(r.next)
, period(r.period)
, handler(std::move(r.handler))
, running(r.running)
{
}
Instance& operator=(Instance const& r) = delete;
Instance& operator=(Instance&& r)
{
if (this != &r)
{
id = r.id;
next = r.next;
period = r.period;
handler = std::move(r.handler);
running = r.running;
}
return *this;
}
timer_id id;
Timestamp next;
Duration period;
handler_type handler;
bool running;
};
typedef std::unordered_map<timer_id, Instance> InstanceMap;
timer_id nextId;
InstanceMap active;
// Comparison functor to sort the timer "queue" by Instance::next
struct NextActiveComparator
{
bool operator()(const Instance &a, const Instance &b) const
{
return a.next < b.next;
}
};
NextActiveComparator comparator;
// Queue is a set of references to Instance objects, sorted by next
typedef std::reference_wrapper<Instance> QueueValue;
typedef std::multiset<QueueValue, NextActiveComparator> Queue;
Queue queue;
// Thread and exit flag
std::thread worker;
bool done;
void threadStart();
public:
Timer();
~Timer();
timer_id create(uint64_t when, uint64_t period, const handler_type& handler);
timer_id create(uint64_t when, uint64_t period, handler_type&& handler);
private:
timer_id createImpl(Instance&& item);
public:
bool destroy(timer_id id);
bool exists(timer_id id);
};
#endif // TIMER_H
</code></pre>
<p><strong>timer.cpp</strong></p>
<pre><code>#include "timer.h"
void Timer::threadStart()
{
ScopedLock lock(sync);
while (!done)
{
if (queue.empty())
{
// Wait (forever) for work
wakeUp.wait(lock);
}
else
{
auto firstInstance = queue.begin();
Instance& instance = *firstInstance;
auto now = Clock::now();
if (now >= instance.next)
{
queue.erase(firstInstance);
// Mark it as running to handle racing destroy
instance.running = true;
// Call the handler
lock.unlock();
instance.handler();
lock.lock();
if (done)
{
break;
}
else if (!instance.running)
{
// Running was set to false, destroy was called
// for this Instance while the callback was in progress
// (this thread was not holding the lock during the callback)
active.erase(instance.id);
}
else
{
instance.running = false;
// If it is periodic, schedule a new one
if (instance.period.count() > 0)
{
instance.next = instance.next + instance.period;
queue.insert(instance);
} else {
active.erase(instance.id);
}
}
} else {
// Wait until the timer is ready or a timer creation notifies
wakeUp.wait_until(lock, instance.next);
}
}
}
}
Timer::Timer()
: nextId(1)
, queue(comparator)
, done(false)
{
ScopedLock lock(sync);
worker = std::thread(std::bind(&Timer::threadStart, this));
}
Timer::~Timer()
{
ScopedLock lock(sync);
done = true;
wakeUp.notify_all();
lock.unlock();
worker.join();
}
Timer::timer_id Timer::create(uint64_t msFromNow, uint64_t msPeriod,
const std::function<void()> &handler)
{
return createImpl(Instance(0,
Clock::now() + Duration(msFromNow), Duration(msPeriod),
handler));
}
Timer::timer_id Timer::create(uint64_t msFromNow, uint64_t msPeriod,
std::function<void()>&& handler)
{
return createImpl(Instance(0,
Clock::now() + Duration(msFromNow), Duration(msPeriod),
std::move(handler)));
}
Timer::timer_id Timer::createImpl(Instance&& item)
{
ScopedLock lock(sync);
item.id = nextId++;
auto iter = active.emplace(item.id, std::move(item));
queue.insert(iter.first->second);
wakeUp.notify_all();
return item.id;
}
bool Timer::destroy(timer_id id)
{
ScopedLock lock(sync);
auto i = active.find(id);
if (i == active.end())
return false;
else if (i->second.running)
{
// A callback is in progress for this Instance,
// so flag it for deletion in the worker
i->second.running = false;
}
else
{
queue.erase(std::ref(i->second));
active.erase(i);
}
wakeUp.notify_all();
return true;
}
bool Timer::exists(timer_id id)
{
ScopedLock lock(sync);
return active.find(id) != active.end();
}
</code></pre>
<p><strong>Example:</strong></p>
<pre><code>#include "timer.h"
int main()
{
Timer t;
// Timer fires once, one second from now
t.create(1000, 0,
[]() {
std::cout << "Non-periodic timer fired" << std::endl;
});
// Timer fires every second, starting five seconds from now
t.create(5000, 1000,
[]() {
std::cout << "Timer fired 0" << std::endl;
});
// Timer fires every second, starting now
t.create(0, 1000,
[]() {
std::cout << "Timer fired 1" << std::endl;
});
// Timer fires every 100ms, starting now
t.create(0, 100,
[]() {
std::cout << "Timer fired 2" << std::endl;
});
}
</code></pre>
<p>The third parameter is a std::function, so it could call a method on some instance of an object, like this:</p>
<pre><code>class Foo
{
public:
void bar() { std::cout << "Foo::bar called" << std::endl; }
};
int something()
{
Foo example;
// Assume "t" is a Timer
auto tid = t.create(0, 100, std::bind(&Foo::bar, &example));
// ... do stuff ...
</code></pre>
<p>The <code>exists</code> method is intended for scenarios where you desperately need to wait for a timer to go away before something goes out of scope. Definitely not pretty but I don't expect this scenario to occur a lot in my intended use cases:</p>
<pre><code> // Not pretty, but better than nothing:
t.destroy(tid);
while (t.exists(tid))
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T21:27:18.643",
"Id": "68171",
"Score": "0",
"body": "Apologies for rolling back your last edit, but it's this site's policy to not edit the original code in a way that would invalidate the previous/existing answers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T21:37:25.270",
"Id": "68172",
"Score": "0",
"body": "@ChrisW No problem. What should I do if/when I implement suggested changes? I couldn't find anything specific in the Help Center."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T22:08:01.340",
"Id": "68184",
"Score": "0",
"body": "You don't necessarily need to edit your improvements into the question: readers of the site will expect to see the code that was reviewed, not necessarily the post-review version of the code. If you want to present the finished post-review version, that's nice of you too (readers can then see how much you were able to improve it, how much difference the reviews made). If you want to do that, then the way is to append the changed code to the end of your question, perhaps separated with a horizontal line ( using `---` in the markdown), ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T22:10:09.020",
"Id": "68187",
"Score": "0",
"body": "@ChrisW Will do. Thanks for answering what is probably a common question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T22:11:37.277",
"Id": "68190",
"Score": "0",
"body": "... for example as on [this question](http://codereview.stackexchange.com/q/39579/34757). If you do that (edit your question) you shouldn't generally expect to see new reviews of your edits: people often review new questions and don't notice edits to existing questions. If you want a review of edits which you make after the original question has been answered, you may post that as a new question: see [How to deal with follow-up questions?](http://meta.codereview.stackexchange.com/a/1066/34757) for a description of how to do that."
}
] |
[
{
"body": "<p>I think I'm being confused by your type names. So each timer is actually called <code>Timer::Instance</code> and <code>Timer</code> is something else? Hmm.</p>\n\n<p>In terms of English I can certainly see why \"Timer\" as a name for the <em>whole timing system</em> might make sense, even if it's atypical in the software world.</p>\n\n<p>At the very least I'd suggest renaming <code>Timer::Instance</code> to <code>Timer::Event</code>.<br>\n<em>Or</em>, rename <code>Timer</code> to <code>TimerManager</code> or some other Javay abomination.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T16:44:32.013",
"Id": "68118",
"Score": "0",
"body": "I agree, `Timer` is too vague and implies that it is singular. `Instance` is probably too vague too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T16:47:32.570",
"Id": "68120",
"Score": "0",
"body": "Worse, \"instance\" conflicts with the C++ meaning of the term."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T19:04:11.113",
"Id": "68142",
"Score": "1",
"body": "Instance is a private implementation detail of the class, therefore harmless. Each timer is actually of type Timer, but each Timer can handle multiple timing tasks, which are each publicly identified by a timer_id."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T19:27:12.257",
"Id": "68154",
"Score": "0",
"body": "@ChrisW: It's not harmless when you have to read the code and come to understand it. Something being an internal implementation detail is not an excuse to give it a confusing and inappropriate name."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T21:54:19.827",
"Id": "68175",
"Score": "0",
"body": "I implemented the rename to `TimerManager`."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T16:21:09.350",
"Id": "40475",
"ParentId": "40473",
"Score": "5"
}
},
{
"body": "<p>I like your syntax, for example C++11 style such as <code>std::reference_wrapper</code>.</p>\n\n<p>I like your algorithm, for example:</p>\n\n<ul>\n<li>Sort the queue so that you only need to check the first one</li>\n<li>Unlock before doing the timer callback (and re-lock afterwards)</li>\n</ul>\n\n<p>Minor things about the style that made it harder to read:</p>\n\n<ul>\n<li>Two private sections in Timer, containing a mix of type definitions and field definitions</li>\n<li>Fields (instance data) defined at the top of the Timer class but at the end of the Instance class</li>\n<li>Inline code in timer.h (users of the class might find it easier if lines of code were hidden away in timer.cpp).</li>\n</ul>\n\n<p>The <code>exists</code> method is strange: what do you think users will use it for? It might return true but then have the timer go off immediately, i.e. it may return stale information.</p>\n\n<p>I don't understand the use case for <code>std::function<void()>&& handler</code> and <code>std::move(handler)</code>. It's probably cleverer than I am, maybe a comment or an example test case which uses it would help me.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T20:32:43.980",
"Id": "68160",
"Score": "1",
"body": "It works because the mutex (`sync`) is released when it is waiting for the condition variable (`wakeUp`). `wakeUp.wait` and `wakeUp.wait_until` both release the lock before waiting. That's why you have to pass the lock as an argument to them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T20:37:05.310",
"Id": "68161",
"Score": "0",
"body": "I didn't feel comfortable mixing the private and public sections to be honest. I sorted that stuff roughly by purpose: first the public types, then the synchronization stuff, then the timing stuff, then the timer instance stuff, then the thing that sorts the queue, then the queue, then the thread related stuff, then the public API. I felt it would be easier to read if the related things were close together, instead of scattered across the class declaration."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T20:47:32.720",
"Id": "68162",
"Score": "2",
"body": "@doug65536 I like to declare data at the top when I'm designing/coding the class; but for users/readers of the class, a harmless convention is to define the public API methods at the top (as you did for the Instance struct): see [suggested style for declaration order](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml?showone=Declaration_Order#Declaration_Order). Otherwise I need to read a lot of implementation details before I find the public API. I also found it confusing to see Timer data members declared both above and delow the definition of the Instance struct."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T20:57:50.200",
"Id": "68165",
"Score": "0",
"body": "I added examples. The purpose of having a const reference and rvalue reference version of create, was to enable move semantics, which could be very useful if you pass a lambda that has by-value captures of something that can't be copied, and improves efficiency when a lambda captures by value values that can be moved."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T21:03:08.330",
"Id": "68166",
"Score": "1",
"body": "I implemented your suggestion of moving the public API to the top. Now it is a public section at the top, and the rest is all private. Way better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T21:46:13.743",
"Id": "68173",
"Score": "0",
"body": "I implemented the suggestion to move the Instance method definitions into the cpp file. Cluttering the declaration with them did hurt readability."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T09:45:24.997",
"Id": "70823",
"Score": "0",
"body": "I finally realized what you meant when you asked about two versions of `create`. I got rid of that duplication and just took `handler` by value, and always `std::move` it. If the caller passes an rvalue, it is moved into the argument, if not, *they* copy it. In both cases my code moves it. Perfect."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T20:12:05.987",
"Id": "40487",
"ParentId": "40473",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "40487",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T16:11:54.940",
"Id": "40473",
"Score": "18",
"Tags": [
"c++",
"multithreading",
"c++11",
"timer"
],
"Title": "Portable periodic/one-shot timer implementation"
}
|
40473
|
<p>The <em>code challenge</em> problem must be solvable with a relatively short solution that can be posted in anyone's favorite programming language.</p>
<p>After the community <a href="http://meta.codereview.stackexchange.com/questions/1201/cr-weekend-challenge">has agreed on a problem for the code challenge</a>, entries can be posted anytime.</p>
<p>Extended discussion on this topic can be carried out in our <a href="http://chat.stackexchange.com/rooms/8595/the-2nd-monitor">chat room</a>.</p>
<p><em>Questions posted must be fully working solutions, and must include all the code.</em> For more info regarding on-topic questions, consult the <a href="http://chat.stackexchange.com/rooms/8595/the-2nd-monitor">Help Center</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T16:34:48.143",
"Id": "40476",
"Score": "0",
"Tags": null,
"Title": null
}
|
40476
|
Reviewing code is fun! Every now and then the community decides on a problem to solve; solutions are posted as questions to be peer reviewed. Use this tag to mark your question as a code-challenge entry. This tag replaces the [weekend-challenge] tag.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T16:34:48.143",
"Id": "40477",
"Score": "0",
"Tags": null,
"Title": null
}
|
40477
|
<p>I am using kendo grid's <code>onDataBound</code> event to do something. Here's my jQuery code:</p>
<pre><code>console.time('withoutnot');
jQuery(e.sender.dataSource._data).each(function (i, v) {
if (v.IsReadonly) {
e.sender.wrapper.find("tr[data-uid='" + v.uid + "'] .k-button")
.each(function (i, j) {
if (!jQuery(this).hasClass('k-grid-edit') && !jQuery(this).hasClass('k-grid-Desc')) {
jQuery(this).addClass('k-state-disabled').prop('disabled', true)
.prop('title', 'Readonly.');
}
});
}
});
console.timeEnd('withoutnot');
</code></pre>
<p><code>onDataBound</code> event gets raised once the grid has completed data-load from serverside.</p>
<p>My problem is that, because of 400 rows in the grid (without paging), it takes around <code>355ms</code> to <code>378ms</code>, which is still slower for me, because it causes visible performance lag in the grids load(readonly button effect).</p>
<p>How can I improve this code snippet even more? or is it the best I can go for? </p>
<p>NOTE: using native <code>for</code> or jQuerys <code>:not</code> (instead of those if conditions), proved disaster to me, load time scaled to <code>460ms</code> to <code>550ms</code>.</p>
<p>I am using <code>jQuery 1.7.1</code></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T22:08:55.757",
"Id": "68185",
"Score": "0",
"body": "Out of curiousity how were you writing the `:not` as I'd expect it to be even with your filter and more elegant"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T22:15:56.417",
"Id": "68191",
"Score": "0",
"body": "like this : `e.sender.wrapper.find(\"tr[data-uid='\" + v.uid + \"'] .k-button:not(.k-grid-edit,.k-grid-Desc )\")`. This would save me the need of that inner if condition.But Pseudo selectors are superbly slow"
}
] |
[
{
"body": "<p>I found out solution to my problem. so basically this is what I learnt </p>\n\n<ol>\n<li>use <a href=\"http://api.jquery.com/filter/\" rel=\"nofollow\">filter</a> to reduce the set of similar items instead of explicit if condition</li>\n<li>use cached variables i.e. <code>var $this = $(this);</code></li>\n<li>use <a href=\"http://www.w3schools.com/jquery/jquery_chaining.asp\" rel=\"nofollow\">methods chaining</a></li>\n<li><p>and if same methods are to be used multiple times, try using it like:</p>\n\n<pre><code>.prop({ disabled: true, title: 'Readonly.' });\n</code></pre>\n\n<p>instead of call <code>.prop</code> (or any other) multiple times.</p></li>\n<li><p>try to scope restrict the context of your selector as far as you can, i.e.</p>\n\n<pre><code>jQuery(\"tr[data-uid='\" + v.uid + \"'] .k-button\", e.sender.wrapper)\n</code></pre></li>\n</ol>\n\n<p>so here's my final query:</p>\n\n<pre><code>jQuery(e.sender.dataSource._data).each(function (i, v) {\n if (v.IsReadonly) {\n jQuery(\"tr[data-uid='\" + v.uid + \"'] .k-button\", e.sender.wrapper)\n .filter(function (i) {\n var $this = jQuery(this);\n return !($this.hasClass('k-grid-edit') || $this.hasClass('k-grid-Desc'));\n })\n .addClass('k-state-disabled')\n .prop({ disabled: true, title: 'Readonly.' });\n }\n});\n</code></pre>\n\n<p>and this query took <code>267ms</code> - <code>296ms</code> (for 10 iterations)</p>\n\n<p>-- I hope there can still be something even more faster like getting rid of that parent <code>.each</code> loop</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T19:54:23.237",
"Id": "40485",
"ParentId": "40480",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T17:49:58.220",
"Id": "40480",
"Score": "4",
"Tags": [
"javascript",
"jquery"
],
"Title": "How to write efficient javascript/jQuery code involving loops and string concat?"
}
|
40480
|
<p>I have a set of links with background images on this <a href="http://codepen.io/JGallardo/pen/kcdHF" rel="noreferrer">CodePen</a>.</p>
<p><img src="https://i.stack.imgur.com/Il5qa.png" alt="Result"></p>
<p>I am seeking feedback to see if I did this the most optimal way. For example, I made a sprite so that I can just load one image. And I leveraged inheritance so that I did not have to assign every containing div a class. Just used a child selector and for the individual buttons, I used <code>:nth-of-type</code> to pass the background image. </p>
<p>Tell me your thoughts if this could use improvement. </p>
<p><strong>HTML</strong></p>
<pre><code><div class="introSelect">
<div>
<a href="#"> <!-- Link Pending -->
<span>Dentist</span>
</a>
</div>
<div>
<a href="#"> <!-- Link Pending -->
<span>Patient</span>
</a>
</div>
<div>
<a href="#"> <!-- Link Pending -->
<span>Lab</span>
</a>
</div>
</div>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>.introSelect { text-align:center; }
.introSelect div {
display:inline-block;
position: relative;
text-align: center;
background: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/101702/bruxzir-user-sprites_1.png') no-repeat;
width: 90px;
height: 90px;
}
.introSelect div:nth-of-type(1) {
background-position: 0 -180px ;
}
.introSelect div:nth-of-type(2) {
background-position: -90px -180px;
}
.introSelect div:nth-of-type(3) {
background-position: -180px -180px;
}
.introSelect a {
display:block;
text-decoration: none;
}
.introSelect span {
background-color: rgba(152, 216, 242, 0.7);
color: #444;
font-weight: bold;
letter-spacing: 1px;
position: absolute; bottom: 0; left: 0; right: 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T21:57:28.353",
"Id": "68177",
"Score": "0",
"body": "Would it be possible for you to use a CSS preprocessor like LESS or SASS? E.g. the templating features of Sass would remove the need for some of the hard-coded pixel offsets."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T22:01:43.043",
"Id": "68179",
"Score": "0",
"body": "@amon, i agree with you but the product owner does not want anything other than standard CSS because of future maintainers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T22:10:37.753",
"Id": "68188",
"Score": "1",
"body": "@Malachi I read fast and appreciated what they had to say about the self-documenting class. I had this at first but had big stupid names. I liked their suggestion of `.introSelect .lab` etc. I agreed that using classes like that would reduce having to change CSS and HTML later."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T22:11:11.143",
"Id": "68189",
"Score": "1",
"body": "@JGallardo You might be able to change your client's mind with Compass (for Sass), which will generate sprite sheets *and* the corresponding CSS (see: http://compass-style.org/help/tutorials/spriting/)."
}
] |
[
{
"body": "<p>if you don't want to mess with all the headache of the HTML and CSS you could just create an Image map</p>\n\n<p>in other words you create the image </p>\n\n<p><img src=\"https://i.stack.imgur.com/YLQsX.png\" alt=\"Image you want\"></p>\n\n<p>and then you map out the separate squares using the HTML syntax and link them to the right pages. this minimizes the amount of HTML and CSS, and makes sure that your font is always displayed.</p>\n\n<p>if you want to see how to do it check with this link about <a href=\"http://www.javascriptkit.com/howto/imagemap.shtml\" rel=\"nofollow noreferrer\">Creating HTML Image Maps</a></p>\n\n<p>it would look something like</p>\n\n<pre><code><img src=\"MenuMap.gif\" usemap=\"#MenuMap\" />\n\n<map name=\"MenuMap\">\n <!-- these are only examples. use a picture editor to get the coords. -->\n <area shape=\"polygon\" coords=\"19,44,45,11,87,37,82,76,49,98\" href=\"http://www.trees.com/save.html\">\n <area shape=\"rect\" coords=\"128,132,241,179\" href=\"http://www.trees.com/furniture.html\">\n <area shape=\"circle\" coords=\"68,211,35\" href=\"http://www.trees.com/plantations.html\">\n</map>\n</code></pre>\n\n<p>the only time that I ever did this I was using Dream Weaver and it gave me the coords.</p>\n\n<p>I think this would be the perfect use for it though. if you want to make it look the way you want. </p>\n\n<p>if the person zooms in or whatever the picture stays the same and so does the map, so they would always hit the links. No Divs, no Spans, just nice and neat.</p>\n\n<hr>\n\n<h1>Updates from Research</h1>\n\n<p><a href=\"http://www.mattstow.com/experiment/responsive-image-maps/rwd-image-maps.html\" rel=\"nofollow noreferrer\">Responsive Image Maps jQuery Plugin</a> by Matt Stow\na little link that I stole from an answer, probably can't be used as OP said that they wanted to use pure CSS, not sure how this translates for jQuery though.</p>\n\n<p>also, found this out about SEO on image maps,</p>\n\n<p>sounds like there are some Google Search Bots that don't crawls these \"links\" and some that do, but the final decision that every blog that I have seen so far is that the image map is SEO Friendly and will still show up for SEO.</p>\n\n<p><a href=\"https://plus.google.com/+JoeHall/posts/8BaxxxRrfuC\" rel=\"nofollow noreferrer\">Joe Hall Post</a></p>\n\n<p><a href=\"http://moz.com/community/q/image-map-crawlability\" rel=\"nofollow noreferrer\">Image Map Crawlability</a></p>\n\n<p><a href=\"http://www.codeitpretty.com/2013/01/what-you-should-know-about-image-maps.html\" rel=\"nofollow noreferrer\">What you should know about Image Maps</a></p>\n\n<p>When it comes down to it, Google is all about content, and <code>alt</code> content is something that SEO is driven on, but you can't just spam it with keywords, because we all know that Google is savvy to this abuse and will shut you down. </p>\n\n<p>One person mentioned the <code>href</code> saying</p>\n\n<blockquote>\n <p>an href is an href is an href </p>\n</blockquote>\n\n<p>I am going to have to agree with this. I think that Google watches the traffic in and out of the site as well as the content on the page to determine what is relevant and what isn't.</p>\n\n<hr>\n\n<p><em>I Tried to make sure that all the links I looked for were the newest ones that I could find</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T21:55:40.553",
"Id": "68176",
"Score": "3",
"body": "MSPaint also gives you the coords ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T22:00:53.067",
"Id": "68178",
"Score": "2",
"body": "Ewww. This reduces searchability, thus also SEO and accessibility. Don't. Use. Maps. At least not for navigation or such."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T22:04:23.730",
"Id": "68180",
"Score": "0",
"body": "it's for a mobile site. let the desktop Site use HTML and stuff. but the mobile site you want small and fast loading @amon, that is why I say do it this way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T22:04:48.013",
"Id": "68181",
"Score": "0",
"body": "do you have proof that it reduces searchability?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T22:07:40.907",
"Id": "68183",
"Score": "2",
"body": "The site is completely responsive. And this is what it looks like in mobile. Hence why i used `<div>` 's that whose size and background image will be controlled with media queries."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T22:09:34.810",
"Id": "68186",
"Score": "0",
"body": "you should still be able to control the size of the image and the map should stay the same, but I would test it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T00:11:54.590",
"Id": "68207",
"Score": "0",
"body": "@Malachi Traditionally it reduces the crawl-able links from the page. I don't think that is correct any more. For accessibility as long as the `alt` attribute is specified you should be fine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T14:08:41.177",
"Id": "68333",
"Score": "3",
"body": "@JamesKhoury The `alt` attribute also helps search engines to find relevant pictures too doesn't it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-02T22:54:08.547",
"Id": "68644",
"Score": "1",
"body": "@Malachi I think you may be right."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-02T23:49:32.720",
"Id": "68651",
"Score": "0",
"body": "The area tags are essentially anchor tags I don't see why they wouldn't be crawlable links like anchor tags. I guess that is something that we would have to ask Google."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T21:43:30.127",
"Id": "40490",
"ParentId": "40488",
"Score": "6"
}
},
{
"body": "<p>There hasn't been a good reason to use extra elements such as spans for purposes of hiding text in the last 10 years. If you need to support very old browsers, negative indentation is the simplest method. Otherwise, there's plenty of clean, modern techniques to choose from.</p>\n\n<pre><code>.foo {\n text-indent: -100em;\n}\n</code></pre>\n\n<ul>\n<li><a href=\"http://nicolasgallagher.com/css-image-replacement-with-pseudo-elements/\">http://nicolasgallagher.com/css-image-replacement-with-pseudo-elements/</a></li>\n<li><a href=\"http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement/\">http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement/</a></li>\n</ul>\n\n<p>There's not really a good reason to use nth-child here. You'd be better off using self-documenting class names. If the order of the images need to be adjusted, then you don't have to make modifications in multiple places (markup <em>and</em> CSS).</p>\n\n<pre><code>.introSelect .dentist {\n background-position: 0 -180px ; \n}\n.introSelect .patient { \n background-position: -90px -180px; \n}\n.introSelect .lab { \n background-position: -180px -180px; \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T22:04:35.950",
"Id": "40492",
"ParentId": "40488",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "40492",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T21:24:13.060",
"Id": "40488",
"Score": "10",
"Tags": [
"html",
"css"
],
"Title": "Is my use of CSS inheritance clean enough for these sprites?"
}
|
40488
|
<p>After testing my site against GTMetrix, I get warnings on not specifying image dimensions. I am working on a WordPress site. Here is my solution:</p>
<p>My first solution was: </p>
<pre><code> // Specify image dimensions
$('img').each(function() {
var findImgWidth = $(this).width();
var findImgHeight = $(this).height();
$(this).attr('width', findImgWidth);
$(this).attr('height', findImgHeight);
});
</code></pre>
<p>Output: This method does fix the "Specify Image Dimensions" but it also removed some of my images on the website. </p>
<p>The second solution is: </p>
<pre><code>// Make sure img have been loaded
$().ready(function() {
imageSize();
});
// Assign width/height to img
function imageSize() {
// Specify image dimensions
$('img').each(function() {
var findImgWidth = $(this).width();
var findImgHeight = $(this).height();
$(this).attr('width', findImgWidth);
$(this).attr('height', findImgHeight);
});
}
</code></pre>
<p>Output: This solution seems to work. My images does not disappear, but I would like someone to help me go over the code to see if it's an efficient way to write.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T23:53:59.073",
"Id": "68203",
"Score": "5",
"body": "Greetings, the reason GTMetrix complains is that the browser can render the page faster if it knows the size of the image. Setting the size *after* the browser has rendered is not going to make your page faster, it will only make the warning go away and fractionally make your page load slower. If you research this and agree, please close this question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T00:50:21.493",
"Id": "68210",
"Score": "4",
"body": "@konijn I think you're wrong ;-). This is a good question... and should not be closed. In fact, your comment would make a worthy answer, and you should convert it to one."
}
] |
[
{
"body": "<p>The reason GTMetrix complains is that the browser can render the page faster if it knows the size of the image. </p>\n\n<p>Setting the size after the browser has rendered is not going to make your page faster, it will only make the warning go away and fractionally make your page load slower.</p>\n\n<p>This means you will have to declare the height and width of the image on the server side, or ignore the warning of GTMetrix.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T14:02:05.310",
"Id": "255697",
"Score": "0",
"body": "Basically, there's no point in setting the image dimensions using jQuery if it wasn't specified before the browser renders then. Correct?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T00:54:27.290",
"Id": "40500",
"ParentId": "40489",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "40500",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T21:37:31.090",
"Id": "40489",
"Score": "12",
"Tags": [
"javascript",
"jquery",
"image"
],
"Title": "Assigning width and height to specify image dimension using jQuery"
}
|
40489
|
<p>I've recently wrote a simple bingo game in Java to refresh myself in oop principals I have not touched in quite a while. I feel like I have accomplished this, but I would like to learn as much as possible from this exercise. Besides the oop principals, I tried to make the code very readable and reusable in case there was ever a 7x7 or a 3x3 version of bingo, and I also tried to eliminate magic numbers. Is there anything that I should do differently or improve on?</p>
<p><strong>BingoBoard.java</strong></p>
<pre><code>package bingoboard;
/**
*
* @author Dom
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
public class BingoBoard
{
private String board[][];
private final int BOARD_DIM = 5;
private final int MAX_SIZE = BOARD_DIM * BOARD_DIM;
private HashMap<String,Boolean> eventCalledMap;
private ArrayList<String> events;
private ArrayList<String> selectedEvents;
private final String FREE = "FREE SPACE";
private final int player;
private boolean win;
BingoBoard()
{
board = new String[BOARD_DIM][BOARD_DIM];
selectedEvents = new ArrayList<>();
events = new ArrayList<>();
eventCalledMap = new HashMap<>();
eventCalledMap.put(FREE, true);
player = -1;
win = false;
}//end BingoBoard
BingoBoard(ArrayList<String> eventList)
{
board = new String[BOARD_DIM][BOARD_DIM];
selectedEvents = new ArrayList<>();
events = eventList;
eventCalledMap = new HashMap<>();
eventCalledMap.put(FREE, true);
player = -1;
win = false;
}//end BingoBoard
BingoBoard(ArrayList<String> eventList, int numb)
{
board = new String[BOARD_DIM][BOARD_DIM];
selectedEvents = new ArrayList<>();
events = eventList;
eventCalledMap = new HashMap<>();
eventCalledMap.put(FREE, true);
player = numb;
win = false;
}//end BingoBoard
//updates the event list.
public void updateEvents(ArrayList<String> eventList)
{
events.addAll(eventList);
}//end updateEvents
//Chooses events and adds them to the board.
public boolean randomizeEvents()
{
if(this.events.size() < MAX_SIZE - 1)
return false;
while(selectedEvents.size() < MAX_SIZE - 1)
{
Random rand = new Random();
int index = rand.nextInt(this.events.size());
String str = events.get(index);
selectedEvents.add(str);
events.remove(str);
}//end while
int count = 0;
for(String str:selectedEvents)
{
eventCalledMap.put(str,false);
if(count == MAX_SIZE/2)
{
board[count/BOARD_DIM][count%BOARD_DIM] = FREE;
count++;
}//end if
board[count/BOARD_DIM][count%BOARD_DIM] = str;
count++;
}//end for
return true;
}//end randomizeEvents
public void printBoard()
{
System.out.printf("Player %d\n",this.player);
System.out.println("_____________________");
for(int i = 0; i < BOARD_DIM; i++)
{
System.out.println("|---|---|---|---|---|");
for(int j = 0; j < BOARD_DIM; j++)
if(eventCalledMap.get(board[i][j]) == true)
System.out.printf("|%3s", "X");
else
System.out.printf("|%3s",board[i][j]);
System.out.println("|");
}//end for
System.out.println("|---|---|---|---|---|");
System.out.println("_____________________\n\n");
}//end printBoard
//Puts maker on given value if it
public void putMarker(String value)
{
if(eventCalledMap.containsKey(value))
eventCalledMap.put(value, Boolean.TRUE);
}//end method putMarker
/*Checks board for a win and returns true if board won and false
otherwise. */
public boolean checkWin()
{
this.win = evalBoard();
return this.win;
}//end method putMarker
//Returns true if
public boolean won()
{
return this.win;
}//end method won
//returns player number
public int getPlayer()
{
return player;
}//end getPlayer
//Checks the board for win. Returns true if a win is found.
private boolean evalBoard()
{
int i, j, count;
for(i = 0; i < BOARD_DIM; i++)
{
j = 0;
count = 0;
//Checks horizontally for a win.
while(eventCalledMap.get(board[i][j]) != false)
{
count++;
j++;
if(count == BOARD_DIM)
return true;
}//end while
j = 0;
count = 0;
//Checks verically for a win.
while(eventCalledMap.get(board[j][i]) != false)
{
count++;
j++;
if(count == BOARD_DIM)
return true;
}//end while
}//end for
i = 0;
count = 0;
//Checks the top left to bottom right diagnal for a win.
while(eventCalledMap.get(board[i][i]) != false)
{
count++;
i++;
if(count == BOARD_DIM)
return true;
}//end while
i = BOARD_DIM -1;
j = 0;
count = 0;
//Checks the top left to bottom right diagnal for a win.
while(eventCalledMap.get(board[i][j]) != false)
{
count++;
i--;
j++;
if(count == BOARD_DIM)
return true;
}//end while
return false;
}//end evalBoard
}//end class
</code></pre>
<p><strong>BingoGame.java</strong></p>
<pre><code>package bingoboard;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* @author Dom
*/
public class BingoGame
{
private ArrayList<String> eventList;
private final int DEFAULT_PLAYER_COUNT = 2;
private int playerCount;
private boolean winnerDetermined;
private ArrayList<BingoBoard> boardList;
BingoGame()
{
this.eventList = new ArrayList<>();
this.playerCount = DEFAULT_PLAYER_COUNT;
this.winnerDetermined = false;
this.boardList = new ArrayList<>();
}//end default constructor
BingoGame(int players)
{
this.eventList = new ArrayList<>();
this.playerCount = players;
this.winnerDetermined = false;
boardList = new ArrayList<>();
}//end constructor
//adds events for game.
public void addEvent(String event)
{
this.eventList.add(event);
}//end method addEvent
//Main driver for the game.
public void startGame()
{
this.winnerDetermined = false;
for(int i = 1; i <= this.playerCount;i++)
{
ArrayList<String> events = (ArrayList<String>) eventList.clone();
BingoBoard board = new BingoBoard(events,i);
board.randomizeEvents();
this.boardList.add(board);
board.printBoard();
}//end for
Scanner in = new Scanner(System.in);
while(this.winnerDetermined == false)
{
System.out.println("Enter Event:");
String check = in.next();
for(BingoBoard boards:boardList)
{
boards.putMarker(check);
boards.printBoard();
if(winnerDetermined == false)
winnerDetermined = boards.checkWin();
else
boards.checkWin();
}//end for
}//end while
this.printWinner();
}//end startGame
//Prints out winning boards. More than one player may win.
private void printWinner()
{
//Prints out winning boards. More than one player may win.
for(BingoBoard boards:boardList)
{
if(boards.won())
System.out.printf("Player %d wins!\n\n",boards.getPlayer());
}//end for
}//end printWinner
}//end class
</code></pre>
<p><strong>BingoTester.java</strong></p>
<pre><code>package bingoboard;
/**
*
* @author Dom
*/
public class BingoTester {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
BingoGame game = new BingoGame(4);
for(int i=1; i<=25; i++)
game.addEvent(Integer.toString(i));
game.startGame();
}//end main
}//end class
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>Initialize variables inline where you can, to reduce boilerplate:\n<code>private String board[][] = new String[BOARD_DIM][BOARD_DIM];</code>, etc.</p></li>\n<li><p>Don't use default scoping unless you really mean to. Prefer public or private, as appropriate.</p></li>\n<li><p>Delegate from one constructor to another, where you can.</p>\n\n<pre><code>public BingoBoard(ArrayList<String> eventList)\n{\n this();\n updateEvents(eventList);\n}\n</code></pre></li>\n<li><p>If you are going to add per-method comments, might as well teach yourself javadoc while you're at it:</p>\n\n<pre><code>/**\n * Chooses events and adds them to the board.\n */\npublic boolean randomizeEvents() {\n</code></pre></li>\n<li><p>Putting <code>Random rand = new Random();</code> inside the loop is wasteful of resources, and will occasionally cause nextInt() to return the same value on consecutive occasions due to reseting the random number generator, rather than getting the next number from the same generator. Move it up, outside the loop.</p></li>\n<li><p>This block deserves a comment, or better, to be moved to a self-documenting method. It looks like a bug to me (if BOARD_DIM is 5, then this is executed on the 12th event.. <code>board[2][3] = FREE;</code>.. really? Is that what you want to do?).</p>\n\n<pre><code>if(count == MAX_SIZE/2)\n{ \n board[count/BOARD_DIM][count%BOARD_DIM] = FREE;\n count++;\n}//end if\n</code></pre></li>\n<li><p>Review all your comments. Some are out of date.</p></li>\n<li><p>Why is there a won() and checkWin() method? And if won() is really, really needed, why doesn't checkWin() call it?</p></li>\n<li><p>evalBoard() shouldn't be necessary. When creating the board, determine how many squares must be marked in order to win; when <code>putMarker()</code> puts a marker (inside the <code>containsKey</code> conditional), increment a <code>markers</code> counter; when <code>markers == markersRequired</code> then the board is won. Also, it's swarming with nested conditionals and loops. That is major code smell.</p></li>\n<li><p>Rename <code>startGame()</code>. That method plays the entire game, it doesn't just start it. In fact, it's probably best to split that method up a bit, separate its concerns a bit. prepareBoard(), pullNumber(), checkNumberAndPlaceMarker(), things like that might work.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T02:38:11.487",
"Id": "68231",
"Score": "0",
"body": "3 things: 1. evalBoard() is necessary because there are no set number of markers you need to win the game it can be anywhere from 5 to 17 markers. If there is a way to make it better I am all ears, but it is necessary. 2. You're right about needing to document some things and you got that I wanted to put the free space in the middle, but I can tell you didn't run the code because it always puts the free space at board[2][2] not board[2][3] and it is designed that way for a reason. If you cut any odd number in half that will be the middle index counting from zero where you want the free space."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T02:53:04.083",
"Id": "68234",
"Score": "0",
"body": "@Dom 1. You mean two people could be playing the same game of bingo and one might need three times as many markers as another? Hardly seems fair! You should require the number of markers as either a constant, or as a parameter to the game. 2. Yes I didn't run the code, I reviewed it. Ok, so the free space is put in the right place, that's good. It's also completely cryptic! Hence the need for a comment or separate method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T07:41:27.667",
"Id": "68265",
"Score": "0",
"body": "Event based programs; games, graphics, gui etc; have some kind of loop in the start up method, (although it may be hidden by runtime). It is Expected that program read something like `{setUp(); mainLoop(); /*optionally*/tearDown();}` Some win32 programs may call the loop routine `PumpMessages()` some OpenGl program may call it startEventLoop(). @Dom need not really name `playEntireGameAndDontFinishUntilItsOver` as a simple rename from `startGame()` to `startGameLoop` or similar would be enough."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T08:16:10.813",
"Id": "68268",
"Score": "1",
"body": "@PaulHicks calling `Random rand = new Random(); rand.nextInt()` in a loop to get a stream of random integers is just wrong. You should use a more forceful language there, it is not a matter of taste."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T01:35:06.647",
"Id": "40501",
"ParentId": "40497",
"Score": "11"
}
},
{
"body": "<p>In addition to the previous answer, I'd like to add:</p>\n\n<p>The <code>evalBoard()</code> method is too long and contains duplicates. I'd extract a method:</p>\n\n<pre><code>/**\n * Checks the board for win\n * @return true if a win is found\n */\nprivate boolean evalBoard() {\n for (int i = 0; i < BOARD_DIM; i++) {\n // Checks horizontally for a win.\n if (evalLine(0, i, 1, 0)) {\n return true;\n }\n\n // Checks vertically for a win.\n if (evalLine(i, 0, 0, 1)) {\n return true;\n }\n }\n\n // Checks the top left to bottom right diagonal for a win.\n if (evalLine(0, 0, 1, 1)) {\n return true;\n }\n\n // Checks the top right to bottom left diagonal for a win.\n if (evalLine(BOARD_DIM-1, 0, -1, 1)) {\n return true;\n }\n\n return false;\n}\n\nprivate boolean evalLine(int startx, int starty, int deltax, int deltay) {\n int count = 0;\n int x = startx;\n int y = starty;\n while (!eventCalledMap.get(board[x][y])) {\n x += deltax;\n y += deltay;\n if (++count == BOARD_DIM) {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T12:13:16.007",
"Id": "68302",
"Score": "0",
"body": "Thanks, I would not have thought of that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T09:56:02.743",
"Id": "40525",
"ParentId": "40497",
"Score": "2"
}
},
{
"body": "<ol>\n<li><p>The <code>BingoBoard</code> class does not fulfill the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">single responsibility principle</a>. It handles the table and also prints it. I'd extract out the printing logic (and other IO logic too) to a separate class. This would make unit-testing easier and help if you want to use a graphical or web UI instead of console. (After that you might notice other responsibilities too which could be moved to separate classes.) </p></li>\n<li><p>It would be cleaner if you don't use <code>System.out</code> directly. Writing to a generic <code>PrintStream</code> or a <code>Writer</code> could enable writing to a network socket etc., and also would make testing easier.</p></li>\n<li>\n\n<pre><code>private ArrayList<String> eventList;\n</code></pre>\n\n<p><code>ArrayList<...></code> reference types should be simply <code>List<...></code>. See: <em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em></p>\n\n<p>The same is true for <code>HashMap</code> (<code>Map</code>).</p></li>\n<li><p>Field declaration and assigning to it an initial value could be on the same line in some cases, like:</p>\n\n<pre><code>private final List<String> eventList = new ArrayList<>();\n</code></pre>\n\n<p>It would remove some duplication from constructors.</p></li>\n<li><p>Instead of cloning and casting you could use a copy constructor:</p>\n\n<pre><code>final List<String> events = new ArrayList<String>(eventList);\n</code></pre></li>\n<li>\n\n<pre><code>final List<String> events = new ArrayList<String>(eventList);\nfinal BingoBoard board = new BingoBoard(events, i);\n</code></pre>\n\n<p>I'd move input list copying to the <code>BingoBoard</code> class. (<em>Effective Java, 2nd Edition, Item 39: Make defensive copies when needed</em>)</p></li>\n<li><p>It would be cleaner to call <code>close</code> on the <code>Scanner</code> instance.</p></li>\n<li><p>The <code>winnerDetermined</code> flag could be declared inside the <code>startGame</code> method. The <code>startGame</code> method override its value at the beginning and no other method reads it. (<em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>)</p></li>\n<li><p>Furthermore, this flag could completely omitted with a <code>break</code> statement:</p>\n\n<pre><code>outer: while (true) {\n System.out.println(\"Enter Event:\");\n final String check = in.next();\n for (final BingoBoard boards: boardList) {\n boards.putMarker(check);\n boards.printBoard();\n final boolean checkWin = boards.checkWin();\n if (checkWin) {\n break outer;\n }\n }\n}\n</code></pre>\n\n<p>(I've not tested this refactoring.) To be honest, the need of a label smells here but I think a few more refactoring steps would help. (For example, extracting out the inner loop to a separate method.)</p></li>\n<li><p>You could use <code>printWinner()</code> instead of <code>this.printWinner()</code>.</p></li>\n<li>\n\n<pre><code>player = -1;\n</code></pre>\n\n<p><code>-1</code> is magic number. Using named constants instead of numbers would make the code more readable and less fragile.</p></li>\n<li><p>Comments on the closing curly braces are unnecessary and disturbing. Modern IDEs could show blocks.</p>\n\n<pre><code> }// end evalBoard\n}// end class\n</code></pre>\n\n<p><a href=\"https://softwareengineering.stackexchange.com/q/53274/36726\">“// …” comments at end of code block after } - good or bad?</a></p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T12:14:12.617",
"Id": "40608",
"ParentId": "40497",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "40501",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-30T23:51:10.197",
"Id": "40497",
"Score": "11",
"Tags": [
"java",
"object-oriented",
"game"
],
"Title": "Basic bingo game in Java"
}
|
40497
|
<p>I've got this Collection in my Backbone application:</p>
<pre><code>var AnswersCollection = Backbone.Collection.extend({
model: Answer,
initialize: function() {
console.log('Hello from new answers collection');
},
getCorrect: function() {
return this.where({correct: true});
},
getWrong: function() {
return this.where({correct: false});
},
randomSet: function(correct, wrong) {
arr1 = _.sample(this.getCorrect(), correct);
arr2 = _.sample(this.getWrong(), wrong);
result = _.shuffle(arr1.concat(arr2));
coll = new AnswersCollection(result)
return coll;
}
});
</code></pre>
<p>This works, and randomSet is called by a View when config have certain options or user click on 'rerender' button, but I'm wondering that maybe I can improve this code ?
The flow looks like this</p>
<ol>
<li>Get randomly selected <strong>X</strong> correct answers</li>
<li>Get randomly selected <strong>Y</strong> wrong answers</li>
<li>Shuffle all answers</li>
<li>Create array of answers, that can be passed to new Collection</li>
</ol>
<p>This code doesn't look to cool, maybe you will have some ideas how to make It cooler?:)</p>
|
[] |
[
{
"body": "<p>Reviewing code for <em>coolness</em> is a first ;)</p>\n\n<p>Some observations:</p>\n\n<ul>\n<li><p><code>initialize</code> : if really all you want to do there is <em>Hello World</em>, then you should take it out. <code>initialize</code> is meant for initializing your model with answers.</p></li>\n<li><p><code>getCorrect</code> and <code>getWrong</code> are short one-liners that are called once, you should inline them</p></li>\n<li><p><code>arr1</code>, <code>arr2</code>, <code>coll</code> and even <code>result</code> are pretty terrible names, how about <code>correctAnswers</code>, <code>wrongAnswers</code>, <code>answers</code> and not creating <code>coll</code> since you could return the results of new AnswersCollection immediately.</p></li>\n<li><p>The most serious problem though is that you are not declaring the prior mentioned variables with <code>var</code>, that is bad.</p></li>\n</ul>\n\n<p>Also, from a <em>coolness</em> perspective, braces on their own line is where it's at.</p>\n\n<p>I would counter-propose this:</p>\n\n<pre><code>var AnswersCollection = Backbone.Collection.extend(\n{\n model: Answer,\n\n randomSet: function(correct, wrong) \n {\n var correctAnswers = _.sample(this.where({correct: true}), correct),\n wrongAnswers = _.sample(this.where({correct: false}), wrong),\n answers = _.shuffle(correctAnswers.concat(wrongAnswers));\n\n return new AnswersCollection( answers );\n }\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-22T18:59:41.677",
"Id": "158555",
"Score": "0",
"body": "braces on their own line is so PHP"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T13:30:54.313",
"Id": "40547",
"ParentId": "40503",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "40547",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T02:18:14.970",
"Id": "40503",
"Score": "5",
"Tags": [
"javascript",
"array",
"backbone.js"
],
"Title": "Backbone collection filter"
}
|
40503
|
<p>Below is the code for what I've called a <code>partitioned_multitype_map</code>. This has two major facets:</p>
<ul>
<li>Allowing a lookup based on keys of multiple lengths and of multiple types. For example:</li>
</ul>
<p><code>typedef partitioned_multitype_map<int32_t, std::string, int64_t, double> map_t;</code></p>
<p>would allow keys of any length 1 to a (specified) maximum, where each member
in the key is one of the template types.</p>
<ul>
<li>The second facet is that it partitions keys based on length, giving easy access to all key/value pairs of a given key length.</li>
</ul>
<p>I'm looking for any comments or criticisms, but particularly, there is quite a bit of code duplication lying around. Simply because of the complexity of the types, I'm having some trouble trying to reduce it, so anything that's directed to that effect would be great.</p>
<pre><code>/*! \file partitioned_multitype_map.hpp
* \brief Implementation of a compile time checked multi-key multi-value store.
*
* A partitioned_multitype_map defines a multi-key multi-value store. The types
* that the keys can store are specified at compile time via variadic template
* parameters Args...
* There are a few concepts that must be adhered to:
* 1) Each type that is to be part of a key must be Hashable.
* 2) Each type that is to be part of a key must be equality comparable
* (using ==).
* 3) At least one of the types must be DefaultConstructable.
* 4) Each type must be either CopyConstructible or MoveConstructable.
*
* Currently, the values must correspond to the types that are stored as keys;
* that is keys and values are composed of the same set of types.
*
* The map is partitioned on key length to make it easy to get all keys (and
* (associated values) of a given length.
*
* The current API is -slightly- awkward as we have to store the inserted
* key iterator to be able to insert a value into that spot. Variadic templates
* makes creating a nice API for this more difficult.
*
* Finally, note that this container isn't parameterized on an Allocator,
* and hence will use std::allocator for all allocations.
*
*/
#ifndef PARTITIONED_MULTI_TYPE_MAP_HPP_
#define PARTITIONED_MULTI_TYPE_MAP_HPP_
#include <algorithm>
#include <cstdint>
#include <functional>
#include <numeric>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include <boost/functional/hash.hpp>
#include <boost/variant.hpp>
#include <boost/optional.hpp>
namespace multi_container
{
template <typename... Args>
class partitioned_multitype_map
{
public:
using variant_type = boost::variant<Args...>;
using key_type = std::vector<variant_type>;
using mapped_type = std::vector<variant_type>;
private:
// Internal struct that is used to hash keys that the
// underlying map will hold.
struct hasher_
{
std::size_t operator()(const key_type& k) const
{
return boost::hash_range(k.begin(), k.end());
}
};
// Internal struct to be used for equality comparison of keys.
// Keys compare equal if they are the same size and each of the
// elements within the keys compares equal (order is significant).
struct equality_compare_
{
bool operator()(const key_type& k1, const key_type& k2) const
{
if(k1.size() != k2.size())
return false;
return std::equal(std::begin(k1), std::end(k1), std::begin(k2));
}
};
using hashmap_type = std::unordered_map<key_type, mapped_type,
hasher_, equality_compare_>;
using partition_type = std::pair<std::uint8_t, hashmap_type>;
using storage_type = std::vector<partition_type>;
storage_type container;
public:
// The maximum number of keys we're allowing. There isn't really a technical limitation
// to this limit, but hashing starts to become quite expensive. Could be removed
// at a later date with almost no impact on the rest of the code however, as it
// is only used in static_assert currently.
constexpr static std::uint8_t max_key_size =
std::numeric_limits<std::uint8_t>::max();
using size_type = typename hashmap_type::size_type;
using difference_type = typename hashmap_type::difference_type;
using hasher = hasher_;
using key_equal = equality_compare_;
using inner_iterator = typename hashmap_type::iterator;
using const_inner_iterator = typename hashmap_type::const_iterator;
partitioned_multitype_map() = default;
~partitioned_multitype_map() = default;
/*! \brief Emplaces the key defined in args into the container, default constructing
* the value that it maps to.
*
* \param args : The key (comprising of 1 or more elements) to be inserted.
* \return A pair where the first element is the iterator where the key was
* inserted, and a boolean specifying if the key was inserted or not.
* If the key already exists, it returns an iterator to the key and false.
*/
template <typename... Keys>
auto emplace_key(Keys&&... args) -> decltype(container[0].second.emplace(args...))
{
static_assert(sizeof...(args) < max_key_size, "Too many keys specified");
key_type key {std::forward<Keys>(args)...};
const std::uint8_t k_size = static_cast<std::uint8_t>(key.size());
auto it = std::find_if(container.begin(), container.end(),
[=](const partition_type& p) { return p.first == k_size; });
if(it == container.end()) {
hashmap_type inner;
inner.emplace(std::move(key), mapped_type());
container.emplace_back(
std::make_pair(k_size, std::move(inner)));
auto where = container.back().second.begin();
return std::make_pair(where, true);
} else {
hashmap_type& inner = it->second;
auto found = inner.find(key);
if(found != inner.end()) {
return std::make_pair(found, false);
}
return inner.emplace(std::move(key), mapped_type());
}
}
/*! \brief Sets the key pointed at by where to the values contained in args.
* This assumes that the iterator passed in is a valid iterator (for
* example, one returned by emplace_key). Behaviour is undefined if
* the iterator does not point into the container.
*
* \param where: An iterator pointing at the key to set the value of.
* \param args: The value(s) (comprising 1 or more) to be mapped to the key
* pointed to by where.
*/
template <typename... Values>
void insert_value(inner_iterator where, Values&&... args)
{
mapped_type v {std::forward<Values>(args)...};
where->second = std::move(v);
}
/*! \brief Checks the container for the existence of a given key.
*
* \param args: The key to search for.
* \returns true if the given key exists in the container, false otherwise.
*/
template <typename... Keys>
bool contains_key(Keys&&... args)
{
static_assert(sizeof...(args) < max_key_size, "Too many keys specified");
key_type key {std::forward<Keys>(args)...};
const std::uint8_t k_size = key.size();
auto it = std::find_if(container.begin(), container.end(),
[=](const partition_type& p) { return p.first == k_size; });
if(it == container.end()) {
return false;
}
hashmap_type& inner = it->second;
return inner.find(key) != inner.end();
}
/*! \brief Returns a copy of the value corresponding to the given key.
*
* \param args: The key to search for.
* \returns A optional copy of the value corresponding to the given key.
* This is the value if found, or a default-constructed value if not.
* Note that this returns a boost::optional<> instead of a pair of iterators.
* This is primarily because the keys are thought of as a "single" entity
* instead of a container in their own right.
*/
template <typename... Keys>
boost::optional<mapped_type> get_value(Keys&&... args) const
{
static_assert(sizeof...(args) < max_key_size, "Too many keys specified");
key_type key {std::forward<Keys>(args)...};
const std::uint8_t k_size = key.size();
auto it = std::find_if(container.begin(), container.end(),
[=](const partition_type& p) { return p.first == k_size; });
if(it == container.end()) {
return boost::optional<mapped_type>();
}
hashmap_type& inner = it->second;
auto found = inner.find(key);
if(found == inner.end()) {
return boost::optional<mapped_type>();
}
return boost::optional<mapped_type>(found->second);
}
/*! \brief Returns a reference to the value corresponding to the given key.
*
* \param args: The key to search for.
* \returns An optional reference to the value corresponding to the given key.
* This is the value if found, or a default-constructed value if not.
*/
template <typename... Keys>
boost::optional<mapped_type&> get_value(Keys&&... args)
{
static_assert(sizeof...(args) < max_key_size, "Too many keys specified");
key_type key {std::forward<Keys>(args)...};
const std::uint8_t k_size = key.size();
auto it = std::find_if(container.begin(), container.end(),
[=](const partition_type& p) { return p.first == k_size; });
if(it == container.end()) {
return boost::optional<mapped_type&>();
}
hashmap_type& inner = it->second;
auto found = inner.find(key);
if(found == inner.end()) {
return boost::optional<mapped_type&>();
}
return boost::optional<mapped_type&>(found->second);
}
/*! \brief Returns a const reference to the value corresponding to the given key.
*
* \param args: The key to search for.
* \returns An optional reference to the value corresponding to the given key.
* This is the value if found, or a default-constructed value if not.
*/
template <typename... Keys>
const boost::optional<mapped_type&> get_value(Keys&&... args) const
{
static_assert(sizeof...(args) < max_key_size, "Too many keys specified");
key_type key {std::forward<Keys>(args)...};
const std::uint8_t k_size = key.size();
auto it = std::find_if(container.begin(), container.end(),
[=](const partition_type& p) { return p.first == k_size; });
if(it == container.end()) {
return boost::optional<mapped_type&>();
}
hashmap_type& inner = it->second;
auto found = inner.find(key);
if(found == inner.end()) {
return boost::optional<mapped_type&>();
}
return boost::optional<mapped_type&>(found->second);
}
bool empty() const
{
return container.empty();
}
size_type size() const
{
size_type sum = 0;
for(const auto& p : container) {
sum += p.second.size();
}
return sum;
}
void clear()
{
container.clear();
}
/*! \brief Returns the number of keys in the container that have a given length.
*
* \param length The length of the keys to search for.
* \return The number of keys of the specified length, or 0 if no keys of
* the given length exist.
*/
std::size_t num_keys(std::uint8_t length)
{
auto it = std::find_if(container.begin(), container.end(),
[=](const partition_type& p) { return p.first == length; });
if(it != container.end()) {
return it->second.size();
}
return 0;
}
/*! \brief Returns a pair of iterators to the beginning/end of the map
* containing keys of a given length.
*
* \param length The length of the keys to search for.
* \return A pair of const iterators pointing to the beginning and end
* of the map.
*/
std::pair<const_inner_iterator, const_inner_iterator>
all_values_length(std::uint8_t length) const
{
auto it = std::find_if(container.begin(), container.end(),
[=](const partition_type& p) { return p.first == length; });
if(it != container.end()) {
return std::make_pair(it->second.begin(), it->second.end());
}
return std::make_pair(const_inner_iterator(), const_inner_iterator());
}
}; // end class partitioned_multitype_map
} // end namespace multi_container
</code></pre>
|
[] |
[
{
"body": "<p>I'd say that the biggest problem with it is the problem it is trying to solve. A collection of objects of unknown types is a very confusing and inefficient thing. Once retrieved, one must then ascertain the identity of the object before deciding what can be done with it. There are only three real use cases:</p>\n\n<ul>\n<li>You don't know the type of the object, but you know that it has certain operations you can perform on it to do what you need. In this case, you should turn it into something you do know, by defining a wrapper type that can enclose any of the desired types and handle the compatibility logic.</li>\n<li>You don't even know what they type of the key is; it is supplied by external sources. In that case, use a wrapper type to turn it into something you do know, as suggested previously.</li>\n<li>You already know what type everything is supposed to be, in which case you should have several different collections, one for each type, and retrieve objects from the applicable collection. (You could even put them all in the same class, where you have <code>http_response.get_uri(\"location\")</code> and <code>http_response.get_int(\"status-code\")</code> or some such thing, if you really have to.)</li>\n</ul>\n\n<p>In short, there is no need for multi-type maps. If you use them, all the dynamic typing needed will plague your code forever and ever, never to be erased or blotted out.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T00:04:19.827",
"Id": "70064",
"Score": "0",
"body": "The types aren't unknown - they're bounded by the initial template arguments. There's no dynamic typing that occurs here - it's all fully type-checked."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T00:44:42.260",
"Id": "70068",
"Score": "0",
"body": "@Yuushi having a `type_A OR type_B` is the same thing as having a `type_A_or_B`. Seriously, just don't do it. (Hint: if you have to use a type cast (except for primitives) to access the desired properties of the retrieved objects, you are doing it wrong. Type casts are inherently evil.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T00:58:41.740",
"Id": "70072",
"Score": "0",
"body": "You don't have to use type casts to access anything. `boost::variant` gives you a safe way to use the underlying type using a `static_vistor` (which in itself can be generic), or to find out what it is using `which()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T21:47:48.290",
"Id": "70271",
"Score": "1",
"body": "@Yuushi then you should just be using a map containing these `boost::variant`s. Put the complexity where it belongs, in the type container."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T16:36:50.803",
"Id": "40858",
"ParentId": "40505",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T03:24:27.420",
"Id": "40505",
"Score": "11",
"Tags": [
"c++",
"c++11",
"lookup",
"boost",
"hash-map"
],
"Title": "Partitioned Multikey Map"
}
|
40505
|
<p>I'm trying to write a bash function that will take a command such as <code>xcode-select -v</code> or <code>brew -v</code> that outputs a lot of extra text, and format it to my liking. Just to further the example, say I run <code>xcode-select -v</code>, it will output <code>xcode-select version 2333.</code>. I want to be able to split this string up and only take the <code>2333</code> part so I can put it in an <code>echo</code> statement. I want the same function to be able to handle the various outputs of stuff like <code>brew -v</code>, or <code>git --version</code>, etc.</p>
<pre><code>get_version_number() {
# set local variable to executed arguments that is passed in
local command="$($@)"
# set up temp variable and assign to global IFS variable
OIFS=$IFS
# set up IFS to split the string on empty space
IFS=" "
# read commands output into an array and store it in $array variable
read -a array <<< "$command"
# clear out IFS back to what it original was for further use
IFS=$OIFS
# echo out array at a particular indices that should be passed in
echo ${array[@]}
}
# store output of this command into variable for further usage
version=$(get_version_number xcode-select -v)
echo $version
</code></pre>
<p><strong>Edit 1:</strong>
Originally the idea came from me having to copy/paste these same lines within different conditional blocks...</p>
<pre><code>command=$(git -v)
OIFS=$IFS
IFS=" "
read -a output_array <<< "$command"
IFS=$OIFS
printf "Git version ${output_array[2]} is installed."
command=$(brew -v)
OIFS=$IFS
IFS=" "
read -a output_array <<< "$command"
IFS=$OIFS
printf "Homebrew version ${output_array[1]} is installed."
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T06:41:27.347",
"Id": "68253",
"Score": "0",
"body": "The \"How do I do _X_\" aspect of the question is off-topic for Code Review (see [help/on-topic]), though @rolfl has kindly answered it for you. In the future, try http://unix.stackexchange.com, http://superuser.com, or http://stackoverflow.com first for such questions, then let us review working code here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T16:05:41.147",
"Id": "68363",
"Score": "0",
"body": "Sorry @200_success I did have working code, but I guess by posing it as a question, it leads to some confusion. Thanks for the kindness."
}
] |
[
{
"body": "<p>The trick for splitting up the version blurb for just the version number, is to pass the values you want in <strong>before</strong> the command, and then shift them off <code>$@</code>.</p>\n<p>you have done a relatively unfamiliar-to-me parsing mechanism with the resetting the field separators, etc. Using bash as a parser is a problem for me (and I've never hated myself enough to try....).</p>\n<p>I would set up a function that takes a co-ordinate of a version as a line/word combination, and rely on out-of-bash tools to do it......</p>\n<p>I will probably get nailed for starting 4 sub-processes, but head, tail, and cut are small.... right? (Forgive me already, you won't be calling this in a tight loop, will you? You're already doing that a bit with the bash <code>$( ...)</code> operator...)</p>\n<pre><code>get_version_number() {\n local line=$1\n shift\n local word=$1\n shift\n\n # echo Line $line Word $word and Commend $@\n\n # set local variable to executed arguments that is passed in\n echo "$( $@ | head -$line | tail -1 | cut -d ' ' -f $word)"\n}\n</code></pre>\n<p>Then you would call it like:</p>\n<pre><code>gitver=$(get_version_number 1 3 git --version)\nperlver=$(get_version_number 2 4 perl -version)\n\necho Git and Perl are $gitver and $perlver respectively\n</code></pre>\n<p>which for me, produces:</p>\n<blockquote>\n<p>Git and Perl are 1.7.1 and v5.10.1 respectively</p>\n</blockquote>\n<p>This also allows you to do things like get the redhat version as</p>\n<pre><code>rhelver=$(get_version_number 1 7 cat /etc/issue)\njavaver=$(get_version_number 1 3 java -version)\n</code></pre>\n<p>and even things like the current time <code>23:45:08</code> ;-)</p>\n<pre><code>time=$(get_version_number 1 4 date)\n</code></pre>\n<hr />\n<h2>Some notes:</h2>\n<ul>\n<li>historically, it is 'expensive' to start lots of child processes. It still is a problem, but not quite as bad as it was. Doing that hundreds or thousands of times may add up to seconds of time wasted. If you can avoid creating child processes, do it.... but, sometimes it's just easier to be lazy than to be super-bash-smart.</li>\n<li>I create an additional 4 processes (actually 5) each time you call the function. One for the <code>$( ... )</code>, one for the <code>$@</code> inside that, one for <code>head</code>, one for <code>tail</code>, and one for <code>cut</code>. That is <em>almost</em> excessive.... but if you are calling this 100 times, then it's OK, if you are calling it 1000 times, you will be able to save seconds by doing it differently.</li>\n<li>the <code>$( ... )</code> operator is formally called the <a href=\"http://www.gnu.org/software/bash/manual/bashref.html#Command-Substitution\" rel=\"nofollow noreferrer\">Command Substitution</a>. What it means is that everything inside the structure is run as if in a 'child' bash process.... (so a new process is created, and the output is substituted in place of the command)</li>\n<li>what the <code>shift</code> operator does is take $@ and remove the first item.... so, your function called as <code>get_version_number 1 3 git --version</code> gets 4 parameters, <code>1</code>, <code>3</code>, <code>git</code> and <code>--version</code>. We copy <code>$1</code> off as <code>$line</code>, and then shift $@, so there are now only 3 parameters in <code>$@</code>. We then copy <code>$1</code> again (but because of the shift, it is a different value) as <code>$word</code>, and then shift again to remove it. We are left with just <code>git</code> and <code>--version</code> as the parameters.</li>\n</ul>\n<p>If you wanted, for example, to save one process each time, you could instead do:</p>\n<pre><code>get_version_number() {\n local line=$1\n shift\n local word=$1\n shift\n GOTVERSION="$( $@ | head -$line | tail -1 | cut -d ' ' -f $word)"\n}\n\nget_version_number 1 3 java -version\njavaversion=$GOTVERSION\n</code></pre>\n<p>That saves using the <code>$( .... )</code> and <code>echo</code> combination, so you save a process, but the code is a bit more complicated.</p>\n<hr />\n<h2>Edit 2.</h2>\n<p>'Obviously', what I suggest you do is not necessarily the best thing. Your code was working fine, and the mechanism will be faster (slightly) than mine because it does not do the additional 4 processes and keeps the logic inside bash internal commands.</p>\n<p>Here is my 'shift' system applied to your code:</p>\n<pre><code>get_version_number() {\n local word=$1\n shift\n # set local variable to executed arguments that is passed in\n local command="$($@)"\n # set up temp variable and assign to global IFS variable\n OIFS=$IFS\n # set up IFS to split the string on empty space\n IFS=" "\n # read commands output into an array and store it in $array variable\n read -a array <<< "$command"\n # clear out IFS back to what it original was for further use\n IFS=$OIFS\n # echo out array at a particular indices that should be passed in \n echo ${array[$word]}\n}\n</code></pre>\n<p>and you would call it with the word-number for the version as the first argument:</p>\n<pre><code>gitver=$(get_version_number 3 git --version)\n</code></pre>\n<p>But this does not allow you to find versions on multi-line outputs.....</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T04:46:14.547",
"Id": "68245",
"Score": "0",
"body": "I'm a bit of a Bash noob, so would you mind breaking down the solution so I can understand it and/or can you point to some online resources. Particularly the 4 sub-processes part, the tight loop part, `$(...)` operator in my understand is only to call a function so it can be return/assigned to a value. The Perl part returns `5,` on Mac so I'm curious as to if this isn't as full proof as I'd like."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T05:07:06.790",
"Id": "68246",
"Score": "1",
"body": "Updated answer with some more detail.... zzzzzz time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T18:50:36.353",
"Id": "68389",
"Score": "0",
"body": "This is even better than my dreamed up solution, so marking this one as the answer. Thanks @rolfl"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T04:31:33.010",
"Id": "40509",
"ParentId": "40508",
"Score": "3"
}
},
{
"body": "<p>To temporarily override a variable while executing a command, use this syntax<sup>1</sup>:</p>\n\n<pre><code>VAR=value command\n</code></pre>\n\n<p>That relieves you of the duty to save and restore <code>$IFS</code>.</p>\n\n<pre><code>get_version_number() {\n # set local variable to executed arguments that is passed in\n local command=\"$($@)\"\n # set up IFS to split the string on empty space\n IFS=\" \" read -a array <<< \"$command\" \n # echo out array at a particular indices that should be passed in \n echo ${array[@]}\n}\n</code></pre>\n\n<p>I'm not happy about the readability of <code>$($@)</code>, nor do I like the idea of storing the entire command output in a variable when you only want the first line. An alternate approach is to pipe the command output to a subshell. (Forking a Bash subshell should be cheap, relative to forking and execing a command such as <code>awk</code>. Anyway, shell programs routinely use external commands, and performance is generally not a concern until it proves to be a problem.)</p>\n\n<pre><code>get_version_number() {\n $@ | while IFS=\" \" read -a array ; do\n echo ${array[@]}\n break # Exit after processing the first line\n done\n}\n</code></pre>\n\n<p>By the way, <code>git -v</code> is an error. You want <code>git --version</code>.</p>\n\n<hr>\n\n<p><sup>1</sup> From <a href=\"http://www.gnu.org/software/bash/manual/bashref.html#Environment\" rel=\"nofollow\"><code>bash(1)</code></a>:</p>\n\n<blockquote>\n <p>The environment for any simple command or function may be augmented temporarily by prefixing it with parameter assignments, as described in <a href=\"http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameters\" rel=\"nofollow\">Shell Parameters</a>. These assignment statements affect only the environment seen by that command.</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T06:03:12.623",
"Id": "40514",
"ParentId": "40508",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "40509",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T03:57:35.200",
"Id": "40508",
"Score": "4",
"Tags": [
"parsing",
"bash",
"shell"
],
"Title": "Mixing function parameters, commands and command arguments in Bash functions"
}
|
40508
|
<p>I have refactored one of my old homework assignments (mainly to utilize <code>std::stack</code> and some C++11), and I'm still having trouble making it less repetitive.</p>
<p>It reads in a text file, character by character, and determines whether all of the opening and closing brackets (<code>{}</code>, <code>()</code>, and <code>[]</code>) match properly. All other characters are ignored.</p>
<p>If a mismatch is found, an error message will be displayed to specify the specific one, and the program will terminate. Otherwise, at the end, a message will be displayed to indicate that they all match.</p>
<p>Here are the possible error types:</p>
<ul>
<li><p>missing opening bracket:</p>
<pre><code>int main() { /*...*/ } ] // missing [
</code></pre></li>
<li><p>missing closing bracket:</p>
<pre><code>int main() { /*...*/ // missing }
</code></pre></li>
<li><p>opening bracket closed with the wrong closing bracket:</p>
<pre><code>int main() { /*...*/ ] // should close with }
</code></pre></li>
</ul>
<p>My questions:</p>
<ol>
<li>Is pushing each opening bracket onto a stack a practical way of doing this? I feel that my approach with it isn't too practical as it involves a lot of conditionals. When a closing bracket is found, there has to be some way to determine if they match properly.</li>
<li>Would an <code>std::map</code> be beneficial in serving as a look-up table for associating the opening and closing brackets with each other? I feel that it may help with DRY here.</li>
<li>Although it <em>may</em> seem easy to maintain all the error-checking in one function, should they still be split into separate functions? If so, should the messages be displayed in them or in <code>main()</code>?</li>
<li>Does it make sense to return <code>EXIT_SUCCESS</code> if the program terminated from a matching error but <em>not</em> a file error? I'm not sure if I should return <code>EXIT_FAILURE</code> instead, even though it already does that if the file cannot be opened.</li>
</ol>
<p>I don't mind following an entirely different procedure if this one isn't very practical. If you have something more complicated in mind, please share it. I want to approach this the right way.</p>
<pre><code>#include <cstdlib>
#include <fstream>
#include <iostream>
#include <stack>
#include <string>
typedef std::stack<char> Brackets;
void pushOpeningBrackets(Brackets& opening, char ch)
{
if (ch == '{')
opening.push('{');
else if (ch == '(')
opening.push('(');
else if (ch == '[')
opening.push('[');
}
bool errorsFound(Brackets& stack, char openingBracket, char closingBracket)
{
// unmatched?
if (stack.empty())
{
std::cerr << "Unmatched " << closingBracket;
return true;
}
char topBracket = stack.top();
stack.pop();
// not a match?
if (topBracket != openingBracket)
{
if (topBracket == '{')
std::cerr << "Expected } but found " << closingBracket;
else if (topBracket == '(')
std::cerr << "Expected ) but found " << closingBracket;
else if (topBracket == '[')
std::cerr << "Expected ] but found " << closingBracket;
return true;
}
return false;
}
int main()
{
std::cout << "Enter a text file name: ";
std::string filename;
std::getline(std::cin, filename);
std::ifstream inFile(filename.c_str(), std::ios::in);
if (!inFile) return EXIT_FAILURE;
Brackets stack;
std::string fileLine;
while (inFile >> fileLine)
{
for (char ch : fileLine)
{
pushOpeningBrackets(stack, ch);
if (ch == '}')
{
if (errorsFound(stack, '{', '}'))
{
return EXIT_SUCCESS;
}
}
else if (ch == ')')
{
if (errorsFound(stack, '(', ')'))
{
return EXIT_SUCCESS;
}
}
else if (ch == ']')
{
if (errorsFound(stack, '[', ']'))
{
return EXIT_SUCCESS;
}
}
}
}
// checks for missing bracket or full match
if (!stack.empty())
{
char topBracket = stack.top();
stack.pop();
if ('{' == topBracket)
std::cerr << "Missing }";
else if ('(' == topBracket)
std::cerr << "Missing )";
else if ('[' == topBracket)
std::cerr << "Missing ]";
}
else
std::cout << "All brackets match!";
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T13:50:55.640",
"Id": "68328",
"Score": "5",
"body": "Since this is covered by *\"All other characters are ignored\"* I just wanted to comment that it's not unusual for languages that match brackets to use them in scenarios that don't require matches (i.e. quoted or in comments). That might be a good extension to consider."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T20:15:29.917",
"Id": "68397",
"Score": "0",
"body": "It'd be all but mandatory to handle string and char literals, at least. Note that your code almost certainly wouldn't be able to validate itself due to the literals."
}
] |
[
{
"body": "<p>Let's answer the questions you have first:</p>\n\n<ol>\n<li><p>Using a stack is fine for this. You need to keep track of the ordering of the tokens you encounter, removing them in a LIFO manner - pretty much the definition of a stack. </p></li>\n<li><p><code>std::map</code> is overkill for 3 tokens. I would store them, but in a (gasp!) plain stack allocated array. Because of the way <code>std::map</code> is implemented, the constant factors it has for a lookup are much much higher than for a plain array. Of course, dealing with large numbers, the fact that it is <code>O(log n)</code> instead of <code>O(n)</code> to search kicks in, however, that crossover point is likely to be (depending on a whole bunch of factors) somewhere in the thousands. Not that speed matters much here (it doesn't), but searching this is arguably simpler anyway.</p></li>\n<li><p>I think having the error functionality in one function is perfectly fine. As much as splitting things into separate functions is good, in something this simple, I find there is little point. Actually outputting the error is again fine within the function - it has all the information it needs at this point. If you handled this in <code>main</code> instead, you'd have to figure out a return value that said either \"here's what I was expecting, here's what I found, there's an error\" or \"everything is ok\". That's almost certainly going to be uglier than what you've got here already.</p></li>\n<li><p>Personally, I think it should be returning <code>EXIT_SUCESS</code> if everything is good (everything matches properly), and <code>EXIT_FAILURE</code> otherwise. Think of using this in some kind of pipeline where the file has to undergo a bunch of checks, one after the other - you'd then want it to have no errors before continuing. Best way to signal everything is good? Using <code>EXIT_SUCCESS</code>.</p></li>\n</ol>\n\n<p>Ok, a few other suggestions:</p>\n\n<p>Keep a list of tokens (as a simple array):</p>\n\n<pre><code>constexpr char tokenList[] = {'{', '(', '['};\n</code></pre>\n\n<p>You can then change <code>pushOpeningBrackets</code> to:</p>\n\n<pre><code>void pushOpeningBrackets(Brackets& opening, char ch)\n{\n for(char tok : tokenList)\n {\n if(ch == tok) \n opening.push(tok);\n }\n}\n</code></pre>\n\n<p>This has the added benefit that if you want to add another token, you only have to add it to your <code>tokenList</code>, instead of having to add another <code>else if</code> statement.</p>\n\n<p>One place you could potentially use a <code>map</code> (for simplicity) is in <code>errorsFound</code>,\nwhere you want the associated closing brace with an opening brace:</p>\n\n<pre><code>const std::map<char, char> closing = {{'{', '}'}, {'(', ')'}, {'[', ']'}};\n\nbool errorsFound(Brackets& stack, char openingBracket, char closingBracket)\n{\n if(stack.empty()) \n {\n std::cout << \"Unmatched \" << closingBracket;\n return true;\n }\n\n char topBracket = stack.top();\n stack.pop();\n\n if(topBracket != openingBracket) {\n auto expectedClosing = closing.find(topBracket);\n std::cout << \"Expected \" << expectedClosing->second << \" but found \"\n << closingBracket;\n return true;\n }\n\n return false;\n} \n</code></pre>\n\n<p>This could also be used to simplify your check at the bottom of <code>main</code> in a similar way.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T06:54:12.540",
"Id": "40517",
"ParentId": "40515",
"Score": "11"
}
},
{
"body": "<p>I'd rewrite it with three main changes:</p>\n\n<ol>\n<li><p><strong>Keep <code>main()</code> minimal and improve the user interface.</strong></p>\n\n<p>By the Single Responsibility Principle, it's a good idea to limit <code>main()</code> to just calling the primary function with the appropriate parameters. In this case, the functionality splits very cleanly.</p>\n\n<p>Being a Unix/Linux user, I would prefer to see tools that adhere to some Unixy conventions:</p>\n\n<ul>\n<li>Take input from a file named on the command line, or from standard input if there is no command-line parameter.</li>\n<li>On success, remain silent and return 0 (unless you add support for a <code>--verbose</code> flag, which I haven't bothered to implement).</li>\n</ul>\n\n<p>In the context of this program, I would consider failure to open the input file as an error condition to be reported to <code>std::cerr</code>, and a delimiter mismatch to be normal output to be reported to <code>std::cout</code>. (To answer your question 3, I've just taken the easy route and printed the errors as I encounter them. That may not be the most elegant method, but it saves me the trouble of encoding the mismatch into some kind of representation. When in doubt, keep it simple, I think.)</p>\n\n<p>To answer your question 4 about the exit status of the program: 0 means success; beyond that there is no universal convention.</p></li>\n<li><p><strong>Use <code>std::string::find_first_of()</code>.</strong></p>\n\n<p>That saves you from the tedium of iterating character by character.</p></li>\n<li><p><strong>Keep the expected closing delimiters in the stack.</strong></p>\n\n<p>That seems to reduce redundancy in the code. This addresses your questions 1 and 2.</p></li>\n</ol>\n\n<p>In addition, I've enhanced it to keep track of line and column numbers to help find the location of the mismatch. The diagnostics could be even more informative if you kept track of the location of every delimiter you push onto the stack.</p>\n\n<pre><code>#include <cstdlib>\n#include <cstring>\n#include <fstream>\n#include <iostream>\n#include <stack>\n#include <string>\n\nbool bracketsMatch(std::istream &in) {\n std::stack<char> expectedDelimiters;\n int lineNum = 0;\n std::string line;\n while (std::getline(in, line)) {\n lineNum++;\n size_t pos = 0; \n while (std::string::npos != (pos = line.find_first_of(\"(){}[]\", pos))) {\n int colNum = pos + 1;\n switch (line[pos]) {\n case '(': expectedDelimiters.push(')'); break;\n case '{': expectedDelimiters.push('}'); break;\n case '[': expectedDelimiters.push(']'); break;\n\n case ']':\n case '}':\n case ')':\n if (expectedDelimiters.empty()) {\n std::cout << \"Mismatched \" << line[pos]\n << \" at line \" << lineNum << \", col \" << colNum\n << std::endl;\n return false;\n }\n if (line[pos] != expectedDelimiters.top()) {\n std::cout << \"Expected \" << expectedDelimiters.top()\n << \", found \" << line[pos]\n << \" at line \" << lineNum << \", col \" << colNum\n << std::endl;\n return false;\n }\n expectedDelimiters.pop();\n }\n pos = colNum;\n }\n }\n // Should check for a possible input error here, but I didn't bother.\n if (!expectedDelimiters.empty()) {\n std::cout << \"Expected \" << expectedDelimiters.top()\n << \" at end of file\" << std::endl;\n return false;\n }\n return true;\n}\n\nint main(int argc, const char *argv[]) {\n // The command-line parsing below is a bit sloppy (no validation,\n // help message, or option handling, for example).\n std::ifstream f;\n std::istream &in = (argc > 1) ? (f.open(argv[1]), f) : std::cin;\n if (!in) {\n std::cerr << argv[0] << \": \" << argv[1] << \": \"\n << std::strerror(errno) << std::endl;\n return 2; // A rather arbitrary error code\n }\n return bracketsMatch(in) ? EXIT_SUCCESS : EXIT_FAILURE;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T08:21:26.610",
"Id": "40518",
"ParentId": "40515",
"Score": "18"
}
},
{
"body": "<p>Your <code>typedef</code></p>\n\n<pre><code>typedef std::stack<char> Brackets;\n</code></pre>\n\n<p>… seems awkward to me.</p>\n\n<p>Without the <code>typedef</code>, your stack would probably have been declared as</p>\n\n<pre><code>std::stack<char> brackets;\n</code></pre>\n\n<p>However, with the <code>typedef</code>, that ends up being <code>Brackets stack</code>, which feels unfortunately backwards, since I expect <code>stack</code> to be a type rather than a variable name.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T08:35:16.870",
"Id": "68273",
"Score": "0",
"body": "Yeah, I was a bit hasty with the naming. I'll go back and fix some of them."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T08:26:08.067",
"Id": "40519",
"ParentId": "40515",
"Score": "11"
}
},
{
"body": "<p>The technique you are looking for is called \"Data Driven\" programming:</p>\n\n<pre><code>static char map[256] = {0}; // init all the data to 0.\n\nmap['{'] = 1;\nmap['['] = 1;\nmap['('] = 1;\nmap['}'] = '{';\nmap[']'] = '[';\nmap[')'] = '(';\n\nfor(char ch: data) {\n char action = map[ch];\n if (action == 0) {\n /* do nothing */\n }\n else if (action == 1) {\n stack.push(ch);\n }\n else {\n if (stack.empty()) {\n // Error\n } else {\n char open = stack.top();\n stack.pop();\n if (open != action) {\n // Error\n }\n }\n }\n}\nif (!stack.empty()) {\n // Error\n}\n</code></pre>\n\n<blockquote>\n <p>Is pushing each opening bracket onto a stack a practical way of doing this? </p>\n</blockquote>\n\n<p>Yes</p>\n\n<blockquote>\n <p>I feel that my approach with it isn't too practical as it involves a lot of conditionals. When a closing bracket is found, there has to be some way to determine if they match properly.</p>\n</blockquote>\n\n<p>Yes you are doing way too much programming that would involve change the code if your requirements changed a little bit. By using a data driven approach your code becomes more flexible and you can get your code to behave correctly with minor modifications to the data structure used to drive your code.</p>\n\n<blockquote>\n <p>Would an <code>std::map</code> be beneficial in serving as a look-up table for associating the opening and closing brackets with each other? I feel that it may help with DRY here.</p>\n</blockquote>\n\n<p>Overkill.<br>\nBut a data structure is required.<br>\nI used an array of character to hold my decision state. If you were using unicode or some other larger character type then a vector. The size of your decision set is small so a linear scan would not cost much, either. \\$O(ln(n)) + K1\\$ is probably larger than \\$O(n) + K2\\$ for small values of <code>n</code>. Your <code>n</code> is 6.</p>\n\n<blockquote>\n <p>Although it may seem easy to maintain all the error-checking in one function, should they still be split into separate functions?</p>\n</blockquote>\n\n<p>I like the concept of a single log function. You can maintain a consistent way of formatting the message in a single location.</p>\n\n<blockquote>\n <p>If so, should the messages be displayed in them or in <code>main()</code>?</p>\n</blockquote>\n\n<p>You could move messages to a resource file for easier L10N and I18N.</p>\n\n<blockquote>\n <p>Does it make sense to return <code>EXIT_SUCCESS</code> if the program terminated from a matching error but not a file error? I'm not sure if I should return <code>EXIT_FAILURE</code> instead, even though it already does that if the file cannot be opened.</p>\n</blockquote>\n\n<p>Think about usage in a UNIX environment. Any error should return <code>EXIT_FAILURE</code> so that the command using forces the script to stop correctly (or not continue with invalid input).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T09:22:10.210",
"Id": "68278",
"Score": "3",
"body": "Mixing `0`, `1`, `{`, `[`, and `(` as values feels a bit hackish, though it does work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T09:28:34.750",
"Id": "68281",
"Score": "1",
"body": "By hackish you mean C like. Yes. If the problem was more complex then I would not do this. But no point getting complex on such a trivial problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T01:26:32.263",
"Id": "84605",
"Score": "0",
"body": "@LokiAstari: I've just looked at this again, and I pretty much understand it, except for `if (action == 0)`. Is there any significance to it? It doesn't correspond to any of the pre-set error conditions, and it isn't triggered by adding a non-bracket character (which is what I've tried based on how it looks)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T03:31:38.520",
"Id": "84609",
"Score": "0",
"body": "@Jamal: `if (action == 0)` is the default action. If it is not an open or close (so the most common situation). It is mostly there as documentation to say `\"If we don't see any of the expected situations then do nothing\"`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T03:34:51.837",
"Id": "84610",
"Score": "0",
"body": "Ah, okay. I was a little unclear on this due to the lack of comments, but I still know what it's doing. I've tried it on my computer, and it seems to work well. It does seem simpler than my approach."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-28T23:47:30.650",
"Id": "242507",
"Score": "0",
"body": "@LokiAstari I do not understand how are you understanding your hashmap? by doing `static char map[256] = {0}` do all values in the map become 0, or the 256th position?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-29T03:47:15.473",
"Id": "242514",
"Score": "1",
"body": "@AkshatAgarwal: That initializes all positions to `0`;"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T08:59:53.927",
"Id": "40522",
"ParentId": "40515",
"Score": "16"
}
},
{
"body": "<p>Instead of ...</p>\n\n<pre><code>void pushOpeningBrackets(Brackets& opening, char ch)\n{\n if (ch == '{')\n opening.push('{');\n else if (ch == '(')\n opening.push('(');\n else if (ch == '[')\n opening.push('[');\n}\n</code></pre>\n\n<p>... use ...</p>\n\n<pre><code>void pushOpeningBrackets(Brackets& opening, char ch)\n{\n switch (ch)\n {\n case '{':\n case '(':\n case '[':\n opening.push(ch);\n break;\n }\n}\n</code></pre>\n\n<p>Or using a <code>std:map</code>:</p>\n\n<pre><code>std::map<char,char> charmap;\ncharmap['('] = ')';\n...etc...\n\nvoid pushOpeningBrackets(Brackets& opening, char ch)\n{\n if (charmap.find(ch) != charmap.end())\n opening.push(ch);\n}\n</code></pre>\n\n<p>Similarly, instead of ...</p>\n\n<pre><code>if (topBracket != openingBracket)\n{\n if (topBracket == '{')\n std::cerr << \"Expected } but found \" << closingBracket;\n else if (topBracket == '(')\n std::cerr << \"Expected ) but found \" << closingBracket;\n else if (topBracket == '[')\n std::cerr << \"Expected ] but found \" << closingBracket;\n\n return true;\n}\n</code></pre>\n\n<p>... you could ...</p>\n\n<pre><code>if (topBracket != openingBracket)\n{\n char expected;\n switch (topBracket)\n {\n case '{': expected = '}'; break;\n case '(': expected = ')'; break;\n case '[': expected = ']'; break;\n default: ; // WHAT TO DO HERE?!\n }\n std::cerr << \"Expected \" << expected << \" but found \" << closingBracket;\n return true;\n}\n</code></pre>\n\n<p>... or ...</p>\n\n<pre><code>if (topBracket != openingBracket)\n{\n std::cerr << \"Expected \" << charmap[topBracket] << \" but found \" << closingBracket;\n return true;\n}\n</code></pre>\n\n<hr>\n\n<p>In your existing code you have three different places where you define the pairs: e.g. here ...</p>\n\n<pre><code>if (errorsFound(stack, '{', '}'))\n</code></pre>\n\n<p>... and here ...</p>\n\n<pre><code> if ('{' == topBracket)\n std::cerr << \"Missing }\";\n</code></pre>\n\n<p>... and here ...</p>\n\n<pre><code> if (topBracket == '{')\n std::cerr << \"Expected } but found \" << closingBracket;\n</code></pre>\n\n<p>You can fix that by making a subroutine, <code>char getCloseOf(char) { ... }</code> and/or by defining it in data using a <code>std::map</code> or similar container.</p>\n\n<hr>\n\n<p>You haven't implemented escaping strings and comments in the source; also C++ macros in the text being parsed could mess it up, e.g. <code>#define FOO a(</code></p>\n\n<hr>\n\n<blockquote>\n <p>Although it may seem easy to maintain all the error-checking in one function, should they still be split into separate functions? If so, should the messages be displayed in them or in main()?</p>\n</blockquote>\n\n<p>I didn't like your subroutines much. For example <code>pushOpeningBrackets</code> is only called once and its implementation is short (and it's easier to understand it by reading its implementation than by reading its name). So you might as well have that code inline instead of as a subroutine, perhaps with a comment <code>// push opening brackets</code>.</p>\n\n<hr>\n\n<blockquote>\n <p>Does it make sense to return EXIT_SUCCESS if the program terminated from a matching error but not a file error? I'm not sure if I should return EXIT_FAILURE instead, even though it already does that if the file cannot be opened.</p>\n</blockquote>\n\n<p>You could document several return codes, e.g.:</p>\n\n<ul>\n<li>0: source parses - OK</li>\n<li>1: source parses - BADLY</li>\n<li>-1: couldn't parse source - file error</li>\n<li>-2: couldn't parse source - memory error</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T10:49:41.593",
"Id": "40532",
"ParentId": "40515",
"Score": "14"
}
},
{
"body": "<p>First, to make it really useful add the original line that you parsed into the mix</p>\n\n<pre><code>typedef std::pair<std::string, size_t> lineNumber\nstd::vector<lineNumber> readFile(const std::string &fileName) {\n std::ifstream fileStream(fileName.c_str(), std::ios::in);\n if (fileStream.fail()) {\n throw std::runtime_error(\"Cannot open file \" + fileName + \"\\n\");\n }\n\n std::vector<lineNumber> lines;\n std::string temp;\n while (getline(fileStream, temp)) {\n lines.push_back(std::make_pair(temp, lines.size()+1));\n }\n\n if (lines.empty()) {\n throw std::runtime_error(\"Empty file \" + fileName + \"\\n\");\n }\n fileStream.close();\n\n return lines;\n}\n</code></pre>\n\n<p>That way the user doesnt have to manually scan a possibly huge document by hand.</p>\n\n<hr>\n\n<p>I would say, that you should put the error checking into one single function. Also i would strongly recommend to keep track of the position of the error. Nothing makes more fun as manually parsing a very long line for a tiny mistake, similar to parsing a huge file for a certain line.</p>\n\n<pre><code>void checkBrackets(const std::vector<lineNumber> &lines) {\n std::map<char, char> bracketPairs= {std::make_pair(')', '('),\n std::make_pair(']', '['),\n std::make_pair('}', '{')};\n std::stack<std::pair<char, size_t>> brackets;\n for (lineNumber line : lines) {\n for (auto it = line.first.begin(); it != line.first.end(); ++it) {\n switch (*it) {\n case '(':\n case '[':\n case '{':\n brackets.push(std::make_pair(*it, std::distance(line.first.begin(), it)));\n break;\n case ')':\n case ']':\n case '}':\n if (brackets.empty()) {\n throw bracketException(MISSING_OPENING_BRACKET, line, \n std::distance(line.first.begin(), it));\n } else if (brackets.top().first != bracketPairs[*it]) {\n throw bracketException(MISSING_CLOSING_BRACKET, line,\n brackets.top().second);\n }\n brackets.pop();\n break;\n default:\n continue;\n }\n }\n if (!brackets.empty()) {\n throw bracketException(MISSING_CLOSING_BRACKET, line,\n brackets.top().second);\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Now you can add a custom exception to tell your user what is wrong with the code and standardize your error warnings. This might obviously be an overkill, but i used it for a parser I wrote and naturally the number of different errors increases. </p>\n\n<pre><code>enum bracketError {\n MISSING_CLOSING_BRACKET,\n MISSING_OPENING_BRACKET\n}\nclass bracketException : public std::exception {\nprivate:\n std::string m_msg;\npublic:\n explicit bracketException(const bracketError errorType,\n const lineNumber &line,\n const size_t pos)\n {\n switch (errorType) {\n case MISSING_CLOSING_BRACKET:\n m_msg = std::string(\"Cannot find closing bracket\");\n break;\n case MISSING_OPENING_BRACKET:\n m_msg = std::string(\"Cannot find opening bracket\");\n break;\n }\n m_msg += \" in line \" + std::to_string(line.second) + \":\\n\";\n m_msg += line.first + \"\\n\";\n m_msg += std::string(pos, ' ') + \"^\\n\";\n }\n\n virtual const char* what() const throw()\n {\n return m_msg.c_str();\n }\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-10-05T13:50:11.570",
"Id": "143313",
"ParentId": "40515",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "40532",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T06:11:31.080",
"Id": "40515",
"Score": "27",
"Tags": [
"c++",
"c++11",
"parsing",
"validation",
"balanced-delimiters"
],
"Title": "Validating opening and closing bracket pairs"
}
|
40515
|
<p>I'm a newbie self-learned programmer, I've started poking around a bit at C# around two months ago, since I will be starting formal programming studies in about 7 months. I heard the best way to learn how to code is to code so I've written this trivia application and I would love some constructive feedback, what are the good things? And what are the things I could improve on / have done better. </p>
<p><strong>Progam.cs</strong></p>
<pre><code>namespace EasyTrivia
{
class Program
{
const bool DEBUG_MODE = false;
public static void DebugPrint(string printOut) {
if (DEBUG_MODE) { Console.WriteLine("[DEBUG]: {0}", printOut); }
}
static void Main(string[] args)
{
//PLACEHOLDER, check for command line arguments
for (int y = 0; y < args.Length; y++)
{
switch (args[y])
{
case "debug1":
Console.WriteLine("DEBUG {0} ARGUMENT", y);
break;
case "debug2":
Console.WriteLine("DEBUG {0} ARGUMENT", y);
break;
case "debug3":
Console.WriteLine("DEBUG {0} ARGUMENT", y);
break;
}
}
const int MAX_PLAYERS = 4; // TODO: Add more freedom here, so you can have any number of players
string[] pNames = new string[4];
Player[] player = new Player[4];
Console.WriteLine("How many players wish to play? (max 4)");
string input = Console.ReadLine();
int noOfPlayers;
bool parseInput = Int32.TryParse(input, out noOfPlayers); // We're doing the easy check
while (noOfPlayers > MAX_PLAYERS || noOfPlayers < 1)
{
Console.WriteLine("Incorrect input. Please enter a valid number of players inbetween 1 and 4");
input = Console.ReadLine();
parseInput = Int32.TryParse(input, out noOfPlayers);
} Console.Clear();
for (int i = 0; i < noOfPlayers; i++)
{
Console.WriteLine("Please enter the name for player {0}", i + 1);
pNames[i] = Console.ReadLine();
player[i] = new Player();
player[i].Name = pNames[i];
player[i].Score = 0;
} Console.Clear();
GameLoop(player, noOfPlayers);
}
static void GameLoop(Player[] player, int noOfPlayers)
{
bool GameState = true;
List<int> blacklist = new List<int>();
Random RNG = new Random();
const int WINNING_SCORE = 3; // TODO: Custom winning score should be configurable through commandline argument.
TriviaHandler trivia = new TriviaHandler();
trivia.InitializeQuestion();
//Begin Game Loop
while (GameState)
{
DebugPrint("Game loop initializing...");
string questionString = trivia.FetchQuestion(blacklist, RNG);
//If it's a duplicate entry FetchQuestion() will return null
while (questionString == null) { questionString = trivia.FetchQuestion(blacklist, RNG); }
Console.WriteLine(questionString);
for (int i = 0; i < noOfPlayers; i++)
{
Console.WriteLine("Player {0}, type in your answer:", i+1);
string pInput = Console.ReadLine();
if (trivia.CheckAnswer(pInput))
{
Console.WriteLine("Correct! You have been awarded 1 point");
player[i].Score += 1;
// If they get enough pts to win we gotta end the game here too.
if (player[i].Score == WINNING_SCORE)
{
Console.WriteLine("Congratulations player {0} has won the game! Would you like to play another one? (Y/N)", player[i].Name);
string choice = Console.ReadLine().ToUpper();
while (choice != "Y" && choice != "N")
{
Console.WriteLine("Incorrect input! Please press Y for yes or N for no");
choice = Console.ReadLine().ToUpper();
}
if (choice == "Y")
{
//Reset player score first
for (int z = 0; i < player.Length; i++)
{
player[z].Score = 0;
}
GameLoop(player, noOfPlayers);
}
else { Environment.Exit(0); }
}
//If the answer is correct break the loop
break;
}
else { Console.WriteLine("Incorrect Answer, question is passed on to next player"); }
}
}
}
}
}
</code></pre>
<p><strong>Player.cs</strong></p>
<pre><code>namespace EasyTrivia
{
class Player
{
private string name;
public string Name { get; set; }
private int score;
public int Score { get; set; }
}
}
</code></pre>
<p><strong>TriviaHandler</strong></p>
<pre><code>namespace EasyTrivia
{
class TriviaHandler
{
Question[] question = new Question[Question.GetMaxQuestions(true)];
private int qID;
public int QID { get; set; }
public void InitializeQuestion()
{
List<string> questions = new List<string>(Question.ListA);
//questions.AddRange(Question.ListA);
List<string> answers = new List<string>();
answers.AddRange(Question.ListB);
Program.DebugPrint("Initializing questions...");
for (int i = 0; i < answers.Count; i++)
{
question[i] = new Question();
question[i].Pretext = questions[i];
question[i].Answer = answers[i];
//if (options) { question[i].LoadOptions() }
}
}
public bool CheckAnswer(string input)
{
//if (input == "debug") { return true; }
if (input.ToUpper() == question[QID].Answer.ToUpper()) { return true; }
else { return false; }
}
public string FetchQuestion(List<int> blacklist, Random RNG)
{
bool blisted = false;
int QuestionID = RNG.Next(Question.counter);
if (blacklist.Contains(QuestionID)) { blisted = true; }
if (!blisted)
{
QID = QuestionID;
blacklist.Add(QuestionID);
return question[QuestionID].Pretext;
}
else { return null; }
}
}
}
</code></pre>
<p><strong>Question.cs</strong></p>
<pre><code>namespace EasyTrivia
{
class Question
{
private string pretext;
private string answer;
private string[] options;
private string[] listA;
private string[] listB;
public static string[] ListA { get; set; }
public static string[] ListB { get; set; }
public string Pretext { get; set; }
public string Answer { get; set; }
public static int counter { get; set; }
public static int GetMaxQuestions(bool initialize)
{
int count = new int();
List<string> questions = new List<string>();
List<string> answers = new List<string>();
Program.DebugPrint("Getting max questions...");
XElement rawXML = XElement.Load(@"C:\Users\Gabriel\Documents\Visual Studio 2013\Projects\EasyTrivia\EasyTrivia\Questions.xml");
IEnumerable<XElement> elements = rawXML.Elements();
//So I've written three ways of fetching the Q/A data
//Method 1
//foreach (XElement question in elements)
//{
// if (initialize) { count++; }
// questions.Add(question.Element("Pretext").Value);
// answers.Add(question.Element("Answer").Value);
//}
//if (initialize)
//{
// ListA = questions.ToArray();
// ListB = answers.ToArray();
//}
//Method 2
var pQuery = from lQ in elements.Elements()
where lQ.Name == "Pretext"
select lQ.Value;
var aQuery = from aQ in elements.Elements()
where aQ.Name == "Answer"
select aQ.Value;
foreach (var pretext in pQuery)
{
if (initialize) { count++; }
questions.Add(pretext);
}
foreach (var answer in aQuery)
{
answers.Add(answer);
}
if (initialize)
{
ListA = questions.ToArray();
ListB = answers.ToArray();
}
//Method 3
//string[] lines = File.ReadAllLines("Questions.txt");
//for (int i = 0; i < lines.Length; i++)
//{
// if (lines[i].Contains("[QUESTION") == true) { count++; }
// if (initialize && lines[i].Contains("[QUESTION"))
// {
// string[] delimiter1 = lines[i + 1].Split('=');
// string[] delimiter2 = lines[i + 2].Split('=');
// questions.Add(delimiter1[1]);
// answers.Add(delimiter2[1]);
// ListA = questions.ToArray();
// ListB = answers.ToArray();
// }
//}
if (initialize) { counter = count; }
return count;
}
}
}
</code></pre>
<p><strong>Questions.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<QUESTIONS>
<Question id="1">
<Pretext>This is the first test question</Pretext>
<Answer>test1</Answer>
</Question>
<Question id="2">
<Pretext>This is the second test question</Pretext>
<Answer>test2</Answer>
</Question>
<Question id="3">
<Pretext>This is the third test question</Pretext>
<Answer>test3</Answer>
</Question>
</QUESTIONS>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T10:03:41.683",
"Id": "68285",
"Score": "2",
"body": "Consider to ask for review of single class/method instead of asking to review whole application code. Reviewing whole application and writing feedback is *time-consuming* activity"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T12:28:23.827",
"Id": "68307",
"Score": "2",
"body": "@SergeyBerezovskiy I hear you (been there!), however remember that you may address only *some* aspects of the code in your answer - I know it's compelling to review the entire app at once, but you can answer with more than one shorter answers that address different aspects. In an effort to increase the number of per-question answers on CR, we encourage shorter reviews - yours was a great answer nonetheless. Thank you for your contributions, keep answering, and feel free to join us (CR addicts) in chat anytime! ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T12:59:40.160",
"Id": "68314",
"Score": "0",
"body": "Sergey I will remember that till next time, nevertheless thanks for taking the time to help me out :)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T15:49:09.173",
"Id": "68358",
"Score": "0",
"body": "I'm not going to add to the excellent feedback already provided. But as far as style e.g. naming conventions are concerned check out [Lance Hunt's C# Coding Standards](http://weblogs.asp.net/lhunt/pages/CSharp-Coding-Standards-document.aspx)."
}
] |
[
{
"body": "<ol>\n<li><p>When using an auto-property like <code>public string Name { get; set; }</code> you don't add a backing field like you do in <code>Player</code>:</p>\n\n<pre><code>private string name;\npublic string Name { get; set; }\n</code></pre>\n\n<p>The point of an auto-property is to generate the backing field for you. By adding <code>private string name;</code> you have added an additional field to your class that is not used. It should be deleted. The same goes for all the properties in your code. </p></li>\n<li><p>A possible bug in <code>GameLoop</code> after finishing a game:</p>\n\n<pre><code>if (choice == \"Y\")\n{\n //Reset player score first\n for (int z = 0; i < player.Length; i++)\n {\n player[z].Score = 0;\n }\n GameLoop(player, noOfPlayers);\n}\nelse { Environment.Exit(0); }\n</code></pre>\n\n<p>In the for loop you use <code>z</code> as a loop variable but increment and check <code>i</code> instead.\nAlso you are calling <code>GameLoop</code> recursively which works in this case but it is an unsuall way of restarting the game. Theoretically after playing thousand of games in a row the call stack could get full and crash the game.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T12:58:00.873",
"Id": "68313",
"Score": "0",
"body": "Visual studio was warning me about the unused fields, I thought it was strange but now it all makes sense. Also good catching that bug! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T15:00:36.243",
"Id": "68350",
"Score": "0",
"body": "To add to your comment on that snippet, in Java, `if(choice == \"Y\")` would simply check for the memory location of `\"Y\"`, and we should instead be using `.Equals()` for string equality. IIRC it's the same in C#. Am I right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T15:06:40.387",
"Id": "68352",
"Score": "1",
"body": "In C# comparison operator is overloaded for String."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T06:28:41.267",
"Id": "68678",
"Score": "1",
"body": "@KubaWyrostek It might be worthwhile to take a look at some gotcha's in connection with the comparison operator: http://blogs.msdn.com/ericlippert/archive/2009/04/09/double-your-dispatch-double-your-fun.aspx"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T10:43:14.743",
"Id": "40530",
"ParentId": "40523",
"Score": "8"
}
},
{
"body": "<p>First note - do not use DEBUG_MODE constant to define whether you should print debug message or not. There are better ways to do it. You can either use <a href=\"http://msdn.microsoft.com/en-us/library/aa664622%28v=vs.71%29.aspx\">conditional attribute</a> to check if compilation symbol \"DEBUG\" is defined. Calls to methods marked with Conditional attribute completely removed from generated code if symbol is not defined (\"DEBUG\" is defined by default when you start application in debug mode):</p>\n\n<pre><code>[Conditional(\"DEBUG\")]\npublic static void DebugPrint(string printOut) \n{\n Console.WriteLine(\"[DEBUG]: {0}\", printOut);\n}\n</code></pre>\n\n<p>Another option is usage of logging library (NLog, log4net etc). You will be able to define logging targets (or appenders) which will write messages to console, file, database etc. You will be able to define levels of logging messages from configuration file without changing your application code. E.g. with NLog you can get instance of logger</p>\n\n<pre><code>private static Logger Logger = LogManager.GetCurrentClassLogger();\n</code></pre>\n\n<p>And use it to write debug messages if debug level message are enabled in configuration (you can change message format from config):</p>\n\n<pre><code>Logger.Debug(\"Initializing questions...\");\n</code></pre>\n\n<hr>\n\n<p>Back to application. I suggest you to follow <a href=\"http://msdn.microsoft.com/en-us/library/x2dbyw72%28v=vs.71%29.aspx\">capitalization styles</a> for naming types, methods and variables suggested by Microsoft. E.g. local variables should have camelCase names. Also do not use prefixes and shortenings in variable names - <code>pNames</code> is less readable than <code>playerNames</code>. And it's hard to understand what is <code>listA</code> and <code>listB</code>, why queries have names <code>pQuery</code> and <code>aQuery</code>, and their query variables names <code>lQ</code> and <code>aQ</code>. Choose names wisely to help others understand your code.</p>\n\n<hr>\n\n<p>If you are using auto-implemented properties, than you don't need to define fields:</p>\n\n<pre><code>class Player\n{ \n public string Name { get; set; } // back-storage will be generated\n public int Score { get; set; }\n}\n</code></pre>\n\n<hr>\n\n<p>Your <code>Question</code> class is strange. First thing which is not obvious is that it gets initialized when you check questions max something. I suggest you to create <code>Question</code> class which will represent data you have in xml:</p>\n\n<pre><code>public class Question\n{\n public int Id { get; set; }\n public string Pretext { get; set; }\n public string Answer { get; set; }\n}\n</code></pre>\n\n<p>I suggest not to hard-code file names in your application. Move move questions file name to application settings:</p>\n\n<pre><code><appSettings>\n <add key=\"questionsFileName\" \n value=\"C:\\EasyTrivia\\EasyTrivia\\Questions.xml\"/>\n</appSettings> \n</code></pre>\n\n<p>And move data-access logic into separate class (with this Question class you event can use <a href=\"http://msdn.microsoft.com/en-us/library/83y7df3e%28v=vs.110%29.aspx\">Xml serialization attributes</a> to deserialize questions from xml file), e.g.</p>\n\n<pre><code>public class QuestionRepository\n{\n private static readonly string fileName;\n\n static QuestionRepository()\n {\n fileName = ConfigurationManager.AppSettings[\"questionsFileName\"];\n }\n\n public List<Question> GetAllQuestions()\n {\n XDocument xdoc = XDocument.Load(fileName);\n var query = from q in xdoc.Root.Elements(\"Question\")\n select new Question {\n Id = (int)q.Attribute(\"id\"),\n Pretext = (string)q.Element(\"Pretext\"),\n Answer = (string)q..Element(\"Answer\")\n };\n\n return query.ToList();\n }\n}\n</code></pre>\n\n<p>As I understand logic of your <code>blackList</code> - you don't want to fetch same question several times and you want to have questions in random order. Than can be done really easy without any blacklists and looping while next random question is not in blacklist:</p>\n\n<pre><code>var repository = new QuestionRepositor();\nvar random = new Random();\nvar questions = repository.GetAllQuestions().OrderBy(q => random.Next());\n</code></pre>\n\n<p>That will parse xml, return questions and sort them in random order. Now your game loop can look like:</p>\n\n<pre><code>foreach(var question in questions)\n{\n Ask(question); // extract all loop code to some method\n if (players.Any(IsWinner))\n break;\n}\n</code></pre>\n\n<p>Extracted code can look like:</p>\n\n<pre><code>private void Ask(Question question)\n{\n Console.WriteLine(question.Pretext);\n foreach(var player in players) \n {\n if (question.IsAnswerCorrect(GetAnswer()))\n player.Score++;\n\n if (IsWinner(player))\n return;\n }\n}\n\nprivate bool IsWinner(Player player)\n{\n return player.Score == WinningScore;\n}\n</code></pre>\n\n<hr>\n\n<p>Your program has another parts to improve, but answer is already too big for question-answer format. Keep going and use recommendations above.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T11:05:12.043",
"Id": "68293",
"Score": "0",
"body": "`OrderBy` and `Random` might not be the best solution to shuffle a list: http://stackoverflow.com/questions/1287567/is-using-random-and-orderby-a-good-shuffle-algorithm"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T11:11:51.320",
"Id": "68294",
"Score": "0",
"body": "@Andris not best for performance, but best for development time and it has good readability. [Premature optimization is evil](http://programmers.stackexchange.com/questions/80084/is-premature-optimization-really-the-root-of-all-evil)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T11:22:25.783",
"Id": "68297",
"Score": "1",
"body": "At first glance the non-deterministic nature or Random seamed to be a problem but after reading about it a bit I find it to be a simple, short and good enough solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T12:52:29.773",
"Id": "68311",
"Score": "1",
"body": "First of all. Thanks alot for taking the time to review my code and leave helpful feedback. I'm not so familiar with the naming conventions yet so I'll make sure to check out the MSDN article you mentioned. I'm gonna read through the other things you linked, your code is definitely a lot cleaner. Thanks again!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T10:44:09.277",
"Id": "40531",
"ParentId": "40523",
"Score": "15"
}
},
{
"body": "<p>There are a lot of good inputs from both Sergey and Andris, so I'll make mine short :)</p>\n\n<ul>\n<li>You should avoid repetetive code like you have in your main method with the switch case.</li>\n<li>You should avoid large methods like GameLoops and GetMaxQuestions. Break them up into smaller methods.</li>\n<li>You can replace some of your for loops with foreach loops for simplicity.</li>\n</ul>\n\n<p>One thing that is vital for refactoring and testability is that you understand whats happening inside a method without actually decifering the content. To achieve that use naming to clarify and avoid variables like question/questions unless they are in a foreach loop. \nRenaming questions to something like allAvailableQuestions would help you not to mix the two and should make it clearer what that array is for</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T11:57:19.040",
"Id": "40537",
"ParentId": "40523",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "40531",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T09:45:29.390",
"Id": "40523",
"Score": "11",
"Tags": [
"c#"
],
"Title": "Feedback requested on simple trivia"
}
|
40523
|
<p>I was told to create a calculator design on AWT, which is also my first project on AWT. I wrote the program and submitted it. I was then told that my program contains around 70 lines of code, and I should try to write less code. How can I shorten this code?</p>
<pre><code>import java.awt.*;
class Demo{
Frame f;
TextField tf;
Button add,sub,mul,div,find,zero,num1,num2,num3,num4,num5,num6,num7,num8,num9;
Button num0,decimal,per;
Demo(String s)
{
f=new Frame(s);
tf=new TextField("0");
tf.setBounds(20, 40, 205, 40);
f.add(tf);
add=new Button("+");
sub=new Button("-");
div=new Button("/");
mul=new Button("x");
find=new Button("=");
zero=new Button("C");
num1=new Button("1");
num2=new Button("2");
num3=new Button("3");
num4=new Button("4");
num5=new Button("5");
num6=new Button("6");
num7=new Button("7");
num8=new Button("8");
num9=new Button("9");
num0=new Button("0");
per=new Button("%");
decimal=new Button(".");
mul.setBounds(125,100,50,40);
add.setBounds(70,100,50,40);
sub.setBounds(15, 100, 50, 40);
div.setBounds(180, 100, 50, 40);
find.setBounds(180,250,50,88);
zero.setBounds(180, 150, 50, 40);
num9.setBounds(15,150,50,40);
num8.setBounds(70,150,50,40);
num7.setBounds(125,150,50,40);
num6.setBounds(15,200,50,40);
num5.setBounds(70,200,50,40);
num4.setBounds(125,200,50,40);
num3.setBounds(15,250,50,40);
num2.setBounds(70,250,50,40);
num1.setBounds(125,250,50,40);
num0.setBounds(15,300,105,40);
decimal.setBounds(125,300,50,40);
per.setBounds(180,200,50,40);
f.add(per);
f.add(add);
f.add(mul);
f.add(div);
f.add(sub);
f.add(find);
f.add(zero);
f.add(num1);
f.add(num2);
f.add(num3);
f.add(num4);
f.add(num5);
f.add(num6);
f.add(num7);
f.add(num8);
f.add(num9);
f.add(num0);
f.add(decimal);
f.setLayout(null);
f.setSize(250,350);
f.setVisible(true);
}
public static void main(String[] args)
{
new Demo("Calculator");
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T10:24:37.383",
"Id": "68288",
"Score": "0",
"body": "Even though the program seems far from complete, I think there are some things that we can review here. Thanks for coming here, you will most likely get an answer soon!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T21:44:21.583",
"Id": "68406",
"Score": "0",
"body": "Whenever you start seeing yourself repeating code, you should think of ways to abstract that portion. @amon made a great suggestion. Single Responsibility and DRY (Don't repeat yourself) are really great concepts to look into."
}
] |
[
{
"body": "<p>Write a helper method, e.g.</p>\n\n<pre><code>static Button createButton(Frame f, String label, int x0, int y0, int width, int height) {\n Button b = new Button(label);\n b.setBounds(x0, y0, width, height);\n f.add(b);\n return b;\n}\n</code></pre>\n\n<p>Then your code would simplify to lines like:</p>\n\n<pre><code>createButton(f, \"+\", 70, 100, 50, 40);\n</code></pre>\n\n<p>which is a reduction of roughly 2/3.</p>\n\n<p>Of course this does not address the problem that you are trying to do pixel-exact layouts. You should rather be dropping elements on a grid which can be resized freely. (However, it has been a long time since I've used AWT so I can't give an example).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T15:09:28.323",
"Id": "68354",
"Score": "1",
"body": "+1 this would be a very readable and maintainable solution. 1 line per button looks pretty elegant to me. I may have not passed in frame and instead just returned the button, then each line would read f.Add(SimpleButton(\"+\", 70,100,50,40)) but either way looks pretty good."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T16:44:19.380",
"Id": "68367",
"Score": "3",
"body": "Returning the button already added to the frame has an advantage: It allows to assign the button to a Button variable for later reference (adding action listeners etc.), without a second line for adding it to the frame. Like so: `Button add = createButton(f, \"+\", 70, 100, 50, 40);`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T10:25:34.360",
"Id": "40527",
"ParentId": "40526",
"Score": "14"
}
},
{
"body": "<p>First thing what have written is nice try for the first time programer but you should use layout instead of using null out.</p>\n\n<p>use 2 panel & add in to frame in border layout.(top & center)</p>\n\n<p>in top add textField.</p>\n\n<p>& 2nd panel use grid layout & simply add them. this might decrease your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T10:33:03.153",
"Id": "68291",
"Score": "0",
"body": "Thanks for suggestion but my teacher yet not explain the concept of Layout so when I'll understand this layout concept. I'll Definitely use your suggestion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T14:52:07.663",
"Id": "68348",
"Score": "4",
"body": "@user1444692 although you haven't been taught about layouts yet, there's no harm in doing a bit of extra-curricular study and working them out. I'm sure there are plenty of AWT books out there to get you started ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T10:28:48.487",
"Id": "40528",
"ParentId": "40526",
"Score": "2"
}
},
{
"body": "<p>In addition to what @amon said, I suggest that you use an <a href=\"http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html\" rel=\"nofollow\">array</a> for storing the numerical buttons</p>\n\n<pre><code>Button[] numbers = new Button[10];\n\nnumbers[9].setBounds(15, 150,50, 40);\nnumbers[8].setBounds(70, 150,50, 40);\nnumbers[7].setBounds(125,150,50, 40);\nnumbers[6].setBounds(15, 200,50, 40);\nnumbers[5].setBounds(70, 200,50, 40);\nnumbers[4].setBounds(125,200,50, 40);\nnumbers[3].setBounds(15, 250,50, 40);\nnumbers[2].setBounds(70, 250,50, 40);\nnumbers[1].setBounds(125,250,50, 40);\nnumbers[0].setBounds(15, 300,105,40);\n</code></pre>\n\n<p>The positions of the 1-9 numbers can be computed mathematically which makes it possible to create these buttons in a for-loop. I have not tested this calculation, but I believe it is correct:</p>\n\n<pre><code>numbers[0] = new Button(\"0\");\nnumbers[0].setBounds(15, 300,105,40);\nfor (int i = 1; i <= 9; i++) {\n numbers[i] = new Button(Integer.toString(i));\n int x = (i - 1) % 3;\n int y = i / 3;\n numbers[i].setBounds(125 - 55 * x, 250 - 50 * y, 50, 40);\n}\n</code></pre>\n\n<p>However, it is really a good idea to put these buttons into a Layout. Using exact pixel values is not recommended as it will not be scalable at all if you want to resize your form.</p>\n\n<p>In addition to this, there is also some other things that I suggest you improve:</p>\n\n<ul>\n<li>All the variables in your class can be <code>private</code>, and prefferably also <code>final</code></li>\n<li>Use spaces around the assignment operator, <code>f = new Frame(s);</code> looks better</li>\n<li>Naming a <code>TextField</code> to <code>tf</code> provides not much information about the variable. What is it used for? <code>input</code> can be a better name.</li>\n<li>Don't be afraid of using variable names longer than four characters, <code>percent</code> is better than <code>per</code> for example.</li>\n<li>I recommend to also use spaces after a comma. <code>Button add, subtract, multiply</code> would be better (also improving the variable names)</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T14:38:52.230",
"Id": "68344",
"Score": "0",
"body": "`=` is not character, it's assignment operator."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T14:41:52.640",
"Id": "68345",
"Score": "0",
"body": "@tintinmj Technically, i'd say that it's a character also - at least in the computer world :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T07:59:46.883",
"Id": "68457",
"Score": "0",
"body": "@SimonAndréForsberg I think the OP has the primitive `char` in mind."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T10:50:36.417",
"Id": "40533",
"ParentId": "40526",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "40527",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T10:18:36.260",
"Id": "40526",
"Score": "6",
"Tags": [
"java",
"awt",
"calculator"
],
"Title": "Shortening calculator project code"
}
|
40526
|
<p>I wrote a simple thread pool, which works pretty well. I would like to see your review of it.</p>
<p>One important feature that I needed in the pool is the ability to wait until all the tasks that I sent to the pool are complete (so that later I could send other tasks that are dependent on the result of the previous tasks).</p>
<p>This is the basic task which you inherit from, to send tasks: </p>
<pre><code>class Task
{
public :
virtual void ExecuteTask() = 0;
};
</code></pre>
<p>This is the .h file of the Thread pool:</p>
<pre><code>#include<time.h>
#include <Windows.h>
#include<list>
using namespace std;
class ThreadPool
{
public :
ThreadPool(int threadCount=0);
bool ScheduleTask(Task* task);
bool WaitForWorkToBeFinished(DWORD dwMilliseconds);
~ThreadPool();
private :
static DWORD WINAPI ThreadStart(LPVOID threadParameters);
DWORD ThreadMain();
list<Task*> mTasks;
HANDLE* mThreads;
int mThreadCount;
CRITICAL_SECTION mCriticalSection;
CONDITION_VARIABLE mConditionVariable;
CONDITION_VARIABLE mConditionVariableTaskFinished;
int mNumberOfTasksNotFinished;
bool mConsum;
};
</code></pre>
<p>This is the CPP file:</p>
<pre><code>#include "ThreadPool.h"
ThreadPool::ThreadPool(int threadCount)
{
mThreadCount=threadCount;
mThreads = new HANDLE[mThreadCount]; //This handles will be used to wait upon them
InitializeCriticalSection(&mCriticalSection);
InitializeConditionVariable(&mConditionVariable);
InitializeConditionVariable(&mConditionVariableTaskFinished);
mConsum = true;
mNumberOfTasksNotFinished = 0;
for(int i = 0; i< mThreadCount;i++)
mThreads[i] = CreateThread(NULL, 0, ThreadStart, (void*)this, 0,NULL);
}
bool ThreadPool::ScheduleTask(Task* task)
{
EnterCriticalSection(&mCriticalSection);
mTasks.push_back(task); //This is a simple std::list
mNumberOfTasksNotFinished++;
LeaveCriticalSection(&mCriticalSection);
WakeConditionVariable(&mConditionVariable); //Waking up the threads so they will know there is a job to do
return true;
}
DWORD WINAPI ThreadPool::ThreadStart(LPVOID threadParameters) //Just a static function to help me use member function as a thread
{
ThreadPool* referenceToThis = (ThreadPool*)threadParameters;
return referenceToThis->ThreadMain();
}
DWORD ThreadPool::ThreadMain() //The main thread function
{
do
{
Task* currentTask;
EnterCriticalSection(&mCriticalSection);
while(mTasks.size() ==0 && mConsum)
SleepConditionVariableCS(&mConditionVariable,&mCriticalSection, INFINITE);
if(!mConsum) //Destructor ordered on abort
{
LeaveCriticalSection(&mCriticalSection);
return 0;
}
//If we got here, we successfully aquired the lock and the list<Task> is not empty
currentTask = mTasks.front();
mTasks.pop_front();
LeaveCriticalSection(&mCriticalSection);
currentTask->ExecuteTask();
//delete currentTask;
EnterCriticalSection(&mCriticalSection);
mNumberOfTasksNotFinished--;
LeaveCriticalSection(&mCriticalSection);
WakeConditionVariable(&mConditionVariableTaskFinished);
}while(mConsum);
return 0;
}
//This function is very important, it gives the user the ability to send 10 tasks to the thread pool
// then to wait till all the tasks completed, and give the next 10 which are dependand on the result of the previous ones.
bool ThreadPool::WaitForWorkToBeFinished(DWORD dwMilliseconds)
{
EnterCriticalSection(&mCriticalSection);
while(mNumberOfTasksNotFinished!=0)
SleepConditionVariableCS(&mConditionVariableTaskFinished,&mCriticalSection, INFINITE);
LeaveCriticalSection(&mCriticalSection);
return true;
}
ThreadPool::~ThreadPool()
{
mConsum = false;
WakeAllConditionVariable (&mConditionVariable);
WaitForMultipleObjects(mThreadCount,mThreads, true, INFINITE);
DeleteCriticalSection(&mCriticalSection);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T17:37:54.323",
"Id": "68370",
"Score": "1",
"body": "Yes its fun writing your own thread pool. But this has been done to death before. Use one of the available ones that has been thoroughly tested and de-bugged."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T17:40:10.597",
"Id": "68371",
"Score": "1",
"body": "Its 2014. Can we please start using C++11 at least with its built in standard threads. All modern compilers now support it. Most modern compilers will support C++14 by now (yes I know 2014 has only just started and they have not offically voted on it buts its so close and the compilers are so ready)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T17:45:08.120",
"Id": "68374",
"Score": "0",
"body": "What happens if the task throws an exception? In most threading libraries if an exception causes a thread to unroll past its start point the application will exit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T17:48:03.960",
"Id": "68375",
"Score": "0",
"body": "You are leaking all but one of the resources you created."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T21:23:21.683",
"Id": "68403",
"Score": "0",
"body": "Loki can you please elaborate ? i implementing it to study about threading and to understand how things work. It is important for me to know things thoroughly (I'm also preparing for interviews, and to implement a thread pool is totally possible question)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-17T08:37:26.050",
"Id": "122044",
"Score": "0",
"body": "There is also an implementation of mine here maybe it will help: https://github.com/tghosgor/threadpool11/"
}
] |
[
{
"body": "<p>A few points:</p>\n\n<p>Your <code>EnterCriticalSection</code>/<code>LeaveCriticalSection</code> code should be placed into a scoped RAII object. This saves you from explicitly calling leave, makes your code smaller, and avoids a deadlock if the synchronized code throws.</p>\n\n<p>Do something similar with everything that requires cleanup (like <code>mThreads = new HANDLE[mThreadCount];</code>).</p>\n\n<p><strike>The interface of your class should receive the tasks by reference and store them by pointer within. This way, you make it clear to client code that the class doesn't take ownership of the tasks it receives.</strike> (see <strong>Third Edit</strong> below).</p>\n\n<p>Use reinterpret_cast instead of C-style casts (because C-style casts = bad, mmmkay?!)</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>Don't do this. It greatly restricts what client code (whoever includes your class) can write, and the errors generated in client code are almost always obscure. You're better off repeating that in local scopes (if you must) or (better still) not using it (consider writing <code>using std::string;</code> and similar, in the scopes you use the type, or simply declaring <code>std::string x;</code>).</p>\n\n<p><strong>Edit:</strong> If <code>bool ThreadPool::ScheduleTask(Task* task)</code> never returns false, why does it return bool? Shouldn't it be <code>void</code>?</p>\n\n<p><strong>Second Edit</strong>: Consder using an unsigned int for the number of threads (<code>mThreadCount</code>).</p>\n\n<p><strong>Third edit</strong> ( <em>Hi Loki</em> :) )</p>\n\n<p>Regarding ownership of the threads and object lifetime management (how to implement safely and indicate it in the public interface of the class).</p>\n\n<p>Consider this client code:</p>\n\n<pre><code>ThreadPool runner();\n\n// bad bad code: don't call new with raw pointers like this in practice\n// but easy to write to make my point below.\nBackgroundTask *t = new BackgroundTask(); // class BackgroundTask: public Task\n // defined elsewhere\n\nrunner.ScheduleTask(t);\n</code></pre>\n\n<p>What you don't know looking at this code: should you delete <code>t</code> after the ThreadPool completes running? Will <code>runner</code> delete the task itself? If it does, <code>t</code> will point to deleted memory after <code>runner</code> finishes. If it doesn't, you will have to remember to check when runner has finished, and call delete explicitly, <em>every single time</em> you use the thread pool.</p>\n\n<p>You <em>could</em> implement the ThreadPool to <code>delete</code> all tasks after execution, but then, an enterprising programmer (maybe yourself) could write:</p>\n\n<pre><code>ThreadPool runner();\nBackgroundTask t();\nrunner.ScheduleTask(&t); // pass address of automatic storage object\n</code></pre>\n\n<p>and this will crash your program when your ThreadPool deletes the task.</p>\n\n<p>Another client code alternative, this one much much worse:</p>\n\n<pre><code>void crashy(ThreadPool& pool) {\n BackgroundTask t;\n pool.ScheduleTask(&t);\n} // t goes out of scope here and is destroyed but p still holds it's address\n\nThreadPool p;\ncrashy(p); // some compilers tend to happily accept this (maybe with a warning)\n// p now has a pointer to a deleted BackgroundTask instance\n</code></pre>\n\n<p>The interface doesn't indicate ownership and makes you interrupt your coding, to look at the implementation, just so you know how to write client code that doesn't leak or crash.</p>\n\n<p>Solutions:</p>\n\n<p>You could change your interface to take a <code>Task&</code> instead. (Similar to passing by pointer), the only drawback is that you need to make sure the tasks you pass to ScheduleTask must still be in scope until the ThreadPool stops running (in other words, you can still write the nice <code>crashy</code> function).</p>\n\n<p>This is better, as at least you don't need to wonder if it will delete the task (which passing by pointer may, or may not suggest).</p>\n\n<p>Better yet, change your interface to take a std::unique_ptr instead:</p>\n\n<pre><code>class ThreadPool\n{\npublic :\n bool ScheduleTask(std::unique_ptr<Task> task) // << std::unique_ptr by val.\n {\n EnterCriticalSection(&mCriticalSection);\n mTasks.push_back( std::move(task) ); // << notice std::move\n mNumberOfTasksNotFinished++;\n LeaveCriticalSection(&mCriticalSection); // also notice non-raii unlock;\n // if push_back throws on \n // allocating new list node,\n // your whole app is deadlocked\n\n WakeConditionVariable(&mConditionVariable);\n return true;\n }\n\nprivate :\n\n list<std::unique_ptr<Task>> mTasks; // << notice std::unique_ptr\n ... \n};\n</code></pre>\n\n<p>Client code:</p>\n\n<pre><code>ThreadPool runner();\nstd::unique_ptr<Task> p(new BackgroundTask());\nrunner.ScheduleTask(std::move(p)); // works, no lifetime management problems\n // and no ambguity either\n</code></pre>\n\n<p>Since the function takes a unique_ptr now, you now <em>know</em> you need to pass a pointer and you also know you are passing ownership as well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T17:41:26.540",
"Id": "68372",
"Score": "0",
"body": "http://stackoverflow.com/q/1452721/14065"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T17:42:08.403",
"Id": "68373",
"Score": "0",
"body": "Talk about ownership of the `task` in `ScheduleTask()` and why you should not be using RAW pointers then you will get my vote."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T11:39:47.943",
"Id": "68464",
"Score": "1",
"body": "+1: A nice alternative to `std::list<std::unique_ptr<Task>>` is `boost::ptr_list<Task>`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-02T14:33:23.990",
"Id": "68579",
"Score": "0",
"body": "is it a good idea to make a copy of task (like vector/list in std) instead of using unique_ptr ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-02T19:30:41.573",
"Id": "68612",
"Score": "0",
"body": "@OopsUser, it could work, but (keeping in mind that Task is the base of other classes) you would need to preserve polymorphic behavior, so you would probably need a `virtual Task* Task::clone()` or similar for creating the copy. It complicates the design and adds to the effort necessary to implement `Task` specializations (but maybe there are other reasons for that). All in all, unless there is a specific reason, I would keep the design with `std::unique_ptr`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T17:55:56.823",
"Id": "68761",
"Score": "0",
"body": "if i edited my thread pool according to the tips i received and i want to put it to review again, should i open a new question ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-01T06:53:30.263",
"Id": "105520",
"Score": "0",
"body": "This answer is a victim of **C++ vexing parse**. `ThreadPool runner();` is **not** an object declaration; it is a function declaration. Same problem is with `BackgroundTask t();`."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T14:30:14.327",
"Id": "40553",
"ParentId": "40536",
"Score": "7"
}
},
{
"body": "<p>Re. the comments to this question, I don't see (<a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms683469%28v=vs.85%29.aspx\" rel=\"nofollow\">in the Win32 API documentation</a>) any function required to delete a condition variable initialized using <code>InitializeConditionVariable</code>.</p>\n\n<p>But, all the thread handles which you created using <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms682453%28v=vs.85%29.aspx\" rel=\"nofollow\"><code>CreateThread</code></a> should be closed: by using a corresponding call to <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms724211%28v=vs.85%29.aspx\" rel=\"nofollow\"><code>CloseHandle(mThreads[i])</code></a> in your <code>ThreadPool::~ThreadPool()</code> destructor.</p>\n\n<hr>\n\n<p>One more thing: your <code>Task</code> class should probably have a defined destructor; see for example:</p>\n\n<blockquote>\n <p><a href=\"http://www.gotw.ca/publications/mill18.htm\" rel=\"nofollow\">Guideline #4: A base class destructor should be either public and virtual, or protected and nonvirtual.</a></p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T00:25:14.753",
"Id": "40587",
"ParentId": "40536",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "40553",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T11:57:02.297",
"Id": "40536",
"Score": "6",
"Tags": [
"c++",
"multithreading",
"thread-safety",
"synchronization",
"windows"
],
"Title": "Simple thread pool in C++"
}
|
40536
|
<p>My script, which is a web scraping script, is very slow, I even needed to put set_time_limit(0);</p>
<p>This is the whole <a href="http://phpfiddle.org/main/code/9qt-78n" rel="nofollow">http://phpfiddle.org/main/code/9qt-78n</a></p>
<p>I think the problem is here:</p>
<pre><code>foreach ($array_with_links as $url_job) {
$info=Array(getTitle($url_job, getID($url_job)), getTitle_Short($url_job, getID($url_job)), getCity($url_job),
getDepartment($url_job), getSalary($url_job), getJobNumber($url_job), getPositionStartDate($url_job), getFullTimeEquivalent($url_job),
getPermTermCasual($url_job), getLocation($url_job), getQualifications($url_job), getDuties($url_job),
getClosingDate($url_job), getContact($url_job), getEmail($url_job), getCreated_On($url_job), getID($url_job) );
array_push($data, $info);}
</code></pre>
<p>Example of some of those functions:</p>
<pre><code>function getCity($url)
{
$url = curl_get_contents($url);
$html_object = str_get_html($url);
return $ret = $html_object->find('td', 86)->plaintext;
}
function getDepartment($url)
{
$url = curl_get_contents($url);
$html_object = str_get_html($url);
return $ret = $html_object->find('td', 90)->plaintext;
}
</code></pre>
<p>And this is my cURL funtion:</p>
<pre><code>function curl_get_contents($url)
{
$curl_moteur = curl_init();
curl_setopt($curl_moteur, CURLOPT_URL, $url);
curl_setopt($curl_moteur, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_moteur,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
curl_setopt($curl_moteur, CURLOPT_FOLLOWLOCATION, 1);
$web = curl_exec($curl_moteur);
curl_close($curl_moteur);
return $web;
}
</code></pre>
<p>Those getX come from an URL one by one. Maybe is there any method to make multiple simultaneous insertions in that array?</p>
<p>I really don't know what to do and what's my mistake.</p>
|
[] |
[
{
"body": "<p>It seems that every one of your <code>getCity()</code>, <code>getDepartment()</code> etc functions loads the same web page over and over. </p>\n\n<p>You should load each URL once with your <code>curl_get_contents()</code>, then pass its result into each <code>get*()</code> function to parse it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T12:23:56.477",
"Id": "68304",
"Score": "0",
"body": "I believe you just hit the bullseye! Spot on! Nailed it!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T12:24:39.557",
"Id": "68306",
"Score": "0",
"body": "str_get_html is also called repeatedly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T12:32:09.983",
"Id": "68308",
"Score": "0",
"body": "that's it!!! so, how can I implement a cache system in order to extract all the information fields requesting each url just one time"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T14:17:55.447",
"Id": "68334",
"Score": "1",
"body": "@user204415 Invoke `curl_get_contents` and `str_get_html` only once at the start of your `foreach` loop, and pass `$html_object` instead of `$url` as the parameter to each of your `getXXX` functions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T15:41:44.950",
"Id": "68355",
"Score": "0",
"body": "@user204415 you are right sir."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T12:21:27.730",
"Id": "40539",
"ParentId": "40538",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "40539",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T12:10:25.190",
"Id": "40538",
"Score": "3",
"Tags": [
"php",
"performance",
"http",
"scrapy"
],
"Title": "Why is my web scraping script so slow?"
}
|
40538
|
<p>I have an array of items on which I have to perform 2 tasks:</p>
<ol>
<li>Applying a function on the array item</li>
<li>Checking if the value is true or false.</li>
</ol>
<p>The functional approach to solving this would be</p>
<pre><code>var result = arr.map(function(item){return some_action(item);}).filter(function(item){return other_action(item) == true;});
</code></pre>
<p>But here the array <code>arr</code> is traversed twice in comparison to </p>
<pre><code>var result = [];
arr.forEach(function(item){
var x = other_action(some_action(item));
if (x)
result.push(x);
});
</code></pre>
<p>Isn't the functional approach bad in this case or am I not using <code>map</code> and <code>filter</code> the right way?</p>
|
[] |
[
{
"body": "<p>Your “functional” approach is overly complicated. Notice that this is completely equivalent:</p>\n\n<pre><code>var result = arr.map(some_action).filter(other_action);\n</code></pre>\n\n<p>I.e. If you're only delegating to another function, you can specify that function directly. Also, an <code>== true</code> test is superfluous.</p>\n\n<p>Your “procedural” variant is not equivalent, that would have to be:</p>\n\n<pre><code>var result = [];\narr.forEach(function(item){\n var changedItem = some_action(item);\n if (other_action(changedItem))\n result.push(changedItem);\n});\n</code></pre>\n\n<p>Note that both variants have the same <em>algorithmic complexity</em>, and that the cost of iteration is likely negligible compared with the cost of <code>some_action</code> and <code>other_action</code>.</p>\n\n<p>Functional programming does not mean unreadable code. Even if you're not just delegating to another function, you could improve formatting, e.g. to</p>\n\n<pre><code>var result = arr.map(function (item) {\n return some_action(item);\n}).filter(function (item) {\n return other_action(item);\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T12:52:35.510",
"Id": "68312",
"Score": "0",
"body": "sorry i mistyped the procedural version"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T12:42:38.477",
"Id": "40544",
"ParentId": "40541",
"Score": "8"
}
},
{
"body": "<p>Your loops are not equivalent. In the first one <code>result</code> will be <code>arr</code> mapped with some action, while in the second you could do that just using a filter.</p>\n\n<p>The equivalent way of writing the <code>forEach</code> loop would be to use <code>result.push(some_action(item))</code>. Of course you would cache it as you use <code>some_action(item)</code> earlier in the function.</p>\n\n<p>The equivalent way of writing your <code>forEach</code> loop with just <code>filter</code> would be </p>\n\n<pre><code>arr.filter(function(item){return other_action(some_action(item));});\n</code></pre>\n\n<p>Also, as this is code review I would like to point out you can probably write</p>\n\n<pre><code>arr.map(function(item){return some_action(item);})\n</code></pre>\n\n<p>As</p>\n\n<pre><code>arr.map(some_action) //note this is not equivalent if some_action can take multiple params.\n</code></pre>\n\n<p>Anyway, you are correct in that calling these loop methods will take <code>O(n)</code> time per call and it's a good idea to apply filters first to limit <code>n</code>. If you're looking for an interesting read take a look at the <a href=\"http://danieltao.com/lazy.js/\" rel=\"nofollow\">Lazy.js documentation</a>.</p>\n\n<p><strong>Edit</strong>, just noticed, because you mention reduce, the way you'd write this with reduce is akin to you <code>forEach</code> way</p>\n\n<pre><code>arr.reduce(function(result, item){\n var item = other_action(some_action(item));\n if (item) result.push(item);\n return result;\n}, []);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T12:44:33.410",
"Id": "40545",
"ParentId": "40541",
"Score": "5"
}
},
{
"body": "<p>Don't do this: </p>\n\n<pre><code> var result = arr.map(function(item){\n var result=some_action(item);\n if(other_action(result)){ \n return result;\n }\n });\n</code></pre>\n\n<p>if other_action() return false, the item position in array will be undefined.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T04:17:30.133",
"Id": "68666",
"Score": "1",
"body": "When `other_action(result)` is falsy the mapped value will be undefined which is not desired. `$.map` will allow you to do that though"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T07:12:27.367",
"Id": "68680",
"Score": "0",
"body": "you are right. I am not aware of it. thanks."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T03:21:20.940",
"Id": "40713",
"ParentId": "40541",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T12:32:18.000",
"Id": "40541",
"Score": "3",
"Tags": [
"javascript",
"functional-programming"
],
"Title": "Better way to write this code in functional manner using map and reduce?"
}
|
40541
|
<p>I was assigned to make a Rational class to perform functions on fractions. After awhile I got it to work, but now I'm wondering how to simplify and clean up my code. Basically how to improve and use good Java practices so I can write better Java in the future.</p>
<pre><code>public class Rational {
private int numer, denom;
//constructors
public Rational(){
int num = 1;
int den = 2;
reduce();
}
public Rational(int num, int den){
numer = num;
denom = den;
reduce();
}
public Rational(Rational x){
numer = x.numer;
denom = x.denom;
reduce();
}
//setters
public void setNumer(int num){
numer = num;
reduce();
}
public void setDenom(int den){
denom = den;
reduce();
}
public void setRational(int num, int den){
numer = num;
denom = den;
reduce();
}
//getters
public int getNumer(){
return numer;
}
public int getDenom(){
return denom;
}
//Copy method
public void copyFrom(Rational x){
numer = x.numer;
denom = x.denom;
reduce();
}
//Equals method
public boolean equals(Rational x){
if (numer / denom == x.numer / x.denom){
return(true);
}
else {
return(false);
}
}
//Compare to method
public int compareTo(Rational x){
if (numer / denom == x.numer / x.denom){
return (0);
}
else if (numer / denom < x.numer / x.denom){
return (-1);
}
else{
return (1);
}
}
//Find greatest common divisor
static int gcd(int x, int y){
int r;
while (y != 0) {
r = x % y;
x = y;
y = r;
}
return x;
}
//Rational Addition
public void plus(Rational x){
int greatdenom = x.denom * denom;
int multx = greatdenom / x.denom;
int mult = greatdenom / denom;
denom = x.denom * denom;
numer = (x.numer * multx) + (numer * mult);
reduce();
}
//Rational Subtraction
public void minus(Rational x){
int greatdenom = x.denom * denom;
int multx = greatdenom / x.denom;
int mult = greatdenom / denom;
denom = x.denom * denom;
if (x.numer > numer){
numer = (x.numer * multx) - (numer * mult);
}
else {
numer = (numer * mult) - (x.numer * multx);
}
reduce();
}
//Multiplication
public void times(Rational x){
numer = numer * x.numer;
denom = denom * x.denom;
reduce();
}
//Division
public void divBy(Rational x){
numer = numer / x.numer;
denom = denom / x.denom;
reduce();
}
//Fraction simplifier
private void reduce(){
int divisor;
divisor = Rational.gcd(numer, denom);
numer = numer / divisor;
denom = denom / divisor;
}
@Override
public String toString(){
if (denom == 1){
return numer + "";
}
else{
return numer + " / " + denom;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T21:01:03.497",
"Id": "68398",
"Score": "4",
"body": "Default constructor should be `0/1` or non-existent. All constructors should prohibit `0` as the denominator value. This ensures that `Rational` forms an [field](http://en.wikipedia.org/wiki/Field_%28mathematics%29)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-01-10T10:06:00.593",
"Id": "287348",
"Score": "0",
"body": "I'm writing a similar rational number library for PHP. I found that Wikipedia's articles on rational numbers and fractions are both very useful when it comes to how to implement the various mathematical operations. You might want to look at those for ideas."
}
] |
[
{
"body": "<p>You can make all the other constructors call the 2-variable constructor. For example:</p>\n\n<pre><code>public Rational(int num, int den){\n numer = num;\n denom = den;\n reduce();\n}\npublic Rational(){this(1,2);}\npublic Rational(Rational r){this(r.numer,r.denom);} \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T14:50:30.077",
"Id": "40555",
"ParentId": "40554",
"Score": "7"
}
},
{
"body": "<p>Your indentation style is a mess, fix that first.</p>\n\n<p>Java normally uses a modified K&R style, like this:</p>\n\n<pre><code>function void style() {\n if (true) {\n // Code\n } else {\n // Code\n }\n}\n</code></pre>\n\n<hr>\n\n<p>You should totally use JavaDoc!</p>\n\n<hr>\n\n<pre><code>private int numer, denom;\n</code></pre>\n\n<p>Do not declare variables on the same line for clarity purposes. It's easy to overlook the declaration of a variable if they are declared on the same line.</p>\n\n<hr>\n\n<pre><code>public boolean equals(Rational x){\n</code></pre>\n\n<p>You should only overwrite <code>equals()</code> with a typed variant. <a href=\"https://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java\">Also, overriding <code>equals()</code> and doing it correctly is hard</a>.</p>\n\n<hr>\n\n<pre><code>public boolean equals(Rational x){\nif (numer / denom == x.numer / x.denom){\nreturn(true);\n }\nelse {\nreturn(false);\n }\n}\n</code></pre>\n\n<p>This can be shortened:</p>\n\n<pre><code>public boolean equals(Rational x) {\n return (numer / denom) == (x.numer / x.denom);\n}\n</code></pre>\n\n<hr>\n\n<pre><code>public int compareTo(Rational x){\n</code></pre>\n\n<p>You should <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html\" rel=\"nofollow noreferrer\">implement the Comparable interface if you create such a method</a>.</p>\n\n<hr>\n\n<p>All of your methods that accept a <code>Rational</code> do not handle the case if it is <code>null</code>.</p>\n\n<hr>\n\n<pre><code>@Override\n public String toString(){\n if (denom == 1){\n return numer + \"\";\n }\n else{\n return numer + \" / \" + denom;\n }\n</code></pre>\n\n<p>Never, ever for what ever reason is <code>int + \"\"</code> a valid way to cast an integer (or anything for that matter) to a String!</p>\n\n<pre><code>@Override\npublic String toString() {\n if (denom == 1) {\n return Integer.toString(numer);\n } else {\n return Integer.toString(numer) + \" / \" + Integer.ToString(denom);\n }\n}\n</code></pre>\n\n<p>Or use <code>String.format()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T16:39:32.340",
"Id": "68366",
"Score": "7",
"body": "Great comment! However, I do not agree with the function name : gcd is a perfectly fine function/method name for a module/class dealing with fraction. From a quick search : Java.math.BigInteger has it, the Python Fraction class has it, Perl 6 has it as a built-in... Also, having \"get\" in the name of a Math function is a bit awkward : cos() would be prefered over getCosinus() and so should gcd() over getGreatestCommonDivisior(). Again, I agree on everything else and find your comments relevant."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T14:59:25.277",
"Id": "68478",
"Score": "1",
"body": "@Josay +1, style guidelines are fine but sometimes you need to make some compromises to make the code readable (especially since `cos`, `gcd`, etc... are fairly standard). If someone doesn't know what `gcd` is he sure as hell isn't going to know what `greatest common divisor` is. Stop the madness!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T15:09:04.960",
"Id": "40557",
"ParentId": "40554",
"Score": "7"
}
},
{
"body": "<p>Right, there's two parts to this review:</p>\n\n<ol>\n<li>Is what you are doing 'good'?</li>\n<li>Is there a better way?</li>\n</ol>\n\n<p>The answer to the second question is 'yes', but we'll have to explore your current code to understand why....</p>\n\n<h2>Current code, is it good?</h2>\n\n<p>Your code, for the most part, is neat, well-named, and generally understandable. Great. But, there are some significant problems too:</p>\n\n<ul>\n<li><p>your 'default' constructor creates the Rational <code>1/2</code> .... why? What's special about that....? Remove it.</p></li>\n<li><p>It is better to have one 'core' constructor, and then have the other constructors call it.... :</p>\n\n<pre><code>public Rational(int num, int den){\n numer = num;\n denom = den;\n reduce();\n}\n\npublic Rational(Rational x){\n this(x.numer, x.demon);\n}\n</code></pre></li>\n<li><p>The <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals%28java.lang.Object%29\"><code>equals(...)</code></a> and <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode%28%29\"><code>hashCode()</code></a> contract. If you override one of <code>equals()</code> or <code>hashCode()</code> you should always also override the other.</p></li>\n<li><p>your equals() method is oddly broken because it should take an <code>Object</code> as an argument. You have a situation where you may compare two rationals in a context where Java will call the <code>equals(Rational)</code> in one situation, but in a different situation (if Java does not know that the value really is a Rational) it may call equals(Object)... and that may return false. This will lead to some interesting confusion..... hmmm.</p></li>\n<li><p>you implement the method <code>compareTo(Rational)</code> but your class does not implement the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html\">Comparable</a> interface. If you implement the Comparable interface you can do things like put your values in an array and then sort them using the native Java mechanisms, etc.</p></li>\n<li><p>your public interface methods should have comprehensive names, even if your variables do not: <code>setNumer(int)</code> and <code>setDemon(int)</code> should be <code>setNumerator(int)</code> and <code>setDenominator(int)</code> respectively. The same is true for the get* versions. Just because you were a bit lazy and used the auto-generated getter/setter mechanism in your IDE to create these methods, does not mean they are good names.</p></li>\n<li><p>you are not validating your denominator for division-by-zero.</p></li>\n<li><p>if your numerator is 0 you should have a special case for it.</p></li>\n<li><p>you should check for nulls for all input Rationals</p></li>\n</ul>\n\n<p>OK, that's enough about the style.... let's go through the bugs... ;-)</p>\n\n<ul>\n<li><p>you do integer division a lot, and you are getting wrong answers (note that this equals() method is broken for other reasons too):</p>\n\n<pre><code>public boolean equals(Rational x){\n if (numer / denom == x.numer / x.denom){\n return(true);\n } else {\n return(false);\n }\n}\n</code></pre>\n\n<p>This is broken, because, consider two Rationals <code>1/1</code> and <code>99/50</code> ... when you do your math, you are doing integer division, so both of them have the result <code>1</code>, and <code>1 == 1</code> so your code will declare that 1 == 1.5, which is only off by nearly 100%....</p>\n\n<p>This same type of logic is used in the compareTo() method.</p>\n\n<p>Since you <code>reduce()</code> your Rational after every operation, your equals method could be as simple as <code>return numer == x.numer && denom == x.denom;</code></p></li>\n</ul>\n\n<p>OK, that's enough about the general issues....</p>\n\n<h2>The better way.</h2>\n\n<p>Storing your Rational numbers is an important part of many programs. The underlying problem with your class is that it is Mutable. .... you can change the value of a Rational. This is unfortunate for a few reasons:</p>\n\n<ol>\n<li>you cannot use it as a Key in a <code>java.util.Map<Rational,...></code> because, if the value changes, it will break the internal hashing in the map.</li>\n<li>similarly, you cannot store these rationals in a <code>java.util.Set<Rational>()</code>.</li>\n<li>If you sort your data, the order will change if you change a Rational's value.</li>\n<li>The instances are not thread safe.</li>\n<li>serializing the instances is a problem.</li>\n</ol>\n\n<p>This problem is well understood, and <em>all</em> the Java number-type classes are Immutable (Integer, Long, Double, BigInteger, BigDecimal, ......).</p>\n\n<p><code>BigDecimal</code> is a really good example of what you should be doing here. Have a look at <a href=\"http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html\">it's Javadoc</a>. Notice how all the mathematical methods do not modify the <code>BigDecimal</code>, but return a new <code>BigDecimal</code> with the right value.</p>\n\n<p>Putting all of this together, your class should really look something like:</p>\n\n<pre><code>public final Rational implements Comparable<Rational> {\n\n private static final int getGCD(int a, int b) {\n .....\n return divisor;\n }\n\n private static final Rational checkRational(rat) {\n if (rational == null) {\n throw new NullPoiterException(\"Must supply a non-null Rational value\");\n }\n return rat;\n }\n\n private final int numer, denom;\n\n public Rational(int numerator, denominator) {\n if (denominator == 0) {\n throw new IllegalArgumentException(\"Denominator cannot be 0\");\n }\n // reduce the value at construct time....\n int div = numerator == 0 ? 1 : getGCD(numerator, denominator);\n // div is guaranteed to be a divisor, so integer division is safe\n this.numer = numerator/div;\n this.denom = numerator == 0 ? 1 : denominator/div;\n }\n\n public Rational(Rational other) {\n this(other.numer, other.denom);\n }\n\n @Override\n public int hashCode() {\n // somewhat convenient hashcode ... it's a bitwise trick...\n // could be improved...\n return numer * 31 ^ denom * 31;\n }\n\n @Override\n public boolean equals(Object other) {\n return other instanceof Rational\n && ((Rational)other).numer == numer\n && ((Rational)other).denom == denom;\n }\n\n @Override\n public int compareTo(Rational other) {\n checkRational(other);\n Rational difference = subtract(other);\n if (difference.numer > 0) {\n return 1;\n }\n if (difference.numer < 0) {\n return -1;\n }\n return 0;\n }\n\n // return a new instance instead of updating ourselves...\n public Rational add(Rational addend) {\n checkRational(other);\n return new Rational(addend.numer * denom + numer * other.denom, denom * other.denom);\n }\n\n\n ....... Lots more .....\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T18:05:22.147",
"Id": "68378",
"Score": "0",
"body": "What would you think of the idea of including `reducedNumerator` and `reducedDenominator` as fields, with the specification that those fields may only be written once, the first time a rational number is used in a fashion that requires reduction? When adding many fractions together, reducing each intermediate results will not only take time--it will in many cases increase the cost of the next addition."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T18:11:11.927",
"Id": "68379",
"Score": "0",
"body": "For example, adding 1/30 to 20/720 will be easier than adding it to 1/36, since in the former case a single division will reveal that multiplying the first fraction by 24/24 will allow it to be added to the second, whereas the latter would require much more work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T18:32:35.153",
"Id": "68383",
"Score": "0",
"body": "@supercat that would, in a multi-threaded environment, make it very complicated.... requiring synchronization which will slow down everything, even single-thread."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T18:41:58.887",
"Id": "68386",
"Score": "0",
"body": "If reduced numerator and reduced denominator can only be written once, I think the JVM would absolutely guarantee that any read would either yield a correct value or zero, would it not? A thread which sees zeroes instead of legitimate values might end up doing redundant work, but I think correctness would be maintained. Alternatively, if one wanted to allow for longer numeric types, one could have a field `reducedForm` of type `Rational`. A rational number that was in reduced form could set that field to `this`, and otherwise any code which computed a reduced form could set it to that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T18:46:02.893",
"Id": "68387",
"Score": "0",
"body": "I'm pretty certain taht if the fields which hold the numerator and denominator are `final`, regardless of how complicated they might be, any thread which saw that a reference had been stored to `reducedForm` would be guaranteed to see an instance where those fields were correctly written. Threading issues in that case would really be no different from `String#hashCode()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T18:47:20.580",
"Id": "68388",
"Score": "1",
"body": "@supercat without sync, there's no guarantee that both redN and redD would both be visible to the second thread at the same time... one may arrive before the other. It is broken without sync."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T18:55:23.917",
"Id": "68390",
"Score": "0",
"body": "If code assumes that it will need to reduce a fraction itself if `reducedDenominator` and `reducedNumerator` do not *both* read non-zero, what harm could occur beyond redundant work? I'm pretty certain that `if (reducedNumerator==0 || reducedDenominator==0) handleReduction();` decides not to call `handleReduction`, there's no way a subsequent statement *on that thread* could still read zero from `reducedNumerator` or `reducedDenominator`. Having `reducedForm` be a field of type `Rational` might be more flexible, but I don't see how `int` fields as described wouldn't be correct."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T19:04:16.763",
"Id": "68391",
"Score": "0",
"body": "What you are describing is similar to what `String.hashCode()` does... but, the differences are: there's two variables in Rational; *every* method in Rational will need to use the reduced value (or would be more efficient and less-likely to overflow) with the reduced value). I'm not saying it won't work, but it won't be worth it.... I don't think. It will need benchmarking to prove...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T19:55:43.440",
"Id": "68394",
"Score": "0",
"body": "How is adding 1/30 to 1/36 more efficient than adding 1/30 to e.g. 20/720? The result of adding a/b to c/d, when d divides b [with quotient m], is (am+c)/d. If am+c would risk overflow, one could divide m, c, and d by their greatest common divisor, but if not, why bother?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T19:58:53.700",
"Id": "68395",
"Score": "0",
"body": "I think *why bother* has been my point all along. This is adding a lot of complexity for something that may or may not solve time (lots of duplicate checks in every method...). Care to perform a benchmark to prove it one way or the other? I would not spend the time on it myself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T01:55:36.250",
"Id": "68426",
"Score": "3",
"body": "\"your 'default' constructor creates the Rational 1/2\" No it doesn't! It declares local variables `num` and `den`, assigns the values 1 and 2 to them and discards them, leaving the class's fields `numer` and `denom` uninitialized."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T09:00:53.387",
"Id": "68459",
"Score": "3",
"body": "@rolfl: In the `equals` method, it should be `==`, not `=` ?"
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T15:40:06.413",
"Id": "40561",
"ParentId": "40554",
"Score": "24"
}
},
{
"body": "<p>I am a mathematician who hasn't written a real line of code in a decade, and not a computer scientist, so please take what I say with huge grains of salt! Just thought you might think my perspective is interesting. </p>\n\n<ol>\n<li><p>Why are you reducing so often? It seems computationally expensive. Of course you will want to reduce when the user asks e.g. what is my fraction, but in the meantime you may wish just to store and compute with un-reduced fractions.</p></li>\n<li><p>It seems like your algorithm will handle negative fractions poorly, because when you run the Euclidean algorithm to reduce, it is random whether your numerator or denominator will wind up with the negative sign (unless I am confused). This won't cause mathematical errors, but it seems like sometimes you will tell the user his fraction is -3/5 and other times that it is 3/-5.</p></li>\n<li><p>In fact, does your code know that (-3/-5) = (3/5) ? (Well, it does, because you have defined equality this way, but will it sometimes tell the user that their fraction is -3/-5 and other times tell the user it is 3/5 ?)</p></li>\n<li><p>You define things by using the built-in division operation on integers. This seems a little circular mathematically (but may well be the right way to do things from a CS perspective) -- how do you define what 3 divided by 5 is if you don't already know what a rational number is? For instance, for your boolean equals, it seems more natural to use cross-multiplication and say </p>\n\n<pre><code>return (numer * x.denom) == (denom * x.numer)\n</code></pre>\n\n<p>as this is the standard definition of equality of rational numbers (and doesn't require things to be reduced, and appeals only to a statement working entirely in the class Int). Same complaint for when you compare fractions.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T17:57:28.203",
"Id": "68376",
"Score": "2",
"body": "Hey Hunter, and welcome to CodeReview.... Your logic and reasoning, as expected is right.... The excessive reducing is a good point , but even better is your negative fraction observations... That's a flaw I missed in my assessment. Learned something. The integer division is broken in the source. In computers, `(-3/-5)` == 0 (his computer math is buggy). The circular logic is because this is an exercise for the asker... but you would be right for a non-trivial implementation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T22:52:00.210",
"Id": "68412",
"Score": "1",
"body": "The language (Java, in this case) does have a concept of rational numbers (single-precision floating point `float` and double-precision `double` are the primitive types), however a computer's storage of rational numbers is imprecise; consider how to write out 1/3: you get a repeating decimal 0.333... The computer has the same problem (with different rationals, since they are base-2 instead of base-10), and in addition can't correctly store particularly small (~10^-324 for `double`) or large (~10^307) numbers... nor numbers with digits near them. `1+10^-325 == 1` as far as Java is concerned."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T22:54:56.237",
"Id": "68413",
"Score": "0",
"body": "The other issue is that the OP is using _integer_ division, rather than floating-point division. `3 / 4` is `0.75` mathematically, but Java will tell you it's `0`, since the integer will have all the decimal places simply chopped off. `3.0 / 4`, on the other hand (or `(double)3 / 4`), will correctly evaluate to `0.75`. That said, because of the imprecision of the floating-point format combined with base-2 data storage creating unexpected rounding errors, comparing the equality of rational numbers rarely works. Equality on the numerator and denominator is best."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T23:00:30.197",
"Id": "68414",
"Score": "0",
"body": "(Also: `numeratorA * denominatorB` won't give precision problems, since they're integers rather than rationals, so your #4 is a fine answer. It's possible for them to _overflow_ or _underflow_, but that would require one of them to be outside the range [-2147483648, 2147483647].)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T00:26:25.270",
"Id": "68419",
"Score": "0",
"body": "10 votes! Congratulations for your [badge:nice-answer]! Welcome to CR, hope you stick around! :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T17:44:37.483",
"Id": "40568",
"ParentId": "40554",
"Score": "15"
}
},
{
"body": "<p>Your are not handling overflow, and rational numbers can very easily get overflow, even when they don't get close to infinity. This code (assuming you have immutable rationals) approximates sqrt(2):</p>\n\n<pre><code> Rational r = two;\n for (int i=0; i < 5; ++i) {\n r = r.plus(two.divide(r)).divide(two);\n System.out.println(r);\n }\n</code></pre>\n\n<p>Even just 5 iterations and your ints get out of range. If your ints overflow, at the very least you should write (extremely complex) code to get an approximate answer, or (much better) use BigInteger for the numerator and denominator.</p>\n\n<p>With BigInteger, after five iterations you get</p>\n\n<pre><code> 886731088897/627013566048\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T09:06:57.530",
"Id": "40603",
"ParentId": "40554",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T14:38:00.307",
"Id": "40554",
"Score": "18",
"Tags": [
"java",
"classes"
],
"Title": "Rational number arithmetic"
}
|
40554
|
<p>I am using Java and COM4j to communicate with Word. The approach I used here is brute force. I have a password protected <code>.doc</code>, and I forgot its password.</p>
<p>Complexity is (26)<sup>(<code>maxPassLength</code>)</sup>. [a-z characters only]</p>
<p>Before I run this code and wait for 7-10 days here are my concerns.</p>
<p>My main concern is checking whether a generated string matches the password. Is there any alternative to this? Would you recommend threading to reduce the search space?</p>
<pre><code>import com4j.Variant;
import java.util.HashMap;
import javax.swing.JOptionPane;
import word.Documents;
import word.WdOpenFormat;
import word._Application;
import word._Document;
public class DocPasswordFinder {
public final static String filePath2 = "\\file\\abc.doc";
private static HashMap<Integer, Character> mapC;
private static final int passMaxLength;
public static _Application app;
public static Documents doc;
public static char[] arr;
static {
passMaxLength=9;
arr = new char[passMaxLength];
app = word.ClassFactory.createApplication();
doc = app.documents();
mapC=new HashMap<>();
for (int i = 0; i < 26; ++i) {
mapC.put(i, (char) ('a' + i));
}
}
public static void genPass(int start, int indx) {
if (indx == passMaxLength) {
String PASSWORD = String.valueOf(arr);
try {
doc.open2000(filePath, false, true, false, PASSWORD, "", false,
PASSWORD, "", WdOpenFormat.wdOpenFormatAuto, false, false);
JOptionPane.showMessageDialog(null, "FOUND: " + PASSWORD);
System.exit(0);
} catch (com4j.ComException ex) {
//continue;
}
} else {
if (indx < arr.length) {
for (int i = start; i < 26; ++i) {
arr[indx] = mapC.get(i);
genPass(start, indx + 1);
}
}
}
}
public static void main(String[] args) {
genPass(0, 0);
}
}
</code></pre>
<p><strong>EDIT</strong><br>
Bottleneck appears to be the <code>doc.open2000()</code> part.</p>
|
[] |
[
{
"body": "<blockquote>\n <p>Complexity is (26)<sup>(maxPassLength).</sup></p>\n</blockquote>\n\n<p>You know that the password is only lower-case alpha characters?</p>\n\n<blockquote>\n <p>Would you recommend threading to reduce the search space?</p>\n</blockquote>\n\n<p>It's possible that threads wouldn't help. The <code>doc.open2000</code> will be more expensive than anything else, and your communication with Word may (I don't know) be effectively single-threaded (i.e. talking to a single Word process/task).</p>\n\n<p>You might get better performance from a Word emulator which is designed to run on a server, e.g. from <a href=\"http://www.aspose.com/\" rel=\"nofollow\">http://www.aspose.com/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T15:46:34.103",
"Id": "68356",
"Score": "0",
"body": "Yes i do know that. Hence 26(lower case alpha characters) in `maxPassLength` positions (26^`maxPassLength`). It is supposed to work for my doc file."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T15:51:15.390",
"Id": "68359",
"Score": "0",
"body": "That sounds like 10^14 possible combinations. To do all those in 10 days you would need to do 2 x 10^7 per second."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T16:14:24.127",
"Id": "68364",
"Score": "2",
"body": "@boxed__l I can't answer that question and it's off-topic on this site. [You might find an answer here](http://superuser.com/search?q=word+password)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T15:18:55.210",
"Id": "68481",
"Score": "0",
"body": "@boxed__l Its behaviour is allegedly described here: http://www.password-crackers.com/crack/guaword.html I think that implies something like: a) Know Word document format well enough to extract encrypted password from the document; b) Know the (one-way) encryption algorithm; c) Use the PC's GPU (video card) to iterate-and-encrypt 2^40 possible password guesses to find a password which (when encrypted) will match the document's encrypted password."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T15:43:03.980",
"Id": "40562",
"ParentId": "40558",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "40562",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T15:09:17.443",
"Id": "40558",
"Score": "2",
"Tags": [
"java",
"performance",
"com"
],
"Title": "Find password to a word document"
}
|
40558
|
<p>I have a <code>Factory</code> class that gives out instances of <code>ResponseImpl</code> class. It accepts one <code>Destination</code> class and up to four <code>Source</code> classes. At least one of the four <code>Source</code> classes should be not <code>null</code>.</p>
<p>So, instead of asking calling program to pass <code>null</code>s in the arguments to <code>Factory</code> class, I have overloaded the method to accept at least one up to four <code>Source</code> classes. But, something tells me that this way of doing it is not a good idea. Although this works, I feel like this can be handled better.</p>
<p>Could you let me know how to make the following piece of code better?</p>
<pre><code>public static Response initResponse(final Destination destination, final Source1 source1) {
return initResponse(destination, source1, null, null, null);
}
public static Response initResponse(final Destination destination, final Source1 source1, final Source2 source2) {
return initResponse(destination, source1, source2, null, null);
}
public static Response initResponse(final Destination destination, final Source1 source1, final Source2 source2, final Source3 source3) {
return initResponse(destination, source1, source2, source3, null);
}
public static Response initResponse(final Destination destination, final Source1 source1, final Source2 source2, final Source3 source3, final Source4 source4) {
try {
if(source1 == null && source2 == null && source3 == null && source4 == null) {
throw new ABODataException("Atleast one source has to be not null");
}
return ResponseImplManager.getInstance(destination, source1, source2, source3, source4);
} catch (Exception e) {
throw new ABODataException("Unable to instantiate Response:"+e.getMessage());
}
}
</code></pre>
|
[] |
[
{
"body": "<p>It seems to me that you are not quite making good use of exceptions and as long as I believe it is possible that you are disrespecting some principles. First things first, you really should be using <code>IllegalArgumentException</code> because that is the java standard exception class for invalid arguments. You shouldn't also throw a exception and then catch it so your throw statement should be outside the try block. Why should you ever raise a error to treat it imeadiatly? You should avoid it instead!</p>\n\n<pre><code>public static Response initResponse(final Destination destination, final Source1 source1, final Source2 source2, final Source3 source3, final Source4 source4) {\n if(source1 == null && source2 == null && source3 == null && source4 == null) {\n throw new IllegalArgumentException (\"Atleast one source has to be not null\");\n }\n try {\n return ResponseImplManager.getInstance(destination, source1, source2, source3, source4);\n } catch (Exception e) {//if possible catch the specific type of the exception that is thrown by getInstance thought I don't see it as a huge issue as you don't have any other method calls\n throw new ABODataException(\"Unable to instantiate Response:\"+e.getMessage());\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T16:45:49.237",
"Id": "40564",
"ParentId": "40559",
"Score": "7"
}
},
{
"body": "<p>It's a bit problematic to refactor when the parameters are from four different types of classes. I have a couple of alternative approaches for you though, pick one if you like one.</p>\n\n<p>One option would be to make your classes <code>Source1</code>, <code>Source2</code>, etc. implement one common interface. Perhaps this would even simplify your <code>ResponseImplManager.getInstance</code>? If they would be of the same interface (or shared superclass would also be possible of course), then you could use a method like this:</p>\n\n<pre><code>public static Response initResponse(final Destination destination,\n final SourceInterface... sources) {\n // sources is treated as an array here\n}\n</code></pre>\n\n<p>Or you could send a list of sources</p>\n\n<pre><code>public static Response initResponse(final Destination destination,\n final List<SourceInterface> sources)\n</code></pre>\n\n<p>Another option would be to use a <a href=\"http://en.wikipedia.org/wiki/Builder_pattern\">Builder pattern</a></p>\n\n<p>Whichever way you go in, I got one more suggestion. Use the two-parameter constructor for Exceptions to provide \"Caused by\" information, this will give you a more detailed stack trace</p>\n\n<pre><code> } catch (Exception e) {\n throw new ABODataException(\"Unable to instantiate Response\", e);\n\n // or use this:\n throw new ABODataException(\"Unable to instantiate Response: \" + e.getMessage(), e);\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T17:09:32.633",
"Id": "68368",
"Score": "2",
"body": "I was going to add a edit about using variable arguments too but then I noticed that the classes were not the same and then reached the same conclusion as your. a big +1 for you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T20:55:36.173",
"Id": "68790",
"Score": "1",
"body": "Looks like using Builder pattern is the way to go. I didn't think about that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T20:57:06.070",
"Id": "68792",
"Score": "1",
"body": "@would_like_to_be_anon That's what you have us for, to think for you after you've done the initial thinking :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T17:06:41.683",
"Id": "40566",
"ParentId": "40559",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "40566",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T15:13:01.043",
"Id": "40559",
"Score": "10",
"Tags": [
"java",
"design-patterns"
],
"Title": "Handling null arguments in a factory class"
}
|
40559
|
<p>I am writing C++ code to enumerate the whole HDD and drive listing. However, it takes more than 15 minutes to complete the disk enumeration of all drives (HDD capacity of 500GB) and compile the response in a binary file.</p>
<p>However, I have a 3rd party executable which gives me the listing of the whole disk in just less than two minutes. Can you please look into my code and suggest some performance improvement techniques?</p>
<pre><code>EnumFiles(CString FolderPath, CString SearchParameter,WIN32_FIND_DATAW *FileInfoData)
{
CString SearchFile = FolderPath + SearchParameter;
CString FileName;
hFile = FindFirstFileW(SearchFile, FileInfoData); // \\?\C:\*
if (hFile == INVALID_HANDLE_VALUE)
{
// Error
}
else
{
do
{
FileName = FileInfoData->cFileName;
if (FileInfoData->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if (! (FileName == L"." || FileName == L".."))
{
// Save the Folder Information
EnumFiles(FolderPath + FileName +(L"\\"), SearchParameter,FileInfoData);
}
}
else
{
// Save the File Parameters
}
} while (FindNextFileW(hFile, FileInfoData));
}
FindClose(hFile);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T17:32:05.580",
"Id": "68369",
"Score": "3",
"body": "The difference between your code and the 3rd party app is they are not recursively scanning the directory structure. They will basically be running threw the directory tables on the disk and dumping the content. Yours is very random access into the disk and will incor lets of seek time. Theres is probably just a linear scan of a few hundred drive sectors (no extra seek time)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T18:12:52.157",
"Id": "68380",
"Score": "2",
"body": "Does the code extracted into and quoted in the question take a long time? Or does the code which takes a long time also include code to write output to the binary file?"
}
] |
[
{
"body": "<blockquote>\n <p><em>Can you please look into my code and suggest me some performance improvement techniques.</em></p>\n</blockquote>\n\n<p><strong>No -- it doesn't work like that.</strong> While there are some obvious things you may catch visually (like observing string comparisons at each iteration) every time you optimize you should start by profiling your execution, then isolating the parts that take the most time, then optimizing, then profiling again.</p>\n\n<p>For example, it's possible that optimizing in this case is not removing or changing something you \"do wrong\" but splitting your hard drive into chunks and parallelizing the effort.</p>\n\n<p>Either way, first, profile the execution and identify the worst offenders.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T02:21:09.800",
"Id": "68432",
"Score": "2",
"body": "Hi, please note whether this [type of] answer is acceptable or not as a CR answer [is being debated on meta](http://meta.codereview.stackexchange.com/questions/1491/must-answers-include-a-code-review)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T02:41:15.397",
"Id": "68437",
"Score": "2",
"body": "I think this answer may be off-topic, for the reasons I gave in [this answer on meta](http://meta.codereview.stackexchange.com/a/1492/34757): although it may be good advice and help the OP, it is not a code review."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T16:49:02.793",
"Id": "40565",
"ParentId": "40560",
"Score": "6"
}
},
{
"body": "<p>You don't show the code to \"compile the response in a binary file\" so we can't review that. Does your testing show that only the code shown in the OP, without the output, is slow?\nReviewing the code you showed ...</p>\n\n<hr>\n\n<p>I don't know a faster Windows API than <code>FindFirstFileW/FindFirstNextW</code>: my Googling found no asynchronous version of these APIs. However:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/11979961/49942\">Someone suggested that <code>IShellFolder::EnumObjects</code> might be faster</a>.</li>\n<li><a href=\"https://stackoverflow.com/a/15374130/49942\">Someone else suggested that DeviceIoControl() with FSCTL_ENUM_USN_DATA might be faster</a>\n-- and DeviceIoControl() is optionally an asynchronous API, so you can issue several of them at the same time (which <em>might</em> be faster)</li>\n</ul>\n\n<hr>\n\n<p>This is unnecessary (you're copying the filename into heap-allocated memory) ...</p>\n\n<pre><code>FileName = FileInfoData->cFileName;\n</code></pre>\n\n<p>... why not use the C-style cFileName string value directly? Reusing memory which already exists is probably faster than anything which allocates new memory buffers.</p>\n\n<hr>\n\n<p>This could be slightly faster ...</p>\n\n<pre><code>if (! (FileName == L\".\" || FileName == L\"..\"))\n</code></pre>\n\n<p>... because it's currently doing two whole-string comparisons; you could use something like this instead ...</p>\n\n<pre><code>if ((FileInfoData->cFileName[0] != L`.`)\n ? true // doesn't start with '.'\n : (FileInfoData->cFileName[1] == 0)\n ? false // is \".\"\n : (FileInfoData->cFileName[1] != L`.`)\n ? true // doesn't start with \"..\"\n : (FileInfoData->cFileName[2] != 0) // is not \"..\"\n )\n</code></pre>\n\n<hr>\n\n<p>I usually prefer pass-by-reference instead of pass-by-copying-the-value, for any type of class; so instead of ...</p>\n\n<pre><code>EnumFiles(CString FolderPath, CString SearchParameter,WIN32_FIND_DATAW *FileInfoData) {...}\n</code></pre>\n\n<p>... this instead ...</p>\n\n<pre><code>EnumFiles(const CString& FolderPath, const CString& SearchParameter,\n WIN32_FIND_DATAW *FileInfoData) {...}\n</code></pre>\n\n<p>Pass-by-value is likely to be copying string values from one object to another, or at least running code to share the value between two objects.</p>\n\n<p>Alternatively, all (recursive) instances of the EnumFiles function could share a <code>WCHAR filenameBuffer[MAX_FILENAME_LEN]</code> used for <code>FolderPath</code> and for <code>FolderPath + FileName +(L\"\\\\\")</code>, and passed between the recursive EnumFiles function instances as a non-const <code>WCHAR*</code> pointer or as a static private variable. That would avoid doing a heap operation (e.g. <code>malloc</code>) for each new filename.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T10:36:39.583",
"Id": "68462",
"Score": "0",
"body": "Regarding \"why no instead `FileName[0] != L'.'`\": You will now all of a sudden ignore directories starting with a dot."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T11:42:59.067",
"Id": "68465",
"Score": "0",
"body": "@ChrisWue Thank you, I had forgotten about those. I've edited the answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T22:02:26.283",
"Id": "40584",
"ParentId": "40560",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T15:24:22.757",
"Id": "40560",
"Score": "5",
"Tags": [
"c++",
"recursion",
"file-system",
"windows",
"winapi"
],
"Title": "Disk enumeration and file listing"
}
|
40560
|
<p>I have been making my own scoreboard, and needed a custom spectate function for it, so I made this:</p>
<pre><code> util.AddNetworkString( "spectatePlayer" )
local playerLocal
local isSpectating = false
net.Receive("spectatePlayer", function(length, client)
if isSpectating then return end
isSpectating = true
playerLocal = client
print(client:Nick() .. "Started spectating: " .. net.ReadEntity():Nick())
client:Spectate(5)
client:SpectateEntity(net.ReadEntity())
end)
hook.Add("Tick", "keydown", function()
if not isSpectating then return end
if (playerLocal:KeyDown(IN_FORWARD)) then
isSpectating = false
playerLocal:UnSpectate()
print(playerLocal:Nick().."Finished Spectating")
end
end)
</code></pre>
<p>Is there anything I could improve on? Am I over-complicating anything?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-02T23:21:59.770",
"Id": "174524",
"Score": "6",
"body": "Please add in what the custom behavior is -- just saying that it's custom isn't very specific."
}
] |
[
{
"body": "<p>There's a few things to comment on:</p>\n\n<hr>\n\n<p>I'm not a Gmod developer, so I'm not familiar with the spectating abilities built in, but, I'd assume that if any exist, they're probably better to use than re-inventing the wheel.</p>\n\n<hr>\n\n<p>There's only two states: not spectating, and spectating. What happens if I want to simply switch between players? Do I have to stop spectating, and then select a new player to spectate?</p>\n\n<p>Why can I not just press <kbd>lmb</kbd> and go to the next?</p>\n\n<hr>\n\n<blockquote>\n<pre><code>util.AddNetworkString( \"spectatePlayer\" )\n</code></pre>\n</blockquote>\n\n<p>You've got extraneous whitespace in your brackets.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>print(client:Nick() .. \"Started spectating: \" .. net.ReadEntity():Nick())\nprint(playerLocal:Nick()..\"Finished Spectating\")\n</code></pre>\n</blockquote>\n\n<p>String concatenation joins the strings, as they are. Meaning, it would read like:</p>\n\n<blockquote>\n <p>QuillStarted spectating: James Heald.<br>\n QuillFinished Spectating</p>\n</blockquote>\n\n<p>Add some whitespace in there.</p>\n\n<pre><code>print(client:Nick() .. \" Started spectating: \" .. net.ReadEntity():Nick())\nprint(playerLocal:Nick()..\" Finished Spectating\")\n</code></pre>\n\n<hr>\n\n<p>Oh, and you should be keeping the cases (upper and lower) consistent in your messages:</p>\n\n<blockquote>\n<pre><code>\"Started spectating: \"\n ^\n\"Finished Spectating\"\n ^\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-23T21:39:52.653",
"Id": "101742",
"ParentId": "40563",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T16:44:35.177",
"Id": "40563",
"Score": "10",
"Tags": [
"game",
"lua"
],
"Title": "Garry's Mod custom spectate player"
}
|
40563
|
<p>I wrote Conway's Game of Life in Python with Pyglet. It works pretty well but is very slow when the number of cells gets high. Any easier speedups I can attain with this code?</p>
<pre><code>import pyglet
import numpy
from itertools import cycle
from pyglet.window import key, mouse
window_width = 700
window_height = 700
cell_size = 10
cells_high = window_height / cell_size
cells_wide = window_width / cell_size
grid = numpy.zeros(dtype=int, shape=(cells_wide, cells_high))
working_grid = numpy.zeros(dtype=int, shape=(cells_wide, cells_high))
born = {3}
survives = {2, 3}
paused = False
window = pyglet.window.Window(window_width, window_height)
window.set_caption("Cellular Automaton")
@window.event
def on_draw():
window.clear()
color_cells()
draw_grid()
@window.event
def on_key_press(symbol, modifiers):
global paused
if symbol == key.ENTER:
paused = not paused
elif paused:
if symbol == key.I:
grid.fill(0)
elif symbol == key.O:
grid.fill(1)
elif symbol == key.P:
randomize_grid()
elif symbol == key.RIGHT:
update_grid()
@window.event
def on_mouse_press(x, y, button, modifiers):
if paused:
if button == mouse.LEFT:
grid[x/cell_size][y/cell_size] = 1
elif button == mouse.RIGHT:
grid[x/cell_size][y/cell_size] = 0
@window.event
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
if paused:
if 0 <= x / cell_size < cells_wide and 0 <= y / cell_size < cells_high:
if buttons == mouse.LEFT:
grid[x/cell_size][y/cell_size] = 1
elif buttons == mouse.RIGHT:
grid[x/cell_size][y/cell_size] = 0
def update(dt):
if not paused:
update_grid()
def draw_grid():
pyglet.gl.glColor4f(1.0, 1.0, 1.0, 1.0)
for i in range(0, window_width, cell_size):
pyglet.graphics.draw(2, pyglet.gl.GL_LINES, ('v2i', (i, 0, i, window_height)))
for i in range(0, window_height, cell_size):
pyglet.graphics.draw(2, pyglet.gl.GL_LINES, ('v2i', (0, i, window_width, i)))
def color_cells():
alive_color = color_iterator.next()
pyglet.gl.glColor4f(alive_color[0], alive_color[1], alive_color[2], alive_color[3])
for x in xrange(cells_wide):
for y in xrange(cells_high):
if grid[x][y]:
x1 = x * cell_size
y1 = y * cell_size
x2 = x1 + cell_size
y2 = y1 + cell_size
pyglet.graphics.draw(4, pyglet.gl.GL_QUADS, ('v2i', (x1, y1, x1, y2, x2, y2, x2, y1)))
def update_grid():
global grid
for x in xrange(cells_wide):
for y in xrange(cells_high):
n = get_neighbors(x, y)
if not grid[x][y]:
if n in born:
working_grid[x][y] = 1
else:
working_grid[x][y] = 0
else:
if n in survives:
working_grid[x][y] = 1
else:
working_grid[x][y] = 0
grid = numpy.copy(working_grid)
def get_neighbors(x, y):
n = 0
for i in range(-1, 2):
for j in range(-1, 2):
if i or j:
if 0 <= x + i < cells_wide and 0 <= y + j < cells_high:
n += grid[x + i][y + j]
return n
def randomize_grid():
for x in xrange(cells_wide):
for y in xrange(cells_high):
grid[x][y] = numpy.random.randint(0, 2)
def color_generator():
color = [1.0, 0, 0]
iterations = 50
increment = 1.0 / iterations
fill = True
for i in cycle((1, 0, 2)):
for n in xrange(iterations):
if fill:
color[i] += increment
else:
color[i] -= increment
color.append(1.0);
yield color
fill = not fill
if __name__ == "__main__":
randomize_grid()
color_iterator = color_generator()
pyglet.clock.schedule_interval(update, 1.0/15.0)
pyglet.app.run()
else:
exit()
</code></pre>
<p>And here it is on github: <a href="https://github.com/Igglyboo/Cellular-Automaton" rel="nofollow">https://github.com/Igglyboo/Cellular-Automaton</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T17:58:20.143",
"Id": "68377",
"Score": "2",
"body": "There are algorithmic speedups suggested on [Wikipedia](http://en.wikipedia.org/wiki/Conway's_Game_of_Life#Algorithms) and probably [on this site too](http://www.conwaylife.com/): for example, remember which cells or areas of the board aren't changing and don't recalculate those."
}
] |
[
{
"body": "<p>Here's a couple of ways to shorten the code, which may or may not involve perf gains but may make it easier to work with. I tested this with plain lists-of-lists instead of numpy.arrays but I think it should work the same way. I used itertools.product to get rid of the nested loops and used sum() to avoid another loop. </p>\n\n<p><strong>get neighbors</strong> will be called for every cell, and it's going to loop and iterate mamy times. You can get the same result by summing the rows of a subset:</p>\n\n<pre><code>import itertools\n\ndef get_neighbors (x, y, cells_wide, cells_high, grid):\n cols = range(x-1, x + 2)\n rows = range(y-1, y +2 )\n cells = sum (grid[r % (cells_high - 1)][c % (cells_wide - 1)] for r, c in itertools.product(cols, rows))\n return cells - grid[x][y] # don't count ourselves\n</code></pre>\n\n<p><strong>update grid</strong> is creating a copy of the working grid You could try to collect the list of born and survived cells and only update changes:</p>\n\n<pre><code> def update_grid(cells_wide, cells_high, grid, born =[3], survives = [2,3]):\n cols = range(cells_wide)\n rows = range(cells_high)\n changes = []\n for r, c in itertools.product(rows,cols):\n condition = get_neighbors(r, c, cells_wide, cells_high, grid)\n if condition in born:\n changes.append ( ((r, c), 1) ) # it's ok to overwrite if we're alive\n else: \n if not condition in survives:\n changes.append( ((r,c), 0) )\n for address, value in changes:\n grid[address[0]][address[1]] = value\n return grid\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T04:16:44.190",
"Id": "68451",
"Score": "0",
"body": "OMG thank you so much I can't believe I didn't think of just summing all the neighbors, I knew it seemed way too complex."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T21:46:40.123",
"Id": "40580",
"ParentId": "40567",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T17:36:02.393",
"Id": "40567",
"Score": "4",
"Tags": [
"python",
"performance",
"game-of-life",
"opengl",
"pyglet"
],
"Title": "Speedups for Conway's Game of Life"
}
|
40567
|
<p>I'd like you to review my attempt at creating an authorization class and let me know if there is re-factoring to be done and/or how I can make the code cleaner and abide by the MVC structure. </p>
<p><strong>UsersController.php</strong></p>
<pre><code><?php
class UsersController extends BaseController {
protected $user;
public function __construct(User $user)
{
$this->beforeFilter('csrf', array('on' => 'post'));
$this->user = $user;
}
public function getRegister()
{
return View::make('admin.register');
}
public function postRegister()
{
try
{
$this->user->insertUserIntoDatabase(Input::all());
}
catch (ValidationError $e)
{
return Redirect::to('admin/register')
->with('message', 'Something went wrong')
->withInput()
->withErrors($e->getErrors());
}
return Redirect::to('admin/login')
->with('message', 'Thank you for creating a new account');
}
public function getLogin()
{
return View::make('admin.login');
}
public function postLogin()
{
if (Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password') ))){
return Redirect::to('admin/dashboard')->with('message', 'Thanks for logging in');
}
return Redirect::to('admin/login')->with('message', 'Your email/password combo failed.');
}
public function getLogout()
{
Auth::logout();
return Redirect::to('admin/login')->with('message', 'You have been logged out.');
}
public function getDashboard()
{
return View::make('admin/dashboard');
}
}
</code></pre>
<p><strong>Users.php (Model)</strong></p>
<pre><code><?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password');
protected $fillable = array('firstname', 'lastname', 'email');
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* @return string
*/
public function getReminderEmail()
{
return $this->email;
}
public function insertUserIntoDatabase($input)
{
$validation = new Services\Validators\Users;
if ($validation->passes()) {
$user = new User;
$user->firstname = Input::get('firstname');
$user->lastname = Input::get('lastname');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->save();
}
else {
$this->errors = $validation->errors;
throw new ValidationError($validation->errors);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I didn't used PHP in the last few years, so just some generic notes:</p>\n\n<ol>\n<li><p>The <code>$input</code> parameter of <code>insertUserIntoDatabase($input)</code> is unused. I guess you wanted to use the parameter instead of direct <code>Input::</code> calls inside the function.</p></li>\n<li><p>You could use a <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow noreferrer\">guard clause</a> in <code>insertUserIntoDatabase</code> to make the code flatten:</p>\n\n<pre><code>public function insertUserIntoDatabase($input)\n{\n $validation = new Services\\Validators\\Users;\n\n if (!$validation->passes()) {\n $this->errors = $validation->errors;\n throw new ValidationError($validation->errors);\n }\n\n $user = new User;\n $user->firstname = Input::get('firstname');\n $user->lastname = Input::get('lastname');\n $user->email = Input::get('email');\n $user->password = Hash::make(Input::get('password'));\n $user->save();\n}\n</code></pre></li>\n<li><p>The fields in the User class are <code>protected</code>. You might want to use <code>private</code> instead. See: <a href=\"https://stackoverflow.com/q/5484845/843804\">Should I always use the private access modifier for class fields?</a>; <em>Item 13</em> of <em>Effective Java 2nd Edition</em>: <em>Minimize the accessibility of classes and members</em>.</p></li>\n<li><p>In <code>postRegister()</code> you could move the return inside the try block. I guess <code>Redirect::to</code> doesn't throw any <code>ValidationError</code> exceptions, so the following is the same:</p>\n\n<pre><code>public function postRegister()\n{\n try \n {\n $this->user->insertUserIntoDatabase(Input::all());\n return Redirect::to('admin/login')\n ->with('message', 'Thank you for creating a new account');\n } \n catch (ValidationError $e) \n {\n return Redirect::to('admin/register')\n ->with('message', 'Something went wrong')\n ->withInput() \n ->withErrors($e->getErrors());\n }\n}\n</code></pre></li>\n<li><pre><code>if (Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password') ))){\n return Redirect::to('admin/dashboard')->with('message', 'Thanks for logging in');\n}\n</code></pre>\n\n<p>I would create an explanatory local variable for the array for better readability:</p>\n\n<pre><code>$credentials = array(\n 'email' => Input::get('email'), \n 'password' => Input::get('password') \n);\nif (Auth::attempt($credentials)) {\n return Redirect::to('admin/dashboard')->with('message', 'Thanks for logging in');\n}\n</code></pre>\n\n<p>(<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G19: Use Explanatory Variables</em>; <em>Refactoring: Improving the Design of Existing Code by Martin Fowler</em>, <em>Introduce Explaining Variable</em>)</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-27T23:46:35.380",
"Id": "136314",
"Score": "0",
"body": "I think that your guard clause logic might be reversed. It appears to be saying, \"If validation passes, then throw an error\". Should it be, if(!$validation->passes()) ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-28T00:19:30.950",
"Id": "136319",
"Score": "0",
"body": "@clone45: Yes, you're right, it should be that. Thanks, I've fixed it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-22T13:21:33.740",
"Id": "45083",
"ParentId": "40571",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "45083",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T19:24:44.200",
"Id": "40571",
"Score": "4",
"Tags": [
"php",
"mvc",
"laravel"
],
"Title": "Laravel 4 clean code review of users controller and model, trying to maintain MVC structure"
}
|
40571
|
<p>Okay, so just having a little fun I thought I'd see if I could write an algorithm to find all of the prime factors of a number. The solution I came up with is as follows:</p>
<pre><code>class Program
{
static void Main(string[] args)
{
var subject = long.MaxValue;
var factors = new List<long>();
var maxFactor = 0;
Console.WriteLine("Factoring {0} ...", subject);
var sw = new Stopwatch();
sw.Start();
while (subject > 1)
{
var nextFactor = 2;
if (subject % nextFactor > 0)
{
nextFactor = 3;
do
{
if (subject % nextFactor == 0)
{
break;
}
nextFactor += 2;
} while (nextFactor < subject);
}
subject /= nextFactor;
factors.Add(nextFactor);
if (nextFactor > maxFactor)
{
maxFactor = nextFactor;
}
}
sw.Stop();
var factorAnswer = 1L;
factors.ForEach(f => factorAnswer *= f);
Console.WriteLine("Factors: {0} = {1}",
string.Join(" * ",
factors.Select(i => i.ToString()).ToArray()),
factorAnswer);
Console.WriteLine("Max Factor: {0}", maxFactor);
Console.WriteLine("Elapsed Time: {0}ms", sw.ElapsedMilliseconds);
}
}
</code></pre>
<p>and its output is:</p>
<pre><code>Factoring 9223372036854775807 ...
Factors: 7 * 7 * 73 * 127 * 337 * 92737 * 649657 = 9223372036854775807
Max Factor: 649657
Elapsed Time: 3ms
</code></pre>
<p>It works, and IMO awfully fast, but it's a little brute force. Is there a better way of doing it?</p>
|
[] |
[
{
"body": "<p><strong>Other algorithms</strong></p>\n\n<p>Wikipedia has an article which lists other <a href=\"http://en.wikipedia.org/wiki/Integer_factorization#Factoring_algorithms\">Factoring algorithms</a>.</p>\n\n<hr>\n\n<p><strong>Your algorithm</strong></p>\n\n<p>Re. your algorithm, I see you're checking all odd numbers, which includes non-prime numbers such as 9.</p>\n\n<p>Your sieve would be faster if you only checked prime numbers, for example by using a list like <a href=\"http://primes.utm.edu/lists/small/10000.txt\">this one</a> or <a href=\"http://www.bigprimes.net/\">this one</a>.</p>\n\n<p>Furthermore you're checking all the way to subject. Your last time through the loop would be faster if you give up as soon as nextFactor > sqrt(subject).</p>\n\n<hr>\n\n<p><strong>Your C# code</strong></p>\n\n<p>As for your C# code:</p>\n\n<ul>\n<li>What type is <code>nextFactor</code> when you declare it as <code>var nextFactor = 2;</code>? I fear that it might be <code>int</code> not <code>long</code>.</li>\n<li>Your code might be very slightly faster if you used the <code>Capacity</code> property of <code>List</code>.</li>\n<li>There's something very strange (and slow) about your loop: after you find a nextFactor value such as 7, then you begin your search from 2 again! You code would be faster if you moved your <code>long nextFactor = 2;</code> initialization to do it only once, before/outside the <code>while</code> loop, and changed your <code>nextFactor = 3;</code> statement to <code>nextFactor += (nextFactor == 2) ? 1 : 2;</code>. You could then also eliminate your <code>maxFactor</code> variable, because the largest factor value would be left/stored in <code>nextValue</code> after you exit the <code>while</code> loop.</li>\n<li>It might be better to use <a href=\"http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx\">System.Numerics.BigInteger</a> instead of <code>long</code> (because <code>long.MaxValue</code> is only about 10^18, whereas some people want to factorize larger numbers than that).</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T21:15:18.447",
"Id": "68399",
"Score": "0",
"body": "What do you mean by that `Capacity` remark? I don't see how would it help here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T21:16:58.140",
"Id": "68401",
"Score": "0",
"body": "Just that `factors.Add` might be ever-so-slightly slower if List has to reallocate internal memory instead of having enough Capacity from the moment it's constructed?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T21:19:31.323",
"Id": "68402",
"Score": "0",
"body": "And how do you know how much `Capacity` is enough? Or do you mean to always assume the worst (and for example unnecessarily allocate large list if the number is a prime)? In any case, this doesn't matter here, as long as the list is less than hundreds of elements or so."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T21:24:20.140",
"Id": "68404",
"Score": "0",
"body": "@svick I'm guessing that List.Add is the single most expensive statement in the loop; and that setting a sensibly large Capacity once [would be faster than allowing it to grow](http://stackoverflow.com/questions/1762817/default-capacity-of-list)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T00:40:44.967",
"Id": "68421",
"Score": "1",
"body": "For the example 2^63-1, that Add was executed 7 times, while nextFactor += 2 something like 300 000 times. I think the Add won't measurably affect the overall performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T00:45:00.720",
"Id": "68423",
"Score": "1",
"body": "@svick I don't think it's very important either; I'm just trying to be thorough. The behaviour would be different if the `subject` were exactly 2^62 ... Add would be executed 62 times and might dominate the performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-01T05:46:33.290",
"Id": "68453",
"Score": "1",
"body": "For 32-bit integers there really isn't anything much faster than just brute-forcing all primes under 65536. For 64-bit integers you might gain some performance by doing a quick sieve for these factors and then using Fermat's or Pollard's p - 1 to weed out the larger ones. Up to 256-300 bits the Rho algorithm (cycle finding) is probably optimal. After that you should pull out the big guns with ECM, QS, NFS, ... and eventually you are screwed because there is no known polynomial-time general purpose factoring algorithm. But implementing these is a great exercise!"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T19:54:37.993",
"Id": "40573",
"ParentId": "40572",
"Score": "11"
}
},
{
"body": "<h1>Code</h1>\n<p>Your code seems fine.</p>\n<p>Like <a href=\"https://codereview.stackexchange.com/a/40573/7773\">@ChrisW</a> highlighted, take care about types. Your variables <code>nextFactor</code> and <code>maxFactor</code> are actually integers.</p>\n<p>Also, <code>string.Join</code> can take objects - it will call ToString() internally. You can convert <code>string.Join(" * ", factors.Select(i => i.ToString()).ToArray())</code> to <code>string.Join(" * ", factors)</code></p>\n<h1>Algorithm</h1>\n<p>I suggest 2 improvements to the algorithm.</p>\n<h2>You are re-iterating values that you already discarded as not being factors.</h2>\n<p>If 2 is not a factor of <code>subject</code> on the first iteration, it will never be. So when you find a new factor X, on the next iteration you can continue looking for factors from X upwards - instead of re-checking the already-discarded values [2..X].</p>\n<h2>You only need to check until <code>nextFactor*nextFactor>subject</code></h2>\n<p>And then the last factor is actually <code>subject</code> itself. :)<br />\nRight now, you check until <code>nextFactor==subject</code> (thus next iteration <code>subject==1</code>).</p>\n<h3>Explanation:</h3>\n<p>if subject is e.g. 21 and nextFactor is 11... since no number smaller than 11 is a factor, then all its factors are bigger or equal to 11.</p>\n<ul>\n<li>If subject has <strong>one</strong> factor, that factor must be the <code>subject</code> itself (21);</li>\n<li>If it has more than one, and because its factors are at least as big as 11, then <code>21>=X*Y</code>, <code>X>=11</code>, and <code>Y>=11</code>.<br />\n(X being the next factor, and Y being the next subject.)</li>\n</ul>\n<p>So, in the case where <code>nextFactor*nextFactor > subject</code>, you know that the last factor has to be subject itself, and you can terminate processing earlier.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T20:02:39.543",
"Id": "40575",
"ParentId": "40572",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T19:34:39.780",
"Id": "40572",
"Score": "9",
"Tags": [
"c#",
"algorithm",
"primes"
],
"Title": "Finding prime factors of a number?"
}
|
40572
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.