body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I'm working on the <a href="http://projecteuler.net/problem=3" rel="nofollow">third Euler problem</a> and I've written a simple little function that returns the list of <em>prime</em> factors of a given number.</p>
<p>The number for which I have to get all the factors is over 6 billion, so building this huge freakin list of numbers in memory struck me as wonky. </p>
<p><strike>I decided I'd build a <code>factor</code> function that generates output by the chunk and spits it out so that I can write it to a text file chunk by chunk. A <code>buffered_factor</code> function:</strike></p>
<p>Ok, I've decided that doing the 'buffered' thing isn't needful. The computation is just going to take a while, and making my <code>factor</code> function a generator will keep my program light in memory.</p>
<p>I'm looking for best practices and practical advice about (what I think is describable as) buffering the output of a function.</p>
<p>Here's the prime sieve:</p>
<pre><code>def is_prime(n):
if n == 1:
return False
if n == 2:
return True
for i in range(2, int(math.ciel(math.sqrt(n))):
if n % i:
return False
return True
</code></pre>
<p>And the factoratorizer:</p>
<pre><code>def factor(num):
"""Get factors of given number.
:param num: get us them there factors o this number here
:type num: integer
:param chunk_size: number of operations to work through before crapping out a list
:rtype: list of factors
:raises: ValueError on num < 1
"""
if num < 1:
raise ValueError('Given %s. Numbers >= 1, please' % num)
for i in (n + 1 for n in xrange(num)):
if num % i == 0:
if is_prime(i):
yield i
</code></pre>
<p>I'm trying to use it thusly:</p>
<pre><code>import os
from factor import factor
TARGET = 600851475143
OUTFILE = 'factors.txt'
with open(OUTFILE, 'w') as f:
for output in buffered_factor(TARGET):
f.write(str(output))
f.flush()
</code></pre>
<p><strike>Nothing's being written to file, so obviously I'm doing something wrong.</strike> </p>
|
[] |
[
{
"body": "<p>Some advice about maths and algorithms which will be useful for this problem and for future problems:</p>\n\n<ul>\n<li><p>You are interested in <strong>prime</strong> factors.</p></li>\n<li><p>You don't care about the non-biggest factors (you might go through them but there is not much point in storing them).</p></li>\n<li><p>If a number <code>n</code> can be decomposed in <code>n = m*p</code> then at least one of <code>m</code> and <code>p</code> is smaller than <code>sqrt(n)</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T00:22:28.583",
"Id": "50855",
"Score": "0",
"body": "my math is crap, so i'm trying to figure out how to use that last hint you gave me. bear with me. -_-;"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T00:48:56.383",
"Id": "50857",
"Score": "0",
"body": "ok, now i get it. http://mathforum.org/library/drmath/view/56001.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-12T21:54:28.760",
"Id": "191118",
"Score": "0",
"body": "... at least one of m and p is less than or equal to sqrt (n). Example: 121 = 11 x 11."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T21:00:05.697",
"Id": "31709",
"ParentId": "31661",
"Score": "2"
}
},
{
"body": "<p>You've changed the question several times. To be clear, I'm reviewing <a href=\"https://codereview.stackexchange.com/revisions/31661/6\">revision 6</a>.</p>\n\n<p>Be careful not to introduce bugs when revising your code. You're still calling <code>buffered_factor(TARGET)</code> when you have changed the function name to <code>factor()</code>. Also, the optional <code>chunk_size</code> parameter is no longer being used, but you haven't removed it.</p>\n\n<p>There is a lot of duplication between your <code>is_prime()</code> and <code>factor()</code> functions, which is not surprising, since they do similar things. Checking for primality is going to drastically hurt performance — it's like starting to factor the result all over again. So, let's just decide that your <code>is_prime()</code> function needs to be eliminated. You have to rewrite <code>factor()</code> such that once it yields a factor, you eliminate all of its multiples from consideration. (Hint: You know that <code>num % i == 0</code> — now modify <code>num</code>.)</p>\n\n<p>The only even prime number is 2. Use that fact to modify your <code>xrange()</code> to halve your work. Also, your <code>n + 1</code> is weird, and should be eliminated by using <code>xrange()</code> correctly.</p>\n\n<p>Why do you want to remove your output file before <code>open</code>ing it? It would be simpler to truncate it automatically if necessary with <code>open(..., 'w')</code>. (Note that truncation is not the same as removing and re-creating, when it comes to preserving the file's creation time and extended attributes (on systems that keep track of such things), the behaviour when you don't have write access to the containing directory, the effect on existing open filehandles, and the effect of existing open filehandles on the removal. However, I doubt that you care about any of those considerations for this exercise.) Better yet, for greater flexibility, just print your results to standard output and let your shell command redirect the output to wherever you wish.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T18:52:17.637",
"Id": "50951",
"Score": "0",
"body": "you've given me a lot to chew on. thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T17:50:56.850",
"Id": "31909",
"ParentId": "31661",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "31909",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T00:08:14.950",
"Id": "31661",
"Score": "3",
"Tags": [
"python",
"programming-challenge",
"primes",
"io"
],
"Title": "Attempting to efficiently compute the largest prime factor"
}
|
31661
|
<p>I want you to pick my code apart and give me some feedback on how I could make it better or simpler. For a full tree (all nodes with 0 or 2 children) it works deterministically:</p>
<pre><code>public class Construct {
private TreeNode root;
private static class TreeNode {
TreeNode left;
TreeNode right;
int item;
public TreeNode(TreeNode left, TreeNode right, int item) {
this.left = left;
this.right = right;
this.item = item;
}
}
public void treeFromPreOrderAndInorder(int[] pre, int[] inorder) {
if (pre == null || inorder == null) {
throw new IllegalArgumentException("Your tree is not accurate");
}
if (pre.length != inorder.length) {
throw new IllegalArgumentException("Your tree is not accurate");
}
// should this be overloaded + testing.
root = treeFromPreOrderAndInorder(pre, 0, inorder, 0, inorder.length - 1);
}
/**
* Private functions are not overloaded.
* Check binary0.
*/
private TreeNode treeFromPreOrderAndInorder(int[] pre, int pos, int[] inorder, int lb, int hb) {
if (lb > hb) return null;
// step 1: fetch parent
int parent = pre[pos];
// step 2: fetch position
int parentPosInorder;
for (parentPosInorder = lb; parentPosInorder <= hb; parentPosInorder++) {
if (inorder[parentPosInorder] == parent) {
break;
}
}
if (parentPosInorder > hb) {
throw new IllegalArgumentException("Your tree is not accurate");
}
// proof in diagram : https://bitbucket.org/ameyapatil/pointstonote/commits/a3137e1e5c9f40f28c53b9c62e27f0e8bf81a000
int numElemsInLeftSubTree = parentPosInorder - lb;
/**
* Basically absolutely same as construct Balanced BST from sorted array
* with this extra junk to be added.
*/
int leftParentPosPre = pos + 1;
// proof in diagram : https://bitbucket.org/ameyapatil/pointstonote/commits/458d044f96226e8df1c47775dbe3c8c5ad9ecce4
int rightParentPosPre = pos + numElemsInLeftSubTree + 1;
// step 3: recurse
TreeNode node = new TreeNode(null, null, parent);
node.left = treeFromPreOrderAndInorder(pre, leftParentPosPre, inorder, lb, parentPosInorder - 1);
node.right = treeFromPreOrderAndInorder(pre, rightParentPosPre, inorder, parentPosInorder + 1, hb);
return node;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T18:36:56.820",
"Id": "50580",
"Score": "0",
"body": "Is the tree reconstruction necessarily deterministic? If the inorder array is `[8, 8, 8, 8]` and the preorder array is also `[8, 8, 8, 8]`, then what should the result look like?"
}
] |
[
{
"body": "<p>The algorithm looks good to me. Regarding the code, here are a few points:</p>\n\n<ol>\n<li>You don't need to overload the function. Semantically it's a tree builder, and probably the <code>private</code> function can be termed as <code>buildTree</code>.</li>\n<li><p>The following condition should throw the <code>IllegalStateException</code> instead of <code>IllegalArgumentException</code>:</p>\n\n<pre><code>if (parentPosInorder > hb) {\n throw new IllegalArgumentException(\"Your tree is not accurate\");\n}\n</code></pre></li>\n<li><p>You can make the code generic by using a generic data type for the node value. Accordingly, the API will be extensible enough.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-12T10:57:41.217",
"Id": "39084",
"ParentId": "31664",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T00:55:33.080",
"Id": "31664",
"Score": "1",
"Tags": [
"java",
"algorithm",
"recursion",
"tree"
],
"Title": "Construct a tree given pre and inorder or post and inorder"
}
|
31664
|
<p>I wrote a small program which shows all possible permutations of choosing <em>m</em> integers from the set \${1, 2, ..., n}\$, as follows:</p>
<pre><code>def perm(nlist, m):
"""
Find all possible permutations of choosing m integers from a len(n)-list.
INPUT:
@para nlist: a list of length n.
@para m: a integer.
OUTPUT:
All permutations arranged in ascending order lexicographically.
"""
if m > len(nlist):
return
if m == 0 or m == len(nlist):
return [[]]
results = []
for list_i in nlist:
temp = list(nlist)
temp.remove(list_i)
results.extend(map(lambda x: [list_i] + x, perm(temp, m-1)))
return results
</code></pre>
<p>However, this code is inefficient. Perhaps the recursive structure is not well-designed. How can I improve this code?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T02:40:59.590",
"Id": "50528",
"Score": "0",
"body": "If `m == len(nlist)` then shouldn't it return `[nlist]` instead of `[[]]`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T03:15:19.437",
"Id": "50531",
"Score": "0",
"body": "@200_success Return `[nlist]` does not work in this recursive structure, which is to select the first element of a list recursively until empty."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T03:52:07.387",
"Id": "50532",
"Score": "1",
"body": "`m == len(nlist)` is simply not a base case; it should flow through for normal handling. (It should return neither `[[]]` nor `[nlist]` — both are wrong.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T09:13:32.837",
"Id": "50542",
"Score": "4",
"body": "@fishiwhj Python standard library has a function for permutations. It's worth using instead of homebrew one unless you are studying programming/algorithms: http://docs.python.org/2/library/itertools.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T09:23:57.193",
"Id": "50543",
"Score": "0",
"body": "@RomanSusi Thanks! Maybe I can read the source code of the permutation function in Python standard library."
}
] |
[
{
"body": "<p>As noted by 200_success in the comments, the <code>m == len(nlist)</code> check is a bug that can be fixed by simply removing the condition.</p>\n\n<p>Also, <code>if m > len(nlist): return</code> is almost redundant because you would get an empty list as the result anyway in that case. (The deepest levels of recursion give empty results when the list runs out and the emptiness propagates all the way up)</p>\n\n<p>Turning the function into a generator simplifies it and speeds it up at the same time: from 10.9 ms to 6.6 ms for the case <code>perm(range(6), 6)</code>. (Of course I wrapped that in <code>list()</code> when timing the generator version)</p>\n\n<pre><code>def perm(nlist, m):\n if m == 0:\n yield []\n return\n\n for list_i in nlist:\n temp = list(nlist) \n temp.remove(list_i)\n for p in perm(temp, m-1):\n yield [list_i] + p\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T20:28:53.780",
"Id": "35778",
"ParentId": "31665",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "35778",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T01:42:09.743",
"Id": "31665",
"Score": "4",
"Tags": [
"python",
"combinatorics"
],
"Title": "Showing all possible permutations from a set"
}
|
31665
|
<p>This is my first program in java. I am wondering if there would be a better way to tackle this. I am only allowed to use one class. It's not quite finished, but I am thinking it doesn't look very elegant.</p>
<pre><code>import java.io.*;
public class CarHire
{
public static void main(String[] args) throws IOException
{
BufferedReader stdin = new BufferedReader(new InputStreamReader (System.in));
//customer details
System.out.println("Input customer's name: ");
String name = stdin.readLine();
System.out.println("Input customer's address: ");
String address = stdin.readLine();
System.out.println("Input customer's telephone: ");
String telephone = stdin.readLine();
System.out.println("Input customer's licence: ");
String licence = stdin.readLine();
System.out.println("Input customer's credit card number: ");
String creditCard = stdin.readLine();
System.out.println("Input customer's credit card expiry date: ");
String cardExpiry = stdin.readLine();
//days booked for hire
System.out.println("Input number of days for hire: ");
int daysBooked = Integer.parseInt (stdin.readLine());
//car details
System.out.println("Input make/model: ");
String makeModel = stdin.readLine();
System.out.println("Input registration number: ");
String regNumber = stdin.readLine();
System.out.printf("%-20s %n %-40s %n","Select a car size:", "Small (S), Medium (M) or Large (L):");
String carSize = stdin.readLine();
//daily hire rate
double dailyRate;
if (carSize.equalsIgnoreCase("S") == true)
{
dailyRate=80;
}
else if (carSize.equalsIgnoreCase("M") == true)
{
dailyRate=110;
}
else
{
dailyRate=140;
}
//Calculate stage 1 hire
double basicHire = dailyRate*daysBooked;
System.out.printf("%-20s %15s %.2f %n %n", "Basic Hire is:", "$", basicHire);
System.out.println("Number of days hired:");
int daysHired = Integer.parseInt(stdin.readLine());
int lateDays = daysHired - daysBooked;
double lateFee = 0;
if (lateDays >0)
{
lateFee = dailyRate * 2 * lateDays;
}
//my test line
double subTotal = basicHire + lateFee;
System.out.printf("%-15s %8.2f %n %-15s %8.2f %n %-15s %8.2f %n",
"Basic Hire: $", basicHire, "Late Fee: $", lateFee,
"Subtotal: $", subTotal );
String damage = null;
String infringement = null;
double repairCost = 0;
double fines = 0;
double repairCostTotal = 0;
double finesTotal = 0;
System.out.printf("%-30s %n %-30s %n %-30s %n","Damage? D", "Infringements? F", "Exit? X");
String userInput = stdin.readLine();
while (!userInput.equalsIgnoreCase("X"))
if (userInput.equalsIgnoreCase("D"))
{
System.out.println("Damage description:");
damage = stdin.readLine();
System.out.println("Repair Costs:");
repairCost = Double.parseDouble(stdin.readLine());
}
else if (userInput.equalsIgnoreCase("F"))
{
System.out.println("Infringement type:");
infringement = stdin.readLine();
System.out.println("Fine:");
fines = Double.parseDouble(stdin.readLine());
}
else if (!userInput.equalsIgnoreCase("X")==true)
{
System.out.printf("%-30s %n %-30s %n %-30s %n %-30s %n",
"Enter a valid option:", "Damage? D", "Infringements? F", "Exit? X");
}
double finalHire = lateFee + basicHire + repairCostTotal + finesTotal
}
}
</code></pre>
<p>We have been told not to worry about data validation; with the exception of the enter D,F or X. And to use printf to format. It's an exercise to see if we can grasp the basics of java, using strings and nothing too fancy. We have been instructed which datatypes to use, for which variables.
So it is one of those restrictive programs, where there may be a better way to do it, that doesn't conform to what we have been asked. Nevertheless, I'm still keen to hear ideas. ty</p>
|
[] |
[
{
"body": "<ol>\n<li><p>Given the constraints, your code looks mostly good. Ideally I would collect the user input in a loop instead of repating code for each entry. This may be out of scope for you at this point.</p></li>\n<li><p>Your usage of <code>printf</code> is a bit contrived; again, it may be OK as practice.</p></li>\n<li><p>One thing I'd definitely not leave is this line:</p>\n\n<pre><code>while (!userInput.equalsIgnoreCase(\"X\"))\n</code></pre>\n\n<p>Its subordinate clause is one huge if-else cascade: you should surround it with braces to make that clearer.</p></li>\n<li><p>Still on the while-loop: you must involve <code>userInput=stdin.readLine()</code> within the loop. As you have it now, you read the command from the user only once, so it will be either an endless loop or never executed. The most convenient way could be a <code>while (true)</code>, then print the prompt, read it, and have another <code>else if</code> for the <code>X</code> case, which does a <code>break</code>.</p></li>\n<li><p>Remove <code>==true</code> from <code>!userInput.equalsIgnoreCase(\"X\")==true</code>. This just confuses the logic.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T11:57:13.487",
"Id": "50555",
"Score": "1",
"body": "In fact, you'll need to change the logic with that while-loop because at the moment you never reassign to `userInput`. You must involve `userInput = stdin.readLine();` as a part of the loop. I'll add some more text to the answer..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T12:01:51.973",
"Id": "50557",
"Score": "0",
"body": "Love your edit.. yes.. I knew there was something unhappy in my while.. and yes. already got rid of the ==true.. man tysm I appreciate it.. you wouldn't have a do while? As it needs to loop through it at least once anyway"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T12:24:51.350",
"Id": "50558",
"Score": "1",
"body": "You have nothing useful to put into the `while` condition because the decision to break out happens in the middle of loop code: after printing the prompt, but before the logic specific to each choice. The choice between `do-while(true)` and `while(true)` is arbitrary, but the latter is more obvious and concise."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T11:52:56.420",
"Id": "31682",
"ParentId": "31666",
"Score": "2"
}
},
{
"body": "<p>Since you can only use this one class, the key to having better, more beautiful code is to encapsulate logic in reusable and well-named methods. Below is a modified version of the code which follows some basic design principles, which I will explain piece by piece. Also, you have a lot of variables that you declare and never use, but I left them there under the assumption that they were going to be used in a future release.</p>\n\n<pre><code>import java.util.Scanner;\n\npublic class CarHire {\n\n private static final Scanner STDIN = new Scanner(System.in);\n\n public static void main(String[] args) {\n\n //Customer Details\n String name = getInput(\"customer's name\");\n String address = getInput(\"customer's address\");\n String telephone = getInput(\"customer's telephone\");\n String license = getInput(\"customer's license\");\n String creditCard = getInput(\"customer's credit card number\");\n String cardExpiry = getInput(\"customer's credit card expiry date\");\n\n //Days Booked for Hire\n int daysBooked = getIntegerInput(\"number of days for hire\");\n\n //Car Details\n String makeModel = getInput(\"make/model\");\n String regNumber = getInput(\"registration number\");\n String carSize = getInput(\"car size\");\n\n //Daily Hire Rate\n int dailyRate = 0;\n if(carSize.equalsIgnoreCase(\"s\")) {\n dailyRate = 80;\n }\n else if(carSize.equalsIgnoreCase(\"m\")) {\n dailyRate = 110;\n }\n else if(carSize.equalsIgnoreCase(\"l\")) {\n dailyRate = 140;\n }\n else {\n //TODO - what will you do if this is invalid?\n }\n\n //Calculate Stage 1 Hire\n int basicHire = dailyRate * daysBooked;\n System.out.println(\"Basic Hire is: \" + basicHire);\n\n int daysHired = getIntegerInput(\"number of days hired\");\n\n int lateDays = daysHired - daysBooked;\n int lateFee = lateDays > 0 ? (2 * dailyRate * lateDays) : 0;\n\n //My Test Line\n int subTotal = basicHire + lateFee;\n\n double finalHire = processFinalHire(basicHire, lateFee);\n\n System.out.println(\"Final hire: \" + finalHire);\n }\n\n private static double processFinalHire(double basicHire, double lateFee) {\n\n String input = \"\";\n\n String damage, infringement;\n double repairTotal = 0.0;\n double finesTotal = 0.0;\n\n while(!input.equalsIgnoreCase(\"x\")) {\n input = getInput(\"(Damage = D, Infringements = F, Exit = X\");\n if(input.equalsIgnoreCase(\"d\")) {\n damage = getInput(\"damage description\");\n repairTotal += getDoubleInput(\"repair costs\");\n }\n else if(input.equalsIgnoreCase(\"f\")) {\n infringement = getInput(\"infringement type\");\n finesTotal += getDoubleInput(\"fine\");\n }\n else if(!input.equalsIgnoreCase(\"x\")) {\n System.out.println(\"Please enter a valid option.\");\n }\n }\n\n return lateFee + basicHire + repairTotal + finesTotal;\n }\n\n private static String getInput(String prompt) {\n System.out.print(\"Input \" + prompt + \": \");\n return STDIN.nextLine().trim();\n }\n\n private static int getIntegerInput(String prompt) {\n Integer returnValue = null;\n while(returnValue == null) {\n System.out.print(\"Input \" + prompt + \": \");\n try {\n returnValue = Integer.parseInt(STDIN.nextLine().trim());\n }\n catch(NumberFormatException nfe) {\n System.out.println(\"Please input a valid integer.\");\n }\n }\n return returnValue;\n }\n\n private static double getDoubleInput(String prompt) {\n Double returnValue = null;\n while(returnValue == null) {\n String input = getInput(prompt);\n try {\n returnValue = Double.parseDouble(input);\n }\n catch(NumberFormatException nfe) {\n System.out.println(\"Please input a valid decimal.\");\n }\n }\n return returnValue;\n }\n\n}\n</code></pre>\n\n<p>So let's walk through it!</p>\n\n<pre><code>private static final Scanner STDIN = new Scanner(System.in);\n</code></pre>\n\n<p>I changed your <code>BufferedReader</code> to a <code>Scanner</code> in order to avoid your having to handle <code>IOException</code>s in its initialization (or ignore them by having that ugly <code>throws IOException</code> clause on your <code>main</code> method, haha). This is just an easier API to use at this level. I've also moved it to be a <code>private static final</code> field for the entire <code>CarHire</code> class. This will allow it to be referenced from all of the methods we create from here on out.</p>\n\n<pre><code>//Customer Details\nString name = getInput(\"customer's name\");\nString address = getInput(\"customer's address\");\nString telephone = getInput(\"customer's telephone\");\nString license = getInput(\"customer's license\");\nString creditCard = getInput(\"customer's credit card number\");\nString cardExpiry = getInput(\"customer's credit card expiry date\");\n</code></pre>\n\n<p>Notice how much cleaner this is than having the constant pairs of <code>System.out.println()</code> and <code>stdin.readLine()</code>? It's because any processing which is repeated over and over can usually be encapsulated in its own method. This makes your code more readable and reusable. Let's skip down to the <code>getInput()</code> method to see what that means.</p>\n\n<pre><code>private static String getInput(String prompt) {\n System.out.print(\"Input \" + prompt + \": \");\n return STDIN.nextLine().trim();\n}\n</code></pre>\n\n<p>This method will print your input prompt and then wait for the user to hit enter/return on STDIN, then return whatever was typed. I've added a <code>.trim()</code> call on the result for convenience and cleaner input. (To see why that's relevant, consider what happens if your user types in \"s \" for your <code>carSize</code> variable.) I also changed the <code>println()</code> to be <code>print()</code>, just because I think it's a more beautiful command-line interface when the prompt is on the same line as where the user types. Of course, that's very subjective and completely up to you.</p>\n\n<pre><code>//Days Booked for Hire\nint daysBooked = getIntegerInput(\"number of days for hire\");\n</code></pre>\n\n<p>Same thing here. Since we're going to be getting multiple integers from the user, we may as well encapsulate the processing.</p>\n\n<pre><code>private static int getIntegerInput(String prompt) {\n Integer returnValue = null;\n while(returnValue == null) {\n String input = getInput(prompt);\n try {\n returnValue = Integer.parseInt(input);\n }\n catch(NumberFormatException nfe) {\n System.out.println(\"Please input a valid integer.\");\n }\n }\n return returnValue;\n}\n</code></pre>\n\n<p>So this method is a little more complicated because I've added input validation to it. We want to make sure the user actually inputs an integer, otherwise our program will crash, right? This method may be a little more advanced than where you're at, so you can just skip over all of this if you want to ignore it. But it's a good reference point for when you start to learn it later.</p>\n\n<p>Step-by-step through this method...</p>\n\n<pre><code>Integer returnValue = null;\n</code></pre>\n\n<p>You might wonder why I'm using an <code>Integer</code> here instead of an <code>int</code>, and how that could possibly work with the rest of the code (since I explicitly declare that I'm returning an <code>int</code> in the method signature). Java has a handy little feature called <a href=\"http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html\" rel=\"nofollow\">autoboxing</a> which lets you switch pretty much at will between the <a href=\"http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html\" rel=\"nofollow\">primitive data type</a> and its associated object wrapper. In this example, an <code>int</code> is associated with the <code>Integer</code> object, so when I <code>return returnValue</code> (where <code>returnValue</code> is an <code>Integer</code> object), it will automatically be converted to an <code>int</code> to the caller since that's what I've declared as the return type.</p>\n\n<p>Why would I bother going through all this hassle and trickery? It's a good question. The reason is that a primitive type can't be <code>null</code>. An <code>int</code> defaults to <code>0</code>. I want to have something good to check for in my <code>while</code> condition, and I can't really check against an <code>int</code> appropriately, since anything an <code>int</code> can hold is... well... a valid <code>int</code>! By doing it this way, I always know that I haven't gotten valid input by checking that one variable, rather than setting a dummy (possibly valid) value like <code>-1</code> or making another needless <code>boolean</code>.</p>\n\n<pre><code>try {\n returnValue = Integer.parseInt(input);\n}\ncatch(NumberFormatException nfe) {\n System.out.println(\"Please input a valid integer.\");\n}\n</code></pre>\n\n<p>This <code>try</code>/<code>catch</code> construction allows us to do some basic <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html\" rel=\"nofollow\">exception handling</a>. Basically what's happening here is that <code>Integer.parseInt(input)</code> will try to force the <code>String input</code> into an <code>int</code>, which will then get autoboxed into our <code>Integer</code> variable. If <code>input</code> <em>can't</em> be parsed as an <code>int</code> (i.e., if it's not a valid integer), then the <code>Integer.parseInt()</code> call will throw a <code>NumberFormatException</code>. This will be immediately caught in our <code>catch</code> block, at which point we simply print the error message to the user and continue execution as normal. Because we are still within our <code>while</code> loop, we will keep doing this until the user enters a valid integer.</p>\n\n<pre><code>int lateFee = lateDays > 0 ? (2 * dailyRate * lateDays) : 0;\n</code></pre>\n\n<p>This is a small modification which I just thought prettied up the code a little bit. It just uses the <a href=\"http://en.wikipedia.org/wiki/%3F%3a#Java\" rel=\"nofollow\">ternary operator</a> to shorten all the variable declaration and if/else assignments into one line.</p>\n\n<p>I think everything else pretty much follows what I've already said, so that's about it! Let me know if you have any questions about the code.</p>\n\n<hr>\n\n<p>Below is another version which is a bit more advanced because it uses an <a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html\" rel=\"nofollow\">enum</a>, <a href=\"http://docs.oracle.com/javase/tutorial/reflect/\" rel=\"nofollow\">Reflection</a>, and <a href=\"http://docs.oracle.com/javase/tutorial/java/generics/\" rel=\"nofollow\">Generics</a>. I like this because it makes getting a valid car size from the user and retrieving a <code>dailyRate</code> from it much cleaner and ties all the data together nicely. It also prevents me from having to make <code>getIntegerInput()</code>, <code>getDoubleInput()</code>, <code>getLongInput()</code>... etc., etc. It may be a bit over-engineered for this particular example, but it was fun to make. Figuring it all out is left as an exercise to the reader. :)</p>\n\n<pre><code>import java.lang.reflect.Method;\nimport java.util.Scanner;\n\npublic class CarHire {\n\n private static final Scanner STDIN = new Scanner(System.in);\n\n private enum CarSize {\n SMALL (\"S\", 80),\n MEDIUM (\"M\", 110),\n LARGE (\"L\", 140);\n\n private final String inputOption;\n private final int dailyRate;\n\n private CarSize(String inputOption, int dailyRate) {\n this.inputOption = inputOption;\n this.dailyRate = dailyRate;\n }\n\n public int getDailyRate() {\n return dailyRate;\n }\n\n public static CarSize fromString(String input) {\n for(CarSize size : values()) {\n if(input.equalsIgnoreCase(size.inputOption)) {\n return size;\n }\n }\n return null;\n }\n }\n\n public static void main(String[] args) {\n\n //Customer Details\n String name = getInput(\"customer's name\");\n String address = getInput(\"customer's address\");\n String telephone = getInput(\"customer's telephone\");\n String license = getInput(\"customer's license\");\n String creditCard = getInput(\"customer's credit card number\");\n String cardExpiry = getInput(\"customer's credit card expiry date\");\n\n //Days Booked for Hire\n int daysBooked = getNumericInput(\"number of days for hire\", Integer.class);\n\n //Car Details\n String makeModel = getInput(\"make/model\");\n String regNumber = getInput(\"registration number\");\n CarSize carSize = getCarSize();\n\n //Daily Hire Rate\n int dailyRate = carSize.getDailyRate();\n\n //Calculate Stage 1 Hire\n int basicHire = dailyRate * daysBooked;\n System.out.println(\"Basic Hire is: \" + basicHire);\n\n int daysHired = getNumericInput(\"number of days hired\", Integer.class);\n\n int lateDays = daysHired - daysBooked;\n int lateFee = lateDays > 0 ? (2 * dailyRate * lateDays) : 0;\n\n //My Test Line\n int subTotal = basicHire + lateFee;\n\n double finalHire = processFinalHire(basicHire, lateFee);\n\n System.out.println(\"Final hire: \" + finalHire);\n }\n\n private static double processFinalHire(double basicHire, double lateFee) {\n\n String input = \"\";\n\n String damage, infringement;\n double repairTotal = 0.0;\n double finesTotal = 0.0;\n\n while(!input.equalsIgnoreCase(\"x\")) {\n input = getInput(\"(Damage = D, Infringements = F, Exit = X\");\n if(input.equalsIgnoreCase(\"d\")) {\n damage = getInput(\"damage description\");\n repairTotal += getNumericInput(\"repair costs\", Double.class);\n }\n else if(input.equalsIgnoreCase(\"f\")) {\n infringement = getInput(\"infringement type\");\n finesTotal += getNumericInput(\"fine\", Double.class);\n }\n else if(!input.equalsIgnoreCase(\"x\")) {\n System.out.println(\"Please enter a valid option.\");\n }\n }\n\n return lateFee + basicHire + repairTotal + finesTotal;\n }\n\n private static String getInput(String prompt) {\n System.out.print(\"Input \" + prompt + \": \");\n return STDIN.nextLine().trim();\n }\n\n private static CarSize getCarSize() {\n CarSize returnValue = null;\n while(returnValue == null) {\n returnValue = CarSize.fromString(getInput(\"car size (Small = S, Medium = M, Large = L)\"));\n }\n return returnValue;\n }\n\n private static <T> T getNumericInput(String prompt, Class<T> numberType) {\n\n T returnValue = null;\n Method valueOf = null;\n\n if(!Number.class.isAssignableFrom(numberType)) {\n throw new IllegalArgumentException(\"Type must be a subclass of Number\");\n }\n else {\n try {\n valueOf = numberType.getMethod(\"valueOf\", String.class);\n }\n catch (SecurityException e) {\n throw e;\n }\n catch (NoSuchMethodException e) {\n throw new IllegalArgumentException(\"Number type must support valueOf(String)\");\n }\n }\n\n while(returnValue == null) {\n try {\n returnValue = numberType.cast(valueOf.invoke(null, getInput(prompt)));\n }\n catch(Exception e) {\n System.out.println(\"Please input a valid number.\");\n }\n }\n\n return returnValue;\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T16:48:51.287",
"Id": "50570",
"Score": "2",
"body": "@ThinksALot Sure thing! :) Good luck with your class. Don't let them hold you back from learning too much, haha."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T08:25:50.543",
"Id": "50619",
"Score": "2",
"body": "I like this answer. I would just suggest `switch (Character.toLowerCase(input.charAt(0)))` to make it obvious that all of the chained `if`s have something in common."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T13:02:10.247",
"Id": "50629",
"Score": "0",
"body": "@200_success Yeah, I thought of that, but that's why in the advanced version I just went with the `enum`. :) Makes it much cleaner, in my opinion, since the `dailyRate` is directly tied to the `CarSize`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T15:30:49.970",
"Id": "31691",
"ParentId": "31666",
"Score": "4"
}
},
{
"body": "<p>I am posting my code (as per the requirements for the assignment, which was very specific re; data validation, methods and packages used).</p>\n\n<p>I ended up using a <code>do while loop</code>. My logic behind this, was that it has to be run at least once to end the program. I've also fixed the formatting.</p>\n\n<p>I was only allowed to concatenate my strings; rather than use arrays or lists. </p>\n\n<pre><code>import java.io.*;\n\npublic class CarHire\n{\n public static void main(String[] args) throws IOException\n {\n\n BufferedReader stdin = new BufferedReader(new InputStreamReader (System.in));\n\n //customer details \n System.out.print(\"Input customer's name: \");\n String name = stdin.readLine();\n\n System.out.print(\"Input customer's address: \");\n String address = stdin.readLine();\n\n System.out.print(\"Input customer's telephone: \");\n String telephone = stdin.readLine();\n\n System.out.print(\"Input customer's licence: \");\n String licence = stdin.readLine();\n\n System.out.print(\"\\n\" + \"Input customer's credit card number: \");\n String creditCard = stdin.readLine();\n\n System.out.print(\"Input customer's credit card expiry date: \");\n String cardExpiry = stdin.readLine();\n\n //days booked for hire\n System.out.print(\"\\n\" + \"Input number of days for hire: \");\n int daysBooked = Integer.parseInt (stdin.readLine());\n\n //car details\n System.out.print(\"Input make/model: \");\n String makeModel = stdin.readLine();\n\n System.out.print(\"Input registration number: \");\n String regNumber = stdin.readLine();\n\n System.out.print(\"\\n\" + \"Select a car size: Small (S), Medium (M) or Large (L):\");\n String carSize = stdin.readLine();\n\n //STAGE 2\n //daily hire rate\n double dailyRate;\n\n if (carSize.equalsIgnoreCase(\"S\"))\n {\n dailyRate=80;\n }\n else if (carSize.equalsIgnoreCase(\"M\"))\n {\n dailyRate=110;\n }\n else\n {\n dailyRate=140;\n }\n\n //Calculate stage 1 hire (basic hire)\n double basicHire = dailyRate * daysBooked;\n\n System.out.print(\"Number of days hired:\");\n int daysHired = Integer.parseInt(stdin.readLine());\n\n\n //Calculate hire (with late fee)\n int lateDays = daysHired - daysBooked;\n double lateFee = 0.00;\n\n if (lateDays > 0)\n {\n lateFee = dailyRate * 2 * lateDays;\n }\n\n //my test line\n double subTotal = basicHire + lateFee;\n\n String userInput, damages, infringements; \n String damageSummary = \"\";\n String fineSummary = \"\";\n double repairs = 0;\n double fines = 0;\n double repairTotal = 0;\n double fineTotal = 0;\n double hireTotal = 0;\n\n do\n {\n System.out.print(\"\\n\" + \"Damage and infringement inventory:\" + \"\\n\" + \n \"Damage: D\" + \"\\n\" + \"Infringements: F\" + \"\\n\" + \"Exit: X\" + \"\\n\" +\n \"Enter Selection:\");\n userInput = stdin.readLine();\n if (userInput.equalsIgnoreCase(\"D\"))\n {\n System.out.println(\"Damage description:\" );\n damages = stdin.readLine();\n\n System.out.println(\"Repair Costs:\");\n repairs = Double.parseDouble(stdin.readLine());\n\n damageSummary = damageSummary + \"\\n\" + damages + \" $\" + repairs;\n\n repairTotal = repairTotal + repairs;\n }\n else if (userInput.equalsIgnoreCase(\"F\"))\n { \n System.out.println(\"Infringement type:\");\n infringements = stdin.readLine();\n\n System.out.println(\"Fine:\");\n fines = Double.parseDouble(stdin.readLine());\n\n fineSummary = fineSummary + \"\\n\" + infringements + \" $\" + fines;\n fineTotal = fineTotal + fines;\n }\n }\n while (!userInput.equalsIgnoreCase(\"x\"));\n\n //Customer details\n System.out.println(\"\\n\" + \"Customer Details: \" + \"\\n\");\n System.out.printf(\"%-30s %40s %n\", \"Name: \", name);\n System.out.printf(\"%-30s %40s %n\", \"Address: \", address);\n System.out.printf(\"%-30s %40s %n\", \"Telephone:\", telephone);\n System.out.printf(\"%-30s %40s %n\", \"Driver's licence:\", licence);\n System.out.printf(\"%-30s %40s %n\", \"Credit card number:\", creditCard);\n System.out.printf(\"%-30s %40s %n\", \"Credit card expiry:\", cardExpiry);\n\n //Car hire details\n System.out.println(\"\\n\" + \"Car Hire Details: \" + \"\\n\");\n System.out.printf(\"%-30s %40s %n\", \"Make and Model:\", makeModel);\n System.out.printf(\"%-30s %40s %n\", \"Registration No:\", regNumber);\n System.out.printf(\"%-30s %40s %n\", \"Hire Length (days):\", daysBooked);\n System.out.printf(\"%-30s %40s %n\", \"Daily Hire Rate:\", dailyRate);\n System.out.printf(\"%-30s %40s %n\", \"Basic Hire Charge:\", basicHire);\n\n //Days Hired\n System.out.println(\"\\n\" + \"Days Hired: \" + \"\\n\");\n System.out.printf(\"%-30s %30.2f %n\", \"Late Return Surcharge:\", lateFee);\n System.out.printf(\"%-30s %30.2f %n\", \"Adjusted Hire Charge:\", subTotal);\n\n //Damage Repair Details\n System.out.println(\"\\n\" + \"Damage Repair Details:\");\n System.out.print(damageSummary);\n System.out.printf(\"%n %-30s %30.2f %n\", \"Total Damages:\", repairTotal);\n\n //Infringement details\n System.out.println(\"\\n\" + \"Traffic Infringement Details:\");\n System.out.print(fineSummary);\n System.out.printf(\"%n %-30s %30.2f %n\", \"Total Fines:\", fineTotal);\n\n //Final Hire Charge\n hireTotal = lateFee + basicHire + repairTotal + fineTotal;\n System.out.printf(\"%n %-30s %30.2f %n\", \"Final Hire Charge:\", hireTotal);\n }\n}\n</code></pre>\n\n<p><em>Please feel free to offer feedback.</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T08:57:00.947",
"Id": "50759",
"Score": "1",
"body": "It's kind of inconvenient that you have a doubled check for `\"X\"`. You could use `while (true)` and have a `else break;` after `if (...\"x\")`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T15:03:47.247",
"Id": "50788",
"Score": "0",
"body": "@MarkoTopolnik I have to show this menu, at least once. I cannot bypass this menu. You don't like the do while? and by double check, the else if not \"X\" was to validate the data, so it would loop back if not F, D or X ... we had to validate using a loop! It was an exercise on the course work we had learnt to date... so if If I did while true and if \"x\" break.. I'd still need a condition to prompt for more user input, if the data was not valid.. so would I really be saving a step??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T18:14:22.410",
"Id": "50815",
"Score": "1",
"body": "No, there would be no more checks, there would just be one less: the one you now have in the `while` check."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T08:15:48.737",
"Id": "50873",
"Score": "0",
"body": "@MarkoTopolnik took out extra line. kept it as a `do`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T08:39:16.550",
"Id": "50874",
"Score": "0",
"body": "@MarkoTopolnik created another question to discuss merits of loops http://codereview.stackexchange.com/questions/31893/differences-between-using-a-do-while-and-a-while-and-initializing-variables"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T09:33:59.593",
"Id": "50891",
"Score": "1",
"body": "`do - while(true)` and `while(true)` are semantically identical, but the latter is more obvious because you see the loop condition at the top."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T09:35:21.540",
"Id": "50892",
"Score": "0",
"body": "@MarkoTopolnik can you write this into an answer.. it would be helpful.. I am not trying to be a dick.. just trying to understand ;) an answer to the new question"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T09:38:25.340",
"Id": "50894",
"Score": "0",
"body": "But it doesn't apply to your new question because it works only for the specific case `while (true)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T09:39:31.213",
"Id": "50896",
"Score": "0",
"body": "@MarkoTopolnik huh? the new question is just a snippet of the old code.. it could include anything"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T09:40:12.237",
"Id": "50897",
"Score": "0",
"body": "You don't have `while (true)` there, but a real condition. In that case the equivalence disappears."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T10:42:47.173",
"Id": "50906",
"Score": "0",
"body": "@MarkoTopolnik: If you mean by \"semantically identical\" that both work the same way, then no, that's not the case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T10:47:24.203",
"Id": "50907",
"Score": "0",
"body": "@bobby `while (true)` and `do ... while (true)` do not work the same way? Explain."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T10:48:15.130",
"Id": "50908",
"Score": "0",
"body": "@MarkoTopolnik: `while (false) {}` will never execute, `do {} while (false)` will execute once."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T11:11:40.627",
"Id": "50909",
"Score": "0",
"body": "@Bobby Thanks for that lovely note, but it is clearly irrelevant. You seem to have just misunderstood my statement, which pertains to the particular condition which I have mentioned and no other (a point which I have reiterated several times in the above comments)."
}
],
"meta_data": {
"CommentCount": "14",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T18:23:25.623",
"Id": "31807",
"ParentId": "31666",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "31682",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T02:21:10.670",
"Id": "31666",
"Score": "3",
"Tags": [
"java",
"beginner"
],
"Title": "Prompting for values to plug into a formula — how to do it elegantly"
}
|
31666
|
<p>Below is the current code which is used to update/insert records from Oracle view to SQL Server table using <a href="https://code.google.com/p/dapper-dot-net/">Dapper</a>. There is not a field to check last record updated date in the oracle view so I have added a method to get hashcode by using property values. Since Oracle table has more than 15k records and each record has more more than 60 columns, this approach take more than 5 minutes. Any ideas/suggestions to improve below code?</p>
<pre><code>using System;
using System.Configuration;
using System.Data.OracleClient;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using Dapper;
namespace SyncSQLSvrWithHRDB
{
internal class Program
{
public static PropertyInfo[] PropertyNames = typeof(Employee).GetProperties();
private static void Main(string[] args)
{
var OracleConStr = ConfigurationManager.ConnectionStrings["OracleCon"].ConnectionString;
var SqlSvrConStr = ConfigurationManager.ConnectionStrings["SqlSvrCon"].ConnectionString;
using (OracleConnection OraCon = new OracleConnection(OracleConStr))
{
var res = OraCon.Query<Employee>(Constants.SelectSql).ToList();
res = res.GroupBy(x => x.EmpNumber.ToUpper()).Select(x => x.LastOrDefault()).ToList();
using (SqlConnection Sqlcon = new SqlConnection(SqlSvrConStr))
{
Sqlcon.Open();
for (int i = 0; i < res.Count; i++)
{
var item = Sqlcon.Query<Employee>(Constants.SelectEmpSql, new { EmpNumber= res[i].EmpNumber}).FirstOrDefault();
if (item == null) // new record found
{
Sqlcon.Execute(Constants.InsertSql, res[i]);
}
else if (GetHashcode(res[i]) != GetHashcode(item)) // record updated
{
Sqlcon.Execute(Constants.UpdateSql, res[i]);
}
}
}
}
}
public static int GetHashcode(Employee o)
{
int ret = 0;
foreach (var prop in PropertyNames)
{
object propValue = o.GetType().GetProperty(prop.Name).GetValue(o, null);
if (propValue != null)
{
ret += propValue.GetHashCode();
}
}
return ret;
}
}
public class Employee
{
public String EmpNumber{ get; set; }
// ... other properties (70)
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T07:29:29.500",
"Id": "50541",
"Score": "4",
"body": "Consider creating a linked server to Oracle from your SQL Server. You can then perform your necessary work in T-SQL, in a set-based manner. Consider using the new MERGE syntax in SQL Server too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T18:57:57.130",
"Id": "57442",
"Score": "2",
"body": "As an aside, you should *really* implement GetHashCode on Employee, both for better encapsulation and for speed. Hash code generation is supposed to be fast, and reflecting the fields like that are the opposite of fast."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-18T23:17:12.610",
"Id": "57888",
"Score": "0",
"body": "Have you done any profiling? You're running a zillion queries against SQL instead of merging the two data sets, I'd guess that's your problem."
}
] |
[
{
"body": "<p>One thing I would say is that you don't need to create those connection string variables, you are only using them once in this program and you have them nicely hidden where they should be, so you can just call them when you use them, which in this case is once.</p>\n\n<p>so instead of this</p>\n\n<pre><code>var OracleConStr = ConfigurationManager.ConnectionStrings[\"OracleCon\"].ConnectionString;\nvar SqlSvrConStr = ConfigurationManager.ConnectionStrings[\"SqlSvrCon\"].ConnectionString;\nusing (OracleConnection OraCon = new OracleConnection(OracleConStr))\n{\n var res = OraCon.Query<Employee>(Constants.SelectSql).ToList();\n\n res = res.GroupBy(x => x.EmpNumber.ToUpper()).Select(x => x.LastOrDefault()).ToList();\n using (SqlConnection Sqlcon = new SqlConnection(SqlSvrConStr))\n {\n</code></pre>\n\n<p>Do this instead</p>\n\n<pre><code>using (OracleConnection OraCon = new OracleConnection(ConfigurationManager.ConnectionStrings[\"OracleCon\"].ConnectionString))\n{\n var res = OraCon.Query<Employee>(Constants.SelectSql).ToList();\n\n res = res.GroupBy(x => x.EmpNumber.ToUpper()).Select(x => x.LastOrDefault()).ToList();\n using (SqlConnection Sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings[\"SqlSvrCon\"].ConnectionString))\n {\n</code></pre>\n\n<p>You have already named them nicely so you know exactly what they are, meaning there is no reason to create variables for these, they are only used once.</p>\n\n<hr>\n\n<p>and instead of a for loop here:</p>\n\n<pre><code>using (SqlConnection Sqlcon = new SqlConnection(SqlSvrConStr))\n{\n Sqlcon.Open();\n for (int i = 0; i < res.Count; i++)\n {\n var item = Sqlcon.Query<Employee>(Constants.SelectEmpSql, new { EmpNumber= res[i].EmpNumber}).FirstOrDefault();\n if (item == null) // new record found\n {\n Sqlcon.Execute(Constants.InsertSql, res[i]);\n }\n else if (GetHashcode(res[i]) != GetHashcode(item)) // record updated\n {\n Sqlcon.Execute(Constants.UpdateSql, res[i]);\n }\n }\n}\n</code></pre>\n\n<p>you could use a foreach loop</p>\n\n<pre><code>using (SqlConnection Sqlcon = new SqlConnection(SqlSvrConStr))\n{\n Sqlcon.Open();\n\n foreach (var record in res)\n {\n var item = Sqlcon.Query<Employee>(Constants.SelectEmpSql, new { EmpNumber= record.EmpNumber}).FirstOrDefault();\n if (item == null) // new record found\n {\n Sqlcon.Execute(Constants.InsertSql, record);\n }\n else if (GetHashcode(record) != GetHashcode(item)) // record updated\n {\n Sqlcon.Execute(Constants.UpdateSql, record);\n }\n }\n}\n</code></pre>\n\n<p>This is a little bit cleaner and is more straight to the point about what you are doing. I would probably change some variable names around, but I will let you have that fun.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-22T14:18:05.143",
"Id": "60801",
"ParentId": "31673",
"Score": "7"
}
},
{
"body": "<p>This code queries the SQL server 15K times (for each and every employee in the Oracle view). Suggest generating the SQL query based on the Oracle view data set and retrieve the data from SQL in one go and then do the comparison in memory. You can generate the insert and update queries in the loop and execute them outside the loop as two batches if you have <a href=\"https://dapper-plus.net/\" rel=\"nofollow noreferrer\">Dapper Plus</a> ;)</p>\n\n<p>Otherwise, you will have to instantiate a DataTable and populate it in the loop and use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlbulkcopy?view=netframework-4.7.2\" rel=\"nofollow noreferrer\">SQLBulkCopy</a> for inserts. </p>\n\n<p>Additionally, GetHashCode can be optimized as per below;</p>\n\n<pre><code>public static int GetHashcode(Employee o)\n{\n int hashCode = 0;\n foreach (var property in PropertyNames)\n {\n object propValue = property.GetValue(o, null);\n if (propValue != null)\n {\n hashCode += propValue.GetHashCode();\n }\n }\n return hashCode;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T13:42:36.653",
"Id": "212796",
"ParentId": "31673",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T07:15:53.960",
"Id": "31673",
"Score": "9",
"Tags": [
"c#",
"sql-server",
"oracle",
"dapper"
],
"Title": "Compare Oracle Table with SQL Server Table and Update/Insert"
}
|
31673
|
<p>All of the class here share these same property</p>
<p>Country, Total and Date.</p>
<p>Total property are integer in some classes and decimal in some classed.</p>
<p>The extension method below has a lot of duplication. i have tried to refactor it using interface but i can't find a way to refactor it at the last step on selection since it need different class</p>
<pre><code> public static class TotalApprovedPOAmountStatisticExtension
{
public static void MergeNullAndEmplyCountry(this IEnumerable<TotalApprovedPOAmountStatistic> totalUserStatistic)
{
foreach (var item in totalUserStatistic)
{
if (string.IsNullOrWhiteSpace(item.Country))
{
item.Country = "";
}
}
totalUserStatistic = totalUserStatistic
.GroupBy(item => new { item.Country, item.Date })
.Select(groupedUser => new TotalApprovedPOAmountStatistic()
{ Country = groupedUser.Key.Country, Total = groupedUser.Sum(item => item.Total), Date = groupedUser.Key.Date }).ToList();
}
}
public static class TotalPOStatisticListExtension
{
public static void MergeNullAndEmplyCountry(this IEnumerable<TotalPOStatistic> totalUserStatistic)
{
foreach (var item in totalUserStatistic)
{
if (string.IsNullOrWhiteSpace(item.Country))
{
item.Country = "";
}
}
totalUserStatistic = totalUserStatistic
.GroupBy(item => new { item.Country, item.Date })
.Select(groupedUser => new TotalPOStatistic() { Country = groupedUser.Key.Country, Total = groupedUser.Sum(item => item.Total), Date = groupedUser.Key.Date }).ToList();
}
}
public static class TotalProjectAmountStatisticListExtension
{
public static void MergeNullAndEmplyCountry(this IEnumerable<TotalProjectAmountStatistic> totalUserStatistic)
{
foreach (var item in totalUserStatistic)
{
if (string.IsNullOrWhiteSpace(item.Country))
{
item.Country = "";
}
}
totalUserStatistic = totalUserStatistic
.GroupBy(item => new { item.Country, item.Date })
.Select(groupedUser => new TotalProjectAmountStatistic() { Country = groupedUser.Key.Country, Total = groupedUser.Sum(item => item.Total), Date = groupedUser.Key.Date }).ToList();
}
}
public static class TotalProjectStatisticListExtension
{
public static void MergeNullAndEmplyCountry(this IEnumerable<TotalProjectStatistic> totalUserStatistic)
{
foreach (var item in totalUserStatistic)
{
if (string.IsNullOrWhiteSpace(item.Country))
{
item.Country = "";
}
}
totalUserStatistic = totalUserStatistic
.GroupBy(item => new { item.Country, item.Date })
.Select(groupedUser => new TotalProjectStatistic() { Country = groupedUser.Key.Country, Total = groupedUser.Sum(item => item.Total), Date = groupedUser.Key.Date }).ToList();
}
}
public static class TotalUserStatisticListExtension
{
public static void MergeNullAndEmplyCountry(this IEnumerable<TotalUserStatistic> totalUserStatistic)
{
foreach (var item in totalUserStatistic)
{
if (string.IsNullOrWhiteSpace(item.Country))
{
item.Country = "";
}
}
totalUserStatistic = totalUserStatistic
.GroupBy(item => new { item.Country, item.Date })
.Select(groupedUser => new TotalUserStatistic() { Country = groupedUser.Key.Country, Total = groupedUser.Sum(item => item.Total), Date = groupedUser.Key.Date }).ToList();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You can use an interface and a generic method to remove the code duplication:</p>\n\n<pre><code>public interface IStatistic\n{\n string Country {get; set;}\n DateTime Date {get; set;}\n Decimal Total {get; set;}\n}\n\npublic static class StatisticExtension\n{\n public static void MergeNullAndEmplyCountry<T>(this IEnumerable<T> totalUserStatistic) where T : IStatistic, new()\n {\n foreach (var item in totalUserStatistic)\n if (string.IsNullOrWhiteSpace(item.Country))\n item.Country = \"\";\n\n totalUserStatistic = totalUserStatistic.GroupBy(item => new { item.Country, item.Date })\n .Select(groupedUser => new T() \n { \n Country = groupedUser.Key.Country, \n Total = groupedUser.Sum(item => item.Total), \n Date = groupedUser.Key.Date \n }).ToList();\n }\n}\n</code></pre>\n\n<p>Important here is the <code>new()</code> constraint, which allows us to create an instance of <code>T</code>.</p>\n\n<p>If the <code>Total</code> property of a class is <code>int</code> instead of <code>decimal</code>, we can make use of an explicit interface implementation:</p>\n\n<pre><code>public class BlaStatistic : IStatistic\n{\n public string Country {get; set;}\n public DateTime Date {get; set;}\n public Int32 Total {get; set;}\n Decimal IStatistic.Total \n { \n get { return Convert.ToDecimal(Total); }\n set { Total = Convert.ToInt32(value); }\n }\n}\n</code></pre>\n\n<p>Also, your extension method should actually return something, because it won't change the <code>IEnumerable<...></code> you pass in:</p>\n\n<pre><code>public static IEnumerable<T> MergeNullAndEmplyCountry<T>(this IEnumerable<T> totalUserStatistic) where T : IStatistic, new()\n{\n ...\n return totalUserStatistic.GroupBy...\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T12:40:15.497",
"Id": "31684",
"ParentId": "31674",
"Score": "4"
}
},
{
"body": "<p>First of all, your code can't possibly work. All your methods do is to modify one of its parameters, which won't have any effect from the outside. So I'm going to assume your code actually does something useful, like returning the grouped collection.</p>\n\n<p>Now, what you could do (if you don't have it already) is to create a generic interface <code>IStatistic</code> (or abstract base class) that will contain the three properties (<code>Country</code>, <code>Date</code> and generic <code>Total</code>):</p>\n\n<pre><code>public interface IStatistic<TTotal>\n{\n string Country { get; set; }\n DateTime Date { get; set; }\n TTotal Total { get; set; }\n}\n</code></pre>\n\n<p>Then you implement this interface in all your <code>Statistic</code> classes and write an extension method for this interface. The only problem will be with <code>Total</code>, because you can't call <code>Sum()</code> on just any type.</p>\n\n<p>You can fix this by having two extension methods: one for <code>int</code> and one for <code>decimal</code>. These methods can share almost all of their code, by using a delegate that represents the right <code>Sum()</code> method for the given type.</p>\n\n<p>Another problem is that if the extension methods for <code>int</code> and <code>decimal</code> had the same name, overload resolution wouldn't be able to choose between the two. Changing the name to include the type is not nice, but works:</p>\n\n<pre><code>public static class StatisticExtension\n{\n // doesn't have to be public\n public static IEnumerable<TStatistic> MergeNullAndEmptyCountry<TStatistic, TTotal>(\n this IEnumerable<TStatistic> totalStatistic,\n Func<IEnumerable<TTotal>, TTotal> sumFunction)\n where TStatistic : class, IStatistic<TTotal>, new()\n {\n foreach (var item in totalStatistic)\n {\n if (String.IsNullOrWhiteSpace(item.Country))\n {\n item.Country = \"\";\n }\n }\n\n return totalStatistic\n .GroupBy(item => new { item.Country, item.Date })\n .Select(\n groupedUser =>\n new TStatistic\n {\n Country = groupedUser.Key.Country,\n Total = sumFunction(groupedUser.Select(item => item.Total)),\n Date = groupedUser.Key.Date\n }).ToList();\n }\n\n public static IEnumerable<TStatistic> MergeNullAndEmptyCountryInt32<TStatistic>(\n this IEnumerable<TStatistic> totalStatistic)\n where TStatistic : class, IStatistic<int>, new()\n {\n return totalStatistic.MergeNullAndEmptyCountry<TStatistic, int>(Enumerable.Sum);\n }\n\n public static IEnumerable<TStatistic> MergeNullAndEmptyCountryDecimal<TStatistic>(\n this IEnumerable<TStatistic> totalStatistic)\n where TStatistic : class, IStatistic<decimal>, new()\n {\n return totalStatistic.MergeNullAndEmptyCountry<TStatistic, decimal>(Enumerable.Sum);\n }\n}\n</code></pre>\n\n<p>Also, the name of the method is quite confusing (even ignoring the typo): it doesn't merge just null and empty countries, it merges everything.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T14:41:45.700",
"Id": "31735",
"ParentId": "31674",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "31684",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T07:40:45.950",
"Id": "31674",
"Score": "4",
"Tags": [
"c#",
"linq"
],
"Title": "Refactor Linq grouping"
}
|
31674
|
<p>I'm trying to implement an inversion counting routine in Scala in a functional way (I don't want to port Java solution) but have real troubles with it. The sorting routine works fine but adding the code to count inversions leads to stack overflow error. Here's the code in question:</p>
<pre><code> object FuncSort
def streamMerge(l: Stream[Int], r: Stream[Int]) : Stream[Int] = {
(l, r) match {
case (x#::xs, Empty) => l
case (Empty, y#::ys) => r
case (x#::xs, y#::ys) => if(x < y) x#::streamMerge(xs, r) else y#::streamMerge(l, ys)
}
}
// This function works albeit slow
def streamSort(xs: Stream[Int]) : Stream[Int] = {
if(xs.lengthCompare(1) <= 0) xs
else {
val m = xs.length / 2
val (l, r) = xs.splitAt(m)
streamMerge(streamSort(l), streamSort(r))
}
}
// This one fails with StackOverflowError
def mergeAndCount(l: Stream[Int], r: Stream[Int]) : (Long, Stream[Int]) = {
(l, r) match {
case (x#::xs, Empty) => (0, l)
case (Empty, y#::ys) => (0, r)
case (x#::xs, y#::ys) => if(x < y) {
lazy val (i, s) = mergeAndCount(xs, r)
(i, x#::s)
} else {
lazy val (i, s) = mergeAndCount(l, ys)
(i + l.length, y#::s)
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>The recursive calls to <code>mergeAndCount</code> are not in tail position, so the Scala compiler can not use tail optimisation and the stack grows till it overflows its alloted space. The <code>lazy</code> modifier in <code>lazy val (i, s)</code> is doing you no good at all, by the way.</p>\n\n<p>Scala can only do tail optimisation if the recursive call to <code>mergeAndCount</code> is the last expression to be called <em>and even then</em> only if the value returned is not modified in anyway but simply passed straight back, all the way to the first recursive call to <code>mergeAndCount</code>.</p>\n\n<p>To fix this, you could add a local helper function inside <code>mergeAndCount</code>, which takes as parameters not only the two streams but also the state you need to carry forward. It would look something like this..</p>\n\n<pre><code>def mergeAndCount(left: Stream[Int], right: Stream[Int]) = {\n def mac(l: Stream[Int], r: Stream[Int], m: Stream[Int], count: Long): (Long, Stream[Int]) = (l, r) match {\n case (x #:: xs, Empty) => (count, merge append l)\n case (Empty, y #:: ys) => (count, merge append r)\n case (x #:: xs, y #:: ys) if x < y => mac(xs, r, x #:: m, count + 1)\n case (x #:: xs, y #:: ys) => mac(l, ys, y #:: m, count + 1)\n }\n mac(left, right, Stream.empty, 0)\n}\n</code></pre>\n\n<p>I may not have understood how the count is supposed to work, but I think the general idea is clear. Note how I split your final case statement into two by turning the <code>if</code> condition into a guard - it's tidier, I think. Note also that if an entire function is one big pattern match, you don't have to wrap the match in braces.</p>\n\n<p>To be fair, nothing about</p>\n\n<pre><code>streamMerge(streamSort(l), streamSort(r))\n</code></pre>\n\n<p>is in tail position either, but because all 3 functions return only a stream, you get away with it. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T05:54:33.430",
"Id": "50606",
"Score": "0",
"body": "Then how does the `streamMerge` method work with large streams? It's not tail-recursive."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T07:45:44.590",
"Id": "50612",
"Score": "0",
"body": "Well, that's exactly what I'm asking about. Inversion counter introduces strict evaluation into sorting routine so I'm looking for a way to lazily evaluate it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T07:47:41.350",
"Id": "50613",
"Score": "0",
"body": "@synapse Streams use **thunks** and lazy evaluation to return as quickly as possible. `StreamMerge` is *mathematically* recursive but it isn't *actually* recursive in the generated code; there is only ever one call to `StreamMerge` happening at once."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T07:49:56.017",
"Id": "50614",
"Score": "0",
"body": "Oop, edited my comment so things are out of sequence. @synapse, your original question talks about the stack overflow problem and nothing else - the code comments happen to mention the slow performance of the sort, but you only made that the focus of your question in the comment you just made here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T07:55:50.280",
"Id": "50616",
"Score": "0",
"body": "What makes StreamSort slow is the calls to `lengthCompare` and `length`, because they force realisation of the entire stream. There are ways to work around this. Don't have time to go into them now but can find some time tonight."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T08:02:36.847",
"Id": "50617",
"Score": "0",
"body": "Is it because the second argument to `#::` operator is lazily evaluated? (Changing `Stream` to `List` results in stack overflow) How can I do the same with numbers?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T08:52:30.677",
"Id": "50622",
"Score": "0",
"body": "Yes, the lazy evaluation is the key. What do you mean by \"How can I do the same with numbers?\"? Anything that can be expressed as a recursive function can be turned into a stream."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T11:40:44.793",
"Id": "50628",
"Score": "0",
"body": "it looks like the question is out of scope of this substack. Please visit http://stackoverflow.com/questions/18980612/porting-haskell-inversion-counter-to-scala"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T22:31:12.403",
"Id": "31711",
"ParentId": "31675",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T08:01:01.017",
"Id": "31675",
"Score": "1",
"Tags": [
"scala",
"sorting"
],
"Title": "Counting inversions"
}
|
31675
|
<p>This is a batch program to xcopy from host PC to remote destination with multi-processing.</p>
<p>Kepler, Python-3.x are my environment.</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# based on Carnival http://ask.python.kr/users/6970/carnival/
import os
import os.path
import csv
import re
from multiprocessing import Process, Lock
class Server:
def __init__(self, addr, path):
self.addr = addr
self.path = path
def distribute_file(server_list, pathname):
print("Read from {}".format(pathname))
with open(pathname, 'rb') as inFile:
buffer = inFile.read()
for server in server_list:
remotepath = "//%s/%s/%s" % (server.addr, server.path, pathname)
print ("Write to {}".format(remotepath))
with open(remotepath, 'wb') as outFile:
outFile.write(buffer)
def multi_distribute_file(lo, server, dirpath, filename, path):
lo.acquire()
pathname = os.path.join(dirpath, filename)
print("Read from {}".format(pathname))
with open(pathname, 'rb') as inFile:
buffer = inFile.read()
if(path == ''):
remotepath = "//%s/%s/%s" % (server.addr, server.path, filename)
else:
remotepath = "//%s/%s/%s/%s" % (server.addr, server.path, path, filename)
print ("Write to {}".format(remotepath))
with open(remotepath, 'wb') as outFile:
outFile.write(buffer)
lo.release()
def make_dir(server_list, path):
for server in server_list:
dirpath = "//%s/%s/%s" % (server.addr, server.path, path)
d = os.path.dirname(dirpath)
if not os.path.exists(d):
os.makedirs(d)
print ("Make dir {}".format(d))
else:
print ("dir {} already exists.".format(d))
if not os.path.exists(dirpath):
os.makedirs(dirpath)
print ("Make dir {}".format(dirpath))
else:
print ("dir {} already exists.".format(dirpath))
def dist_files(server_list, subdir):
for dirpath, dirnames, filenames in os.walk(subdir):
l = re.findall(r"[\w']+",subdir)
m = re.findall(r"[\w']+",dirpath)
path = ''
if(l != m):
path = m[len(m)-1]
make_dir(server_list, path)
for filename in filenames:
for server in server_list:
lock = Lock()
Process(target=multi_distribute_file,args=(lock, server, dirpath, filename, path)).start()
def get_server_list(filename):
mydictionary = []
csvFile = csv.reader(open(filename, "r"))
for row in csvFile:
mydictionary.append(Server(row[0], row[1]))
print("{}, {}".format(row[0], row[1]))
return mydictionary
if __name__ == '__main__':
server_list = get_server_list('client_list.csv')
dist_files(server_list, 'C:\\Users\\Public\\Test')
</code></pre>
<p><strong>client_list.csv</strong></p>
<blockquote>
<ul>
<li>192.168.10.100, Test </li>
<li>192.168.10.101, Test </li>
<li>192.168.10.102, Test</li>
</ul>
</blockquote>
|
[] |
[
{
"body": "<p><strong>Technical issues:</strong></p>\n\n<ul>\n<li>You are reading whole files into memory at once. Consider what happens if the directory contains huge files.</li>\n<li>You use <code>multiprocessing</code>, apparently in an attempt to parallelize things, and use locks to synchronize.</li>\n<li>First, why do you need a lock anyway? Which data do you want to protect? The only shared data are in the filesystems, which could be changed by other processes at any time anyway.</li>\n<li>Next, each call to <code>multi_distribute_file</code> gets its own lock instance, that is only used once by this call. So there is no synchronization happening at all.</li>\n<li>On the other hand, if you would use a single lock for all calls to <code>multi_distribute_file</code>, the processes will execute one after another, as each acquires the lock for its entire runtime. Your parallelizing efforts would be in vain.</li>\n<li>You are spawning a new process for each file being copied. This can create a <strong>huge</strong> number of processes very quickly. Consider what this will do to your system performance.</li>\n<li>If something goes wrong in <code>multi_distribute_file</code> and raises an exception, the lock will never be released. And things <strong>will</strong> go wrong occassionaly as you are communicating over a network. Use a <code>with</code> statement instead.</li>\n<li>Don't use string manipulation (<code>format</code> and <code>re</code>) to manipulate paths. Use <code>os.path</code> instead. This is saver and more reliable.</li>\n</ul>\n\n<p><strong>Style issues</strong>:</p>\n\n<ul>\n<li>There are no docstrings and no comments (apart from the header)</li>\n<li>Avoid single-letter and other abbreviated names like <code>d</code>, <code>l</code>, <code>m</code>, and <code>lo</code>. </li>\n<li><code>mydictionary</code> is a meaningless and misleading name. Meaningless, as it doesn't tell us anything about the purpose of the variable, and misleading as it is actually a list, not a dictionary. A better name might be <code>server_list</code> (like you do elsewhere).</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-09T22:03:22.923",
"Id": "35105",
"ParentId": "31678",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "35105",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T11:14:49.977",
"Id": "31678",
"Score": "4",
"Tags": [
"python",
"optimization",
"python-3.x",
"csv",
"multiprocessing"
],
"Title": "Batch program to xcopy from host PC to remote destination with multi-processing"
}
|
31678
|
<p>Just looking for some help reviewing/refactoring. For example, could the classes random/vertical be refactored into 1 class instead of 2?</p>
<h3>BouncingBalls.java</h3>
<pre class="lang-java prettyprint-override"><code>import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class BouncingBalls extends JPanel implements MouseListener {
protected List<RandomBall> randomBalls = new ArrayList<RandomBall>(20);
protected List<VerticalBall> verticalBalls = new ArrayList<VerticalBall>(20);
private Container container;
private DrawCanvas canvas;
private Boolean doubleClick = false;
private final Integer waitTime = (Integer) Toolkit.getDefaultToolkit()
.getDesktopProperty("awt.multiClickInterval");
private static int canvasWidth = 500;
private static int canvasHeight = 500;
public static final int UPDATE_RATE = 30;
int count = 0;
public static int random(int maxRange) {
return (int) Math.round((Math.random() * maxRange));
}
public BouncingBalls(int width, int height) {
canvasWidth = width;
canvasHeight = height;
container = new Container();
canvas = new DrawCanvas();
this.setLayout(new BorderLayout());
this.add(canvas, BorderLayout.CENTER);
this.addMouseListener(this);
start();
}
public void start() {
Thread t = new Thread() {
public void run() {
while (true) {
update();
repaint();
try {
Thread.sleep(1000 / UPDATE_RATE);
} catch (InterruptedException e) {
}
}
}
};
t.start();
}
public void update() {
for (RandomBall ball : randomBalls) {
ball.ballBounce(container);
}
for (VerticalBall ball : verticalBalls) {
ball.verticalBounce(container);
}
}
class DrawCanvas extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
container.draw(g);
for (RandomBall ball : randomBalls) {
ball.draw(g);
}
for (VerticalBall ball : verticalBalls) {
ball.draw(g);
}
}
public Dimension getPreferredSize() {
return (new Dimension(canvasWidth, canvasHeight));
}
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame("Stack Answer 2");
f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
f.setContentPane(new BouncingBalls(canvasHeight, canvasWidth));
f.pack();
f.setVisible(true);
}
});
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
final int x = e.getX();
final int y = e.getY();
if (e.getClickCount() >= 2) {
doubleClick = true;
verticalBalls.add(new VerticalBall(x, y, canvasWidth, canvasHeight));
System.out.println("double click");
} else {
Timer timer = new Timer(waitTime, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (doubleClick) {
/* we are the first click of a double click */
doubleClick = false;
} else {
count++;
randomBalls.add(new RandomBall(x, y, canvasWidth, canvasHeight));
/* the second click never happened */
System.out.println("single click");
}
}
});
timer.setRepeats(false);
timer.start();
}
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
</code></pre>
<h3>RandomBall.java</h3>
<pre class="lang-java prettyprint-override"><code>import java.awt.Color;
import java.awt.Graphics;
public class RandomBall {
public static int random(int maxRange) {
return (int) Math.round((Math.random() * maxRange));
}
private int x;
private int y;
private int canvasWidth = 500;
private int canvasHeight = 500;
private boolean leftRight;
private boolean upDown;
private int deltaX;
private int deltaY;
private int radius = 20;
private int red = random(255);
private int green = random(255);
private int blue = random(255);
RandomBall(int x, int y, int width, int height) {
this(x, y, width, height, false, false);
}
RandomBall(int x, int y, int width, int height, boolean leftRight, boolean upDown) {
this.x = x;
this.y = y;
this.canvasWidth = width;
this.canvasHeight = height;
this.leftRight = leftRight;
this.upDown = upDown;
updateDelta();
}
public void draw(Graphics g) {
g.setColor(new Color(red, green, blue));
g.fillOval((int) (x - radius), (int) (y - radius), (int) (2 * radius),
(int) (2 * radius));
}
private void updateDelta() {
final int minimumMovement = 5;
final int maxExtra = 10;
deltaY = minimumMovement + (int) (Math.random() * maxExtra);
deltaX = minimumMovement + (int) (Math.random() * maxExtra);
}
public void ballBounce(Container container) {
// controls horizontal ball motion
if (leftRight) {
x += deltaX;
if (x >= getWidth()) {
leftRight = false;
updateDelta();
}
} else {
x += -deltaX;
if (x <= 0) {
leftRight = true;
updateDelta();
}
}
// controls vertical ball motion
if (upDown) {
y += deltaY;
if (y >= getHeight()) {
upDown = false;
updateDelta();
}
} else {
y += -deltaY;
if (y <= 0) {
upDown = true;
updateDelta();
}
}
}
public void verticalBounce(Container container) {
// controls vertical ball motion
if (upDown) {
y += deltaY;
if (y >= getHeight()) {
upDown = false;
updateDelta();
}
} else {
y += -deltaY;
if (y <= 0) {
upDown = true;
updateDelta();
}
}
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getWidth() {
return canvasWidth;
}
public int getHeight() {
return canvasHeight;
}
}
</code></pre>
<h3>VerticalBall.java</h3>
<pre class="lang-java prettyprint-override"><code>import java.awt.Color;
import java.awt.Graphics;
public class VerticalBall {
public static int random(int maxRange) {
return (int) Math.round((Math.random() * maxRange));
}
private int x;
private int y;
private int canvasWidth = 500;
private int canvasHeight = 500;
private boolean upDown;
private int deltaY;
private int radius = 20;
private int red = random(255);
private int green = random(255);
private int blue = random(255);
VerticalBall(int x, int y, int width, int height) {
this(x, y, width, height, false);
}
VerticalBall(int x, int y, int width, int height, boolean upDown) {
this.x = x;
this.y = y;
this.canvasWidth = width;
this.canvasHeight = height;
this.upDown = upDown;
updateDelta();
}
public void draw(Graphics g) {
g.setColor(new Color(red, green, blue));
g.fillOval((int) (x - radius), (int) (y - radius), (int) (2 * radius),
(int) (2 * radius));
}
private void updateDelta() {
final int minimumMovement = 5;
final int maxExtra = 10;
deltaY = minimumMovement + (int) (Math.random() * maxExtra);
}
public void verticalBounce(Container container) {
// controls vertical ball motion
if (upDown) {
y += deltaY;
if (y >= getHeight()) {
upDown = false;
updateDelta();
}
} else {
y += -deltaY;
if (y <= 0) {
upDown = true;
updateDelta();
}
}
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getWidth() {
return canvasWidth;
}
public int getHeight() {
return canvasHeight;
}
}
</code></pre>
<h3>Container.java</h3>
<pre class="lang-java prettyprint-override"><code>import java.awt.Color;
import java.awt.Graphics;
public class Container {
private static final int HEIGHT = 500;
private static final int WIDTH = 500;
private static final Color COLOR = Color.WHITE;
public void draw(Graphics g) {
g.setColor(COLOR);
g.fillRect(0, 0, WIDTH, HEIGHT);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Your <code>VerticalBall</code> class and <code>RandomBall</code> have lots of duplicate code(should it?). So you can make an <code>abstract</code> <strong><code>Ball</code></strong> class and define the duplicate codes there. This way you can have a clear hierarchy of classes. </p>\n\n<p>See : <a href=\"http://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html\" rel=\"nofollow\">re-factoring</a> also.</p>\n\n<p>BTW in Java final variable names are written like CAPITAL_WITH_UNDERSCORES.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T15:48:17.933",
"Id": "31692",
"ParentId": "31687",
"Score": "2"
}
},
{
"body": "<p>i believe that the main issue here is code duplication, like tintinmj already said.</p>\n\n<p>also, <a href=\"http://www.java-gaming.org/index.php?topic=24220.0\" rel=\"nofollow\">here</a> s a good article about different kinds of game loops. yours seems to be not scaling according to real time passed since the last game update.</p>\n\n<pre><code> g.setColor(new Color(red, green, blue));\n</code></pre>\n\n<p>do you really need to create new instance of Color every time here?</p>\n\n<p>in RandomBall class, there's code duplication in ballBounce and verticalBounce. probably first one should call the second instead.</p>\n\n<p>public getters in *Ball classes seems to be useless for now?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T16:56:19.550",
"Id": "31748",
"ParentId": "31687",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T14:09:48.693",
"Id": "31687",
"Score": "3",
"Tags": [
"java",
"multithreading",
"gui"
],
"Title": "Java Bouncing Ball Review"
}
|
31687
|
<p>I have implemented an <code>IDataContractSurrogate</code> to enable serialization of <code>ImmutableList<T></code> (from the Microsoft Immutable Collections BCL) using the <code>DataContractSerialization</code> framework.</p>
<p>The code is a bit wild using reflection and compiling of delegates. Are there any subtle improvements or obvious over engineering problems here?</p>
<p>This is a follow-up from a <a href="https://stackoverflow.com/questions/18955441/how-to-serialize-deserialize-immutable-list-type-in-c-sharp">Stack Overflow question</a>, but further improvements feel like code review rather than specific questions.</p>
<p><strong>TESTCASE</strong></p>
<pre><code>using FluentAssertions;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using Xunit;
namespace ReactiveUI.Ext.Spec
{
[DataContract(Name="Node", Namespace="http://foo.com/")]
class Node
{
[DataMember()]
public string Name;
}
[DataContract(Name="Fixture", Namespace="http://foo.com/")]
class FixtureType
{
[DataMember()]
public ImmutableList<Node> Nodes;
public FixtureType(){
Nodes = ImmutableList<Node>.Empty.AddRange( new []
{ new Node(){Name="A"}
, new Node(){Name="B"}
, new Node(){Name="C"}
});
}
}
public class ImmutableSurrogateSpec
{
public static string ToXML(object obj)
{
var settings = new XmlWriterSettings { Indent = true };
using (MemoryStream memoryStream = new MemoryStream())
using (StreamReader reader = new StreamReader(memoryStream))
using (XmlWriter writer = XmlWriter.Create(memoryStream, settings))
{
DataContractSerializer serializer =
new DataContractSerializer
( obj.GetType()
, new DataContractSerializerSettings() { DataContractSurrogate = new ImmutableSurrogateSerializer() }
);
serializer.WriteObject(writer, obj);
writer.Flush();
memoryStream.Position = 0;
return reader.ReadToEnd();
}
}
public static T Load<T>(Stream data)
{
DataContractSerializer ser = new DataContractSerializer
( typeof(T)
, new DataContractSerializerSettings() { DataContractSurrogate = new ImmutableSurrogateSerializer() }
);
return (T)ser.ReadObject(data);
}
public static T Load<T>(string data)
{
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(data)))
{
return Load<T>(stream);
}
}
[Fact]
public void ShouldWork()
{
var o = new FixtureType();
var s = ToXML(o);
var oo = Load<FixtureType>(s);
oo.Nodes.Count().Should().Be(3);
var names = oo.Nodes.Select(n => n.Name).ToList();
names.ShouldAllBeEquivalentTo(new[]{"A", "B", "C"});
}
}
}
</code></pre>
<p><strong>IMPLEMENTATION</strong></p>
<pre><code>using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.Serialization;
namespace ReactiveUI.Ext
{
class ImmutableListListConverter<T>
{
public static ImmutableList<T> ToImmutable( List<T> list )
{
return ImmutableList<T>.Empty.AddRange(list);
}
public static List<T> ToList(ImmutableList<T> list){
return list.ToList();
}
public static object ToImmutable( object list )
{
return ToImmutable(( List<T> ) list);
}
public static object ToList(object list){
return ToList(( ImmutableList<T> ) list);
}
}
static class ImmutableListListConverter {
static ConcurrentDictionary<Tuple<string, Type>, Func<object,object>> _MethodCache
= new ConcurrentDictionary<Tuple<string, Type>, Func<object,object>>();
public static Func<object,object> CreateMethod( string name, Type genericType )
{
var key = Tuple.Create(name, genericType);
if ( !_MethodCache.ContainsKey(key) )
{
_MethodCache[key] = typeof(ImmutableListListConverter<>)
.MakeGenericType(new []{genericType})
.GetMethod(name, new []{typeof(object)})
.MakeLambda();
}
return _MethodCache[key];
}
public static Func<object,object> ToImmutableMethod( Type targetType )
{
return ImmutableListListConverter.CreateMethod("ToImmutable", targetType.GenericTypeArguments[0]);
}
public static Func<object,object> ToListMethod( Type targetType )
{
return ImmutableListListConverter.CreateMethod("ToList", targetType.GenericTypeArguments[0]);
}
private static Func<object,object> MakeLambda(this MethodInfo method )
{
return (Func<object,object>) method.CreateDelegate(Expression.GetDelegateType(
(from parameter in method.GetParameters() select parameter.ParameterType)
.Concat(new[] { method.ReturnType })
.ToArray()));
}
}
public class ImmutableSurrogateSerializer : IDataContractSurrogate
{
static ConcurrentDictionary<Type, Type> _TypeCache = new ConcurrentDictionary<Type, Type>();
public Type GetDataContractType( Type targetType )
{
if ( _TypeCache.ContainsKey(targetType) )
{
return _TypeCache[targetType];
}
if(targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(ImmutableList<>))
{
return _TypeCache[targetType]
= typeof(List<>).MakeGenericType(targetType.GetGenericArguments());
}
else
{
return targetType;
}
}
public object GetDeserializedObject( object obj, Type targetType )
{
if ( _TypeCache.ContainsKey(targetType) )
{
return ImmutableListListConverter.ToImmutableMethod(targetType)(obj);
}
return obj;
}
public object GetObjectToSerialize( object obj, Type targetType )
{
if ( targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(ImmutableList<>) )
{
return ImmutableListListConverter.ToListMethod(targetType)(obj);
}
return obj;
}
public object GetCustomDataToExport( Type clrType, Type dataContractType )
{
throw new NotImplementedException();
}
public object GetCustomDataToExport( System.Reflection.MemberInfo memberInfo, Type dataContractType )
{
throw new NotImplementedException();
}
public void GetKnownCustomDataTypes( System.Collections.ObjectModel.Collection<Type> customDataTypes )
{
throw new NotImplementedException();
}
public Type GetReferencedTypeOnImport( string typeName, string typeNamespace, object customData )
{
throw new NotImplementedException();
}
public System.CodeDom.CodeTypeDeclaration ProcessImportedType( System.CodeDom.CodeTypeDeclaration typeDeclaration, System.CodeDom.CodeCompileUnit compileUnit )
{
throw new NotImplementedException();
}
public ImmutableSurrogateSerializer() { }
}
}
</code></pre>
|
[] |
[
{
"body": "<p>This actually looks pretty nice and I am bookmarking it. :)</p>\n\n<p>Two tiny details, which are probably a waste of time:</p>\n\n<ol>\n<li><p>I would personally (probably) make the <code>ImmutableListListConverter<T></code> a private class inside of the <code>ImmutableListListConverter</code>, since it's an implementation detail of the latter class. </p></li>\n<li><p>I usually try to avoid looking up a hash table multiple times, even though the performance difference is usually negligible. In your case, <code>ImmutableSurrogateSerializer.GetDataContractType</code> could probably avoid looking at the dictionary most of the time by doing the <code>if</code> guard at the beginning and then doing the lookup/insertion in a single step. Also, the indexer right after <code>ContainsKey</code> results in that unnecessary second lookup. Note that this is what I find <strong>simpler to read</strong>, not because the performance difference is anything but negligible:</p>\n\n<pre><code>public Type GetDataContractType(Type t)\n{\n // if this is not an immutable list, we can just skip the rest immediately \n if (!t.IsGenericType || t.GetGenericTypeDefinition() != typeof(ImmutableList<>))\n { \n return type;\n }\n\n // get the result through the cache\n return _TypeCache.GetOrAdd(t, t => typeof(List<>).MakeGenericType(t.GetGenericArguments()));\n}\n</code></pre></li>\n</ol>\n\n<p>But as I've written, apart from that, it's a really nice approach. Proper de/serialization of immutable types is something I've been looking for since .NET 2.0 and the plain old <code>XmlSerializer</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-02T17:03:15.587",
"Id": "36525",
"ParentId": "31688",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T14:14:09.153",
"Id": "31688",
"Score": "8",
"Tags": [
"c#",
"reflection",
"serialization"
],
"Title": "Improve this reflection bashing code"
}
|
31688
|
<p>Kml uses an 8 digit HEX color format. The traditional Hex format for red looks like #FF0000. In Kml, red would look like this FFFF0000. The first 2 digits are for opacity (alpha). Color format is in AABBGGRR. I was looking for a way to set the color as well as the opacity and return it in a string to be placed in an attribute of a KML.</p>
<pre><code>string color
string polyColor;
int opacity;
decimal percentOpacity;
string opacityString;
//This allows the user to set the color with a colorDialog adding the chosen color to a string in HEX (without opacity (BBGGRR))
private void btnColor_Click(object sender, EventArgs e)
{
if (colorDialog1.ShowDialog() == DialogResult.OK)
{
btnColor.BackColor = colorDialog1.Color;
Color clr = colorDialog1.Color;
color = String.Format("{0:X2}{1:X2}{2:X2}", clr.B, clr.G, clr.R); //Color returned in Hex format
}
}
//This method takes the Opacity (0% - 100%) set by a textbox and gets the HEX value. Then adds Opacity to Color and adds it to a string.
private void PolyColor()
{
percentOpacity = ((Convert.ToDecimal(txtOpacity.Text) / 100) * 255);
percentOpacity = Math.Floor(percentOpacity); //rounds down
opacity = Convert.ToInt32(percentOpacity);
opacityString = opacity.ToString("x");
polyColor = opacityString + color;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T15:35:08.733",
"Id": "50563",
"Score": "2",
"body": "“The traditional Hex format for black looks like #FF0000.” That's not black, that's red."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T21:18:07.297",
"Id": "50592",
"Score": "1",
"body": "If the format is AABBGGRR, shoudn't red be FF0000FF instead of FFFF000000?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T11:25:53.813",
"Id": "50626",
"Score": "0",
"body": "@Pierre-Luc Pineeault, Thats blue...and there is only 4 zeros not 6."
}
] |
[
{
"body": "<p>In the <code>System.Drawing</code> namespace lives the <code>ColorTranslator</code> class which has an <code>ToHtml()</code> method which can be used here. A good way would be to create extension methods for this task. The first extension method will be named <code>ToKMLColor</code> and will expect a String parameter.</p>\n\n<p>By using <code>dec.TryParse()</code> and <code>Math.Min()</code> we assure that the given parameter is a valid representation of a decimal/number with a maximum of <code>100</code>. If the <code>TryParse</code> won't succeed, we assume that the opacity will be <code>0</code>.\nAfter we have got the computed (<code>/100*255</code>) opacity value we pass it </p>\n\n<pre><code>public static string ToKMLColor(this Color color, String percentageOpacity)\n{\n decimal opacity = 0;\n decimal.TryParse(percentageOpacity, out opacity);\n\n opacity = Math.Min(opacity, 100);\n opacity = Math.Floor(opacity / 100 * 255);\n\n return color.ToKMLColor(opacity);\n}\n</code></pre>\n\n<p>to the overloaded <code>ToKMLColor()</code> method, which takes a decimal parameter. After converting the decimal to an int we pass it</p>\n\n<pre><code>public static string ToKMLColor(this Color color, decimal opacity)\n{\n return color.ToKMLColor(Convert.ToInt32(opacity));\n} \n</code></pre>\n\n<p>to the overloaded <code>ToKMLColor()</code> method, which takes an integer parameter. Here we call the <code>ToString()</code> method with the <code>X2</code> format to get the hex representation of the integer parameter and concat the return value of the <code>ToHex()</code> by using the <code>Substring()</code> method to remove the leading <code>#</code>.</p>\n\n<pre><code>public static string ToKMLColor(this Color color, int opacity)\n{\n return opacity.ToString(\"X2\") + color.ToHex().Substring(1);\n}\npublic static String ToHex(this Color color)\n{\n return System.Drawing.ColorTranslator.ToHtml(Color.FromArgb(0, color));\n} \n</code></pre>\n\n<p>Now we can call </p>\n\n<pre><code>polyColor = colorDialog1.Color.ToKMLColor(txtOpacity.Text);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-22T10:59:19.253",
"Id": "60793",
"ParentId": "31689",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "60793",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T14:36:54.010",
"Id": "31689",
"Score": "5",
"Tags": [
"c#"
],
"Title": "Getting the KML color code from colordialog box more efficiently"
}
|
31689
|
<p>I am coding a site where users submit sporting events.</p>
<p>When submitting an event there are a lot of fields that need to be validated.</p>
<p>This is the method I wrote to valid the fields:</p>
<pre><code>class event{
private $dbh;
private $post_data;
public function __construct($post_data, PDO $dbh){
$this->dbh = $dbh;
$this->post_data = array_map('trim', $post_data);
}
// long ass method that checks all the input fields are valid
public function checkValidInput(){
if(!empty($this->post_data['event-name']) && (strlen($this->post_data['event-name']) < 101)){
if(!empty($this->post_data['event-description']) && (strlen($this->post_data['event-description']) < 2001)){
if(!empty($this->post_data['event-location-name']) && (strlen($this->post_data['event-location-name']) < 51)){
if(!empty($this->post_data['event-location-town']) && (strlen($this->post_data['event-location-town']) < 21)){
if(isset($this->post_data['event-county'])){
if(!empty($this->post_data['event-postcode']) && (strlen($this->post_data['event-postcode']) < 21)){
if(isset($this->post_data['event-age-restriction'])){
if(!empty($this->post_data['event-booking-address']) && (strlen($this->post_data['event-booking-address']) < 301)){
if(!empty($this->post_data['event-organiser']) && ($this->post_data['event-organiser'] < 51) ){
if(isset($this->post_data['event-select-difficulty'])){
if(isset($this->post_data['event-select-type'])){
if(isset($this->post_data['event-select-environment'])){
if(isset($this->post_data['event-select-traffic'])){
return TRUE;
}else{
throw new Exception('Please select the type of traffic.');
}
}else{
throw new Exception('Please select the type of environment.');
}
}else{
throw new Exception('Please select the type of event.');
}
}else{
throw new Exception('Please select a difficulty rating for this event.');
}
}else{
throw new Exception('Please enter an organiser name that is no longer than 50 characters.');
}
}else{
throw new Exception('Please enter the booking page url for this event. Or the home website url.');
}
}else{
throw new Exception('Please select appropriate age restriction.');
}
}else{
throw new Exception('Please enter a location post code that is no longer than 10 characters.');
}
}else{
throw new Exception('Please select a location county.');
}
}else{
throw new Exception('Please enter a location town name that is no longer than 20 characters.');
}
}else{
throw new Exception('Please enter a location name that is no longer than 50 characters.');
}
}else{
throw new Exception('Please enter a description that is no longer than 2000 characters.');
}
}else{
throw new Exception('Please enter a name that is no longer than 100 characters.');
}
}
}
</code></pre>
<p>As you can see its a pretty big, ugly looking block of code.</p>
<p>Is there a prettier way of writing this that could half the amount of code?</p>
|
[] |
[
{
"body": "<p>Yeah that's ugly :) </p>\n\n<p>You do not have to nest the ifs because when you throw an error, the function will stop executing right there so you can safely do</p>\n\n<pre><code>try {\n if(!empty($this->post_data['event-name']) && (strlen($this->post_data['event-name']) < 101)){\n throw new Exception(\"Event name is not valid\");\n }\n if((strlen($this->post_data['event-description']) < 2001){\n throw new Exception('event-description is not valid'); \n }\n return TRUE;\n} catch (Exception $e) {\n $error = 'Caught exception: ', $e->getMessage(), \"\\n\";\n return FALSE;\n}\n</code></pre>\n\n<p>But in most cases you want to collect all errors and send all of them errors to client</p>\n\n<pre><code>$errors = array();\nif(!empty($this->post_data['event-name']) && (strlen($this->post_data['event-name']) < 101)){\n $errors[] = \"Event name is not valid\"; // push to the array\n}\nif((strlen($this->post_data['event-description']) < 2001){\n $errors[] = \"Event description is not valid\";\n}\nif(sizeof($errors) === 0) {\n return TRUE;\n}else{\n // do something with errors\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T17:07:05.567",
"Id": "31696",
"ParentId": "31693",
"Score": "1"
}
},
{
"body": "<p>Using exceptions to handle this type or error are generally not preferred. Exceptions should be reserved for situations that are generally unrecoverable such as: no disc space, mathematical errors (divide by 0), network resources are unavailable or perhaps a database schema is missing an expected column. User input can generally be 'fixed'. </p>\n\n<p>A goal of cutting the code in half isn't always the best idea if it sacrifices clarity. </p>\n\n<p>An improved solution is to implement some type of grouped form filtering and validation. Many frameworks have a form class which usually allows for attaching a set of filters to remove unwanted input as well as validators to ensure that the remaining input conforms to your expectations. Let's use your 'event-name' as an example. Such a setup could work roughly like:</p>\n\n<pre><code>$form = new Form();\n$eventNameField = new FormField('event-name');\n$eventNameField->setFilters(array('strip-tags', 'string-trim')); //Exclude any tags and whitespace\n$eventNameField->setValidator('alpha'); //Only allow A-Z (upper or lower) as the name\n$eventNameField->setValidator(\n array(\n 'length' => array(\n 'min' => 3, \n 'max' => 32\n )\n )\n); //Only allow names between 3 and 32 characters\n$form->addField($eventNameField); //Add this field, with this set of filters/validators to the form\n\n//Assuming you are receiving the POST data\n$form->setPostData($_POST); //The Form class will handle setting the correct $_POST data in the correct field.\nif ($form->isValid()) {\n //Process data\n} else {\n //There are errors in the form\n $this->view->errors = $form->getErrors();\n}\n\n//Assuming you are in the view\nforeach ($this->errors as $error) {\n echo $error . \"\\n\";\n}\n</code></pre>\n\n<p>There are other components that allow for even more flexibility in the use of such a design. Setting up fields individually and then pulling a set together to compose a form allows for reuse of a configured field. There are few cases where you would want to have different filters and validators for a given form field. The requirements for an event name should be the same in one part of the application as in another. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T20:02:56.430",
"Id": "47826",
"ParentId": "31693",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "31696",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T16:11:50.850",
"Id": "31693",
"Score": "1",
"Tags": [
"php",
"validation"
],
"Title": "Form validation for sporting events"
}
|
31693
|
<p>I have a method that returns a <code>List<Object></code> from any given <code>Object</code> containing its values. It doesn't get the values of any <code>static</code> or <code>final</code> field in the class.</p>
<pre><code>public List<Object> objectData(Object object) {
Field[] fields = object.getClass().getDeclaredFields();
Set<String> realFields = new LinkedHashSet<String>();
for(Field field : fields) {
if (!(java.lang.reflect.Modifier.isStatic(field.getModifiers()) ||
java.lang.reflect.Modifier.isFinal(field.getModifiers()))) {
realFields.add(field.getName());
}
}
List<Object> row = new ArrayList<Object>();
for(String realField : realFields) {
Field currentField = object.getClass().getDeclaredField(realField);
currentField.setAccessible(true);
row.add(currentField.get(object));
}
return row;
}
</code></pre>
<p>Is this the right approach? Isn't something else I can be missing?</p>
<hr>
<p>EDIT: The method above was adapted from this one. I'm assuming <code>Collection<T> data</code> is a valid non-empty collection.</p>
<pre><code>public List<List<Object>> getData(Collection<T> data) {
try {
Field[] fields = data.iterator().next().getClass().getDeclaredFields();
Set<String> realFields = new LinkedHashSet<String>();
for(Field field : fields) {
if (!(java.lang.reflect.Modifier.isStatic(field.getModifiers()) ||
java.lang.reflect.Modifier.isFinal(field.getModifiers()))) {
realFields.add(field.getName());
}
}
List<List<Object>> realData = new ArrayList<List<Object>>();
for(T element : data) {
List<Object> row = new ArrayList<Object>();
for(String realField : realFields) {
Field currentField = element.getClass().getDeclaredField(realField);
currentField.setAccessible(true);
row.add(currentField.get(element));
}
realData.add(row);
}
} catch (Exception e) {
//basic error handling, this will be improved;
throw new RuntimeException(e);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>In principle, your code is correct (provided you really do not want to deal with fields in superclass). But it can be optimized: inside the first loop, you already have fields so there is no need to save their names in a collection and retrieve later - just use them in place.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T19:10:37.147",
"Id": "50583",
"Score": "0",
"body": "The above method was adapted from another method that returns a `List<List<Object>` from a given `Collection<Object>`. I'll update the code to show the other method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T19:13:54.053",
"Id": "50584",
"Score": "0",
"body": "Question updated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T19:20:45.337",
"Id": "50585",
"Score": "0",
"body": "Then what? Another method is also suboptimal, though in a different way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T19:34:44.893",
"Id": "50586",
"Score": "0",
"body": "Can you explain please?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T04:16:48.620",
"Id": "50602",
"Score": "0",
"body": "`realFields` should be of type `Field[]`, not `Set<String>`."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T18:04:49.530",
"Id": "31702",
"ParentId": "31697",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "31702",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T17:27:02.467",
"Id": "31697",
"Score": "2",
"Tags": [
"java",
"reflection"
],
"Title": "Is this the right way to retrieve all the fields from any Object?"
}
|
31697
|
<p>I've written a piece of code. Would like to know is the below piece of code unit testable or does it need any kind of refactoring.</p>
<p>MatchCilentUrls is the primary method for matching two urls. Based on my business logic i am matching the Urls.</p>
<p>Appreciate your comments on this.</p>
<pre><code> public bool MatchClientUrls(string redirectUrl, string whiteListUrls)
{
if (String.IsNullOrEmpty(redirectUrl) || String.IsNullOrEmpty(whiteListUrls))
throw new ArgumentNullException();
var urlList = whiteListUrls.Split(';');
var redirectUrlScheme = string.Empty;
var redirectUrlDomain = string.Empty;
var urlScheme = string.Empty;
var urlDomain = string.Empty;
ParseUrl(redirectUrl, out redirectUrlScheme, out redirectUrlDomain);
foreach (var url in urlList)
{
urlScheme = string.Empty;
urlDomain = string.Empty;
ParseUrl(url, out urlScheme, out urlDomain);
if (String.IsNullOrEmpty(redirectUrlScheme) || String.IsNullOrEmpty(urlScheme))
{
if (redirectUrlDomain.StartsWith(urlDomain, StringComparison.OrdinalIgnoreCase) || urlDomain.StartsWith(redirectUrlDomain, StringComparison.OrdinalIgnoreCase))
return true;
}
else
{
if (redirectUrlScheme == urlScheme)
{
if (redirectUrlDomain.StartsWith(urlDomain, StringComparison.OrdinalIgnoreCase) || urlDomain.StartsWith(redirectUrlDomain, StringComparison.OrdinalIgnoreCase))
return true;
}
}
}
return false;
}
private void ParseUrl(string url, out string scheme, out string domain)
{
scheme = string.Empty;
domain = string.Empty;
var index = url.IndexOf("//");
if (index > 0)
{
scheme = url.Substring(0, index - 1);
domain = url.Substring(index + 2);
}
else
{
domain = url;
}
}
public bool ValidateUrl(string url)
{
var regEx = @"^(http(s)?://)?[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?$";
if(Regex.IsMatch(url, regEx))
return true;
else
return false;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T08:29:50.020",
"Id": "50620",
"Score": "2",
"body": "I think it's `C#` not `Java`."
}
] |
[
{
"body": "<p>Of course it is unit testable.</p>\n\n<p>All function/methods are.</p>\n\n<p>A unit test is to flex the function to breaking point. i.e. exercise the usual conditions and the boundary points.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T05:55:27.610",
"Id": "31699",
"ParentId": "31698",
"Score": "1"
}
},
{
"body": "<p>Use combination of testng+easymock+powermock.\nIt can just test anything. Even private static methods</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T05:58:41.497",
"Id": "31700",
"ParentId": "31698",
"Score": "1"
}
},
{
"body": "<p>It looks unit testable to me. Every method has a single purpose.</p>\n\n<p>Check that link also: <a href=\"https://stackoverflow.com/questions/2515048/is-my-code-really-not-unit-testable\">https://stackoverflow.com/questions/2515048/is-my-code-really-not-unit-testable</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T05:58:45.747",
"Id": "31701",
"ParentId": "31698",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "31701",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T05:50:34.217",
"Id": "31698",
"Score": "1",
"Tags": [
"java",
"unit-testing"
],
"Title": "Is my code unit testable"
}
|
31698
|
<p>I'm getting back into web development, and I'm creating a mobile-friendly web app. I'm trying to make it SPA-like in the sense that I don't load new pages for each action the user takes. As my index.cshtml page will show, I have a header, and then I have a bunch of <code>div</code>s. Those <code>div</code>s serve as placeholders for each "page" in the app. Only one div is shown at a time. Is this an acceptable approach? Is there a better way that's considered best practice?</p>
<p>Index.cshtml:</p>
<pre class="lang-html prettyprint-override"><code>@model PrestoDashboardWeb.Models.EntityContainer
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link href="~/Content/jquery.mobile-1.3.2.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.mobile-1.3.2.min.js"></script>
<title>Presto</title>
</head>
<body>
<div data-role="header" data-theme="a">
<img src="~/Content/images/wizard1.ico" height="48" width="48" style="display: block; float: right;"/>
<h1 style="font-size: 32px">Presto</h1>
</div>
<div data-role="navbar" data-grid="d">
<ul> <!-- These are the different actions the user can take. -->
<li onclick="showApps()"><a href="#" class="ui-btn-active">Apps</a></li>
<li onclick="showServers()"><a href="#">Servers</a></li>
<li onclick="showVariableGroups()"><a href="#">Variables</a></li>
<li><a href="#">Resolve</a></li>
<li><a href="#">Installs</a></li>
<li><a href="#">Log</a></li>
<li><a href="#">Ping</a></li>
<li><a href="#">Global</a></li>
<li><a href="#">Security</a></li>
</ul>
</div><!-- /navbar -->
<!-- These are the placeholder divs. Only one is shown at a time. -->
<div data-role="header" data-theme="b">
<h1 id="selectedTab"><span>Apps</span></h1>
</div>
<div id="appList">
@Html.Partial("~/Views/PartialViews/AppList.cshtml", Model.Applications)
</div>
<div id="serverList">
@Html.Partial("~/Views/PartialViews/ServerList.cshtml", Model.Servers)
</div>
<div id="variableGroupList">
@Html.Partial("~/Views/PartialViews/VariableGroupList.cshtml", Model.VariableGroups)
</div>
<div id="app">
@Html.Partial("~/Views/PartialViews/App.cshtml")
</div>
</body>
<script>
$(function () {
showApps();
});
function showApps() {
hideAll();
$('#appList').show();
$('#selectedTab').text('Apps');
}
function showServers() {
hideAll();
$('#serverList').show();
$('#selectedTab').text('Servers');
}
function showVariableGroups() {
hideAll();
$('#variableGroupList').show();
$('#selectedTab').text('Variable Groups');
}
function hideAll() {
$('#appList').hide();
$('#serverList').hide();
$('#variableGroupList').hide();
$('#app').hide();
}
function showApp(id) {
hideAll();
$('#app').show();
window.appInitialize(id);
}
</script>
</html>
</code></pre>
<p>The user can select Apps, and this partial view will be displayed:</p>
<pre class="lang-html prettyprint-override"><code>@model IEnumerable<PrestoCommon.Entities.Application>
<ul data-role="listview" data-autodividers="true" @*data-filter="true"*@ data-count-theme="c" data-inset="true" data-divider-theme="d">
@foreach (var app in Model)
{
<li onclick="showApp('@app.Id');"><a href="#">@app.Name</a></li>
}
</ul>
</code></pre>
<p>And if the user clicks an app from above, <code>showApp()</code> gets called (see index.cshtml, above) with the app ID getting passed to it. <code>showApp()</code> will then hide all the other <code>div</code>s and show the only the partial view that displays the app:</p>
<pre class="lang-html prettyprint-override"><code><script>
$(function() {
// Note: This will execute as soon as the main page is loaded.
});
function appInitialize(id) {
$('#selectedTab').text(id); // Show the name of the app in the header
$('#text-14').val(id); // Just show the ID for testing.
}
</script>
<form>
<div data-role="fieldcontain">
<label for="text-14">Text input:</label>
<input type="text" data-mini="true" name="text-14" id="text-14" value="">
</div>
</form>
</code></pre>
<p>This is me totally guessing at an approach to make the site look like the user is staying on a single page. I'm hoping for a sanity check to let me know that this is right or it's way off. And if there are any issues with the code itself, I'd love to know what can be improved.</p>
|
[] |
[
{
"body": "<p>It's more of a personal preference thing, but I would recommend removing the onclicks in the following:</p>\n\n<pre><code><li onclick=\"showApps()\"><a href=\"#\" class=\"ui-btn-active\">Apps</a></li>\n<li onclick=\"showServers()\"><a href=\"#\">Servers</a></li>\n<li onclick=\"showVariableGroups()\"><a href=\"#\">Variables</a></li>\n</code></pre>\n\n<p>Instead, my recommendation would be to put a class on the links, say something like this:</p>\n\n<pre><code><li><a href=\"#\" class=\"navLink\">Apps</a></li>\n<li><a href=\"#\" class=\"navLink\">Servers</a></li>\n</code></pre>\n\n<p>Then in jquery, add something like the following:</p>\n\n<pre><code>$(\".navLink\").click(function (e) {\n var link = $(this);\n switch (link.text()) {\n case \"Apps\":\n $(\"#appList\").fadeIn(500);\n break;\n case \"Servers\":\n $(\"#serverList\").fadeIn(500);\n break;\n }\n});\n</code></pre>\n\n<p>Also, for the partialviews, you cannot render javascript in those (that I've found), so the easiest way to ensure that you can jQuery those would be to add a </p>\n\n<pre><code>$(document).delegate(\".appListItem\", \"click\", function (e) {\n // Stuff to do when clicking an item in the appList.\n});\n</code></pre>\n\n<p>Also, if you would prefer to not have to load all the partialviews on page load (something I've found can slow down a page's loadtime), you might try something along the lines of changing your navlinks to something like this:</p>\n\n<pre><code><li><a href=\"@Url.Action(\"GetMyApps\", \"Apps\")\" class=\"topLevelNavLink\">Apps</a></li>\n</code></pre>\n\n<p>And then in jQuery do this:</p>\n\n<pre><code>$(\".topLevelNavLink\").click(function (e) {\n var url = $(this).attr(\"href\");\n $(\"#contentDiv\").load(url);\n });\n</code></pre>\n\n<p>There are many different ways to do it, and it really is a matter of preference. Your way doesn't look bad, but it would drive my OCD through the roof with the onclicks in the html tags and the loading of the divs that are hidden when loading the page (I'm a firm believer in passing only as much data across the wire as is necessary to display what is expected - to improve performance (even if it's just a few milliseconds) and lower the bandwidth used). But again it's all a matter of preference.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-06T19:09:01.877",
"Id": "155148",
"Score": "0",
"body": "Welcome to CodeReview, nick. Awesome first post. Hope you enjoy the site."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-06T19:11:29.590",
"Id": "155151",
"Score": "0",
"body": "Thanks, Legato! I'm excited to be here. Good code reviews teach the reviewer as well as the submitter, so I'm hoping to leverage this to learn the trade a little better."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-06T18:50:19.377",
"Id": "86058",
"ParentId": "31703",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T18:34:03.940",
"Id": "31703",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"asp.net",
"asp.net-mvc-4"
],
"Title": "Navigating in ASP.NET MVC 4 in SPA-like App"
}
|
31703
|
<p>I have been working on a character escaper for a production server that receives quite a few requests per second (sometimes in the range of 400).</p>
<p>We forward some "query" requests to apache Lucent/SOLR, and I need to escape characters.</p>
<p>Containing also feedback from <a href="https://softwareengineering.stackexchange.com/questions/212254/optimized-special-character-escaper-vs-matcher-pattern">programmers-stackexchange</a> , the code below is the result.</p>
<p><strong>Can anyone see any bugs or additional ways to optimize?</strong></p>
<pre><code>String query = "http://This+*is||a&&test(whatever!!!!!!)";
char[] queryCharArray = new char[query.length()*2];
char c;
int length = query.length();
int currentIndex = 0;
for (int i = 0; i < length; i++)
{
c = query.charAt(i);
if(mustBeEscaped[c]){
if('&'==c || '|'==c){
if(i+1 < length && query.charAt(i+1) == c){
queryCharArray[currentIndex++] = '\\';
queryCharArray[currentIndex++] = c;
queryCharArray[currentIndex++] = c;
i++;
}
}
else{
queryCharArray[currentIndex++] = '\\';
queryCharArray[currentIndex++] = c;
}
}
else{
queryCharArray[currentIndex++] = c;
}
}
query = new String(queryCharArray,0,currentIndex);
System.out.println("TEST="+query);
private static final boolean[] mustBeEscaped = new boolean[65536];
static{
mustBeEscaped[':']= //
for(char c: "\\?+-!(){}[]^\"~*&|".toCharArray()){
mustBeEscaped[c]=true;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T21:00:44.103",
"Id": "50589",
"Score": "0",
"body": "I like your original version a lot better. If you need this to be faster, then I would suggest to just write it in C."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T06:28:22.350",
"Id": "50608",
"Score": "1",
"body": "Have you profiled your application? Are you sure this method is a bottleneck?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T06:31:20.987",
"Id": "50609",
"Score": "0",
"body": "You can avoid creating a new `queryCharArray` on each call by reusing always the same preallocated 'big enough' one. I am not sure if that would improve the speed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T08:03:11.250",
"Id": "50618",
"Score": "1",
"body": "@MrSmith42: Only a good idea if there are no threads involved."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T07:54:46.370",
"Id": "50756",
"Score": "0",
"body": "@Bobby: If threads are involved, you can still reuse threadlocal preallocated arrays."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T08:37:58.000",
"Id": "50758",
"Score": "0",
"body": "@MrSmith42: Depends, I think, but true. Depends if the thread is reused or if it is a worker-thread dedicated to one task with only calling this escaping one or two times (think of accepting connections). I had the that one in mind."
}
] |
[
{
"body": "<p>First I have to be honest and say that this code puts me into WTF-Mode very early on, but that must not be a bad thing. But what took me by surprise is the lack of comments, there are some edge-cases in there I can not make out why they're the way they're.</p>\n\n<p>On the latter, changing, suggestions I did only perform minor profiling by simply running it in a loop with 1 million iterations and seeing if the time differs by much.</p>\n\n<hr>\n\n<p>Rule of thumb: Never roll your own security!</p>\n\n<hr>\n\n<p>Your indentation/brace-style is a mess. Java normally uses a modified K&R-Style, with the opening brace on the same line.</p>\n\n<pre><code>function test() {\n if (condition) {\n // Stuff\n } else {\n // Stuff\n }\n}\n</code></pre>\n\n<p>You should fix that first.</p>\n\n<hr>\n\n<p>Some of your names can be improved. F.e. <code>queryCharArray</code> might be better named <code>escapedQuery</code>.</p>\n\n<hr>\n\n<p>You might want to extract all hard coded chars at least into static final variables for readability.</p>\n\n<hr>\n\n<p>Your loop-beginning can be changed to:</p>\n\n<pre><code>char[] queryCharArray = new char[query.length() * 2];\nint currentIndex = 0;\n for (int i = 0; i < query.length(); i++) {\n char c = query.charAt(i);\n</code></pre>\n\n<p>This improves readability by a lot.</p>\n\n<hr>\n\n<p>Your loop can be optimized to this:</p>\n\n<pre><code>char c = query.charAt(i);\nif (mustBeEscaped[c]) {\n queryCharArray[currentIndex++] = '\\\\';\n if ('&' == c || '|' == c) {\n if (i + 1 < query.length() && query.charAt(i + 1) == c) {\n queryCharArray[currentIndex++] = c;\n i++;\n }\n }\n}\nqueryCharArray[currentIndex++] = c;\n</code></pre>\n\n<p>This removes unnecessary else-blocks.</p>\n\n<hr>\n\n<pre><code>if ('&' == c || '|' == c) {\n if (i + 1 < query.length() && query.charAt(i + 1) == c) {\n</code></pre>\n\n<p>You should leave a comment here explaining why these characters are special. Extracting them into another array might be a good idea.</p>\n\n<pre><code>if (skipNextOccurence[c]) {\n</code></pre>\n\n<hr>\n\n<p>Putting all this together (and renaming the constants to fit the Java naming conventions), I ended up with this in my tests:</p>\n\n<pre><code>private static final boolean[] MUST_BE_ESCAPED = new boolean[65536];\nprivate static final boolean[] SKIP_NEXT_OCCURENCE = new boolean[65536];\nprivate static final char ESCAPE_CHARACTER = '\\\\';\n\nstatic {\n for (char c : \"\\\\?+-!(){}[]^\\\"~*&|\".toCharArray()) {\n MUST_BE_ESCAPED[c] = true;\n }\n for (char c : \"&|\".toCharArray()) {\n SKIP_NEXT_OCCURENCE[c] = true;\n }\n}\n\nprivate static String escape(String query) {\n char[] escapedQuery = new char[query.length() * 2];\n int currentIndex = 0;\n\n for (int idx = 0; idx < query.length(); idx++) {\n char c = query.charAt(idx);\n\n if (MUST_BE_ESCAPED[c]) {\n escapedQuery[currentIndex++] = ESCAPE_CHARACTER;\n\n if (SKIP_NEXT_OCCURENCE[c]) {\n // Check if the next char is the same, and if yes add it to\n // the escapedQuery and make sure that it is skipped.\n if (idx + 1 < query.length() && query.charAt(idx + 1) == c) {\n escapedQuery[currentIndex++] = c;\n idx++;\n }\n }\n }\n\n escapedQuery[currentIndex++] = c;\n }\n\n return new String(escapedQuery, 0, currentIndex);\n}\n</code></pre>\n\n<hr>\n\n<p>To elaborate on the possibilities to use a StringBuilder, or a Set, or pretty much everything else I tried to come up with which looked more readable...damn that thing is fast! Even using a StringBuilder slowed it down considerably. So as long as you're aware that you are, a little bit at least, abusing memory with that 65k array (which will end up as 65k * 8Byte on most platforms) it's fine with me.</p>\n\n<p>Also don't forget that you allocate twice the amount of whatever is passed into this function. So if somebody feels funny and passes a 1Mb query into that, it will <em>at least</em> consume 3Mb (1+1*2) on it's way. That is, if the JVM is not smarter then I think and does not allocate all that at once.</p>\n\n<p>Just use more comments and JavaDoc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T14:31:42.780",
"Id": "50782",
"Score": "1",
"body": "+1 Nice comments overall. Just some further style suggestions. When you have a constant declared as `static final`, it's generally named in `CAPS_WITH_UNDERSCORE_SPACES`. So `escapeCharacter` might be renamed `ESCAPE_CHARACTER`. I might also make these `String` literals into actual constants, just for readability, but that's entirely subjective (`\"\\\\?+-!(){}[]^\\\"~*&|\".toCharArray()`). Really elegant ideas with the two huge `boolean[]`s though. Very clever. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T14:40:03.160",
"Id": "50784",
"Score": "0",
"body": "@JeffGohlke: Good call! I fall for that one *every single time*. And of course feel free to add your own answer, even if just has one or two points, it counts."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T08:28:05.173",
"Id": "31719",
"ParentId": "31705",
"Score": "5"
}
},
{
"body": "<p>First of all, I really doubt that this function is your performance bottleneck. Compared to the act of searching through your document repository, the work involved in escaping the query string is surely negligible!</p>\n\n<p>Second, I think there is a bug. Is your intention to let <code>&&</code> and <code>||</code> pass through unescaped to the output, while prefixing single <code>&</code> or <code>|</code> with a backslash? If so, you should note your intentions in a comment. As written, your code would produce no output corresponding to a solitary <code>&</code> or <code>|</code> in the input.</p>\n\n<p>By the way, I would consider that hybrid treatment of the query string as a red flag. Is your input supposed to contain literal search terms? Or a Lucene/SOLR query? Why are you trying to create a dumbed-down search language that only supports <code>&&</code> and <code>||</code> but not the other features of the Lucene/SOLR language? Even in the best case, it would still lead to a weird user experience.</p>\n\n<p>Third, it's wasteful to use a 65336-element array to detect 17 special characters. That's 64 kiB, or 8 kiB assuming super-efficient packing. Wasteful memory usage could also hurt performance by creating pressure on the cache. The use of a lookup table is particularly deplorable here since you still have special cases for <code>&&</code> and <code>||</code> that have to be hard-coded in the logic anyway. For all these ills, I recommend using a <code>switch</code> statement instead, which should be quite efficient.</p>\n\n<p>Fourth, I recommend using a <code>StringBuilder</code> instead of a <code>char[]</code>, because that's exactly what it's meant for.</p>\n\n<p>Here's how I would write it…</p>\n\n<pre><code>public static String escapeLuceneQuery(String query) {\n int len = query.length();\n StringBuilder result = new StringBuilder(2 * len);\n for (int i = 0; i < len; i++) {\n char c = query.charAt(i);\n switch (c) {\n case '&': case '|':\n if (i + 1 < len && query.charAt(i + 1) == c) {\n // Special case: pass through && and || to the output\n result.append(c).append(c);\n i++;\n break;\n }\n // Solitary & or |. Flow through...\n case '\\\\': case '?': case '+': case '-': case '!':\n case '(': case ')': case '{': case '}':\n case '[': case ']': case '^': case '\"':\n case '~': case '*':\n result.append('\\\\');\n // Flow through...\n default:\n result.append(c);\n }\n }\n return result.toString();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T11:26:55.043",
"Id": "50627",
"Score": "0",
"body": "That's not correct, `&&` should become `\\&&` according to OPs code. Except if I misread that part."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T14:59:54.723",
"Id": "50649",
"Score": "0",
"body": "@Bobby I wrote my solution the way as OP probably intended, rather than bug-compatible with OP's code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T08:59:22.897",
"Id": "50760",
"Score": "1",
"body": "I doubt that this implementation is faster. But only profiling can proof that. It also looks a lot like the implementation before the optimization posted on http://programmers.stackexchange.com/questions/212254/optimized-special-character-escaper-vs-matcher-pattern"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T14:50:06.517",
"Id": "50787",
"Score": "1",
"body": "@MrSmith42: Oh, so you were the mad mind that came up with that 65k-bool-array. The idea is awesome, mad, but awesome."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T16:05:48.140",
"Id": "50792",
"Score": "1",
"body": "@Bobby: *speed* was the goal, memory was not a limitation. And if the problem can be reduced to ASCII, an array of size 128 would be sufficient."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T10:53:22.103",
"Id": "31728",
"ParentId": "31705",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "31719",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T18:46:27.923",
"Id": "31705",
"Score": "2",
"Tags": [
"java"
],
"Title": "CharacterEscaper - further optimizable? Bugs?"
}
|
31705
|
<p>I think that the following query is preventing against SQL injection, but what other measures do I need to take to ensure my queries are 100% safe from any malicious attacks?</p>
<pre><code>$statement = $db->prepare(
"INSERT INTO blogs (blogtitle, blogdesc, coverimage, userID, frontpage, tags)
VALUES (:buildtitle, :builddesc, :buildcover, :userid, :frontpage, :addtags)"
);
if ($statement->execute(array(
':buildtitle' => $_POST['addbuildtitle'],
':builddesc' => $_POST['addbuilddesc'],
':buildcover' => $imagepath,
':userid' => $_POST['adduserid'],
':frontpage' => $frontpage,
':addtags' => $_POST['addtags']))
);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T23:36:05.933",
"Id": "50598",
"Score": "0",
"body": "Which classes are you using (what is $db) ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T08:34:49.600",
"Id": "50621",
"Score": "0",
"body": "@Josay $db is obviously PDO lol"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T08:55:29.803",
"Id": "50623",
"Score": "0",
"body": "Yeah PDO, $db is just the connection"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T09:20:50.187",
"Id": "50624",
"Score": "1",
"body": "@Pinoniq Sorry for asking. My feeling was that PDO was not the only candidate (cf http://php.net/manual/en/mysqli-stmt.execute.php for instance)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T09:33:39.037",
"Id": "50625",
"Score": "0",
"body": "@Josay if you read the doc. you can see that ->execute accepts 'void'. So this code is not mysqli ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T06:35:46.583",
"Id": "51378",
"Score": "0",
"body": "The content that you insert here is propably shown in some HTML document somewhere? In that case, you need to protect against cross-site scripting attacks."
}
] |
[
{
"body": "<p>100% safe is not possible; I'm sure someone will break prepared statements if they haven't already. You have already take an big step in security by using prepared statements over escaping. </p>\n\n<p>One important step is to validate your POST variables. For instance let's say a valid buildtitle only consists of alpha numeric characters; it should be validated against that. Then you would wind up with something like <code>':buildtitle' => $buildtitle_clean,</code>. You may already be doing this and just keeping it in the POST array, but it is important to change if you are not.</p>\n\n<p>Other than that, I think it is as safe as you can make it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-09T14:38:41.760",
"Id": "51863",
"Score": "1",
"body": "Hello, and welcome to CR. Since I noticed your answer in the review section under _\"first posts\"_ I thought I'd give you a heads up: this answer doesn't actually review the code. You don't go into details about how and what the OP should do... sure _validate your POST variable_ is a valid critique, but be more specific... PS: you're not quite right when you say this code is as safe as you can make it (cf my answer)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-09T13:02:52.930",
"Id": "32468",
"ParentId": "31706",
"Score": "-1"
}
},
{
"body": "<p>Though prepared statements do a pretty good job protecting your DB from injection attacks, it never hurts to perform some additional checks on the data you're receiving. For example: when a request is supposed to contain an email address, you might perform a <code>SELECT</code> query usign that email address, or insert it in your DB. If so, you <em>should</em> add this:</p>\n\n<pre><code>if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))\n{\n exit();//redirect, optionally show error message\n}\n</code></pre>\n\n<p>Same goes for <em>any</em> posted data, as one of the comments mentions: XSS attacks are one of the biggest threats on the web today. <a href=\"https://codereview.stackexchange.com/questions/29294/how-can-i-make-this-code-safer-against-xss-attacks/29295#29295\">I've dealt with the matter in this answer</a>.<br/>\nThe very least you could do is:</p>\n\n<pre><code>$execParam = array_map(\n 'strip_tags'\n array(\n ':buildtitle' => $_POST['addbuildtitle'], \n ':builddesc' => $_POST['addbuilddesc'], \n ':buildcover' => $imagepath, \n ':userid' => $_POST['adduserid'], \n ':frontpage' => $frontpage, \n ':addtags' => $_POST['addtags']\n )\n);\n$statement->execute($execParam);\n</code></pre>\n\n<p>Here, I've just called <code>strip_tags</code> on each and every single item you're about to insert, to avoid some jokester posting</p>\n\n<pre><code><script>location.href = 'http://malware-infested-site.org';</script>;\n</code></pre>\n\n<p>in the <code>addbuilddesc</code> field... because, if you don't filter those things out, people visiting your site won't be all too happy about that... and be honest: would you?</p>\n\n<p>You can take this as far as you want. Since you're obviously using a traditional *SQL DB, you might use the table schema, to determine if the POST params are of the correct type and length:</p>\n\n<pre><code>//assume blogtitle is a VARCHAR(255) field:\n':buildtitle' => sprintf('%255s',$_POST['addbuildtitle'])\n//and userID is an unsigned int, 11 long\n':userid' => sprintf(\"%11d\",abs((int)$_POST['adduserid']))\n</code></pre>\n\n<p>This ensures your <code>:buildtitle</code> bind will be <em>no longer</em> than 255 chars. The userid value will <em>not</em> be negative, and will be an integer of <em>max</em> 11 digits long.<br/>\nBut to implement this would mean a huuuge mess of <code>sprintf</code> calls, so you <em>could</em> use dataModels for this (check pretty much all of my DB related answers on this site for details), and use getters and setters that use this <code>sprintf</code> function to format the data accordingly.<Br/>\nstill, this will mean a lot of overhead for <em>each</em> and <em>every</em> query. Sadly, the tradoff will always be one of performance vs security. If security is all you're after, you'll also note that, in my other answers, I basically advise everybody who's trying to create a solid (as in strong, but also as in S.O.L.I.D.) query system, to have a look at doctrine. No need to reinvent the wheel...<br/>\nAnyway, I'm going off course...</p>\n\n<p>Now, as far as injection goes, prepared statements are pretty robust, provided you don't take it to new, absurd, extremes. I've seen people use variables instead of the DB name, just like I've seen them use POST params to fill in the <em>table name</em>. You don't seem to do that, and that's good... great even. Just a friendly warning: if ever you consider using variables in those parts of your query that <em>should</em> be static (<code>SELECT fieldnames FROM tblNames</code>), step back and rethink your approach, because that's where you may still introduce vulnerabilities to your system.</p>\n\n<p>Basically, prepared statements work like this:</p>\n\n<ul>\n<li>Pass a string, from which a statement is to be prepared. This is processed by the DB server as is.</li>\n<li>The DB server parses, and <em>\"prepares\"</em> the query (optimization etc...)</li>\n<li>Pass the arguments, with which the statement is to be executed. These values (binds) are sent via a <em>different protocol</em> and here's where they're being escaped correctly.</li>\n</ul>\n\n<p>As you can see, the binds are what is being escaped and sent completely separatly, that's why prepared statements are safe. This also explains why the actual SELECT and FROM clauses in a prepared statement <em>may not be gotten from user input</em>. This part of the query isn't processed in the same way the binds are...</p>\n\n<p><em>Other niggles:</em></p>\n\n<ul>\n<li>At no point do you seem to be checking <code>isset($_POST['adduserid'])</code> and other post keys. You just seem to <em>expect</em> they're there. That might trigger notices, and slows your code down. Just <code>isset()</code> all those params.</li>\n<li>You have a semi-colon at the end of your <code>if</code> statement. If you copy-pasted this code, then that's going to give you grief.</li>\n<li>Ensure, especially with <code>INSERT</code>'s to set the <code>PDO::ERR_MODE</code> correctly, and insert in transactions. In case something goes wrong, you can still use <code>rollBack</code>!</li>\n</ul>\n\n<p>Here's a little sample of how that would look</p>\n\n<pre><code>$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);//force PDO to throw on error\ntry\n{\n $db->beginTransaction();//start here\n $stmt = $db->prepare($query);\n $stmt->execute($sanitizedInsertParamsArray);\n $db->commit();//make insert permament\n}\ncatch(PDOExcpetion $e)\n{\n $db->rollBack();//revert insert!\n exit($e->getMessage());\n}\n</code></pre>\n\n<p>The code above will throw an instance of <code>PDOException</code> if the <code>prepare</code>, <code>execute</code> call or even the <code>commit</code> fails. As long as <code>commit</code> hasn't been called, the transaction is still pending (ie the data isn't really inserted yet).<br/>\nSo simply put, this snippet asks the DB: prepare this statement, then try to execute it with these values, if you did that, <em>then</em> save it. If any of these three steps failed, <code>$db->rollBack()</code> just tells the DB: OK, so it didn't work, forget about it... don't try and save half of the data, just forget <em>everything</em>.</p>\n\n<p>Transactions are a good way to avoid orphaned data (as are FK's, btw). And they make for a safer query all together, too...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-09T14:05:41.373",
"Id": "32474",
"ParentId": "31706",
"Score": "6"
}
},
{
"body": "<p>Adding extra information about protecting from SQL injections.</p>\n\n<ul>\n<li><p>You should sanitize / validate all data before replace it in queries.\nThis can be achieved with filters ( as said ), regexes, substring, it depends on what to\ncheck.</p></li>\n<li><p>Create different users in db if posible. User for Read, Write or Both. If not possible, create a wrapper that simulates users and permissions per page / per query, again your needs.</p></li>\n<li><p>Create views if posible. Views hides complexities and can be another protection method.</p></li>\n<li><p>I would recomend using unit testing software for example phpunit. It can help you too.</p></li>\n</ul>\n\n<p>And why not. Test your web yourself. Use automated attack tools like havij, sqlmap, etc.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-09T16:11:16.297",
"Id": "32481",
"ParentId": "31706",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T19:11:39.397",
"Id": "31706",
"Score": "2",
"Tags": [
"php",
"sql",
"security",
"pdo"
],
"Title": "Remove vulnerabilities from query on public website"
}
|
31706
|
<p>Here's the query: </p>
<pre><code> using (var db = CreateContext())
{
// performing the check for HasBeenAdded inline here, is this only one db call?
return db.Subjects.Select(s => new SubjectDto(s){HasBeenAdded = db.Interests.Any(x => x.SubjectId == s.SubjectId)}).ToList();
}
</code></pre>
<p>Basically I create a DTO from a subject and then populate a property of that DTO (HasBeenAdded) based on whether or not that entry's foreign key exists in another table. Is this the right way to go?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T23:30:08.863",
"Id": "50596",
"Score": "1",
"body": "Seems relatively simple to me. Some newline characters would spruce it up a bit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T01:48:05.413",
"Id": "50600",
"Score": "1",
"body": "Can you not access Interests from the Subjects object given there is a link between the two? ie. HasBeenAdded = s.Interests.Any()"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T16:58:21.573",
"Id": "64736",
"Score": "0",
"body": "To play with \"LINQ to Entities\" I use the [\"LINQPad\"](http://www.linqpad.net/) application. It helps me a lot to optimize my queries."
}
] |
[
{
"body": "<p>I would normally suggest consistent usage. In the example you provide, you use both constructor parameters as well as property initialisation.</p>\n\n<p>Depending on you options to change etc. the <strong>SubjectDto</strong> I would add another construction parameter to it and pass in a hasBeenAdded variable.</p>\n\n<p>When talking about improving the LINQ query, I think readability and maintainability has highest priority. Often performance optimisations degrade readability and enforces you to write some additional comments.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T18:11:18.927",
"Id": "38647",
"ParentId": "31710",
"Score": "2"
}
},
{
"body": "<p>In terms of \"SQL\" what you need is a <a href=\"http://technet.microsoft.com/pt-br/library/ms187518%28v=sql.105%29.aspx\" rel=\"nofollow\">\"Left Outer Join\"</a>. So I would suggest this:</p>\n\n<pre><code>using (var db = CreateContext())\n{\n var subjectDtos = from subject in Subjects\n join interest in Interests on subject.SubjectId equals interest.SubjectId into si\n from interest in si.DefaultIfEmpty()\n select new SubjectDto { Subject = subject, HasBeenAdded = interest != null };\n return subjectDtos.Distinct().ToList();\n}\n</code></pre>\n\n<p>And here is why:</p>\n\n<ol>\n<li>I think that LINQ query is more readable in 'SQL like' format.</li>\n<li>With the join clause you retrieve only the \"subjects\" that have an \"interest\". But with potential duplications if more than one \"interest\" has the ID of the same \"subject\" (For this reason I introduced the \"Distinct\" in the query, you can remove if the duplicate results interest you).</li>\n<li>As a matter of consistency I suggest you rather than use the constructor, initialize the property directly.</li>\n<li>For \"DefaultIfEmpty\" steatment docs <a href=\"http://msdn.microsoft.com/en-us/library/bb397895.aspx\" rel=\"nofollow\">go here</a>. The Left Outer Join is there.</li>\n</ol>\n\n<p><strong>UPDATE</strong> My first code does not work. Fixed and tested now :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T20:04:45.560",
"Id": "38653",
"ParentId": "31710",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "38653",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T22:19:21.990",
"Id": "31710",
"Score": "3",
"Tags": [
"c#",
"linq"
],
"Title": "LINQ query to select subjects of interest"
}
|
31710
|
<p>I'm learning C with K&R 2nd Ed. I just completed <a href="//stackoverflow.com/questions/7178201/kr-exercise-1-20-need-some-clarification" rel="nofollow">exercise 1-20</a> (which is the <code>detab</code> program). I was hoping to get some feedback on my work. I want to make sure that I am taking a good C approach and that my knowledge in other languages isn't bleeding in.</p>
<pre><code>/*
Exercise 1-20 in K&R 2nd Edition
detab: clarified here: http://stackoverflow.com/questions/7178201/kr-exercise-1-20-need-some-clarification
Written by Z. Bornheimer (provided as is without warranty).
*/
#include <stdio.h>
#define MAXLEN 10000
#define TABSTOP 4
int detab(char c, char str[], int i);
/* calls detab with appropriate data */
main()
{
int i = 0;
char c, str[MAXLEN];
while ((c = getchar()) != EOF)
i = detab(c, str, i);
printf("%s\n", str);
return 0;
}
/* replaces tabs w/ spaces in accordance to TABSTOP */
int detab(char c, char str[], int i)
{
if (c == '\t')
do
str[i++] = ' ';
while ((i % TABSTOP) != 0);
else
str[i++] = c;
return i;
}
</code></pre>
|
[] |
[
{
"body": "<p>I don't think this program is correct, according to my interpretation of tab stops. One problem is that the column count should reset to 0 after every carriage return or newline character encountered.</p>\n\n<p>Your program is vulnerable to buffer overflow. This may be acceptable for a beginner, as long as you acknowledge the problem, but this code should never be put into production use. (You may think that your buffers are generously sized, but a malicious attacker will scoff at whatever limit you choose. There is no substitute for proper bounds checking.) One simple strategy you could use is to minimize the use of a buffer by printing output on every call to <code>detab()</code> — your buffer would not need to be much larger than <code>TABSTOP</code> bytes.</p>\n\n<p>In your <code>detab()</code> function, you want to treat <code>i</code> as an in/out parameter (i.e., the function alters the parameter and passes it back to the caller). It is customary to accomplish this in C by passing a <em>pointer</em> to <code>i</code>, like this:</p>\n\n<pre><code>void func(int *in_out_param) {\n while (0 != *in_out_param % 4) {\n (*in_out_param)++;\n }\n}\n\nvoid caller() {\n int i = 2;\n func(&i);\n printf(\"%d\\n\", *i); /* prints 4 */\n}\n</code></pre>\n\n<p>Your variables are cryptically named. While short variable names are acceptable and even encouraged as, say, dummy variables for iteration where their purpose is obvious, they should not be used as a matter of habit. In particular, it is important to give descriptive names to function parameters, since they help prevent accidental misinterpretation by the function's users. I would suggest this function interface:</p>\n\n<pre><code>/**\n * Converts input character c at column col into a string, with the output\n * placed in buf. If c is a tab character, it is expanded into the appropriate\n * number of spaces. The buffer size should be at least one more than tabwidth.\n */\nvoid detab(unsigned int tabwidth, char c, unsigned int *col, char *buf, size_t bufsize)\n</code></pre>\n\n<p>For best performance, avoid reading one character at a time using <code>getchar()</code>. For this application, I recommend <code>fgets()</code>, which reads one line at a time (or up to the buffer size or until end-of-file, whichever is shortest). Admittedly, that does complicate the solution quite a bit.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T14:42:50.590",
"Id": "50646",
"Score": "0",
"body": "Thanks for the tips. I'm not sure what you mean by the code is vulnerable to buffer overflow or how to fix it. Could you explain that a little? Also, I'm keeping to what's been taught thus far (except for the do-while loop) and not using pointers yet. Lastly, the problem was kind of vague, so I wasn't sure if I should treat `'\\n'` & `'\\r'` as characters that forced `(i % TABSTOP) == 0`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T14:57:58.607",
"Id": "50648",
"Score": "1",
"body": "You've allocated 10000 bytes for `str`. However, if the output exceeds 10000 bytes, you blissfully write past the 10000-byte limit, into memory that you have not requested. That's called a buffer overflow. If you're lucky, you get away with the transgression and nothing bad happens. If you're less lucky, the OS detects the error and crashes your program. If you're unlucky, the user is a hacker who has crafted the input to write specific bytes that also act as machine code, tricking the computer into executing something completely unintended."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T08:02:04.813",
"Id": "31718",
"ParentId": "31712",
"Score": "7"
}
},
{
"body": "<p>This code is wrong:</p>\n\n<pre><code>char c;\nwhile ((c = getchar()) != EOF)\n</code></pre>\n\n<p>Recall the following facts about C:</p>\n\n<ol>\n<li>The type <code>char</code> is either <code>signed char</code> or <code>unsigned char</code> (but it's implementation-defined which).</li>\n<li><code>EOF</code> \"expands to a negative integral constant expression\"</li>\n<li><code>getchar()</code> returns \"the next character (if present) as an\n<code>unsigned char</code> converted to an <code>int</code>\" precisely so that it can distinguish <code>EOF</code> (which is negative) from all valid characters (which are non-negative)</li>\n</ol>\n\n<p>So there are two possible ways this could go wrong:</p>\n\n<ol>\n<li><p>If <code>char</code> is <code>unsigned char</code>, then when <code>getchar()</code> returns <code>EOF</code>, this gets converted to some <code>unsigned char</code> value (for example, <code>-1</code> may be converted to <code>255</code>) when stored in <code>c</code>, and so this will never compare equal to <code>EOF</code> and the loop will never terminate.</p></li>\n<li><p>If <code>char</code> is <code>signed char</code>, then there is a character that can be returned by <code>getchar()</code> which will be converted to the same value as <code>EOF</code> when stored in <code>c</code>. (for example, character 255 may be converted to <code>-1</code> when stored in <code>c</code>, and so compare equal to <code>EOF</code> and terminate the program).</p></li>\n</ol>\n\n<p>So you must replace:</p>\n\n<pre><code>char c;\n</code></pre>\n\n<p>with</p>\n\n<pre><code>int c;\n</code></pre>\n\n<p>(This is one of the classic C-language traps, by the way: <a href=\"http://c-faq.com/stdio/getcharc.html\" rel=\"nofollow\">here it is in the C programming language FAQ</a>.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T16:56:38.740",
"Id": "31803",
"ParentId": "31712",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "31718",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T01:19:10.047",
"Id": "31712",
"Score": "4",
"Tags": [
"beginner",
"c",
"strings",
"io",
"formatting"
],
"Title": "K&R 1-20 Converting tabs to spaces using idiomatic C"
}
|
31712
|
<p>I'm writing a <em>somewhat</em> secure voting system. I'm aware that it won't be really secure because it's on the internet so I'm looking for feedback on any logic errors or glaring mistakes in the security implementation.</p>
<p>The backend is ExpressionEngine CMS.</p>
<p>So, in this system user is allowed to vote anonymously or not anonymously. And in both cases are allowed to change the vote as long as the poll is open. After the vote ends user can verify cast vote by assigned ticket (anonymously) or by name.</p>
<p>One thing I know I haven't taken into account is detection of tampering in the tables. I guess I should have a fingerprint hash of all cast votes in another database, but I'm not sure how to do it.</p>
<p>I have two tables:</p>
<p><code>pt_voters_new: voters_id (int), entry_id (int), member_id (int), change_vote (int), iv (varchar), salt (varchar)</code></p>
<p><code>pt_votes_new: votes_id (varchar), entry_id (int), vote (int), member_id (int), enc (varchar)</code></p>
<p>I have a FORM that submits the chosen vote and other choices via an AJAX call. Here is the main code:</p>
<pre><code><?php
function crypto_rand($min, $max) {
$range = $max - $min;
$length = (int) (log($range,2) / 8) + 1;
$num = hexdec(bin2hex(openssl_random_pseudo_bytes($length,$s))) % $range;
return $num + $min;
}
// str_makerand is used for creating random ticket, that user can use to verify vote later (note mt_rand is not cryptographically secure)
function str_makerand ($minlength, $maxlength, $useupper, $usespecial, $usenumbers) {
$charset = "ACDEFGHJKLMNPQRTUVWXY";
if ($useupper) $charset .= "ACDEFGHJKLMNPQSTUVWXY";
if ($usenumbers) $charset .= "34679";
if ($usespecial) $charset .= "~@#$%^*()_+-={}|][";
for ($i=0; $i<$maxlength; $i++) $key .= $charset[(crypto_rand(0,(strlen($charset)-1)))];
return $key;
}
// Check that members group are allowed to vote
if (($this->EE->session->userdata('group_id') == 1) || ($this->EE->session->userdata('group_id') == 5) || ($this->EE->session->userdata('group_id') == 6) || ($this->EE->session->userdata('group_id') == 7) || ($this->EE->session->userdata('group_id') == 8) || ($this->EE->session->userdata('group_id') == 9) || ($this->EE->session->userdata('group_id') == 10) || ($this->EE->session->userdata('group_id') == 11)) {
// Function for logging
function logvote ($text) {
$handle = fopen("/dana/data/www.parlamentet.dk/votelog/logtest.txt", "a+");
fwrite($handle, $text);
fwrite($handle, "\r\n");
fclose($handle);
}
// Get password_compat for bcrypt.
require('/dana/data/www.parlamentet.dk/scripts/password.php');
// Get DB connection
require('/dana/data/www.parlamentet.dk/scripts/db.php');
// Check of form XID token
$member_id = (int)$this->EE->session->userdata('member_id'); // Users ID from ExpressionEngine session data
$ip_address = $this->EE->session->userdata('ip_address'); // Users IP address, only used for blocking check and error handling
$XID = $_POST['XID'];
$this->EE =& get_instance();
$this->EE->load->library('functions');
if (ee()->security->secure_forms_check($XID) === FALSE) {
echo '
<p style="text-align: center"><strong>AFSTEMNING</strong></p>
<p><strong>Fejl:</strong> Sikkerhedscheck fejlede. Forsøg igen eller kontakt os.</p>
<p><strong>Fejlkode:</strong> 001</p>
';
$log = $member_id." failed securitycheck 001 (from $ip_address)";
logvote($log);
exit();
}
$all_query_ok = TRUE; // Control variable for queries
// $time_now = time() - 3600;
$time_now = time();
$entry_id = (int)$_POST['entry_id']; // Unique entry ID
$vote = (int)$_POST['stemme']; // What user voted - 1, 2 or 3
if ($vote == '') {
echo '
<p style="text-align: center"><strong>AFSTEMNING</strong></p>
<p>Din stemme er <strong>IKKE</strong> registreret, da du ikke valgte noget at stemme. Genindlæs siden for at stemme korrekt.</p>
<p><strong>Fejlkode:</strong> 002</p>
';
$log = $member_id." did not choose voteoptions 002";
logvote($log);
exit();
}
if (($vote > 3) || ($vote < 1)) { // Allowed range of votes
echo '
<p style="text-align: center"><strong>AFSTEMNING</strong></p>
<p><strong>Fejl:</strong> Sikkerhedscheck fejlede. Forsøg igen eller kontakt os.</p>
<p><strong>Fejlkode:</strong> 003</p>
';
$log = $member_id." somehow voted for something strange 003";
logvote($log);
exit();
}
$anonymous_vote = (int)$_POST['anonymous_vote']; // Is it an anonymous vote?
$change_vote = (int)$_POST['change_vote']; // Should user be allowed to change vote later?
$changing_vote = (int)$_POST['changing_vote']; // Is this vote a change of a previous vote?
$password = $_POST['password']; // One time password to change the vote later
if ($change_vote === 1) {
// Blowfish hash of password (bcrypt)
$hash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 10)); // Kan sættes til PASSWORD_DEFAULT (cost 4 - 31)
// Verify hash
if (password_verify($password, $hash) === FALSE) {
echo '
<p style="text-align: center"><strong>AFSTEMNING</strong></p>
<p>Din stemme er <strong>IKKE</strong> registreret, da der opstod en fejl. Forsøg venligst igen!</p>
<p><strong>Fejlkode:</strong> 004</p>
';
$log = $member_id." failed password check 004";
logvote($log);
exit();
}
// Create key from password
$key_from_pw = hash('sha256', $password);
// Get IV
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM);
$iv_base64 = base64_encode($iv);
// Data about vote
$data = json_encode(array('member_id'=>$member_id, 'entry_id'=>$entry_id, 'hash'=>$key_from_pw));
// Encrypt data
$enc = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key_from_pw, json_encode($data), MCRYPT_MODE_CBC, $iv);
$enc_base64 = base64_encode($enc);
}
else {
$change_vote = 0;
$enc_base64 = '';
$iv = '';
$hash = '';
}
// Check if user already voted
$result = mysqli_query($link, "SELECT voters_id FROM pt_voters WHERE member_id = '$member_id' AND entry_id='$entry_id'");
$num_results = mysqli_num_rows($result);
// Check if poll is still open
$result = mysqli_query($link, "SELECT field_id_18,field_id_44,status FROM exp_channel_data,exp_channel_titles WHERE exp_channel_titles.entry_id='$entry_id' AND exp_channel_titles.entry_id=exp_channel_data.entry_id");
$row = mysqli_fetch_array($result);
$slut_ft = (int)$row["field_id_18"]; // Endtime for the vote in Danish Parliament
if ($slut_ft === 0) { // Change this logic!
$slut_ft = 9378133526;
}
$slut_pt = $row["field_id_44"]; // Sluttidspunkt for Parlamentets egne forslag
$status = $row["status"];
if ((($num_results === 0) || ($changing_vote === 1)) && (($time_now <= $slut_ft) || ($time_now <= $slut_pt)) && ($status == 'Fremsat')) { // User has not yet voted or is allowed to change vote
if ($changing_vote === 1) { // Verify password if user is changing vote
$result = mysqli_query($link, "SELECT iv,hash,voters_id FROM pt_voters WHERE member_id = '$member_id' AND entry_id = '$entry_id'");
$row = mysqli_fetch_array($result);
$hash_check = $row['hash'];
$voters_id = $row['voters_id'];
// $hash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 10, "salt" => $salt_check));
if (password_verify($password, $hash_check) === FALSE) {
print '
<p style="text-align: center"><strong>AFSTEMNING</strong></p>
<p>Forkert kodeord! Du kan genindlæse siden og forsøge igen!</p>
<p><strong>Fejlkode:</strong> 005</p>
';
$log = $member_id." failed password check 005";
logvote($log);
exit();
}
$key_from_pw = hash('sha256', $password);
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$old_iv_base64 = $row['iv'];
$old_iv = base64_decode($old_iv_base64);
$data = json_encode(array('member_id'=>$member_id, 'entry_id'=>$entry_id, 'hash'=>$key_from_pw));
$enc_test = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key_from_pw, json_encode($data), MCRYPT_MODE_CBC, $old_iv);
$enc_test_base64 = base64_encode($enc_test);
$result = mysqli_query($link, "SELECT votes_id FROM pt_votes WHERE enc='$enc_test_base64'");
$num_results = mysqli_num_rows($result);
if ($num_results === 1) { // OK - data checked out
// Removing all data from previous vote
$row = mysqli_fetch_array($result);
$votes_id = $row['votes_id'];
mysqli_query($link, "DELETE FROM pt_votes WHERE votes_id='$votes_id'") ? null : $all_query_ok=FALSE;
mysqli_query($link, "DELETE FROM pt_voters WHERE entry_id='$entry_id' AND member_id='$member_id'") ? null : $all_query_ok=FALSE;
}
else {
print '
<p style="text-align: center"><strong>AFSTEMNING</strong></p>
<p>Forkert kodeord! Du kan genindlæse siden og forsøge igen!</p>
<p><strong>Fejlkode:</strong> 007</p>
';
$log = $member_id." did not enter correct password 007";
logvote($log);
exit();
}
}
$num_results_2 = 1;
while ($num_results_2 != 0) {
$votes_id = str_makerand(10,10,1,0,1); // Random ID for vote
$result_2 = mysqli_query($link, "SELECT * FROM pt_votes WHERE votes_id='$votes_id'"); // Check if ID exists
$num_results_2 = mysqli_num_rows($result_2);
if ($num_results_2 === 0) {
// ID OK - casting vote
if ($anonymous_vote === 1) {
// $query = "INSERT INTO pt_votes (votes_id,entry_id,vote,vote_time,enc) VALUES ('$votes_id','$entry_id','$vote','$time_now','$enc_base64')";
$query = "INSERT INTO pt_votes (votes_id,entry_id,vote,enc) VALUES ('$votes_id','$entry_id','$vote','$enc_base64')";
}
else {
// $query = "INSERT INTO pt_votes (votes_id,entry_id,vote,vote_time,enc,member_id) VALUES ('$votes_id','$entry_id','$vote','$time_now','$enc_base64','$member_id')";
$query = "INSERT INTO pt_votes (votes_id,entry_id,vote,enc,member_id) VALUES ('$votes_id','$entry_id','$vote','$enc_base64','$member_id')";
}
mysqli_query($link, $query) ? null : $all_query_ok=FALSE;
// Shuffle table
$query = "ALTER TABLE pt_votes ORDER BY votes_id ASC";
mysqli_query($link, $query) ? null : $all_query_ok=FALSE;
// Getting ID for voters_id
$num_results_3 = 1;
while ($num_results_3 != 0) {
$voters_id = crypto_rand(100,1000000000000);
$result_3 = mysqli_query($link, "SELECT * FROM pt_voters WHERE voters_id='$voters_id'"); // Check for existance of voters_id
$num_results_3 = mysqli_num_rows($result_3);
if ($num_results_3 == 0) {
// $query = "INSERT INTO pt_voters (voters_id,entry_id,member_id,ip_address,change_vote,iv,salt) VALUES ('$voters_id','$entry_id','$member_id','$ip_address','$change_vote','$iv_base64','$salt')";
$query = "INSERT INTO pt_voters (voters_id,entry_id,member_id,change_vote,iv,hash) VALUES ('$voters_id','$entry_id','$member_id','$change_vote','$iv_base64','$hash')";
mysqli_query($link, $query) ? null : $all_query_ok=FALSE;
// Shuffle table
$query = "ALTER TABLE pt_voters ORDER BY voters_id ASC";
mysqli_query($link, $query) ? null : $all_query_ok=FALSE;
}
}
if ($all_query_ok) {
mysqli_commit($link);
}
else {
mysqli_rollback($link);
echo '
<p style="text-align: center"><strong>AFSTEMNING</strong></p>
<p>Der opstod en fejl! Du kan genindlæse siden og forsøge igen!</p>
<p><strong>Fejlkode:</strong> 008</p>
';
mysqli_close($link);
$log = $member_id." made the SQL fail! 008";
logvote($log);
exit();
}
// Everything OK. Inform user and write to logfile, print and/or insert posts in S3
$action = ' voted';
if ($changing_vote === 1) {
$action = ' changed vote';
}
if ($anonymous_vote === 1) {
$action .= ' anonymously';
}
if ($change_vote === 1) {
$action .= ' and is allowed to change vote';
}
$log = $member_id.$action;
logvote($log);
if ($anonymous_vote === 1) {
echo '
<p style="text-align: center;"><strong>AFSTEMNING</strong></p>
<p style="text-align: justify;">Din stemme er registreret anonymt. Du kan bruge nedenstående ID til at verificere stemmens korrekthed, når afstemningen er slut. Bemærk at
ID ikke er tilknyttet dig i vores system, så du skal selv huske det, hvis du ønsker at verificere. Det vises ikke igen, når du forlader denne side.</p>
<div id="printablereceipt">
<p style="text-align: center; font-family: Courier New, monospace; letter-spacing: 3px; font-size: 150%;"><strong>'.$votes_id.'</strong></p>
<div id="QRimage" style="text-align:center;"></div>
</div>
<p style="text-align: center;"><a class="btn btn-success" style="color: white;" href="#" onclick="printReceipt();"><i class="icon-print icon-large"></i> UDSKRIV</a></p>
';
$QRcode = 'https://www.parlamentet.dk/parlamentet/detaljer/'.$entry_id.'#v'.$votes_id;
echo "
<script>
var image = qr.image({
background: '#f5f5f5',
size: 7,
level: 'L',
value: '".$QRcode."'
});
if (image) {
document.getElementById('QRimage').appendChild(image);
}
</script>
";
}
else {
echo '
<p style="text-align: center;"><strong>AFSTEMNING</strong></p>
<p style="text-align: justify;">Din stemme er registreret uden anonymitet. Når afstemningen er slut, vil dit navn vises med din stemme, så du kan verificere stemmen. Du kan også bruge nedenstående ID til at verificere stemmen.</p>
<p style="text-align: center; font-family: Courier New, monospace; letter-spacing: 3px; font-size: 150%;"><strong>'.$votes_id.'</strong></p>
<div id="QRimage" style="text-align:center;"></div>
</div>
<p style="text-align: center;"><a class="btn btn-success" style="color: white;" href="#" onclick="printReceipt();"><i class="icon-print icon-large"></i> UDSKRIV</a></p>
';
$QRcode = 'https://www.parlamentet.dk/parlamentet/detaljer/'.$entry_id.'#v'.$votes_id;
echo "
<script>
var image = qr.image({
background: '#f5f5f5',
size: 7,
level: 'L',
value: '".$QRcode."'
});
if (image) {
document.getElementById('QRimage').appendChild(image);
}
</script>
";
}
}
}
}
else {
echo '
<p style="text-align: center"><strong>AFSTEMNING</strong></p>
<p><strong>Fejl:</strong> Du har allerede stemt i denne afstemning eller afstemningen er ikke åben.</p>
<p><strong>Fejlkode:</strong> 009</p>
';
$log = $member_id." tried to vote but failed 009";
logvote($log);
exit();
}
}
else {
echo '
<p style="text-align: center"><strong>AFSTEMNING</strong></p>
<p><strong>Fejl:</strong> Du har ikke rettigheder til at stemme.</p>
<p><strong>Fejlkode:</strong> 010</p>
';
$log = $member_id." does not have rights to vote 010";
logvote($log);
exit();
}
</code></pre>
<p>?></p>
<p>Help much appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T17:05:46.760",
"Id": "50659",
"Score": "0",
"body": "See the Electronic Voting Systems\nlisted at: https://bitbucket.org/djarvis/world-politics/wiki/Related%20Links"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T19:39:56.383",
"Id": "50661",
"Score": "0",
"body": "Thanks for the extensive list @DaveJarvis. I'll definitely look into those I don't know. However, I will be sticking with this voting system because of the specific requirements of our site."
}
] |
[
{
"body": "<p>Don't use <a href=\"http://php.net/manual/en/function.mt-rand.php\" rel=\"nofollow\">mt_rand</a> as the \"random\" value can be predictable:</p>\n\n<blockquote>\n <p>This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using openssl_random_pseudo_bytes() instead.</p>\n</blockquote>\n\n<p>See <a href=\"http://www.php.net/manual/en/function.openssl-random-pseudo-bytes.php\" rel=\"nofollow\">openssl_random_pseudo_bytes</a></p>\n\n<p>Also, parameterise your queries rather than using string concatenation: <a href=\"https://www.owasp.org/index.php/Query_Parameterization_Cheat_Sheet\" rel=\"nofollow\">https://www.owasp.org/index.php/Query_Parameterization_Cheat_Sheet</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T19:43:32.700",
"Id": "50662",
"Score": "0",
"body": "True about mt_rand. But I don't think it needs to be secure cryptographically as it's not used in any of the crypt functions. Nevertheless, I will use the other function instead.\n\nYes, I know, I should parameterize. But it is necessary when I force all variables to (int)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T10:58:28.797",
"Id": "50709",
"Score": "0",
"body": "It depends where you're using the token - if you don't want a malicious user to be able to guess a token (and possibly change someone else's vote), make sure it is not predictable by using a secure generator. This is good practise. I notice some of your SQL variables are not `int` but even if they were it is good practise to parameterise, then if your code is later updated it is less likely to be overlooked."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T09:32:48.090",
"Id": "50890",
"Score": "0",
"body": "Of course - and no reason not to use it. I have updated my code to reflect the changes (haven't gotten around to parameterizing queries but will do it). Thanks!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T10:34:10.270",
"Id": "31727",
"ParentId": "31716",
"Score": "2"
}
},
{
"body": "<p>A general note on the code - you shouldn't define a function inside a <code>if condition</code> </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T11:50:06.597",
"Id": "50910",
"Score": "0",
"body": "I did to save processing time - no need to define functions that won't be used. Why is it a bad idea?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T12:18:58.600",
"Id": "50911",
"Score": "0",
"body": "Processing time does not depend on the number of functions defined in the code. The function has to be executed. So you can define n number of functions in code that will not have any impact on processing time unless it is called."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T06:57:50.560",
"Id": "51123",
"Score": "0",
"body": "Ok, moving them out then."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T07:55:38.697",
"Id": "51382",
"Score": "0",
"body": "@huulbaek Why have you unaccepted my answer to accept this one instead? They are both valid answers, so it seems unfair to mark one as the accepted one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T16:59:28.840",
"Id": "51408",
"Score": "0",
"body": "@SilverlightFox Sorry, didn't understand the system. Thought it was possible to mark more than one as correct answers."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T10:06:53.840",
"Id": "31896",
"ParentId": "31716",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "31727",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T06:38:53.333",
"Id": "31716",
"Score": "2",
"Tags": [
"php",
"security"
],
"Title": "Somewhat secure voting system"
}
|
31716
|
<p>I want you to pick my code apart and give me some feedback on how I could make it better or more simple. This code will traverse peripheri (clock and anticlockwise) in \$O(n)\$ just traversing the tree once.</p>
<pre><code>public class PeriPheri {
private TreeNode root;
private static class TreeNode {
TreeNode left;
TreeNode right;
int item;
TreeNode(TreeNode left, TreeNode right, int item) {
this.left = left;
this.right = right;
this.item = item;
}
}
private void printChild (TreeNode node) {
if (node == null) {
return;
}
if (node.left == null && node.right == null) {
System.out.print(node.item + " ");
}
if (node != null) {
printChild (node.left);
printChild (node.right);
}
}
private void leftAntiClock(TreeNode node) {
if (node != null) {
System.out.print(node.item + " ");
leftAntiClock (node.left);
printChild (node.right);
}
}
private void rightAntiClock(TreeNode node) {
if (node != null) {
printChild (node.left);
rightAntiClock (node.right);
System.out.print(node.item + " ");
}
}
public void antiClockwise() {
if (root == null) {
return;
}
System.out.print (root.item + " ");
leftAntiClock (root.left);
rightAntiClock (root.right);
}
private void rightClock(TreeNode node) {
if (node != null) {
System.out.print(node.item + " ");
rightClock(node.right);
printChild(node.left);
}
}
private void leftClock(TreeNode node) {
if (node != null) {
printChild(node.right);
printChild(node.left);
System.out.print(node.item + " ");
}
}
public void clockwise() {
if (root == null) {
return null;
}
System.out.print(root.item + " ");
rightClock (root.right);
leftClock (root.left);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I think that <code>printChild()</code> would be better named <code>printDescendantLeaves()</code>. Also, <code>printChild()</code> always works left-to-right, which spoils your clockwise traversal.</p>\n\n<p>For flexibility, consider taking a <a href=\"http://en.wikipedia.org/wiki/Visitor_pattern\" rel=\"nofollow noreferrer\">visitor</a> instead of hard-coding <code>System.out.println()</code> everywhere. Alternatively, implement your traversal as an <code>Iterator</code> (which is admittedly tricky to do recursively since <a href=\"https://stackoverflow.com/q/1980953/1157100\">Java doesn't support <code>yield</code></a>).</p>\n\n<p>\"Periphery\" is misspelled.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T18:18:02.563",
"Id": "51029",
"Score": "0",
"body": "Thanks for feedback, I do appreciate feedback on visitor pattern, but I am preparing strictly for interviews and doubt if visitor would be necessary on white board."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T19:27:46.093",
"Id": "51039",
"Score": "1",
"body": "Demonstrating knowledge of the visitor pattern in an interview bumps you up to the next pay grade. =)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T20:08:23.760",
"Id": "51040",
"Score": "0",
"body": "good point sir. accepted."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T08:44:56.757",
"Id": "31720",
"ParentId": "31717",
"Score": "1"
}
},
{
"body": "<p>The way you handle <code>NULL</code> in <code>private void printChild (TreeNode node) {</code> is confusing and potentially wrong. It would be nice if it could be handled in a consistent way across the different methods : either <code>if (n==null) return;</code> or <code>if (n!=null) { your_code }</code>. That would make everything easier to follow and that would make duplicated code easier to spot </p>\n\n<p>I'd change the order of the argument in the constructor and define :\n<code>TreeNode(int item, TreeNode left, TreeNode right)</code> AND <code>TreeNode(int item)</code> (initialising trees to <code>NULL</code>)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T09:43:33.680",
"Id": "31722",
"ParentId": "31717",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "31722",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T07:58:14.903",
"Id": "31717",
"Score": "2",
"Tags": [
"java",
"algorithm",
"tree"
],
"Title": "Print periphery of a binary tree"
}
|
31717
|
<p>I've written this code for a merge sort, which is meant to implement the pseudo-code from Cormen's <em>Introduction to Algorithms</em>:</p>
<pre><code>#include <iostream>
#include <cstdlib>
using namespace std;
const unsigned long long infinity = -1ULL;
void merge(int* A,int p,const int q, const int r)
{
const int n_1=q-p+1;
const int n_2=r-q;
int* L = new int [n_1+1];
int* R = new int [n_2+1];
L[n_1]=infinity;
R[n_2]=infinity;
for(int i = 0; i < n_1; i++)
L[i] = A[p+i];
for (int j = 0; j < n_2; j++)
R[j] = A[q+j+1];
int i=0;
int j=0;
// for(int k = p; k <= r; p++) broken code
int k;
for(k=p; k <= r && i < n_1 && j < n_2; ++k)
{
if(L[i] <= R[j])
{
A[k] = L[i];
i++;
}
else
{
A[k] = R[j];
j++;
}
}
// Added the following two loop.
// Note only zero or one loop will actually activate.
while (i < n_1) {A[k++] = L[i++];}
while (j < n_2) {A[k++] = R[j++];}
}
void merge_sort(int* A, const int p, const int r)
{
if (p < r)
{
int q = (p+r)/2;
merge_sort(A, p,q);
merge_sort(A,q+1,r);
merge(A,p,q,r);
}
}
int main()
{
int length;
cout << "Specify array length" << endl;
cin >> length;
cout << "\n";
int A [length];
//Populate and print the Array
for(int i = 0; i < length; i++)
{
A[i] = rand()%99-1;
cout << A[i] << " ";
}
cout << "\n";
merge_sort(A,0,length-1);
cout << "Your array has been merge_sorted and is now this: " << endl;
for(int i = 0; i < length; i++) cout << A[i] << " ";
cout << "\n";
//cout << infinity << endl;
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T13:20:57.007",
"Id": "50633",
"Score": "0",
"body": "Did you try to run this using `gdb` or another debugger and check whether the indeces used are correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T13:24:50.377",
"Id": "50634",
"Score": "1",
"body": "Couple of issues. You have used C++ (the language) to write C code. Also this is not a good site to ask questions about why something is broken (check out SO for that). This site is meanly for critiquing style."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T13:27:47.487",
"Id": "50635",
"Score": "0",
"body": "Note: It actually makes things easier in C++ to specify ranges as not inclusive [0,n) rather than inclusive [0,n-1] in C++. You will see this a lot in the standard algorithms."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T13:36:32.133",
"Id": "50639",
"Score": "0",
"body": "PPS. It is usually a good idea to provide sample input that causes the issue. Tracking down the problem can be very hard when you also have to work out the data that causes the described behavior."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T13:54:07.877",
"Id": "50642",
"Score": "0",
"body": "Your bug is here: `for(int k = p; k <= r; p++)`. It should be: `for(int k = p; k <= r && i < n_1 && j < n_2; k++)`. Notice TWO Mistakes. 1) If `i` or `j` get to the end of their section then comparing them against the other section is pointless and can lead to reading beyond the end of the array. 2) You are incrementing `p` when you should be incrementing `k`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T16:33:33.080",
"Id": "50654",
"Score": "0",
"body": "@LokiAstari, 1) \"You have used C++ (the language) to write C code.\" --indeed, but I've only shown C code because it didn't work. I intended to turn it into a template and parallelise it, which, I think, would be using C++, but I needed it to work first. 2) I came here from SO, since I considered code review to be about general review. But thanks for clearing it up."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T16:36:57.363",
"Id": "50655",
"Score": "0",
"body": "3) A sample is generated by the program itself, my only input was the size of the array. It was. for that matter, 20. 4) Thanks a lot for educating what probably looks like a newbie."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T16:38:10.683",
"Id": "50656",
"Score": "0",
"body": "Could you please explain why did you edit out the note about parallelisation?"
}
] |
[
{
"body": "<p>Don't do this:</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">For a detailed explanation</a> on why not to use the usign clause.</p>\n\n<p>This is not used anywhere (also its not infinity so baddy named).</p>\n\n<pre><code>const unsigned long long infinity = -1ULL;\n</code></pre>\n\n<p>Passing pointers is a not a good idea.</p>\n\n<pre><code>void merge(int* A,int p,const int q, const int r)\n</code></pre>\n\n<p>Try and avoid it because you get into the realm of ownership symantics. Here I would be OK with using it but I would definitely rename the variable to explain what it is. You have a tendency to use excessively short variable names; this make the code hard to read.</p>\n\n<p>If you use the standard practive of begin and end (used in the STL (so begin points at the first and end points one past the last)) then you will find that your code becomes a lot simpler to write (especially in this case).</p>\n\n<pre><code> const int n_1=q-p+1;\n const int n_2=r-q;\n</code></pre>\n\n<p>This is stupendously bad for C++ code. This looks like C code.</p>\n\n<pre><code> int* L = new int [n_1+1];\n int* R = new int [n_2+1];\n</code></pre>\n\n<p>You should practically never use <code>new</code>. When you do you should always match it with delete (I see no delete anywhere so your code leaks). The reason you never use <code>new</code> is the problem with matching it with delete (especially when exceptions can be flying around). What you want to do is use a container:</p>\n\n<pre><code> std::vector<int> left(n_1+1);\n std::vector<int> right(n_2+1);\n</code></pre>\n\n<p>You only use <code>new</code> and <code>delete</code> when building your own container types or in very low level code. Normally you will use existing containers <code>std::vector</code> or smart pointers (for these use <code>make_{smartpointertype}</code>.</p>\n\n<p>Has no affect:</p>\n\n<pre><code> L[n_1]=infinity;\n R[n_2]=infinity;\n</code></pre>\n\n<p>Especially since you never check for infinity. Also because you always know the exect bounds and should not fall off the end.</p>\n\n<p>Also this is a particularly bad implementation of the algorithm.<br>\nMost version I have seen use a split/merge in place algorithm. Thus you don't need to copy data around into new arrays all over the place.</p>\n\n<pre><code> for(int i = 0; i < n_1; i++) \n L[i] = A[p+i];\n for (int j = 0; j < n_2; j++)\n R[j] = A[q+j+1];\n\n\n for(k=p; k <= r && i < n_1 && j < n_2; ++k)\n {\n if(L[i] <= R[j])\n {\n A[k] = L[i];\n i++;\n }\n else\n {\n A[k] = R[j];\n j++; \n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T01:50:26.047",
"Id": "50859",
"Score": "0",
"body": "\"This is not used anywhere (also its not infinity so baddy named).\" -- Well, I followed the logic of Cormen as best I could, and understood this particular point as \"use a really large number\". But yes, it isn't actually used. Admittedly several pages later an exercise is proposed to modify the algorithm so that it wouldn't need to be used. \"This is not used anywhere (also its not infinity so baddy named).\" --true, but his is generally a pseudo-code to real C++ code exercise, so all the names were clear for me. But I see how your advice would be relevant in the real world."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T01:56:01.467",
"Id": "50860",
"Score": "0",
"body": "\"This looks like C code.\" -- it is. I wanted to re-write pseudo-code into a simple and fast code. Perhaps I should re-write the C code now into something more like C++. \"I see no delete anywhere so your code leaks \" --true. I've added them to my original code some time after posting the question, though. So, all things considered, thanks a lot for your answer, now I see many points I have to work on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T02:07:47.877",
"Id": "50861",
"Score": "0",
"body": "Read about `using`, but my response is similar to the third one there: as long as I do it in my private code sources, it wouldn't matter much. But perhaps a habit of adding `std::` where needed is worth being formed early."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T02:55:10.113",
"Id": "50862",
"Score": "0",
"body": "I agree with forming a habit of using `std::`. But, if you *really* must use it, then keep it local (inside a function) instead of global."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T15:22:32.950",
"Id": "50929",
"Score": "3",
"body": "@Chiffa: <quote>as long as I do it in my private code sources, it wouldn't matter much</quote>. You already nearly broke your own code with this tiny simple example. `std::merge()` is now in the same namespace as your `::merge()`. You are one parameter off hitting `std::merge()`. If your code is any larger than this you are going to start hitting issues that then become hard to debug. Unless your code is shorter than 20 lines you should never use `using namespace XX;`. It will hit you and debugging it will be a nightmare."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T00:01:03.053",
"Id": "31877",
"ParentId": "31726",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T10:19:30.627",
"Id": "31726",
"Score": "5",
"Tags": [
"c++",
"sorting",
"mergesort"
],
"Title": "Merge Sort in C++"
}
|
31726
|
<p>I've been working on a website status checker.. However this array that I use has around 30 sites within it, I've noticed it's taking around 6-7 seconds to load it.</p>
<p>I was wondering if there's any kind of way of doing below, but more efficiently.</p>
<p>I have thought of doing the below in a cron, and fetching the stored results from a database.</p>
<pre><code><?php
function Visit($url){
$agent = "S3 (SF Service status)";
$ch=curl_init();
curl_setopt ($ch, CURLOPT_URL,$url );
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch,CURLOPT_VERBOSE,false);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch,CURLOPT_SSLVERSION,3);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, FALSE);
$page=curl_exec($ch);
#curl_error($ch);
#
#http header response code
global $httpcode;
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($httpcode>=200 && $httpcode<=308) return true;
else return false;
}
$sites = array(
"Name of site" => "URL",
);
?>
<html>
<head>
<title>Service Status</title>
<link href="static/css/main/main.css" rel="stylesheet" type="css/stylesheet">
</head>
<div id="container">
<div id="header">
<h1>service status</h1>
</div>
<table width="100%" cellpadding="0" cellspacing="0" colspan="2">
<?php
foreach ($sites as $key => $value) {
echo '<tr>';
if (Visit($value)) {
echo "<td><strong>$key</strong> ($value)</td><td class='success'>Available ($httpcode)</td>";
} else {
echo "<td><strong>$key</strong> ($value)</td><td class='error'>Unavailable ($httpcode)</td>";
}
echo '</tr>';
}
?>
</table>
</div>
</html>
</code></pre>
<p>Any recommendations on how parts of this could be done better would be greatly appreciated :)</p>
|
[] |
[
{
"body": "<p>PHP is not suitable for multi-threading. Though there are some extensions that offer ways of multithreading, they all are, basically, hacks IMO. The best way forward in your case would be: to use a tool that is async by nature, and update the url's as you go along.<Br/>\nThankfully, such a thing exists, and it goes by the name JavaScript (AJAX calls), here's what I'd do:</p>\n\n<pre><code>foreach ($sites as $key => $value)\n{\n echo '<tr><td><strong>',$key, '</strong> (', $value, ')</td>',\n '<td class=\"pending\"><img src=\"loading.gif\"/></td></tr>';\n}\n</code></pre>\n\n<p>This will present the client with a complete overview of urls (since that's what you say they are), each row showing a gif (optional, of course) of one of those circular loading things <a href=\"http://sierrafire.cr.usgs.gov/images/loading.gif\" rel=\"nofollow\">This one, for example</a>.<br/>\nOn the page, have script that goes something like this:</p>\n\n<pre><code>window.addEventListener('load',function l()\n{\n var pending = document.querySelectorAll('td.pending'),i=0,\n callNext = function(elem)\n {\n var urlMatch = elem.parentNode.cells[0].textContent.match(/\\(([^)]+)/)[1],\n xhr = new XMLHttpRequest;\n xhr.open('POST','ajax.php', true);\n xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');\n xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');\n xhr.onreadystatechange = callback;\n xhr.send('url=' + encodeURI(urlMatch));\n },\n callback = function()\n {\n if (this.readyState === 4 && this.status === 200)\n {\n var resp = JSON.parse(this.responseText);\n pending[i].setAttribute('class','error');//default error\n if (resp.success)\n {\n pending[i].setAttribute('class','success');\n }\n pending[i].replaceChild(\n document.createTextElement(resp.cellText),\n pending[i].firstChild\n );\n if (++i < pending.length)\n {\n callNext(pending[i]);\n }\n }\n };\n callNext(pending[i]);\n window.removeEventListener('load',l,false);\n},false);\n</code></pre>\n\n<p>Then, the <code>ajax.php</code> script, could just be the <code>Visit</code> function (BTW: please follow the <a href=\"http://www.php-fig.org/\" rel=\"nofollow\">PHP-FIG-coding standards</a> as much as possible, and lower-case that function name). Instead of <code>$url</code> just use:</p>\n\n<pre><code>$url = isset($_POST['url']) && filter_var($_POST['url'], FILTER_VALIDATE_URL) ? $_POST['url'] : false;\nif (!$url)\n{\n echo json_encode(array('cellText' => 'invalid URL'));\n exit;\n}\n//do curl request\necho json_encode(array('success' => true, 'cellText' => 'valid'));//or invalid, depending on curl results\n</code></pre>\n\n<p>This way, the client gets to see the page quite quickly, and sees it's being updated once every 6~7 seconds, depending on how long the curl request takes to complete.<br/>\nIn addition to that, look into caching extensions, such as APC, and <a href=\"http://php.net/manual/en/function.curl-setopt.php\" rel=\"nofollow\">set the cache options</a> for the cUrl requests, too. This usually requires some trial and error to find the right balance...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T15:55:56.983",
"Id": "50652",
"Score": "0",
"body": "This helps a lot, so you think it would be a better case to let the javascript make the calls and update when the php responds to the the request, showing as such an experience which isn't slow to the user? Not to sure what async fully means - so i will look into that, i am guessing it is some kind of way of loading data one by one and not disturbing the end user?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T06:46:47.380",
"Id": "50688",
"Score": "0",
"body": "@Roca: this approach show the client a table almost instantly (no curl requests are being made). Then, once the client loads the page, the JavaScript takes over, and interates the links one by one, The client remains on the page, while -in the background- requests are being sent to perform a curl request for a specific url. Once that request is completed, the page is updated (not refreshed), and the next url is processed. Basically, the client experiences no delays. Async, in this sense, means that the data (gotten from curl requests) is fetched on-the-fly, not before loading the page"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T15:08:40.717",
"Id": "31738",
"ParentId": "31729",
"Score": "3"
}
},
{
"body": "<p>I fully agree with <a href=\"https://codereview.stackexchange.com/a/31738/30065\" title=\"@Elias Van Ootegem\">@Elias Van Ootegem</a> that doing this in the browser (using JavaScript) is a much better way to go as the user sees <em>something</em> rather than just waiting. Due to the slowness of this situation, this makes sense to me.</p>\n\n<p>If you did want to go with PHP instead, though, you <em>can</em> do parallel cURL requests in PHP (one of the few things you <em>can</em> do parallel/concurrently in PHP).<br>\nHere's a SO page on this functionality: <a href=\"https://stackoverflow.com/a/9311112/1544099\">https://stackoverflow.com/a/9311112/1544099</a></p>\n\n<p>Or, you can use a very slick (and very solid) PHP (third-party) library called Guzzle - here's the part of the documentation that shows parallel cURL requests: <a href=\"http://guzzlephp.org/http-client/client.html#sending-requests\" rel=\"nofollow noreferrer\">http://guzzlephp.org/http-client/client.html#sending-requests</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T12:07:58.813",
"Id": "31849",
"ParentId": "31729",
"Score": "0"
}
},
{
"body": "<p>You could use AJAX to decrease the page loading time in addition to PHP and cURL:</p>\n\n<pre><code> //Check Status\n$('#check').click(function(){\n $('#site-list li').each(function(){\n var li = $(this);\n if(!li.hasClass('title')){\n $('span.status', li).html('<img src=\"loader.gif\" alt=\"\" />');\n $.post('process.php', { url:$('span.url', li).text(), id:$('span.id', li).text() }, function(response){\n $('span.status', li).html(response.data);\n $('span.status', li).simpletip({ fixed: true, position: 'right', offset:[5,0], content:response.message }); \n var tooltip = $('span.up', li).eq(0).simpletip(); \n if(response.up){\n $('span.up img', li).attr('src', 'online.png');\n tooltip.update('Site is Up');\n } else {\n $('span.up img', li).attr('src', 'offline.png');\n tooltip.update('Site is Down');\n $('span.status span', li).css('color','red');\n } \n }, 'json');\n }\n });\n return false;\n});\n</code></pre>\n\n<p>In process.php, we want to add some database connection information:</p>\n\n<pre><code>$this->connection = mysql_pconnect('db_host', 'db_username', 'db_password') or die(\"MySQL Error: \" . mysql_error());\n mysql_select_db('db_name');\n</code></pre>\n\n<p>Then add the HTTP response codes:</p>\n\n<pre><code>$codes = Array(\n0 => 'Timeout',\n100 => 'Continue',\n101 => 'Switching Protocols',\n200 => 'OK',\n201 => 'Created',\n202 => 'Accepted',\n203 => 'Non-Authoritative Information',\n204 => 'No Content',\n205 => 'Reset Content',\n206 => 'Partial Content',\n300 => 'Multiple Choices',\n301 => 'Moved Permanently',\n302 => 'Found',\n303 => 'See Other',\n304 => 'Not Modified',\n305 => 'Use Proxy',\n306 => '(Unused)',\n307 => 'Temporary Redirect',\n400 => 'Bad Request',\n401 => 'Unauthorized',\n402 => 'Payment Required',\n403 => 'Forbidden',\n404 => 'Not Found',\n405 => 'Method Not Allowed',\n406 => 'Not Acceptable',\n407 => 'Proxy Authentication Required',\n408 => 'Request Timeout',\n409 => 'Conflict',\n410 => 'Gone',\n411 => 'Length Required',\n412 => 'Precondition Failed',\n413 => 'Request Entity Too Large',\n414 => 'Request-URI Too Long',\n415 => 'Unsupported Media Type',\n416 => 'Requested Range Not Satisfiable',\n417 => 'Expectation Failed',\n500 => 'Internal Server Error',\n501 => 'Not Implemented',\n502 => 'Bad Gateway',\n503 => 'Service Unavailable',\n504 => 'Gateway Timeout',\n505 => 'HTTP Version Not Supported'\n);\n</code></pre>\n\n<p>Our code to check the sites in the database:</p>\n\n<pre><code>if(isset($_POST['url']) && isset($_POST['id'])){\n$ch = curl_init($_POST['url']); \ncurl_setopt($ch, CURLOPT_TIMEOUT, 10); \ncurl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); \ncurl_setopt($ch, CURLOPT_RETURNTRANSFER, true); \n$data = curl_exec($ch); \n$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); \ncurl_close($ch); \n\n$response = array();\n$response['up'] = true;\n$id = $db->escape_string($_POST['id']);\nif($httpcode >= 200 && $httpcode < 400){\n $db->execute(\"UPDATE sites SET up='yes' WHERE id='{$id}'\");\n} else {\n $db->execute(\"UPDATE sites SET up='no' WHERE id='{$id}'\");\n $response['up'] = false;\n}\n$response['data'] = '<span>'.$httpcode.'</span>';\n$response['message'] = $httpcode .' - '. $codes[$httpcode];\necho json_encode($response);\n} else {\n//Non JS Version\necho '<h1>Results</h1><ul>';\n$sites = $db->query(\"SELECT * FROM sites ORDER BY id ASC\");\nforeach($sites as $site){ \n if(!empty($site)){\n $ch = curl_init($site->url); \n curl_setopt($ch, CURLOPT_TIMEOUT, 5); \n curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); \n curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); \n $data = curl_exec($ch); \n $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); \n curl_close($ch); \n\n if($httpcode >= 200 && $httpcode < 400){\n $db->execute(\"UPDATE sites SET up='yes' WHERE id='\". $site->id .\"'\");\n } else {\n $db->execute(\"UPDATE sites SET up='no' WHERE id='\". $site->id .\"'\");\n }\n echo '<li>'. $site->name .' - '. $httpcode .' '. $codes[$httpcode] .'</li>';\n }\n}\necho '</ul><p><a href=\"../index.php\">Return</a></p>';\n}\n</code></pre>\n\n<p>So we have 5 seconds for the connection timeout in JavaScript, and for non-JavaScript status checking we set it to 10 seconds. When executed, it will update the \"sites\" table with the website statuses - the process.php files can be added as a cronjob to automatically check the sites every selected interval of time. If you wanted, you could set it up so it also emails you with any downtime reports..</p>\n\n<p>Feel free to play around with the code, for your index.php or whatever file is making the check calls, you could do something like:</p>\n\n<pre><code><div id=\"wrapper\">\n<h1>Status Checker</h1>\n<noscript><p>Warning: This site works best with Javascript enabled.</p></noscript>\n<ul id=\"site-list\" class=\"list\">\n <li class=\"title\"><span class=\"up\">&nbsp;</span> <span class=\"name\">Name</span> <span class=\"url\">URL</span> <span class=\"status\">Status</span></li>\n <?php\n $sites = $db->query(\"SELECT * FROM sites ORDER BY id ASC\");\n foreach($sites as $site){ \n if(!empty($site)){\n echo '<li><span class=\"up\">';\n if($site->up == 'yes')\n echo '<img src=\"online.png\" alt=\"Site is Up\" />';\n else \n echo '<img src=\"offline.png\" alt=\"Site is Down\" />';\n echo '</span><span class=\"id\">'. $site->id .'</span> <span class=\"name\">'. $site->name .' </span> \n <span class=\"url\">'. $site->url .'</span> <span class=\"status\"></span></li>';\n }\n }\n ?>\n</ul>\n<br />\n<a href=\"process.php\" id=\"do-check\" class=\"button\">Check Now</a>\n</div>\n</code></pre>\n\n<p>and just add the database connection information at the top of the page. The Check Now button will make an AJAX call to process.php and show a loading GIF while it checks.</p>\n\n<p>Here's a simple MySQL table structure query to get you started:</p>\n\n<pre><code>CREATE TABLE IF NOT EXISTS `sites` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `name` varchar(255) NOT NULL,\n `url` varchar(255) NOT NULL,\n `up` enum('yes','no') NOT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;\n</code></pre>\n\n<p>Where would we be without some test data in there?</p>\n\n<pre><code>INSERT INTO `sites` (`id`, `name`, `url`, `up`) VALUES\n(1, 'Google', 'http://www.google.com', 'yes');\n</code></pre>\n\n<p>Hopefully this gives you some ideas and answers some questions you may have had. If not, let me know! It's not perfect, but I'm sure you can figure out how to make it better.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T03:33:57.833",
"Id": "31882",
"ParentId": "31729",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "31738",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T11:16:26.247",
"Id": "31729",
"Score": "3",
"Tags": [
"javascript",
"php",
"optimization",
"curl"
],
"Title": "Service status checker... Is there a more efficient way?"
}
|
31729
|
<p>I have this if statement</p>
<pre><code>if (dt.Month > 3 && dt.Month < 11)
{
if (hours == 23 || (hours >= 0 && hours <= 6))
{
session = String.Empty;
}
else if (hours == 7)
{
session = String.Empty;
}
else if (hours >= 8 && hours <= 11)
{
session = String.Empty;
}
else if (hours >= 12 && hours <= 15)
{
session = String.Empty;
}
else if (hours >= 16 && hours <= 20)
{
session = String.Empty;
}
else if (hours == 22)
{
session = String.Empty;
}
else
{
session = String.Empty;
}
}
else
{
if (hours == 22)
{
session = String.Empty;
}
else if (hours == 23 || (hours >= 0 && hours <= 6))
{
session = String.Empty;
}
else if (hours == 7)
{
session = String.Empty;
}
else if (hours >= 8 && hours <= 12)
{
session = String.Empty;
}
else if (hours >= 13 && hours <= 16)
{
session = String.Empty;
}
else if (hours >= 17 && hours <= 20)
{
session = String.Empty;
}
else if (hours == 21)
{
session = String.Empty;
}
else
{
session = String.Empty; // I dont think this one is needed
}
}
</code></pre>
<p>As you can see it's pretty long and nasty. Is there a way to shrink it? I was going to use a switch but in C# you can't fall through case statements.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T13:20:38.190",
"Id": "50632",
"Score": "1",
"body": "Easy. `if (dt.Month > 3 && dt.Month < 11) { sesion = String.Empty; }`. I think you can fall through case statements in C# depending what you are trying to do, maybe post real code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T13:32:16.373",
"Id": "50637",
"Score": "0",
"body": "Why not using a array of triple of <rangMin, rangMax, session>, and go though it using an loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T14:11:45.707",
"Id": "50645",
"Score": "4",
"body": "What's stopping you from just doing `session = String.Empty;`? If the value is actually different for each branch, then you should have made that clear in your code."
}
] |
[
{
"body": "<p>Shouldn't you replace the whole code with <code>session = String.Empty;</code> ?</p>\n\n<p>Let's assumme that this is just a placeholder for actual code. If you handle your different cases in order and if <code>hours</code> is an <code>int</code>, then you can make the logic a bit easier to follow :</p>\n\n<pre><code>if (hours == 23 || (hours >= 0 && hours <= 6))\n{\n session = A;\n}\nelse if (hours == 7)\n{\n session = B;\n}\nelse if (hours >= 8 && hours <= 11)\n{\n session = C;\n}\nelse if (hours >= 12 && hours <= 15)\n{\n session = D;\n}\nelse if (hours >= 16 && hours <= 20)\n{\n session = E;\n}\nelse if (hours == 22)\n{\n session = F;\n}\nelse\n{\n session = G;\n}\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>if (hours < 0 || hours > 23)\n{\n session = G;\n}\nelse if (hours <=6)\n{\n session = A;\n}\nelse if (hours <= 7)\n{\n session = B;\n}\nelse if (hours <= 11)\n{\n session = C;\n}\nelse if (hours <= 15)\n{\n session = D;\n}\nelse if (hours <= 20)\n{\n session = E;\n}\nelse if (hours <= 22)\n{\n session = F;\n}\nelse\n{\n session = A;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T13:23:55.683",
"Id": "31732",
"ParentId": "31731",
"Score": "2"
}
},
{
"body": "<blockquote>\n <p>\"in C# you can't fall through case statements\"</p>\n</blockquote>\n\n<p>Yes, you can, as long as there is no code in them.</p>\n\n<pre><code>if (dt.Month > 3 && dt.Month < 11) {\n switch (hours) {\n case 23:\n case 0:\n case 1:\n case 2:\n case 3:\n case 4:\n case 5:\n case 6:\n session = String.Empty; break;\n case 7:\n session = String.Empty; break;\n case 8:\n case 9:\n case 10:\n case 11:\n session = String.Empty; break;\n case 12:\n case 13:\n case 14:\n case 15:\n session = String.Empty; break;\n case 16:\n case 17:\n case 18:\n case 19:\n case 20:\n session = String.Empty; break;\n case 22:\n session = String.Empty; break;\n default:\n session = String.Empty; break;\n }\n} else {\n switch (hours) {\n case 22:\n session = String.Empty; break;\n case 23:\n case 0:\n case 1:\n case 2:\n case 3:\n case 4:\n case 5:\n case 6:\n session = String.Empty; break;\n case 7:\n session = String.Empty; break;\n case 8:\n case 9:\n case 10:\n case 11:\n case 12:\n session = String.Empty; break;\n case 13:\n case 14:\n case 15:\n case 16:\n session = String.Empty; break;\n case 17:\n case 18:\n case 19:\n case 20:\n session = String.Empty; break;\n case 21:\n session = String.Empty; break;\n default:\n session = String.Empty; break;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T15:16:18.907",
"Id": "31739",
"ParentId": "31731",
"Score": "1"
}
},
{
"body": "<blockquote>\n <p>Is there a way to shrink it?</p>\n</blockquote>\n\n<p>Yes. With the specific code you wrote, the equivalent code is:</p>\n\n<pre><code>session = String.Empty;\n</code></pre>\n\n<p>In case you were not referring to the value but the chained/nested if structure (i.e. if in your actual application you use different values in the different branches of the nested if), you can abstract each branch of your if into an object/closure and treat them as an iterable sequence of conditions.</p>\n\n<p>Your objects should probably respect this interface:</p>\n\n<pre><code>interface ICondition {\n bool Applies(your_parameters_here);\n string ResultValue { get; }\n}\n</code></pre>\n\n<p>Then you would have an array of instances of ICondition specializations and iterate through it, until you get one which evaluates <code>Applies()</code> to true, set the value to ResultValue and break the loop.</p>\n\n<p>Advantages:</p>\n\n<ul>\n<li><p>your XXX lines of chained if statements become a simple for loop.</p></li>\n<li><p>it will be easy to extend (just add another specialization/instance of ICondition to your conditions array)</p></li>\n</ul>\n\n<p>Disadvantages:</p>\n\n<ul>\n<li>it will probably be slower than the <code>if/else if</code> construct. This only matters if your condition block is in a critical part of your code (and if you have chained ifs in critical parts of your code, your problem should probably be solved by rethinking your application flow).</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T15:33:48.900",
"Id": "31741",
"ParentId": "31731",
"Score": "2"
}
},
{
"body": "<blockquote>\n <p>I was going to use a switch but in C# you can't fall through case statements.</p>\n</blockquote>\n\n<p>Until recently I would have agreed with this statement. But actually you <em>can</em> do fall-through in C#, you just have to do it manually.</p>\n\n<p>Each <code>case</code> in the <code>switch</code> statement is a special label that you can jump to with a <code>goto case</code> statement. The labels are scoped to the switch statement, so you can't jump into the middle of the switch from outside.</p>\n\n<p>In your case you can use the form that Guffa posted, but for future reference this also works:</p>\n\n<pre><code>switch (hours)\n{\n case 0:\n case 1:\n case 2:\n case 3:\n bIsEarly = true;\n goto case 4;\n case 4:\n case 5:\n case 6:\n session = String.Empty;\n break;\n // ...and so on\n}\n</code></pre>\n\n<p>The <code>goto case</code> statement is more versatile than classic fall-through because it gives you the ability to do conditional fall-through and so on:</p>\n\n<pre><code>switch (hours)\n{\n case 0:\n case 1:\n case 2:\n case 3:\n bIsEarly = true;\n if (dt.Month == 1)\n goto case 4;\n session = String.Empty;\n break;\n case 4:\n case 5:\n case 6:\n session = String.Empty;\n break;\n // ...and so on\n}\n</code></pre>\n\n<p>The downsides of course are the same as for other <code>goto</code> usage, including the howls of rage you'll hear from the rabid anti-goto contingent. Sometimes it's useful, sometimes not. Don't go overboard.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T03:44:51.213",
"Id": "431394",
"Score": "1",
"body": "I've never seen a compiler written without `goto` statements :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T22:35:28.980",
"Id": "431478",
"Score": "0",
"body": "It's not required, but there are certain cases (no pun intended) where it is useful. These days we hide `goto` behind other control structures like `continue` and `break` because they avoid the common problems with `goto`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-24T04:24:38.400",
"Id": "431491",
"Score": "0",
"body": "I'm not blindly against `goto`, but I always get nuked by the team when I argue the case for them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T00:11:47.877",
"Id": "431656",
"Score": "0",
"body": "@dfhwze Yeah, I know. It's because everyone *knows* that `goto` is evil and must be avoided at all costs. Even if it means writing horrible code to achieve that goal. Sure, `goto`-ridden code is a pain in the butt, but if it's the best option then use it. It's not like any .NET language will let you abuse it the way people used to with C."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T21:57:12.560",
"Id": "31870",
"ParentId": "31731",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T13:16:07.510",
"Id": "31731",
"Score": "4",
"Tags": [
"c#"
],
"Title": "Condensing if statement in C#"
}
|
31731
|
<p>I'm working through a Java textbook by Paul and Harvey Deitel and I have come across a review question (Chapter 2 - Intro to Java, Exercise 2.18 for those that have the book) which asks the user to create the following diamond:</p>
<pre><code> *
* *
* *
* *
* *
* *
* *
* *
*
</code></pre>
<p>I have the following code which does this but, as always, I can't help but think there's a better way to do this. Any suggestions on a shorter way? </p>
<pre><code>// Prints the start and end of the diamond
private static void printStartEnd(int numLines, char sign, char filler) {
int xPosition = numLines / 2;
// Loop through
for (int i = 0; i < numLines; i++) {
if (i == xPosition) {
System.out.print(sign);
} else {
System.out.print(filler);
}
}
}
// Prints the other lines
private static void printOtherLines(int numLines, int positionOne,
int positionTwo, char sign, char fill) {
int i = 0;
// Loop through
while (i < numLines) {
if (i == positionOne || i == positionTwo) {
System.out.print(sign);
} else {
System.out.print(fill);
}
i++;
}
}
// Draw the diamond to the console
public static void drawDiamond( int numLines, char sign, char fill )
{
// Diamonds can only be created for odd numbers
if( numLines % 2 != 0 )
{
boolean limitReached = false;
int halfWayPointMinus = numLines / 2 - 1;
int halfWayPointPlus = numLines / 2 + 1;
for( int i = 0; i < numLines; i++ )
{
if( i == 0 || i == numLines-1 )
{
printStartEnd( numLines, sign, fill );
}
else
{
printOtherLines( numLines,halfWayPointMinus,halfWayPointPlus,sign,fill );
if( halfWayPointMinus == 0 || limitReached )
{
limitReached = true;
// Invert values and move back in
halfWayPointMinus++;
halfWayPointPlus--;
}
else
{
halfWayPointMinus--;
halfWayPointPlus++;
}
}
// Move to next line
System.out.println();
}
} else
{
System.out.println( "Sorry, the number of lines entered must be an odd number..." );
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You can do away with the <code>printStartEnd</code> method, as the <code>printOtherLines</code> can do the same job, if you send in the same value for <code>positionOne</code> and <code>positionTwo</code>.</p>\n\n<p>If you have a numeric value for direction instead of a boolean flag, you can use the same code for both movements.</p>\n\n<pre><code> int halfWayPointMinus = numLines / 2;\n int halfWayPointPlus = halfWayPointMinus;\n int dir = -1;\n\n for (int i = 0; i < numLines; i++) {\n printOtherLines(numLines, halfWayPointMinus, halfWayPointPlus, sign, fill);\n if (halfWayPointMinus == 0) {\n dir = 1;\n }\n halfWayPointMinus += dir;\n halfWayPointPlus -= dir;\n System.out.println();\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T15:33:24.397",
"Id": "31740",
"ParentId": "31734",
"Score": "1"
}
},
{
"body": "<h1>Error handling</h1>\n\n<p>When you detect an error condition, it's usually better to put the error handler immediately after the if-condition, then bail out. The error handler is usually shorter than the main code, so it's less mental workload to get it out of the way instead of having to look for the matching <code>else</code> many lines further down. The advantage of putting the error handler first becomes more apparent when multiple errors are involved:</p>\n\n<pre><code>if (SUCCESS != validate1()) {\n return handleError1();\n}\nif (SUCCESS != validate2()) {\n return handleError2();\n}\nif (SUCCESS != validate3()) {\n return handleError3();\n}\n// The main processing can proceed here\n</code></pre>\n\n<p>… is more readable than:</p>\n\n<pre><code>if (SUCCESS == validate1()) {\n if (SUCCESS == validate2()) {\n if (SUCCESS == validate3()) {\n // Do the main processing here\n } else {\n handleError3();\n }\n } else {\n handleError2();\n }\n} else {\n handleError1();\n}\n</code></pre>\n\n<p>Secondly, it is usually more appropriate to print error messages to <code>System.err</code>. You don't want unexpected junk contaminating your output.</p>\n\n<p>Consider changing the behaviour such that it throws an <code>IllegalArgumentException</code> rather than printing an error message. Throwing an exception allows the function's caller to programatically handle the error, making it more flexible and reusable.</p>\n\n<h1>Flow of Control</h1>\n\n<p>Using boolean variables (like <code>limitReached</code>) to control the flow of your program is usually a sign that you could structure the code better. In this case, you always take the else-branch when printing the top half of the diamond, then always take the if-branch for the bottom half. You might as well write it as two for-loops.</p>\n\n<p>On the other hand, there is a competing Don't-Repeat-Yourself principle regarding the body of the loop. In my opinion, you would still be better off clarifying the flow-of-control by splitting it into two loops. To avoid copy-and-pasting the loop body, you want to push the special cases into your printing function, so that the body is just one function call. That would be a smart move anyway, as it makes your printing function more resilient and versatile.</p>\n\n<h1>Printing Function</h1>\n\n<p>It turns out that your <code>printOtherLines()</code> can be used to print the apex and the base just fine. You don't need <code>printStartEnd()</code> at all.</p>\n\n<p>I would rename the <code>numLines</code> parameter to <code>size</code> or <code>width</code>. Calling it <code>numLines</code> in the context of <code>printOtherLines()</code> is a bit confusing, since you are only printing one line per function call.</p>\n\n<h1>Object-Oriented Thinking</h1>\n\n<p>I don't know whether your exercise specifies a particular interface, but I don't like <code>drawDiamond(int numLines, char sign, char fill)</code>. A more object-oriented approach would be:</p>\n\n<pre><code>Diamond d = new Diamond(/* size= */ 5);\nd.draw(System.out, '*', ' ');\n</code></pre>\n\n<p>In other words, the diamond knows how to draw itself.</p>\n\n<h1>Suggested Solution</h1>\n\n<pre><code>import java.io.PrintStream;\n\npublic class Diamond {\n private int size;\n\n /**\n * Constructor.\n * @param size The size of the diamond in lines (or columns)\n * @throw IllegalArgumentException if size is negative or even\n */\n public Diamond(int size) {\n if (size <= 0) {\n throw new IllegalArgumentException(\"Diamond size must be positive\");\n }\n if (size % 2 == 0) {\n throw new IllegalArgumentException(\"Diamond size must be odd\");\n }\n this.size = size;\n }\n\n public void draw(PrintStream out, char sign, char fill) {\n int posL = this.size / 2,\n posR = posL;\n while (posL > 0) {\n // Handle the top half\n this.printLine(out, sign, fill, posL--, posR++);\n }\n while (posL <= posR) {\n // Handle the bottom half, including the middle (widest) line\n this.printLine(out, sign, fill, posL++, posR--);\n }\n }\n\n private void printLine(PrintStream out, char sign, char fill, int posL, int posR) {\n // Loop condition could be (col <= posR) to omit trailing filler\n for (int col = 0; col < this.size; col++) {\n out.print((col == posL || col == posR) ? sign : fill);\n }\n out.println();\n }\n\n public static void main(String[] args) {\n try {\n Diamond d = new Diamond(Integer.parseInt(args[0]));\n d.draw(System.out, '*', ' ');\n } catch (IllegalArgumentException e) {\n System.err.println(\"Sorry, the number of lines must be an odd number...\");\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T21:44:31.533",
"Id": "50668",
"Score": "0",
"body": "I would have one question (at the moment) on your implementation; in the main method you surround the declaration of the class and subsequent call to its Draw method in a try-catch block and catch the err - why do this when the constructor handles this error anyway? Surely its redundant code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T03:47:17.767",
"Id": "50682",
"Score": "0",
"body": "The constructor complains. The main method handles the complaint. It would be inappropriate for the constructor to handle the error all on its own — the illegal argument should cause the `Diamond` object to fail to be created. It would also be inappropriate for the constructor to do `System.err.println(); System.exit();` since the constructor's sole job should be to create an object; it shouldn't unilaterally decide to bring down the JVM. Therefore, it just throws an exception and lets the caller deal with it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T17:36:59.753",
"Id": "31754",
"ParentId": "31734",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "31754",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T13:44:10.503",
"Id": "31734",
"Score": "3",
"Tags": [
"java",
"console",
"formatting"
],
"Title": "Shortening and optimizing diamond-printing code"
}
|
31734
|
<p>I've been trying to emulate MS Windows behavior on my OS X and close processes that do not have a window.</p>
<p>What I'd really like to do is "quit" the process on clicking the red "x" button. Instead, I've managed to code this workaround, which constantly runs in the background.</p>
<p>(see my question <a href="https://stackoverflow.com/questions/18906987/osx-app-to-intercept-the-close-command">here</a>)</p>
<p>It kind of defeat the purpose of not having background apps running, I suppose.</p>
<p>Since I own my Mac for about 2 weeks, I'm not sure if my script is "good" in terms of memory consumption, etc. (right now: CPU = 0, Memory = 12.3 MB, Threads = 3).</p>
<p>How would you guys do it? I'm open to suggestions.</p>
<pre><code>#!/usr/bin/osascript
-- INICIO DAS FUNCOES EXTRAS
set app_path to path to current application
set app_name to get name of me
set myPath to path to me
tell application "Finder" to set myFolder to (container of myPath) as string
set commonScript to load script alias ((myFolder) & "FuncoesExtras.scpt")
-- FIM DAS FUNCOES EXTRAS
set WhiteList to {app_name, "App Store", "iTunes", "Finder", "Mail"}
repeat
tell application "System Events"
repeat with this_app in (get processes whose background only is false and windows is {})
set NomeDoApp to the name of this_app
if NomeDoApp is not in WhiteList then
try
tell NomeDoApp to quit
log_event("App " & NomeDoApp & " encerrado com sucesso", "FecharProgramas") of commonScript
on error
do shell script "killall " & quoted form of NomeDoApp
log_event("Forcando interrupcao do App " & NomeDoApp, "FecharProgramas") of commonScript
end try
end if
end repeat
end tell
tell application "System Events" to set myPID to (unix id of processes whose name is app_name)
do shell script ("/usr/bin/renice 18 " & myPID)
delay 10
end repeat
</code></pre>
|
[] |
[
{
"body": "<p>Maybe a late response but I'm new to codereview but not to AppleScript. The problem with AppleScript and scripts that stays open is that they leak memory. Why? I just blame it on AppleEvents. It's a nice feature, it really is, but it does eats memory somehow. So the longer the script will run the more memory it will eat. Eventually, maybe after 6 months, your fans will start blowing for now reason and the mac becomes significant slower. But maybe it does that after a day, a week or a year. It's hard to tell in AppleScript where and how much a script leaks. </p>\n\n<p>To solve this there are several ways to do this. You can do it with cron (is since Tiger built inside launchd) with a shell script or create a new process of itself and quit. Either way they all remove the repeat loop out of the AppleScript and let that part be handled by other, much better, software. Note: using an idle handler inside AppleScript will eat memory too which should be the nicest solution instead of using a repeat and a delay.</p>\n\n<p>My advise, is that the script won't be eating to much memory so I would spawn a new process of itself just over some time. You're waiting 10 seconds so 360 loops would be enough. You spawn a new process around every hour.</p>\n\n<p>change the repeat to <code>repeat 360 times</code> and add the following code to the end of your AppleScript file. </p>\n\n<blockquote>\n <p>do shell script \"osascript \" & quoted form of posix path of\n (path to me) & \" &>/dev/null &\"</p>\n</blockquote>\n\n<p><em>Note: User interaction (display or choose commands) is not allowed when a script is launched by osascript in Mountain lion or earlier. For any user interaction change the target to SystemUIServer or Finder for instance.</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T11:27:33.867",
"Id": "47346",
"ParentId": "31742",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T15:47:10.027",
"Id": "31742",
"Score": "4",
"Tags": [
"macros",
"osx",
"applescript"
],
"Title": "AppleScript to close running processes"
}
|
31742
|
<p>OS X consists of a Mach/BSD-based kernel, operating system interfaces primarily based on FreeBSD, and additional frameworks (written in C, C++ and Objective-C) providing user interface and application-level services.</p>
<h3>More information:</h3>
<ul>
<li><a href="http://en.wikipedia.org/wiki/OS_X" rel="nofollow">OS X Wikipedia Article</a></li>
<li><a href="http://www.apple.com/osx/" rel="nofollow">OS X website</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T16:00:36.323",
"Id": "31743",
"Score": "0",
"Tags": null,
"Title": null
}
|
31743
|
OS X, previously Mac OS X, is a series of Unix-based graphical interface operating systems developed, marketed, and sold by Apple Inc. It is designed to run exclusively on Mac computers, having been pre-loaded on all Macs since 2002. Use this tag for questions about OS X specific code.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T16:00:36.323",
"Id": "31744",
"Score": "0",
"Tags": null,
"Title": null
}
|
31744
|
<p>AppleScript is a macOS inter-application scripting language, designed to control and exchange data between scriptable applications.</p>
<p>From <a href="http://developer.apple.com/applescript/" rel="nofollow noreferrer">Apple Developer</a> page:</p>
<blockquote>
<p>AppleScript is Apple's powerful and
versatile native scripting technology
for Mac OS X. With AppleScript, you
can control, and communicate among,
applications, databases, networks, Web
services, and even the operating
system itself. You can make your
Macintosh applications scriptable so
that users can write scripts to
automate operations they would rather
not do manually, from simple tasks to
complex workflows involving multiple
applications.</p>
</blockquote>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-09-24T16:14:08.797",
"Id": "31745",
"Score": "0",
"Tags": null,
"Title": null
}
|
31745
|
AppleScript is an end user scripting language that has been available in Mac computers since System 7 Pro (7.1.1). It allows for automation of system tasks, communication between processes, and creation of workflows, amongst other functions.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T16:14:08.797",
"Id": "31746",
"Score": "0",
"Tags": null,
"Title": null
}
|
31746
|
<p>I have attempted to write a method that checks that images being uploaded are valid.</p>
<pre><code>public function checkValidImages(){
$errors = array();
$allowedImages = array('image/jpg','image/jpeg','image/png','img/gif');
$maxFileSize = 2097152;
$invalidSize = 0;
$invalidTypes = 0;
$invalidDimension = 0;
$minWidth = 220;
$minHeight = 220;
// Check atleast one image has been selected
foreach($_FILES['event-images']['tmp_name'] as $tmp_name){
if($tmp_name == ""){
$errors[] = 'Please select atleast one image.'; // This is okay because instance would only occur once
}
}
// Check Images are valid image types
foreach($_FILES['event-images']['type'] as $type){
if(!in_array($type, $allowedImages)){
$invalidTypes++;
}
}
// Check images are valid sizes
foreach($_FILES['event-images']['size'] AS $size){
if($size > $maxFileSize){
$invalidSize++;
}
}
// Check images are atleast 220px high and 220px wide
foreach($_FILES['event-images']['tmp_name'] AS $image){
// Get image width and height
$image_dimensions = getimagesize($image); // returns an array of image info [0] = width, [1] = height
$image_width = $image_dimensions[0]; // Image width
$image_height = $image_dimensions[1]; // Image height
if(($image_width < $minWidth) || ($image_height < $minHeight)){
$invalidDimension++;
}
}
// Add errors to return array
if($invalidDimension > 0){
$errors[] = 'One or more of your images has invalid dimensions. Images must be atleast 220px by 220px.';
}
if($invalidTypes > 0){
$errors[] = 'One or more of your images has an invalid image type. Please only select jpg, png or gif images.';
}
if($invalidSize > 0){
$errors[] = 'One or more of your images is an invalid size. Please only select images less than 2MB in size.';
}
// Return errors
return $errors;
}
</code></pre>
<p>I was wondering if this could be made cleaner or more efficient.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-05T21:46:08.517",
"Id": "54367",
"Score": "0",
"body": "You're not doing any check for exploits nor managing duplicates"
}
] |
[
{
"body": "<p>There are 4 foreach loops for the same files, going for a little more complex but more\norganaized nested loop would be better, like this</p>\n\n<pre><code>foreach ($_FILES['event-images']['tmp_name'] as $tmp_name) {\n if (!empty($tmp_name)){\n $image = $_FILES[\"event-images\"][\"name\"];\n $path_info = pathinfo($image);\n if ($path_info['extension'] == 'jpg' || $path_info['extension'] == 'jpeg' || $path_info['extension'] == 'png' || $path_info['extension'] == 'gif'){\n if ($_FILES[\"image\"][\"size\"] <= $maxFileSize){\n $image_d = getimagesize($image); \n if(($image_d[0] >= $minWidth) && ($image_d[1] >= $minHeight)){\n $errors[]=\"valid image\";\n }else{\n $errors[]=\"invalid dimension\";\n }\n }else{\n $errors[]=\"invalid file size\";\n }\n }else{\n $errors[]=\"format not supported\";\n }\n\n }else{\n $errors[] = 'Please select at least one image.';\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T16:58:33.660",
"Id": "31749",
"ParentId": "31747",
"Score": "1"
}
},
{
"body": "<p>This builds on @Rajarshi answer, but simplifies the nesting (in my opinion)</p>\n\n<pre><code>foreach ($_FILES['event-images']['tmp_name'] as $tmp_name) {\n\n if (empty($tmp_name)){\n $errors[] = 'Please select at least one image.';\n continue;\n }\n\n $image = $_FILES[\"event-images\"][\"name\"];\n $path_info = pathinfo($image);\n\n if (!is_valid_filetype($path_info['extension']) {\n $errors[]=\"format not supported\";\n continue;\n }\n\n if ($_FILES[\"image\"][\"size\"] > $maxFileSize){\n $errors[]=\"invalid file size\";\n continue;\n }\n\n $image_d = getimagesize($image); \n if(($image_d[0] < $minWidth) || ($image_d[1] < $minHeight)){\n $errors[]=\"invalid dimension\";\n continue;\n }\n\n // why return an error for a valid image?\n //$errors[]=\"valid image\";\n}\n\n\nfunction is_valid_filetype($ext) {\n $ext = strtolower($ext);\n return in_array($ext, array('jpg', 'jpeg', 'png', 'gif'));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T20:38:24.113",
"Id": "47830",
"ParentId": "31747",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T16:26:57.420",
"Id": "31747",
"Score": "1",
"Tags": [
"php",
"validation",
"image"
],
"Title": "Validating uploaded images"
}
|
31747
|
<p>I got tired of doing (more or less) this in my rails controllers : </p>
<pre><code>class ThingsController < ApplicationController
def index
@category = Category.find( params[:category_id] ) if params[:category_id].present?
scope = @category ? @category.things : Thing.scoped
@things = scope.order( :title )
end
end
</code></pre>
<p>...wich also leads to a lot of conditionals in the template if <code>@category</code> is absent. </p>
<p>I had this idea (a variation on the <code>NullObject</code> pattern) :</p>
<pre><code>class Category < ActiveRecord::Base
def self.one_or_any( id )
where( id: id ).first || any_category
end
def self.any_category
@any_category ||= begin
new( title: "Any category" ) do |generic|
generic.instance_eval{ def things ; Thing.scoped end }
generic.readonly!
generic.freeze
end
end
end
end
</code></pre>
<p>Which would in turn allow me to do :</p>
<pre><code>class ThingsController < ApplicationController
def index
@category = Category.one_or_any( params[:category_id] )
@things = @category.things.order( :title )
end
end
</code></pre>
<p>... and to get rid of category-related conditionals in the template.</p>
<p><strong>I Just wonder if this is a good idea, and if it has drawbacks i don't see yet. Thoughts ?</strong></p>
<p><em>Note : Of course the actual implementation can be different (use a specific subclass of <code>Category</code> instead of extending an instance, for example - or even using a decorator).</em></p>
|
[] |
[
{
"body": "<p>I'd try to keep it as simple as possible. Instead of multiple in-line conditionals or a weird abstraction, I think a single full-fledged indented conditional makes things very clear. There are two scenarios, write two branches:</p>\n\n<pre><code>class ThingsController < ApplicationController\n def index\n if params[:category_id].present? \n @category = Category.find(params[:category_id])\n @things = @category.things\n else\n @category = nil\n @things = Thing.scoped\n end\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T06:42:22.377",
"Id": "50687",
"Score": "1",
"body": "ok, but the question was more about the \"generic object\" idea. I'd like to avoid that `@category = nil` because it involves a view riddled with conditionals - if i had an object that quacks like a category, it would be better"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T21:46:08.750",
"Id": "31766",
"ParentId": "31750",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T17:09:24.893",
"Id": "31750",
"Score": "2",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "\"specific case\" object that stands for \"any object\" : is it a good idea ?"
}
|
31750
|
<p>I just created a Hangman app (same game mechanics mostly) using Java. I did this mainly to test my knowledge in OOP design/coding. I'd like to know your thoughts on my code</p>
<p>The whole <a href="https://github.com/zurcnay4/Hangman" rel="nofollow">project is on Github</a></p>
<p>I would really appreciate the comments and criticism!</p>
<pre><code>public class Launcher {
private static BufferedReader consoleReader;
public static void main(String[] args) throws IOException {
consoleReader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("***LET'S PLAY HANGMAN (w/o the actual \"man\")***");
System.out.print("Enter name:");
String username = consoleReader.readLine();
Player P1 = new Player(username);
String plyrName = P1.getUsername();
System.out.println("Welcome " + plyrName + "!");
int choice = 0;
while (choice != 4) {
try {
System.out.println();
System.out.println("1. Start game");
System.out.println("2. Help");
System.out.println("3. About this game");
System.out.println("4. Quit");
choice = Integer.parseInt(consoleReader.readLine());
if (choice == 1) {
AI a1 = new AI(P1);
String answer = a1.getAnswer();
P1.setGuess(P1.initGuess(a1));
System.out.println();
System.out.println("***Guess this " + answer.length() + " letter word!***");
while (P1.getTries() != 0) {
try {
for (int x = 0; x < answer.length(); x++) {
System.out.print(P1.getGuess()[x] + " ");
}
System.out.println();
System.out.println("1. Guess a letter");
System.out.println("2. Guess the answer");
System.out.println("3. Concede");
System.out.println();
System.out.println("No. of tries remaining: " + "*" + P1.getTries() + "*");
int controls = Integer.parseInt(consoleReader.readLine());
if (controls == 1) {
System.out.print("Input letter: ");
String ltr = consoleReader.readLine();
if (a1.isLetterInWord(P1, answer, ltr.toLowerCase())) {
if (String.valueOf(P1.getGuess()).equals(answer)) {
System.out.println("***\"" + String.valueOf(P1.getGuess()) + "\"" + " is correct!***");
System.out.print("***You have beaten the game, " + plyrName + "!***");
P1.setTries(0);
}
System.out.println();
} else {
P1.setTries(P1.getTries() - 1);
if (P1.getTries() != 0) {
System.out.println("***Sorry try again!***");
}
}
}
else if (controls == 2) {
System.out.print("Input guess: ");
String word = consoleReader.readLine();
if (a1.isGuessCorrect(answer, word.toLowerCase())) {
P1.setGuess(word.toCharArray());
System.out.println("***\"" + word + "\"" + " is correct!***");
System.out.println("***You have beaten the game, " + plyrName + "!***");
P1.setTries(0);
} else {
System.out.println("***Sorry try again!***");
P1.setTries(P1.getTries() - 1);
}
}
else if (controls == 3) {
System.out.println("***Are you sure you want to concede?***");
System.out.print("Y/N: ");
String yn = consoleReader.readLine();
while (!yn.toLowerCase().equals("n")) {
if(yn.toLowerCase().equals("y")) {
P1.setTries(0);
break;
}
System.out.print("Y/N: ");
yn = consoleReader.readLine();
}
}
} catch (Exception e) {
System.out.println("***ERROR: Invalid input!***");
}
}
if (P1.getTries() == 0 && !String.valueOf(P1.getGuess()).equals(answer)) {
System.out.println("***GAME OVER, " + plyrName + "!***");
System.out.println("***The answer is " + "\"" + answer + "\"***");
}
}
else if (choice == 2) {
System.out.println(" ***Help***");
System.out.println("You will be given a word to try and guess.");
System.out.println("Your number of trials will depend on the length of the word.");
System.out.println("You can guess it by letter or guess it directly.");
System.out.println("Goodluck; Have fun!");
System.out.println(" ***Help***");
}
else if (choice == 3) {
System.out.println(" ***About this game***");
System.out.println("This game was developed to check and exercise");
System.out.println("zurcnay4's OOP knowledge using java. \n");
System.out.println("Comments & suggestions on: ");
System.out.println("- the application's overall design/code");
System.out.println("- how to improve this game");
System.out.println("are highly appreciated! \n");
System.out.println("Fork on github: https://github.com/zurcnay4/Hangman");
System.out.println(" ***About this game***");
}
else if (choice == 4) {
System.out.println("***Are you sure you want to quit?***");
System.out.print("Y/N: ");
String yn = consoleReader.readLine();
while (!yn.toLowerCase().equals("n")) {
if ((yn.toLowerCase().equals("y"))) {
choice = 4;
System.out.println("***Goodbye, " + plyrName + "***");
break;
}
System.out.print("Y/N: ");
yn = consoleReader.readLine();
}
if ((yn.toLowerCase().equals("n"))) {
choice = 0;
}
}
} catch (Exception e) {
System.out.println("***ERROR: Invalid input!***");
}
}
}
}
</code></pre>
<p>Couple of concerns</p>
<ul>
<li>Is there a need to use an abstract class/Interface in my project?</li>
<li>Did I do abstraction correctly? Did I create the right classes/objects?</li>
<li>Is my code readable?</li>
<li>Am I following the right conventions?</li>
</ul>
<p>Please do check the GitHub repo to see the whole application. Aside from the main class, I have these classes:</p>
<ul>
<li><code>AI</code></li>
<li><code>AIService</code></li>
<li><code>Player</code></li>
<li><code>PlayerService</code></li>
<li><code>Dictionary</code></li>
</ul>
|
[] |
[
{
"body": "<p>Please split your code into different smaller functions.\nThis is just impossible to understand. Here's my attempt, it probably doesn't compile but it does look much easier to understand :</p>\n\n<pre><code>public class Launcher {\n private static BufferedReader consoleReader;\n\n public static void main(String[] args) throws IOException {\n consoleReader = new BufferedReader(new InputStreamReader(System.in));\n System.out.println(\"***LET'S PLAY HANGMAN (w/o the actual \\\"man\\\")***\");\n System.out.print(\"Enter name:\");\n String username = consoleReader.readLine();\n\n Player P1 = new Player(username);\n String plyrName = P1.getUsername();\n System.out.println(\"Welcome \" + plyrName + \"!\");\n\n while (true) {\n System.out.println();\n System.out.println(\"1. Start game\");\n System.out.println(\"2. Help\");\n System.out.println(\"3. About this game\");\n System.out.println(\"4. Quit\");\n\n switch (askUserInteger(0)) {\n case 1: game(P1); break;\n case 2: help(); break;\n case 3: about(); break;\n case 4:\n if (userWantsToQuit()) {\n System.out.println(\"***Goodbye, \" + plyrName + \"***\");\n return;\n }\n break;\n default: System.out.println(\"***ERROR: Invalid input!***\");\n }\n }\n }\n\n\n public static void game (Player P1)\n {\n AI a1 = new AI(P1);\n String answer = a1.getAnswer();\n P1.setGuess(P1.initGuess(a1));\n\n System.out.println();\n System.out.println(\"***Guess this \" + answer.length() + \" letter word!***\");\n\n while (P1.getTries() != 0) {\n for (int x = 0; x < answer.length(); x++) {\n System.out.print(P1.getGuess()[x] + \" \");\n }\n System.out.println();\n System.out.println(\"1. Guess a letter\");\n System.out.println(\"2. Guess the answer\");\n System.out.println(\"3. Concede\");\n System.out.println();\n System.out.println(\"No. of tries remaining: \" + \"*\" + P1.getTries() + \"*\");\n\n switch (askUserInteger(0)) {\n case 1: guessLetter(P1); break;\n case 2: guessAnswer(P1); break;\n case 3 : if (userWantsToConcede()) P1.setTries(0); break;\n default : System.out.println(\"***ERROR: Invalid input!***\");\n }\n }\n\n if (P1.getTries() == 0 && !String.valueOf(P1.getGuess()).equals(answer)) {\n System.out.println(\"***GAME OVER, \" + plyrName + \"!***\");\n System.out.println(\"***The answer is \" + \"\\\"\" + answer + \"\\\"***\");\n }\n }\n\n public static void guessLetter(Player P1)\n {\n System.out.print(\"Input letter: \");\n String ltr = consoleReader.readLine();\n\n if (a1.isLetterInWord(P1, answer, ltr.toLowerCase())) {\n if (String.valueOf(P1.getGuess()).equals(answer)) {\n System.out.println(\"***\\\"\" + String.valueOf(P1.getGuess()) + \"\\\"\" + \" is correct!***\");\n System.out.print(\"***You have beaten the game, \" + plyrName + \"!***\");\n P1.setTries(0);\n }\n System.out.println();\n } else {\n P1.setTries(P1.getTries() - 1);\n if (P1.getTries() != 0) {\n System.out.println(\"***Sorry try again!***\");\n }\n }\n }\n\n public static void guessAnswer(Player P1)\n {\n System.out.print(\"Input guess: \");\n String word = consoleReader.readLine();\n if (a1.isGuessCorrect(answer, word.toLowerCase())) {\n P1.setGuess(word.toCharArray());\n System.out.println(\"***\\\"\" + word + \"\\\"\" + \" is correct!***\");\n System.out.println(\"***You have beaten the game, \" + plyrName + \"!***\");\n P1.setTries(0);\n } else {\n System.out.println(\"***Sorry try again!***\");\n P1.setTries(P1.getTries() - 1);\n }\n }\n\n public static void help ()\n {\n System.out.println(\" ***Help***\");\n System.out.println(\"You will be given a word to try and guess.\");\n System.out.println(\"Your number of trials will depend on the length of the word.\");\n System.out.println(\"You can guess it by letter or guess it directly.\");\n System.out.println(\"Goodluck; Have fun!\");\n System.out.println(\" ***Help***\");\n }\n\n public static void about()\n {\n System.out.println(\" ***About this game***\");\n System.out.println(\"This game was developed to check and exercise\");\n System.out.println(\"zurcnay4's OOP knowledge using java. \\n\");\n System.out.println(\"Comments & suggestions on: \");\n System.out.println(\"- the application's overall design/code\");\n System.out.println(\"- how to improve this game\");\n System.out.println(\"are highly appreciated! \\n\");\n System.out.println(\"Fork on github: https://github.com/zurcnay4/Hangman\");\n System.out.println(\" ***About this game***\");\n }\n public static bool userWantsToConcede()\n {\n return askUserYesNoQuestion(\"***Are you sure you want to concede?***\");\n }\n public static bool userWantsToQuit()\n {\n return askUserYesNoQuestion(\"***Are you sure you want to quit?***\");\n }\n public static bool askUserYesNoQuestion(String question)\n {\n System.out.println(question);\n do {\n System.out.print(\"Y/N: \");\n String yn = consoleReader.readLine();\n if (yn.toLowerCase().equals(\"y\")) return true;\n }\n while (!yn.toLowerCase().equals(\"n\"));\n return false;\n }\n public static int askUserInteger(int defValue)\n {\n try {\n return Integer.parseInt(consoleReader.readLine());\n } catch (Exception e) {\n return defValue;\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T01:28:33.063",
"Id": "50678",
"Score": "0",
"body": "This is great! it makes it more readable indeed!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T02:20:25.563",
"Id": "50680",
"Score": "0",
"body": "Question: with the functions game() about() help()... would it be better if I separate them in other classes to make it more OOP?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T18:01:27.623",
"Id": "31756",
"ParentId": "31751",
"Score": "5"
}
},
{
"body": "<p>Nitpick: the variable <code>P1</code> should be named <code>p1</code>, since the convention is to use uppercase for class names and constants.</p>\n\n<p>I agree with @Josay that this function desperately needs to be broken up!</p>\n\n<p>Since you indicate that you want to exercise OOP, I suggest creating a <code>Menu</code> class to help reduce the tedium of prompting for user choices.</p>\n\n<pre><code>public class Menu {\n public final String[] choices;\n\n public Menu(String... choices) {\n this.choices = choices;\n }\n\n int promptInt(BufferedReader in, PrintWriter out) throws IOException {\n while (true) {\n for (int i = 1; i <= this.choices.length; i++) {\n out.printf(\"%d. %s\\n\", i, this.choices[i - 1]);\n }\n out.flush();\n int choice = Integer.parseInt(in.readLine());\n if (choice > 0 && choice <= this.choices.length) {\n return choice;\n }\n }\n }\n\n boolean promptYN(BufferedReader in, PrintWriter out) throws IOException {\n assert 1 == this.choices.length;\n out.println(this.choices[0]);\n while (true) {\n out.print(\"Y/N: \");\n out.flush();\n switch (Character.toLowerCase(in.readLine().charAt(0))) {\n case 'y': return true;\n case 'n': return false;\n }\n }\n }\n}\n</code></pre>\n\n<p>You can use it like this:</p>\n\n<pre><code>static Menu mainMenu = new Menu(\n /* 1 */ \"Start game\",\n /* 2 */ \"Help\",\n /* 3 */ \"About\",\n /* 4 */ \"Quit\"\n);\nstatic Menu quitMenu = new Menu(\"***Are you sure you want to quit?***\");\n\npublic static void main(String[] args) throws IOException {\n BufferedReader conIn = new BufferedReader(new InputStreamReader(System.in));\n PrintWriter conOut = new PrintWriter(System.out);\n\n while (true) {\n switch (mainMenu.promptInt(conIn, conOut)) {\n case 1: game(conIn, conOut); break;\n case 2: help(conIn, conOut); break;\n case 3: about(conIn, conOut); break;\n case 4:\n if (quitMenu.promptYN(conIn, conOut)) {\n System.out.println(\"Bye!\"); return;\n }\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T01:37:33.377",
"Id": "50679",
"Score": "0",
"body": "I see. I didn't think of making a Menu class thank you for pointing that out! Did you check the project on github? what are your thoughts on the classes that I created?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T20:25:01.127",
"Id": "31762",
"ParentId": "31751",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T17:15:40.250",
"Id": "31751",
"Score": "7",
"Tags": [
"java",
"beginner",
"object-oriented",
"hangman"
],
"Title": "Console based Hangman in Java"
}
|
31751
|
<p>This is my first attempt at Clojure! Apart from all game related issues, how is my code? Is there anything I can do to make it more idiomatic?</p>
<pre><code>(ns hangman.core
(:import (java.net ServerSocket Socket SocketException)
(java.io PrintWriter InputStreamReader BufferedReader))
(:gen-class))
(defn guess [guess word]
(apply str (map #(let [x (str %)] (if (.contains guess x) x "*")) word)))
(defn listen [port]
(new ServerSocket port))
(def word "clojure")
(defn conn-handler [conn]
(let [in (:in @conn)
out (:out @conn)]
(.println out "Welcome to this simple hangman game.")
(def the-guess (atom ""))
(loop [conn conn]
(.println out (str "Guess the word: " (guess @the-guess word)))
(.flush out)
(let [g (str @the-guess (.readLine in))
res (guess g word)]
(if (= word res)
(do
(.println out res)
(.println out "Correct!")
(.flush out))
(do
(reset! the-guess g)
(recur conn)))))))
(defn -main [& args]
(println "Server running…")
(with-open [server (listen 3456)]
(loop []
(let [client (.accept server)
in (BufferedReader.(InputStreamReader.(.getInputStream client)))
out (PrintWriter. (.getOutputStream client))
conn (ref {:in in :out out})]
(println "Client connected")
(doto (Thread. #(conn-handler conn)) (.start))
(recur)))))
</code></pre>
|
[] |
[
{
"body": "<p>A bunch of random observations</p>\n\n<ul>\n<li><p>avoid <code>def</code> as a non-top level form e.g. in <code>(def the-guess (atom \"\"))</code>, prefer <code>let</code> bindings</p></li>\n<li><p>there's no need to use a ref for the connection, as it never changes after creation. Prefer a simple map, which also enables you to use plain destructuring instead of using <code>let</code> to extract its components:</p></li>\n</ul>\n\n<p> </p>\n\n<pre><code>(defn conn-handler [{:keys [in out] :as conn}] ...)\n...\nconn {:in in :out out}]\n(println \"Client connected\")\n(doto (Thread. #(conn-handler conn)) (.start))\n</code></pre>\n\n<ul>\n<li><p>instead of using interop to interact with the in/out streams you could use a more idiomatic <code>(binding [*out* out *in* in] (println ...) (read-line))</code></p></li>\n<li><p>you loop over the <code>conn</code>, but you always recur over the very same object. You can remove <code>conn</code> from the loop/recur forms</p></li>\n<li><p>if you follow the <code>binding</code> approach as described above, but within the anonymous function that you use to initialize the thread, you could completely remove the <code>conn</code> name from the whole code:</p></li>\n</ul>\n\n<p> </p>\n\n<pre><code>(defn conn-handler [] (println \"...\") ...)\n\n(doto (Thread. #(binding [*in* in *out* out] (conn-handler)) (.start))\n</code></pre>\n\n<ul>\n<li>there's no need to use an atom for the guess, just use plain recursion:</li>\n</ul>\n\n<p> </p>\n\n<pre><code>(loop [the-guess \"\"]\n...\n (recur g))\n</code></pre>\n\n<p>The following code contains the revised <code>conn-handler</code> and <code>-main</code> functions, including all the suggestions above, plus the cosmetic change of using the threading macro <code>-></code> instead of the <code>doto</code> form, which seems a bit clearer:</p>\n\n<pre><code>(defn conn-handler []\n (println \"Welcome to this simple hangman game.\")\n (loop [the-guess \"\"]\n (println (str \"Guess the word: \" (guess the-guess word)))\n (flush) \n (let [g (str the-guess (readLine)) \n res (guess g word)] \n (if (= word res) \n (do \n (println res) \n (println \"Correct!\") \n (flush)) \n (do \n (recur g)))))) \n\n(defn -main [& args] \n (println \"Server running…\") \n (with-open [server (listen 3456)] \n (while true \n (let [client (.accept server) \n in (BufferedReader.(InputStreamReader.(.getInputStream client))) \n out (PrintWriter. (.getOutputStream client))] \n (println \"Client connected\") \n (-> #(binding [*in* in\n *out* out]\n conn-handler)\n (Thread.)\n (.start))))))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T15:08:02.303",
"Id": "50924",
"Score": "0",
"body": "I have some trouble getting it to work with the threading macro as you suggested."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T09:34:37.683",
"Id": "31787",
"ParentId": "31752",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "31787",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T17:21:43.203",
"Id": "31752",
"Score": "5",
"Tags": [
"beginner",
"clojure",
"hangman"
],
"Title": "Hangman - my first Clojure code"
}
|
31752
|
<p>This is an assignment for an intro to Java course. It works with the test case given, but I would like to know if there is anything / a lot of things that should be different or could be better.</p>
<p>Specification:</p>
<blockquote>
<p>Write a Java application that accepts 5 “valid” numbers from the user.</p>
<p>A valid number is between 50 and 100 inclusive. If the user enters a
number outside of the valid range, an error message should indicate
this. An invalid number is not counted as one of the 5. The user
might enter 50 invalid numbers, and the program will keep asking for
numbers between 50 and 100.</p>
<p>If the user enters a number that they have previously entered, this is
counted as one of the 5. A message appears that it is not unique. A
unique number is a valid number that has not been entered up to this
point. A non-unique number is a valid number that has already been
entered.</p>
<p>After each valid number is entered, the count of the unique numbers
entered so far is printed, and all of the unique numbers are printed
on a single line. (see example)</p>
<p>When the user has entered 5 valid numbers, a message appears informing
the user of how many unique, valid numbers were entered, and the
unique numbers are printed again.</p>
</blockquote>
<pre><code>package partB;
import java.util.Scanner;
public class PartB {
public static void main(String[] args) {
int[] validNumber;
int[] uniqueNumber;
int input, numberOfUnique = 0;
boolean validCheck, uniqueCheck;
validNumber = new int[5];
uniqueNumber = new int[5];
Scanner userInput = new Scanner(System.in);
for (int i = 0; i < validNumber.length; i++) {
System.out.print("\nEnter an integer: \t");
input = userInput.nextInt();
validCheck = isValid(input);
while (validCheck == false) {
System.out.print("\nEnter an integer: \t");
input = userInput.nextInt();
validCheck = isValid(input);
}
if (validCheck == true) {
uniqueCheck = isUnique(validNumber, input);
validNumber[i] = input;
if (uniqueCheck == true) {
numberOfUnique++;
uniqueNumber[i] = input;
System.out.println("Unique so far: \t\t" + numberOfUnique);
outputStatements(uniqueNumber);
} else if (uniqueCheck == false) {
System.out.println(input + " is valid, but not unique");
System.out.println("Unique so far: \t\t" + numberOfUnique);
outputStatements(uniqueNumber);
}
}
}
System.out.println();
System.out.println("You entered " + numberOfUnique
+ " unique valid numbers!");
outputStatements(uniqueNumber);
}
public static boolean isValid(int validParameter) {
boolean result;
if (validParameter >= 50 && validParameter <= 100) {
result = true;
} else {
result = false;
System.out.println("The number " + validParameter
+ " is out of the valid range.");
}
return result;
}
public static boolean isUnique(int[] array, int uniqueParamter) {
boolean result = true;
for (int i = 0; i < array.length; i++)
if (array[i] != 0) {
if (array[i] == uniqueParamter) {
result = false; // is NOT unique
break;
} else {
result = true; // is unique
}
}
return result;
}
public static void outputStatements(int[] array) {
for (int i = 0; i < array.length; i++) {
if (array[i] != 0) {
System.out.print(array[i] + " ");
}
}
System.out.println();
}
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>Comparisons of <code>boolean</code>s:</p>\n\n<p>Please use</p>\n\n<pre><code>if (validCheck)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>if (!validCheck)\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>if (validCheck == true)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>if (validCheck == false)\n</code></pre></li>\n<li><p>Scope:</p>\n\n<p>Define variable in the smallest possible scope, for instance:</p>\n\n<pre><code>int input = userInput.nextInt();\n</code></pre></li>\n<li><p>Avoid useless comparisons:</p>\n\n<pre><code>if (uniqueCheck == true) {\n foo();\n} else if (uniqueCheck == false) {\n bar();\n}\n</code></pre>\n\n<p>could and should be written as:</p>\n\n<pre><code>if (uniqueCheck) {\n foo();\n} else {\n bar();\n}\n</code></pre></li>\n<li><p>Giving variables their final results as soon as possible:</p>\n\n<pre><code>boolean result;\nif (validParameter >= 50 && validParameter <= 100) {\n result = true;\n} else {\n result = false;\n System.out.println(\"The number \" + validParameter\n + \" is out of the valid range.\");\n}\n</code></pre>\n\n<p>could be written as:</p>\n\n<pre><code>boolean valid = (validParameter >= 50 && validParameter <= 100);\nif (!valid) {\n System.out.println(\"The number \" + validParameter\n + \" is out of the valid range.\");\n}\n</code></pre></li>\n<li><p>Return when you can and remove useless variables:</p>\n\n<pre><code>public static boolean isUnique(int[] array, int uniqueParamter) {\n boolean result = true;\n\n for (int i = 0; i < array.length; i++)\n if (array[i] != 0) {\n if (array[i] == uniqueParamter) {\n result = false; // is NOT unique\n break;\n } else {\n result = true; // is unique\n }\n }\n return result;\n }\n</code></pre>\n\n<p>could be written as:</p>\n\n<pre><code>public static boolean isUnique(int[] array, int uniqueParamter) {\n for (int i = 0; i < array.length; i++)\n if (array[i] != 0 && array[i] == uniqueParamter) {\n return false; // is NOT unique\n }\n return true;\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T18:35:36.790",
"Id": "50660",
"Score": "0",
"body": "Thanks for the quick reply. It was the isUnique method that I knew was off, but could not see how to simplify it. The other comments are just icing on the cake as I did not know most of those changes were even possible."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T18:24:33.177",
"Id": "31757",
"ParentId": "31753",
"Score": "0"
}
},
{
"body": "<p>It looks alright, but there are some improvements you can do. First of all, you can still split your program into smaller functions still, which really helps readability. </p>\n\n<p>Also, something glaring to me is that your functions in \"main\" are acting as instance variables for the rest of the class, which should not be the case. <strong>You should choose where you declare your variables based on the necessity of their scope.</strong> If you only use the input int as a store from user input, it should only be declared in the method that gets input from the user.</p>\n\n<p>For instance, you could omit the input int from main and declare it locally in the GetInputFromUser method.</p>\n\n<p>In main:</p>\n\n<pre><code>for (int i = 0; i < validNumber.length; i++) {\n GetInputFromUser(validNumber, uniqueNumber);\n}\n</code></pre>\n\n<p>The method:</p>\n\n<pre><code>public static void GetInputFromUser(int[] validNums, int[] uniqueNums) {\n int input = userInput.nextInt()\n while (!isValid(input)) {\n System.out.print(\"\\nEnter an integer: \\t\");\n input = userInput.nextInt();\n }\n //Code ommitted\n\n}\n</code></pre>\n\n<p>I didn't really have time to read all of the specifications carefully, but I hope this helped a bit! Also, you may want to declare the int arrays as instance variables to avoid passing them around all the time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T18:35:16.927",
"Id": "31758",
"ParentId": "31753",
"Score": "1"
}
},
{
"body": "<p>My three main remarks are:</p>\n\n<ol>\n<li>You call <code>isUnique()</code> incorrectly, causing a bug. (The <code>validNumber</code> array never gets populated.)</li>\n<li>You use boolean variables gratuitously. None of them is necessary to solve this exercise; you should be able to improve your code by eliminating all of them.</li>\n<li><p>The top of your for-loop has repetitive code that could be better written as a do-while loop.</p>\n\n<pre><code>for (int i = 0; i < validNumber.length; i++) {\n do {\n System.out.print(\"\\nEnter an integer: \\t\");\n input = userInput.nextInt();\n } while (!isValid(input));\n // etc.\n}\n</code></pre>\n\n<p>See my solution below for an even better approach.</p></li>\n</ol>\n\n<p>I also have a lot of minor critiques, which I have included below as comments inline.</p>\n\n<pre><code>package PartB;\nimport java.util.Scanner;\n\npublic class PartB {\n\n public static boolean isValid(int num) {\n // A function should do one thing only! Printing a message would be\n // an unexpected side effect, especially considering the name of\n // the function.\n\n // No need to use a boolean variable; just return.\n return num >= 50 && num <= 100;\n }\n\n // I've changed isUnique() to find() because the latter feels more\n // generalized and reusable.\n /**\n * Tests if num is among the first arraySize elements of the array.\n */\n public static boolean find(int num, int[] array, int arraySize) {\n // Pass in the arraySize explicitly to avoid treating 0 as a\n // magic value. (In this example, using 0 to signify that the\n // array element is still unused happens to work, because 0 is\n // outside the valid range anyway. But maybe Part C of the exercise\n // will ask you to modify the valid range, and you might accidentally\n // introduce a bug. Therefore, it's best to code defensively and\n // make the end of the array explicit.)\n for (int i = 0; i < arraySize; i++) {\n if (array[i] == num) {\n // No need to set a result and break. Just return.\n return true;\n }\n }\n return false;\n }\n\n // I've renamed outputStatements() to printArray(), because that's\n // what it does.\n public static void printArray(int[] array, int arraySize) {\n // Again, make the end of the array explicit.\n for (int i = 0; i < arraySize; i++) {\n System.out.print(array[i]);\n System.out.print(' ');\n }\n System.out.println();\n }\n\n public static void run(int size) {\n // Plural names feel more natural for these arrays.\n // You don't need to store validNumbers.\n int[] // validNumbers = new int[size],\n uniqueNumbers = new int[size];\n int numberOfValid = 0,\n numberOfUnique = 0;\n\n Scanner userInput = new Scanner(System.in);\n\n // By not blindly incrementing i each time through the loop,\n // you can change its purpose, from \"one iteration per valid\n // number\" to \"one prompt per iteration\". That way, you can\n // eliminate one layer of loop nesting.\n while (numberOfValid < size) {\n // Prompt\n System.out.print(\"\\nEnter an integer: \\t\");\n int input = userInput.nextInt();\n\n // Check validity\n if (!isValid(input)) {\n System.out.println(\"The number \" + input + \" is out of the valid range.\");\n // When things aren't right, skip to where you want to be\n // as soon as possible. Don't shilly-shally by setting\n // boolean variables to get there.\n continue;\n }\n // You don't need to store validNumbers\n // validNumbers[numberOfValid++] = input;\n numberOfValid++;\n\n // Check uniqueness\n if (!find(input, uniqueNumbers, numberOfUnique)) {\n uniqueNumbers[numberOfUnique++] = input;\n } else {\n System.out.println(input + \" is valid, but not unique\");\n }\n\n // The following two statements are common to both branches,\n // so pull them out of the if-else.\n System.out.println(\"Unique so far: \\t\\t\" + numberOfUnique);\n printArray(uniqueNumbers, numberOfUnique);\n }\n }\n\n public static void main(String[] args) {\n // Anything that can be parameterized should be done so, for\n // flexibility.\n run(5);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T08:12:51.393",
"Id": "50701",
"Score": "1",
"body": "Why would you continue to use an array and not a set? A set gives you the unique test (`Set#add` returns true if element already existed) and removes the need for the `arraySize` parameter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T09:01:11.187",
"Id": "50704",
"Score": "0",
"body": "@JohnMark13 Good point about using `Set`. A `LinkedHashSet` could even preserve the order in which the entries are added."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T19:32:55.487",
"Id": "50733",
"Score": "0",
"body": "@JohnMark13 This is a homework assignment and we have not discussed sets yet. Looks like that comes way later. I will read up on them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T19:37:07.100",
"Id": "50734",
"Score": "0",
"body": "@200_success thanks for all the input, I used the method names because they were given in the assignment. I appreciate the feedback as I know the code was not right but could not figure it out."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T19:18:58.600",
"Id": "31760",
"ParentId": "31753",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "31760",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T17:36:46.913",
"Id": "31753",
"Score": "1",
"Tags": [
"java",
"homework"
],
"Title": "Intro to Java - determine valid unique numbers"
}
|
31753
|
<p><a href="http://projecteuler.net/problem=92" rel="nofollow">Link to problem</a>.</p>
<blockquote>
<p>A number chain is created by continuously adding the square of the
digits in a number to form a new number until it has been seen before.</p>
<p>For example,</p>
<p>44 -> 32 -> 13 -> 10 -> 1 -> 1</p>
<p>85 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 -> 58 -> 89</p>
<p>Therefore any chain that arrives at 1 or 89 will become stuck in an
endless loop. What is most amazing is that EVERY starting number will
eventually arrive at 1 or 89.</p>
<p>How many starting numbers below ten million will arrive at 89?</p>
</blockquote>
<p>This solution to Project Euler problem 92 takes about 80 seconds. How can I reduce the time to well under 60 seconds?</p>
<pre><code>def squareDigits(num):
total = 0
for digit in str(num):
total += int(digit) ** 2
return total
pastChains = [None] * 10000001
pastChains[1], pastChains[89] = False, True
for num in range(2, 10000001):
chain = [num]
while pastChains[chain[-1]] is None:
chain.append(squareDigits(chain[-1]))
for term in chain:
if pastChains[term] is not None:
pastChains[term] = pastChains[chain[-1]]
print pastChains.count(True)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T20:52:33.237",
"Id": "50666",
"Score": "1",
"body": "Memoization might help you"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T21:08:19.243",
"Id": "50667",
"Score": "0",
"body": "There is a nice combinatorial approach, described [here](http://www.mathblog.dk/project-euler-92-square-digits-number-chain/)."
}
] |
[
{
"body": "<h2>1. Bug</h2>\n\n<p>There's a bug in your program. This line</p>\n\n<pre><code>if pastChains[term] is not None:\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>if pastChains[term] is None:\n</code></pre>\n\n<h2>2. Piecewise improvement</h2>\n\n<p>In this section I'm going to show how you can speed up a program like this by making a series of small piecewise improvements. This doesn't often work for the Project Euler problems: normally you have to come up with new algorithmic ideas. But here you're pretty close to getting under the minute mark, and that makes piecewise improvement a plausible approach.</p>\n\n<p>Note that I'm using Python 2.7 here, which is generally faster than Python 3.</p>\n\n<h3>2.1. Base case</h3>\n\n<p>I'm going to start by putting your code into a form which is more convenien for testing (also, where we can run it for smaller limits than ten million, which can be convenient when making frequent measurement). Also, I'll improve the coding style while I'm about it (add docstrings; put local variables in <code>lower_case_with_underscores</code>; use the more meaningful values <code>1</code> and <code>89</code> instead of the Booleans <code>False</code> and <code>True</code>).</p>\n\n<pre><code>def square_digits(n):\n \"\"\"Return the sum of squares of the base-10 digits of n.\"\"\"\n total = 0\n for digit in str(n):\n total += int(digit) ** 2\n return total\n\ndef problem92a(limit):\n \"\"\"Return the count of starting numbers below limit that eventually arrive\n at 89, as a result of iterating the sum-of-squares-of-digits.\n\n \"\"\"\n arrive = [None] * limit # Number eventually arrived at, or None if unknown.\n arrive[1], arrive[89] = 1, 89\n for n in range(2, limit):\n chain = [n]\n while arrive[chain[-1]] is None:\n chain.append(square_digits(chain[-1]))\n for term in chain:\n if arrive[term] is None:\n arrive[term] = arrive[chain[-1]]\n return arrive.count(89)\n\n>>> from timeit import timeit\n>>> timeit(lambda:problem92a(10**7), number=1)\n185.13595986366272\n</code></pre>\n\n<p>That's a lot slower than your reported \"80 seconds\": clearly you have a much faster machine than I do!</p>\n\n<h3>2.2. Avoiding number/string conversion</h3>\n\n<p>Now, let's do some work on the <code>square_digits</code> function. As written, this function has to convert the integer <code>n</code> to a string and then convert each digit back to a number. We could avoid these conversions by working with numbers throughout:</p>\n\n<pre><code>def square_digits(n):\n \"\"\"Return the sum of squares of the base-10 digits of n.\"\"\"\n total = 0\n while n:\n total += (n % 10) ** 2\n n //= 10\n return total\n\n>>> timeit(lambda:problem92a(10**7), number=1)\n61.409788846969604\n</code></pre>\n\n<p>Nearly under the minute already!</p>\n\n<h3>2.3. Second version</h3>\n\n<p>Here are some obvious minor improvements:</p>\n\n<ol>\n<li><p>Avoid the repeated lookup of <code>chain[-1]</code> by remembering the value in a local variable.</p></li>\n<li><p>Reduce the size of <code>chain</code> by one (because the last element in the chain is remembered in the local variable).</p></li>\n<li><p>The test <code>arrive[term] is None</code> is unnecessary: by this point in the code we know that only the last term in <code>chain</code> was found in <code>arrive</code>.</p></li>\n</ol>\n\n<p>That yields the following code:</p>\n\n<pre><code>def problem92b(limit):\n \"\"\"Return the count of starting numbers below limit that eventually arrive\n at 89, as a result of iterating the sum-of-squares-of-digits.\n\n \"\"\"\n arrive = [None] * limit # Number eventually arrived at, or None if unknown.\n arrive[1], arrive[89] = 1, 89\n for n in range(2, limit):\n chain = []\n while not arrive[n]:\n chain.append(n)\n n = square_digits(n)\n dest = arrive[n]\n for term in chain:\n arrive[term] = dest\n return arrive.count(89)\n</code></pre>\n\n<p>When transforming code like this, it's always important to check that our transformations didn't break anything. Here's where the ability to run the program for small values of <code>limit</code> comes in handy:</p>\n\n<pre><code>>>> all(problem92a(i) == problem92b(i) for i in range(1000, 2000))\nTrue\n</code></pre>\n\n<p>And this yields a further 12% speedup:</p>\n\n<pre><code>>>> timeit(lambda:problem92b(10**7), number=1)\n53.771003007888794\n</code></pre>\n\n<h3>2.3. Third version</h3>\n\n<p>The largest number under ten million is 9999999, whose sum of squares of digits is just 567. All other numbers in the range have even smaller sums of squares of digits. So for 568 and up, there is no need to follow the chain: we can just look up the answer directly. That suggests the following approach:</p>\n\n<pre><code>def problem92c(limit):\n \"\"\"Return the count of starting numbers below limit that eventually arrive\n at 89, as a result of iterating the sum-of-squares-of-digits.\n\n \"\"\"\n sum_limit = len(str(limit - 1)) * 9 ** 2 + 1\n arrive = [None] * sum_limit\n arrive[1], arrive[89] = 1, 89\n for n in range(2, sum_limit):\n chain = []\n while not arrive[n]:\n chain.append(n)\n n = square_digits(n)\n dest = arrive[n]\n for term in chain:\n arrive[term] = dest\n c = arrive.count(89)\n for n in range(sum_limit, limit):\n c += arrive[square_digits(n)] == 89\n return c\n</code></pre>\n\n<p>Again, we better check that we didn't break anything:</p>\n\n<pre><code>>>> all(problem92a(i) == problem92c(i) for i in range(1000, 2000))\nTrue\n</code></pre>\n\n<p>And this yields a further 30% improvement:</p>\n\n<pre><code>>>> timeit(lambda:problem92c(10**7), number=1)\n37.56105399131775\n</code></pre>\n\n<p>That's about an 80% speedup on the original version, just by making piecewise and localized improvements.</p>\n\n<h2>3. New algorithm</h2>\n\n<p>For more radical improvements to the runtime, we need to rethink the algorithm completely. Here's a sketch of the combinatorial approach:</p>\n\n<p>For each number <em>k</em> up to 567 that arrives at 89, we work out all the ways to partition <em>k</em> into a sum of no more than seven squares from 1<sup>2</sup> to 9<sup>2</sup> (using the partitioning technique we used in our answer to <a href=\"http://projecteuler.net/problem=76\">problem 76</a>, say). This gives us a multiset of digits, and we can use combinatorial techniques to count the number of ways this multiset can be realised as a number up to 9999999.</p>\n\n<p>For example, the starting number 4 arrives at 89. 4 can be partitioned into 2<sup>2</sup> or into 1<sup>2</sup> + 1<sup>2</sup> + 1<sup>2</sup> + 1<sup>2</sup>. In the first case, there are 7 starting numbers in the range (2, 20, 200, 2000, 20000, 200000 and 2000000). In the second case, writing C(<em>n</em>, <em>k</em>) for the number of combinations of <em>k</em> items out of <em>n</em>, there are C(3,3) + C(4,3) + C(5,3) + C(6,3) = 35 starting numbers in the range (1111, 10111, 11011, and so on).</p>\n\n<p>And here's some code, which I hope is self-documenting! Ask if you don't understand anything.</p>\n\n<p>It uses the <a href=\"https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize\"><code>@memoized</code> decorator</a> from the <a href=\"https://wiki.python.org/moin/PythonDecoratorLibrary\">Python Decorator Library</a> to avoid unnecessary re-computation.</p>\n\n<pre><code>from collections import Counter\nfrom math import factorial\nfrom memoize import memoized\n\n@memoized\ndef partitions(n, k, v):\n \"\"\"Return partitions of n into at most k items from v, with\n repetition. v must be a tuple sorted into numerical order. Each\n partition is returned as multiset in the form of a Counter object\n mapping items from v to the number of times they are used in the\n partition.\n\n >>> partitions(4, 7, (1, 4))\n [Counter({1: 4}), Counter({4: 1})]\n\n \"\"\"\n if n == 0:\n # Base case: the empty partition.\n return [Counter()]\n if k == 0 or len(v) == 0 or n < v[0]:\n # No partitions possible here.\n return []\n pp = [p.copy() for p in partitions(n - v[0], k - 1, v)]\n for p in pp:\n p[v[0]] += 1\n return pp + partitions(n, k, v[1:])\n\n@memoized\ndef multinomial(n, k):\n \"\"\"Return the multinomial coefficient n! / k[0]! k[1]! ... k[m]!.\n\n >>> multinomial(6, (2, 2, 2))\n 90\n\n \"\"\"\n result = factorial(n)\n for i in k:\n result //= factorial(i)\n return result\n\n@memoized\ndef number_count(digit_counts, min_digits, max_digits):\n \"\"\"Return the count of numbers (with between min_digits and max_digits\n inclusive) whose distinct non-zero digits have counts given by the\n sequence digit_counts. For example if we have three identical\n non-zero digits and four digits in total:\n\n >>> number_count((3,), 4, 4)\n 3\n\n because the possible numbers resemble 1011, 1101, and 1110.\n Similarly\n\n >>> number_count((1,1), 4, 4)\n 6\n\n because the possible numbers resemble 1002, 1020, 1200, 2001,\n 2010, and 2100.\n\n \"\"\"\n nonzero_digits = sum(digit_counts)\n total = 0\n for digits in range(max(min_digits, nonzero_digits), max_digits + 1):\n for i, d in enumerate(digit_counts):\n counts = (digit_counts[:i] + (d - 1,) + digit_counts[i+1:]\n + (digits - nonzero_digits,))\n total += multinomial(digits - 1, tuple(sorted(counts)))\n return total\n\ndef problem92d(limit):\n \"\"\"Return the count of starting numbers below limit that eventually arrive\n at 89, as a result of iterating the sum-of-squares-of-digits.\n\n \"\"\"\n max_digits = len(str(limit - 1))\n assert(limit == 10 ** max_digits) # algorithm works for powers of 10 only\n sum_limit = max_digits * 9 ** 2 + 1\n arrive = [None] * sum_limit\n arrive[1], arrive[89] = 1, 89\n for n in range(2, sum_limit):\n chain = []\n while not arrive[n]:\n chain.append(n)\n n = square_digits(n)\n dest = arrive[n]\n for term in chain:\n arrive[term] = dest\n total = 0\n squares = tuple(i ** 2 for i in range(1, 10))\n for n in range(2, sum_limit):\n if arrive[n] == 89:\n for p in partitions(n, max_digits, squares):\n total += number_count(tuple(sorted(p.values())), 1, max_digits)\n return total\n</code></pre>\n\n<p>As usual, we need to check that this radically new approach computes the right results:</p>\n\n<pre><code>>>> all(problem92c(10**i) == problem92d(10**i) for i in range(3, 7))\nTrue\n</code></pre>\n\n<p>Note that since we are using memoization, for fair timing results we must reload the code before running the timer (otherwise we'll get misleadingly fast times due to some of the computation having previously been done and stored in the memoization caches). But with a fresh Python instance:</p>\n\n<pre><code>>>> timeit(lambda:problem92d(10**7), number=1)\n0.7318389415740967\n</code></pre>\n\n<p>Less than a second! I hope that it's clear now how important the choice of algorithm is. With the piecewise improvement approach the code became about five times faster (which is pretty decent result). But with a better algorithm the code is 250 times faster.</p>\n\n<h2>4. Questions in comments</h2>\n\n<p>You asked some questions in the comments.</p>\n\n<ol>\n<li><p>Obviously in Python 3 you'd use <code>range</code>, not <code>xrange</code>. And in fact, even in Python 2.7, substituting <code>xrange</code> for <code>range</code> makes hardly any difference to the runtime (a percent or so), so in my revised answer I've eschewed that.</p></li>\n<li><p>In Python, small integer objects like <code>1</code> and <code>89</code> are shared and reused:</p>\n\n<pre><code>>>> x = 89\n>>> x is 8900 / 100\nTrue\n</code></pre>\n\n<p>If you look at the source code for <a href=\"http://hg.python.org/cpython/file/d5d5b363967e/Objects/longobject.c#l12\"><code>longobject.c</code></a>, you'll see that numbers from <code>NSMALLNEGINTS</code> (−5) up to <code>NSMALLPOSINTS-1</code> (256) are preallocated in an array. So there is no memory penalty to using them.</p></li>\n<li><p>Iteration works in Python by fetching successive values from an \"iterator\" object (here the object returned by <code>range(2, limit)</code>), not by incrementing the loop variable as you might do in languages like C. So there is no need to be scared about updating the loop variable.</p></li>\n<li><p>Yes, that's right. <a href=\"http://projecteuler.net/problem=92\">Project Euler asks</a> \"How many starting numbers <em>below</em> ten million will arrive at 89?\" (my emphasis). So it's convenient to use <code>limit</code> like this.</p></li>\n<li><p>Probably a copy-paste mistake on my part. I've revised the answer and hopefully the sequence of improvements is clearer now.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T00:57:21.900",
"Id": "50677",
"Score": "0",
"body": "Thanks so much! Some questions: 1. I understand that `xrange()` cannot be used in Python 3? 2. Would storing integers in the list instead of Booleans take up much more memory? 3. Would `n = square_digits(n)` affect the iteration? 4. `range(x, y)` iterates from x to y - 1, so `square_digits(limit)` would be skipped? 5. The `timeit` for 92a is `2.3686327934265137` and the `timeit` for 92b is `3.6810498237609863`. How is that a 25% speedup?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T14:24:16.000",
"Id": "50778",
"Score": "0",
"body": "I wonder if psyco (or similar tools) could speed it up even further. Though such tools may have a slight warm-up, so they might be ineffective on your final solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T14:33:31.813",
"Id": "50783",
"Score": "0",
"body": "@Brian: I find that even allowing for warmup, `problem92d` runs slower in PyPy (about 1.0 s) than in Python 2.7 (about 0.7 s)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T22:23:19.353",
"Id": "31767",
"ParentId": "31761",
"Score": "4"
}
},
{
"body": "<h1>Small Hints</h1>\n\n<p>Do away with your <code>squareDigits()</code> function — it's time consuming, and performs a lot of work that could be more efficiently derived from results of <code>squareDigits()</code> of smaller numbers.</p>\n\n<p>Don't bother distinguishing between <code>pastChains</code> and the current <code>chain</code> of interest. In this problem, all chains are the same — given any number, its chain always terminates the same way. Be like an elephant — never forget the result of any calculation.</p>\n\n<h1>Spoiler alert!</h1>\n\n<p>My solution completes in less time than by @GarethRees: 10 seconds on my machine. The solution relies heavily on memoization.</p>\n\n<p>In particular, computing the sum of the squares of the digits of large numbers is quite time consuming. My solution never needs to do that: it just adds the square of the ones' digit to previously calculated sum of the squares of the more significant digits. It also doesn't bother storing any chains; it only needs to keep the furthest known reduced value of each chain. The reduction procedure also doesn't require any calculation, only array lookups.</p>\n\n<pre><code>def euler92(limit):\n # Let sumsq uphold the invariant that the nth element contains\n # the sum of the squares of the digits of n, or better yet, a\n # value somewhere along its reduction chain.\n\n # Start with the base case: chain[0] = sum(0 * 0) = 0.\n # Also preallocate many unknowns...\n sumsq = [sum((0 * 0,))] + [None] * limit\n\n # ... and fill them in. Note how we reuse previous sums!\n for i in xrange(1 + limit):\n sumsq[i] = (i % 10) ** 2 + sumsq[i // 10]\n\n # Keep reducing each element until everything has converged\n # on either 1 or 89.\n all_converged = False\n while not all_converged:\n all_converged, eighty_nines = True, 0\n for i in xrange(1, 1 + limit):\n if sumsq[i] == 1:\n pass\n elif sumsq[i] == 89:\n eighty_nines += 1\n else:\n all_converged = False\n # sumsq[sumsq[i]] is a quick way to calculate\n # the sum of the squares of the digits, and maybe\n # even skip a few steps down the chain.\n sumsq[i] = sumsq[sumsq[i]]\n return eighty_nines\n\nprint euler92(10000000)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T12:38:24.723",
"Id": "50711",
"Score": "0",
"body": "Nice! (I find that `sum(0 * 0)` raises `TypeError: 'int' object is not iterable`, but with that fixed, I make this about twice as fast as my `problem92c` — you must have a much faster machine than me.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T15:02:16.027",
"Id": "50714",
"Score": "0",
"body": "@GarethRees I like that this code is still recognizable as a solution to the original problem. Anyway, I've relaxed my speed claims and fixed the sum(0 * 0) — Thanks!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T05:05:42.127",
"Id": "31781",
"ParentId": "31761",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "31767",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T19:29:30.663",
"Id": "31761",
"Score": "4",
"Tags": [
"python",
"optimization",
"project-euler"
],
"Title": "Project Euler problem 92 - square digit chains"
}
|
31761
|
<p><a href="http://mootools.net/" rel="nofollow noreferrer">MooTools</a> is a compact, modular, object-oriented JavaScript framework designed for the intermediate to advanced JavaScript developer. It allows you to write powerful, flexible, and cross-browser code with its elegant, well documented, and <a href="http://mootools.net/docs/core" rel="nofollow noreferrer">coherent API</a>.</p>
<hr>
<h3>Hello World Example</h3>
<pre><code>window.addEvent("domready", function() {
document.getElements("a").addEvent("click", function(event) {
event.stop();
console.log("hello world from link with href " + this.get("href"));
});
});
</code></pre>
<hr>
<h3>Questions Tagged with <a href="/questions/tagged/mootools" class="post-tag" title="show questions tagged 'mootools'" rel="tag">mootools</a></h3>
<p>When asking a <a href="/questions/tagged/mootools" class="post-tag" title="show questions tagged 'mootools'" rel="tag">mootools</a> question:</p>
<ol>
<li>Consult the <a href="http://mootools.net/docs/core" rel="nofollow noreferrer">MooTools API documentation</a> and <a href="https://codereview.stackexchange.com/search">search Code Review</a> for similar questions already answered before asking a question.</li>
<li>Tag the question with other web-development tags if applicable<br/> (e.g., <a href="/questions/tagged/html" class="post-tag" title="show questions tagged 'html'" rel="tag">html</a>, <a href="/questions/tagged/javascript" class="post-tag" title="show questions tagged 'javascript'" rel="tag">javascript</a>, <a href="/questions/tagged/ajax" class="post-tag" title="show questions tagged 'ajax'" rel="tag">ajax</a>, etc.).</li>
</ol>
<hr>
<h3>MooTools for Beginners</h3>
<p>If you are just starting with <a href="http://mootools.net/" rel="nofollow noreferrer">MooTools</a>, then you should read the following guides:</p>
<ul>
<li><a href="http://mootorial.com/" rel="nofollow noreferrer">The MooTorial</a></li>
<li><a href="http://keetology.com/blog/archive" rel="nofollow noreferrer">"Up the Moo Herd"</a> articles by <a href="http://www.keetology.com/" rel="nofollow noreferrer">Mark "Keeto" Obcena</a></li>
<li><a href="http://ryanflorence.com/" rel="nofollow noreferrer">Ryan Florence Online</a> and his <a href="http://ryanflorence.com/issue-004/" rel="nofollow noreferrer">MooTools 1.3 issue</a></li>
<li><a href="http://jqueryvsmootools.com/" rel="nofollow noreferrer">jQuery vs MooTools</a> if you are choosing what's the best framework for you</li>
<li><a href="http://ryanflorence.com/11-tips-for-creating-great-mootools-plugins/" rel="nofollow noreferrer">11 Tips for Creating Great MooTools Plugins</a></li>
<li><a href="http://www.jonathan-krause.de/artikel/mootools/" rel="nofollow noreferrer">MooTools Overview</a>, getting started in German</li>
<li><a href="http://net.tutsplus.com/tutorials/javascript-ajax/12-steps-to-mootools-mastery/" rel="nofollow noreferrer">12 Steps to MooTools Mastery</a> (for 1.2)</li>
</ul>
<hr>
<h3>Version Information</h3>
<p>The current version is <a href="http://mootools.net/blog/2012/02/26/mootools-1-4-5-released/" rel="nofollow noreferrer">MooTools 1.4.5</a> released February 26th, 2012.</p>
<p><a href="https://github.com/mootools/prime" rel="nofollow noreferrer">MooTools 2.0 (a.k.a. Prime)</a>, currently in development, will stop extending natives, move to CommonJS with an AMD wrapper/converter, and have some considerable API changes as a result.</p>
<p>For specific information about a particular MooTools version, see the tag wiki for that version.</p>
<p><strong>List of MooTools Versions</strong></p>
<ul>
<li><a href="https://github.com/mootools/prime" rel="nofollow noreferrer">MooTools 2.0 (a.k.a. Prime)</a> (<em>in development</em>)</li>
<li>MooTools 1.4.5 <a href="/questions/tagged/mootools1.4" class="post-tag" title="show questions tagged 'mootools1.4'" rel="tag">mootools1.4</a></li>
<li>MooTools 1.3.2</li>
<li>MooTools 1.2.5 <a href="/questions/tagged/mootools1.2" class="post-tag" title="show questions tagged 'mootools1.2'" rel="tag">mootools1.2</a></li>
<li>MooTools 1.1.2 <a href="/questions/tagged/mootools1.12" class="post-tag" title="show questions tagged 'mootools1.12'" rel="tag">mootools1.12</a></li>
</ul>
<hr>
<h3>MooTools Resources</h3>
<p><strong>Online Resources</strong></p>
<ul>
<li><a href="http://mootools.net/docs/core" rel="nofollow noreferrer">MooTools Core Documentation</a></li>
<li><a href="http://mootools.net/core" rel="nofollow noreferrer">MooTools Core Builder</a></li>
<li><a href="http://mootools.net/docs/more" rel="nofollow noreferrer">MooTools More Documentation</a></li>
<li><a href="http://mootools.net/more" rel="nofollow noreferrer">MooTools More Builder</a></li>
<li><a href="http://mootools.net/forge/" rel="nofollow noreferrer">MooTools Plugins Forge Repository</a></li>
<li><a href="https://github.com/mootools" rel="nofollow noreferrer">MooTools on GitHub</a></li>
</ul>
<p><strong>MooTools Tools</strong></p>
<ul>
<li><a href="http://moobilejs.com/" rel="nofollow noreferrer">Moobile</a> - a new mobile application framework launched in April 2012 that is similar to jQuery Mobile in terms of the functionality it affords</li>
<li><a href="http://cheeaun.com/projects/moodoco/core.html#Core/Core" rel="nofollow noreferrer">MooDocu</a> - a browser-based, client-side MooTools documentation parser with search; it works off-line through <code>localStorage</code></li>
</ul>
<p><strong>MooTools Books</strong></p>
<ul>
<li><a href="http://www.amazon.co.uk/MooTools-Essentials-JavaScript-Developement-FirstPress/dp/1430209836/" rel="nofollow noreferrer"><em>MooTools Essentials</em></a> by Aaron Newton</li>
<li><a href="http://www.amazon.co.uk/MooTools-1-2-Beginner%2527s-Guide-Gube/dp/1847194583/" rel="nofollow noreferrer"><em>MooTools 1.2 Beginner's Guide</em></a> by Jacob Gube and Garrick Cheung</li>
<li><a href="http://rads.stackoverflow.com/amzn/click/1430230541" rel="nofollow noreferrer"><em>Pro JavaScript with MooTools</em></a> by Mark Obcena (MooTools 1.3)</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T21:03:58.663",
"Id": "31763",
"Score": "0",
"Tags": null,
"Title": null
}
|
31763
|
MooTools is a compact, modular, object-oriented JavaScript framework designed for the intermediate to advanced JavaScript developer. It allows you to write powerful, flexible, and cross-browser code with its elegant, well documented, and coherent API.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T21:03:58.663",
"Id": "31764",
"Score": "0",
"Tags": null,
"Title": null
}
|
31764
|
<p>I had to do this in a course a while back: make <code>{1,2,3,4,5,6,7,8,9}</code> into <code>{{1,2,3},{6,5,4},{7,8,9}}</code>. When doing it, I just made the inner for-loop do all the work. But most of my friends had a Boolean and an if-statement to chose between a forward or reverse loop. </p>
<p>Which is more optimal and which is more readable?</p>
<pre><code>private double[][] a;
public TwoD(int numRows, int numCols, double[] oneD){
a = new double[numCols][numRows];
int d =1;
int x = 0;
int i = 0;
for (int y=0; y<numCols; y++){
for (;x<numRows&&x>=0;x+=d){
a[y][x] = oneD[i];
i++;
}
d*=-1;
x+=d;
}
}
</code></pre>
<p><strong>Edit:</strong> I had to have an object with a constructor which took width and height and a one dimensional array. The 1d array would be put into a 2d array as if it was a physical string being laid out (→▬▬↓←▬▬↓→▬▬).3x3 is an easy example.<br>
1 3 9 5 4 7 3 1 5 to<br>
1 3 9→<br>
7 4 5←<br>
3 1 5→</p>
<p>The alternative would be like (is pseudo code ok when its not the code being reviewed?)</p>
<pre><code>boolean right = true;
for y
if right
for x++
else
for x--
right= !right;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T22:56:30.050",
"Id": "50670",
"Score": "0",
"body": "Can you give more details on what is expected? Another example or an explanation would be much appreciated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T02:57:06.987",
"Id": "50681",
"Score": "0",
"body": "@Josay this was actually part of a written test I took last year and wasn't sure if I could just ask this but the questions are publicly available online and this is taken out of its original context (it was not explained with a string) so I think its fine. I want my unique answer analyzed to see if it is better or if it can be better. The, also public, answer key just wanted does the code you wrote down get the job done."
}
] |
[
{
"body": "<p>I do prefer the solution with the boolean. Also, a third possible variant would be to fill every other from left to right and remaining rows from right to left</p>\n\n<p>In any case, they way you are supposed to handle arrays where size is not A*B might help you to pick the best solution for you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-30T01:45:23.687",
"Id": "53654",
"Score": "0",
"body": "So you prefer the readability of the method with the boolean and to determine the most efficient method I could just time them?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T09:40:53.587",
"Id": "31788",
"ParentId": "31765",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "31788",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T21:06:59.377",
"Id": "31765",
"Score": "2",
"Tags": [
"java",
"array"
],
"Title": "Switching directions in iterating 2D arrays"
}
|
31765
|
<p>I've written a little command-line utility for filtering log files. It's like grep, except instead of operating on lines it operates on log4j-style messages, which may span multiple lines, with the first line always including the logging level (TRACE, DEBUG etc.).</p>
<p>Example usage on a file short.log with contents like this:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>16:16:12 DEBUG - Something happened, here's a couple lines of info:
debug line
another debug line
16:16:14 - I'm being very verbose 'cause you've put me on TRACE
trace info
16:16:15 TRACE - single line trace
16:16:16 DEBUG - single line debug
</code></pre>
</blockquote>
<p><code>logrep -f short.log DEBUG</code> produces:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>16:16:12 DEBUG - Something happened, here's a couple lines of info:
debug line
another debug line
16:16:16 DEBUG - single line debug
</code></pre>
</blockquote>
<p>I think the main loop of the program could probably be simplified with some sort of parse and filter.</p>
<pre class="lang-python prettyprint-override"><code> file = fileinput.input(options.file)
try:
line = file.next()
while True:
if any(s in line for s in loglevels):
if filter in line:
sys.stdout.write(line)
line = file.next()
while not any(s in line for s in loglevels):
sys.stdout.write(line)
line = file.next()
continue
line = file.next()
except StopIteration:
return
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T22:45:46.867",
"Id": "50669",
"Score": "1",
"body": "Shouldn't you consider the log level only if it is at the beginning of the line? A line could contain info without being the first line of an info log. (Also you should log on a single line and use other separators if its spans on multiple \"lines\" but that is just my point of view because I handle huge quantities of logs)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T23:17:42.797",
"Id": "50671",
"Score": "0",
"body": "The level isn't at the beginning of the line, it's after a timestamp. I could parse it to ensure the level is where I expect it to be, but I'm trying to be robust to minor changes in logging format."
}
] |
[
{
"body": "<p>I see two problems with your loops.</p>\n\n<p>In terms of style, calling <code>file.next()</code> and catching <code>StopIteration</code> is highly unconventional. The normal way to iterate is:</p>\n\n<pre><code>for line in fileinput.input(options.file):\n …\n</code></pre>\n\n<p>In terms of functionality, I would personally consider the grepper to be buggy because it will fail to find a log message where the <code>filter</code> keyword that you are seeking appears on a continuation line.</p>\n\n<p>To solve both problems, I would decompose the problem into two parts: reconstructing the logical messages (somewhat ugly) and searching (relatively straightforward).</p>\n\n<pre><code>import fileinput\nimport re\n\ndef log_messages(lines):\n \"\"\"\n Given an iterator of log lines, generate pairs of\n (level, message), where message is a logical log message.\n possibly multi-line.\n \"\"\"\n log_level_re = re.compile(r'\\b(TRACE|DEBUG|WARN|ERROR|CRITICAL)\\b')\n message = None\n for line in lines:\n match = log_level_re.search(line)\n if match: # First line\n if message is not None:\n yield level, message\n level, message = match.group(), line\n elif message is not None: # Continuation line\n message += line\n if message is not None: # End of file\n yield level, message\n\nfor level, message in log_messages(fileinput.input(options.file)):\n if filter in message:\n sys.stdout.write(message)\n</code></pre>\n\n<p>Note that I've used a regular expression to look for TRACE, DEBUG, etc. The <code>\\b</code> anchors ensure that we don't mistake words like \"INTRACELLULAR\" for a TRACE message.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-04T07:35:27.733",
"Id": "92630",
"ParentId": "31768",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "92630",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T22:33:12.010",
"Id": "31768",
"Score": "3",
"Tags": [
"python",
"logging"
],
"Title": "Filtering file for command line tool"
}
|
31768
|
<p>Kindly look at this code and point out design flaws or areas for improvement. I think I've done the last part right (the enum). I think the rest of the design is flawed but I am very new to object-oriented programming.</p>
<p><strong>Game</strong></p>
<pre><code>//Game class establishes rules and finds winner
public class Game {
String[] gameState = new String[9];
Player player1;
Player player2;
// updates the gamestate array with the latest move
public void updateStatus(int position, String symbol) {
gameState[position] = symbol;
}
public Game() {
player1 = new Player(1);
player2 = new Player(2);
for(int i = 0; i < 9; i++) {
gameState[i] = "";
}
}
// checks if game over. If game over, return winner or tie, else return "Game in prgress"
public String getGameStatus() {
if((gameState[0].equals(gameState[1]))
&& gameState[0].equals(gameState[2])
&& gameState[1].equals(gameState[2])
&& !gameState[0].equals("")){
return gameState[0];
}
else if((gameState[3].equals(gameState[4]))
&& gameState[3].equals(gameState[5])
&& gameState[4].equals(gameState[5])
&& !gameState[3].equals("")){
return gameState[3];
}
else if((gameState[6].equals(gameState[7]))
&& gameState[6].equals(gameState[8])
&& gameState[7].equals(gameState[8])
&& !gameState[6].equals("")){
return gameState[6];
}
else if((gameState[0].equals(gameState[3]))
&& gameState[0].equals(gameState[6])
&& gameState[3].equals(gameState[6])
&& !gameState[0].equals("")){
return gameState[0];
}
else if((gameState[1].equals(gameState[4]))
&& gameState[1].equals(gameState[7])
&& gameState[4].equals(gameState[7])
&& !gameState[1].equals("")){
return gameState[1];
}
else if((gameState[2].equals(gameState[5]))
&& gameState[2].equals(gameState[8])
&& gameState[5].equals(gameState[8])
&& !gameState[2].equals("")){
return gameState[2];
}
else if((gameState[0].equals(gameState[4]))
&& gameState[0].equals(gameState[8])
&& gameState[4].equals(gameState[8])
&& !gameState[0].equals("")){
return gameState[0];
}
else if((gameState[2].equals(gameState[4]))
&& gameState[2].equals(gameState[6])
&& gameState[4].equals(gameState[6])
&& !gameState[2].equals("")){
return gameState[2];
}
else {
for(int i=0; i < 9; i++) {
if(gameState[i].equals("")) {
return "Game in progress";
}
}
return "It's a tie!!";
}
}
public String play(int position) {
if(!player1.hasPlayed()) {
player1.played(true);
player2.played(false);
updateStatus(position,player1.getSymbol());
return player1.getSymbol();
}
else {
player2.played(true);
player1.played(false);
updateStatus(position,player2.getSymbol());
return player2.getSymbol();
}
}
}
</code></pre>
<p><strong>Player</strong></p>
<pre><code>//Player class initializes players in the game using id
public class Player {
private boolean hasPlayed;
private String symbol;
private int id;
Player(int id) {
this.id = id;
if(id == 1) {
hasPlayed = false;
symbol = Symbols.X.toString();
}
else {
hasPlayed = true;
symbol = Symbols.O.toString();
}
}
public void played(boolean flag) {
hasPlayed = flag;
}
public boolean hasPlayed() {
return hasPlayed;
}
public String getSymbol() {
return symbol;
}
}
</code></pre>
<p><strong>Symbols</strong></p>
<pre><code>// Enum stores the symbols used in the game
public enum Symbols {
X,O;
}
</code></pre>
|
[] |
[
{
"body": "<p>If you like enums, this example has two of them. The code is untested but might give you an idea.</p>\n\n<pre><code>public class Game {\n private final Symbol[] gameState = new Symbol[9];\n private final Symbol player1;\n private final Symbol player2;\n private Symbol currentPlayer;\n\n public void updateStatus(int position, Symbol symbol) {\n gameState[position] = symbol;\n }\n\n public Game() {\n player1 = Symbol.X;\n player2 = Symbol.O;\n currentPlayer = player1;\n Arrays.fill(gameState, Symbol.EMPTY);\n }\n\n public GameState getGameStatus() {\n // check horizontal\n for (int i = 0; i < 9; i += 3) {\n if (gameState[i] != Symbol.EMPTY\n && gameState[i] == gameState[i+1]\n && gameState[i+1] == gameState[i+2]) {\n return gameState[i].won();\n }\n }\n\n // check vertical\n for (int i = 0; i < 3; i ++) {\n if (gameState[i] != Symbol.EMPTY\n && gameState[i] == gameState[i+3]\n && gameState[i+3] == gameState[i+6]) {\n return gameState[i].won();\n }\n }\n\n // check diagonal\n if (gameState[0] != Symbol.EMPTY\n && gameState[0] == gameState[4]\n && gameState[4] == gameState[9]) {\n return gameState[0].won();\n }\n if (gameState[2] != Symbol.EMPTY\n && gameState[2] == gameState[4]\n && gameState[4] == gameState[7]) {\n return gameState[2].won();\n }\n\n // check in progress\n for (int i = 0; i < 9; i++) {\n if (gameState[i] == Symbol.EMPTY) {\n return GameState.RUNNING;\n }\n }\n\n // draw\n return GameState.DRAW;\n }\n\n public Symbol play(int position) {\n Symbol playing = currentPlayer;\n updateStatus(position, playing);\n currentPlayer = currentPlayer == player1 ? player2 : player1;\n return playing;\n }\n}\n\npublic enum Symbol {\n EMPTY(null),\n X(GameState.X_WON),\n O(GameState.O_WON);\n\n private final GameState won;\n\n private Symbol(GameState won) {\n this.won = won;\n }\n\n public GameState won() {\n return won;\n }\n}\n\npublic enum GameState {\n RUNNING(\"Game in progress\"),\n X_WON(\"X won\"),\n O_WON(\"O won\"),\n DRAW(\"It's a tie!!\");\n\n private String message;\n\n private GameState(String message) {\n this.message = message;\n }\n\n @Override\n public String toString() {\n return message;\n }\n}\n</code></pre>\n\n<ul>\n<li>use loops to reduce the number of if/else statements</li>\n<li>use meaningful objects wherever possible</li>\n<li>use use <code>String</code>s only where necessary</li>\n<li>reduce the number of mutable objects (here we have only one)</li>\n</ul>\n\n<p>Further improvements:</p>\n\n<ul>\n<li>reduce the number of public methods</li>\n<li>split long methods (<code>getGameStatus</code> in this case)</li>\n<li>reduce the number of conditionals in <code>getGameStatus</code>, it is still spaghetti code</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T00:49:21.780",
"Id": "31773",
"ParentId": "31769",
"Score": "5"
}
},
{
"body": "<p>Use metadata array for checking win combinations.</p>\n\n<p>e.g. <code>int[][] winCombinations = {{1,2,3}, {4,5,6}, {7,8,9}, {1,5,9}, etc}</code></p>\n\n<p>And check them with a loop. Please note that array indexes are starting with 0, and you will need -1 or special method for getting state or changes in metadata. </p>\n\n<pre><code> for(int[] winCombo: winCombinations) {\n String stateOfFirstComboCell = gameState[winCombo[0]];\n if (stateOfFirstComboCell != EMPTY) {\n if (stateOfFirstComboCell.equals(gameState[winCombo[1]])\n && stateOfFirstComboCell.equals(gameState[winCombo[2]])) {\n System.out.println(\"Winner is \" + stateOfFirstComboCell); \n }\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T11:06:03.333",
"Id": "31790",
"ParentId": "31769",
"Score": "5"
}
},
{
"body": "<p>IMHO the getGameStatus() method has extremely high cyclomatic complexity. Also I'm not sure what is the purpose of the Player class. Following is my solution:</p>\n\n<pre><code>public class TicTacToe {\n public static final char BLANK = '\\u0000';\n private final char[][] board;\n private int moveCount;\n private Referee referee;\n\n public TicTacToe(int gridSize) {\n if (gridSize < 3)\n throw new IllegalArgumentException(\"TicTacToe board size has to be minimum 3x3 grid\");\n board = new char[gridSize][gridSize];\n referee = new Referee(gridSize);\n }\n\n public char[][] displayBoard() {\n return board.clone();\n }\n\n public String move(int x, int y) {\n if (board[x][y] != BLANK)\n return \"(\" + x + \",\" + y + \") is already occupied\";\n board[x][y] = whoseTurn();\n return referee.isGameOver(x, y, board[x][y], ++moveCount);\n }\n\n private char whoseTurn() {\n return moveCount % 2 == 0 ? 'X' : 'O';\n }\n}\n</code></pre>\n\n<p>And the core logic to check if the game is over.</p>\n\n<pre><code>private class Referee {\n private static final int NO_OF_DIAGONALS = 2;\n private static final int MINOR = 1;\n private static final int PRINCIPAL = 0;\n private final int gridSize;\n private final int[] rowTotal;\n private final int[] colTotal;\n private final int[] diagonalTotal;\n\n private Referee(int size) {\n gridSize = size;\n rowTotal = new int[size];\n colTotal = new int[size];\n diagonalTotal = new int[NO_OF_DIAGONALS];\n }\n\n private String isGameOver(int x, int y, char symbol, int moveCount) {\n if (isWinningMove(x, y, symbol))\n return symbol + \" won the game!\";\n if (isBoardCompletelyFilled(moveCount))\n return \"Its a Draw!\";\n return \"continue\";\n }\n\n private boolean isBoardCompletelyFilled(int moveCount) {\n return moveCount == gridSize * gridSize;\n }\n\n private boolean isWinningMove(int x, int y, char symbol) {\n if (isPrincipalDiagonal(x, y) && allSymbolsMatch(symbol, diagonalTotal, PRINCIPAL))\n return true;\n if (isMinorDiagonal(x, y) && allSymbolsMatch(symbol, diagonalTotal, MINOR))\n return true;\n return allSymbolsMatch(symbol, rowTotal, x) || allSymbolsMatch(symbol, colTotal, y);\n }\n\n private boolean allSymbolsMatch(char symbol, int[] total, int index) {\n total[index] += symbol;\n return total[index] / gridSize == symbol;\n }\n\n private boolean isPrincipalDiagonal(int x, int y) {\n return x == y;\n }\n\n private boolean isMinorDiagonal(int x, int y) {\n return x + y == gridSize - 1;\n }\n}\n</code></pre>\n\n<p>Full source available at: <a href=\"https://github.com/nashjain/tictactoe/tree/master/java\" rel=\"nofollow\">https://github.com/nashjain/tictactoe/tree/master/java</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-17T13:33:24.303",
"Id": "52467",
"Score": "1",
"body": "Same as on your other post. I would warn the OP that throwing an Exception in order to control the flow of the program rather than when there's actually an error is very poor design. Also, the method names are pretty odd and lengthy (even for Java), and you should declare everything explicitly as `public`, `protected`, or `private`. Other than that, this code has some decent tips contained in it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-17T16:40:49.757",
"Id": "52494",
"Score": "0",
"body": "Good point about using errors to control the flow. If you can suggest better names for the methods, it would really help me learn."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-18T04:16:21.107",
"Id": "52545",
"Score": "0",
"body": "I've removed the exceptions and using a simple string to control the flow. Also fixed a bunch of typos in the name."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-17T12:13:35.233",
"Id": "32811",
"ParentId": "31769",
"Score": "2"
}
},
{
"body": "<p>Dependency injection - there's no particular reason that <code>Game</code> needs to specify a particular implementation of <code>Player</code>, or that the two players need to have the same type. So these should be arguments to a constructor</p>\n\n<pre><code>public Game () {\n this(new Player(1), new Player(2));\n}\n\npublic Game(Player player1, Player player2) {\n this.player1 = player1;\n this.player2 = player2;\n}\n</code></pre>\n\n<p>Although to be honest, it's not clear that the Player object is actually contributing in anyway - at the moment, it is just storing state that you don't seem to need.</p>\n\n<p>You've probably got an enum floating around with five states: X to play, O to play, X wins, O wins, Tie. These enums might each be carrying an isGameOver() flag.</p>\n\n<p><code>Game.gameState</code> could be represented by a finite state machine (FSM). Take a look at the <code>State</code> pattern in <em>Design Patterns</em> (Gamma, et al). Each state knows which cells in the grid are occupied, which player has the move, which moves are valid, and what state comes next for each move. 9 factorial states may seem like a lot, but a number of them get pruned away because the game ends before they can be reached, or because there are multiple paths to get there, or because you can cleverly rotate/reflect the coordinates of the board to take advantage of symmetries.</p>\n\n<p>In the FSM approach, you would probably calculate the status of each state as you create it. I would probably use a <code>Scorer</code> (aka <code>Referee</code>, as suggested by @NareshJain), but break out the different win conditions explicitly (<code>checkColumnForWin()</code>, <code>checkRowForWin()</code>, <code>checkDiagonalForWin()</code>). But given that there are only 8 winning conditions to worry about, maybe @Admit's array is the right idea. Or you could combine the ideas, and have the Referee (implementing the rules in a human readable way) producing a list of winning positions (which are then used to evaluate the states).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-18T16:30:50.667",
"Id": "32878",
"ParentId": "31769",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T23:20:28.240",
"Id": "31769",
"Score": "7",
"Tags": [
"java",
"beginner",
"object-oriented",
"enum",
"tic-tac-toe"
],
"Title": "Tic-Tac-Toe design"
}
|
31769
|
<p>So a page where I do a search based on a bunch of filters but all of them are optionals.
I have my controller here:</p>
<pre><code>def distribution
begin
@service_request = ServiceRequest.find(params[:id])
@claimed, @unclaimed = 0, 0
@conditions = ContractorSearchConditions.new()
@conditions.zipcode = @service_request.zipcode.to_s
@conditions.search_terms = params[:filters].present? && params[:filters][:keywords].present? ? params[:filters][:keywords] : 'general'
params[:filters].present? && params[:filters][:proximity].present? ? @conditions.mile_radius = params[:filters][:proximity] :
params[:filters].present? && params[:filters][:results].present? ? @conditions.page_size = params[:filters][:results] :
@conditions.page = 1
@contractors = Contractor.search(@conditions)
@contractors.each do |contractor|
if contractor.uid == 26
@unclaimed = @unclaimed+ 1
else
@claimed = @claimed+ 1
end
end
rescue => e
flash[:error] = "#{e}"
redirect_to :action => :edit
end
end
</code></pre>
<p>And my struct here:</p>
<pre><code>class ContractorSearchConditions < Struct.new(:search_terms, :state, :zipcode, :lat, :lng, :mile_radius, :account_type, :page, :page_size)
#convert zipcode into lat, lon, and state
def prepare
zip = ZipCode.find(zipcode)
self.state.nil? ? self.state = zip.state : self.state = self.state
self.lat.nil? ? self.lat = zip.latitude.to_f : self.lat = self.lat.to_f
self.lng.nil? ? self.lng = zip.longitude.to_f : self.lng = self.lng.to_f
self.mile_radius.nil? ? self.mile_radius = 15 : self.mile_radius = self.mile_radius.to_i
self.page_size.nil? ? self.page_size = 50 : self.page_size = self.page_size.to_i
self.page.nil? ? self.page = 1 : self.page = self.page
end
end
</code></pre>
<p>and</p>
<p>The thing is that my struct will be used in different controller across the app so I went to check the params and set default ones.</p>
<p>But I'm quite not happy with the all my line of if.</p>
<p>Any idea how I could make it better ?</p>
<p><strong>Edit:</strong>
New distribution method:</p>
<pre><code> begin
@service_request = ServiceRequest.find(params[:id])
if params[:filters].nil?
params[:filters] = Hash.new
params[:filters] = {:mile_radius => 15, :page_size => 50, :search_terms => 'general', :score => 100}
end
@conditions = ContractorSearchConditions.new(params[:filters])
@conditions.zipcode = @service_request.zipcode.to_s
@contractors = Contractor.search(@conditions)
@claimed, @unclaimed = 0, 0
@contractors.each do |contractor|
if contractor.uid == 26
@unclaimed = @unclaimed+ 1
else
@claimed = @claimed+ 1
end
rescue => e
flash[:error] = "#{e}"
redirect_to :action => :edit
end
end
</code></pre>
<p>and here is the view:</p>
<pre><code><fieldset>
<div class="row">
<div class="form-group col-lg-12">
<%= f.label :keywords, "Keywords", :class => 'control-label' %>
<%= f.input :keywords, :required => true, :label => false, :as => :string, :input_html => {:class => 'form-control', :maxlength => 255, :value => params[:filters][:keywords]}, :no_wrapper => true %>
<hr>
</div>
</div>
<div class="row">
<div class="form-group col-lg-2">
<%= f.label :results, "# Results", :class => 'control-label' %>
<%= f.input :results, :required => true, :label => false, :input_html => {:class => 'form-control', :value => params[:filters][:results]}, :no_wrapper => true, :as => :number %>
</div>
<div class="form-group col-lg-2">
<%= f.label :proximity, "Proximity", :class => 'control-label' %>
<%= f.input :proximity, :required => true, :label => false, :input_html => {:class => 'form-control', :value => params[:filters][:proximity]}, :no_wrapper => true, :as => :number %>
</div>
</div>
</fieldset>
</code></pre>
<p>and my struct:</p>
<pre><code>class ContractorSearchConditions < Struct.new(:search_terms, :state, :zipcode, :lat, :lon, :mile_radius, :account_type, :page, :page_size)
#convert zipcode into lat, lon, and state
def prepare
zip = ZipCode.find(zipcode)
self.lat = (lat.nil? ? zip.latitude : lat).to_f
self.lon = (lon.nil? ? zip.longitude : lon).to_f
self.state = (state.nil? ? zip.state : state).to_s
self.mile_radius = (mile_radius.nil? ? '15' : mile_radius).to_i
self.page_size = (page_size.nil? ? 50 : page_size).to_i
self.page = (page.nil? ? 1 : page).to_i
self.search_terms = (search_terms.nil? ? 'general' : search_terms).to_s
end
end
</code></pre>
|
[] |
[
{
"body": "<p>Many things here.</p>\n\n<h2>Style considerations</h2>\n\n<p>First, in ruby <a href=\"http://rubylearning.com/blog/2011/12/21/lets-talk-about-conditional-expressions/\" rel=\"nofollow\">conditionals are expressions</a>, so instead of :</p>\n\n<pre><code>self.lat.nil? ? self.lat = zip.latitude.to_f : self.lat = self.lat.to_f\n</code></pre>\n\n<p>you can do :</p>\n\n<pre><code>self.lat = self.lat.nil? ? zip.latitude.to_f : self.lat.to_f\n</code></pre>\n\n<p>you can also get rid of <code>self</code> when not assigning :</p>\n\n<pre><code>self.lat = lat.nil? ? zip.latitude.to_f : lat.to_f\n</code></pre>\n\n<p>you can also group statements :</p>\n\n<pre><code>self.lat = (lat.nil? ? zip.latitude : lat).to_f\n</code></pre>\n\n<p>also, this is roughly equivalent to :</p>\n\n<pre><code>self.lat ||= zip_latitude\nself.lat = lat.to_f\n</code></pre>\n\n<h2>Design considerations</h2>\n\n<p>Your controller is too fat. especially this : </p>\n\n<pre><code> @conditions = ContractorSearchConditions.new()\n @conditions.zipcode = @service_request.zipcode.to_s\n @conditions.search_terms = params[:filters].present? && params[:filters][:keywords].present? ? params[:filters][:keywords] : 'general'\n params[:filters].present? && params[:filters][:proximity].present? ? @conditions.mile_radius = params[:filters][:proximity] :\n params[:filters].present? && params[:filters][:results].present? ? @conditions.page_size = params[:filters][:results] :\n @conditions.page = 1\n</code></pre>\n\n<p>Basicly all of this should be in the body of <code>ContractorSearchConditions#initialize</code> method (give up the struct, use a real class : too much logic is attached to this entity to be a simple bag of data), so that you can do :</p>\n\n<pre><code>@conditions = ContractorSearchConditions.new( params[:search_conditions] )\n</code></pre>\n\n<p><strong>To be continued</strong> I will come back when i have more time to analyze your logic, but here's a hint : when you have a lot of conditionals, it usually means you failed to capture a concept / mechanism as an object. Find out what concept(s) it is and you should be able to clean this. </p>\n\n<p><strong>EDIT : Refactoring</strong></p>\n\n<p>Let's analyze this bit of code :</p>\n\n<pre><code> @conditions.search_terms = params[:filters].present? && params[:filters][:keywords].present? ? params[:filters][:keywords] : 'general'\n params[:filters].present? && params[:filters][:proximity].present? ? @conditions.mile_radius = params[:filters][:proximity] :\n params[:filters].present? && params[:filters][:results].present? ? @conditions.page_size = params[:filters][:results] :\n @conditions.page = 1\n</code></pre>\n\n<p>first, we will use \"real ifs\" and proper indentation to see clear in this mess :</p>\n\n<pre><code> if params[:filters].present? && params[:filters][:keywords].present?\n @conditions.search_terms = params[:filters][:keywords]\n else \n @conditions.search_terms = 'general' \n end\n\n if params[:filters].present? && params[:filters][:proximity].present?\n @conditions.mile_radius = params[:filters][:proximity]\n end\n\n if params[:filters].present? && params[:filters][:results].present?\n @conditions.page_size = params[:filters][:results]\n else\n @conditions.page = 1\n end\n</code></pre>\n\n<p>Still ugly, but more clear. Something important now stands out... Do you see it ? </p>\n\n<pre><code> if params[:filters].present?\n\n # side note : here we use \"presence\" from ActiveSupport, \n # which returns the object itself if it is not blank, or nil.\n @conditions.search_terms = params[:filters][:keywords].presence\n @conditions.mile_radius = params[:filters][:proximity].presence \n @conditions.page_size = params[:filters][:results].presence\n\n end\n\n @conditions.search_terms ||= 'general'\n @conditions.page = 1 unless @condition.page_size\n</code></pre>\n\n<p>The whole logic has, in fact, <strong>two purposes</strong> : </p>\n\n<ul>\n<li>initialize the <code>@conditions</code> object using <code>params[:filters]</code></li>\n<li>set default values if necessary</li>\n</ul>\n\n<p>All of this should be the responsibility of <code>ContractorSearchConditions#initialize</code>. </p>\n\n<pre><code>class ContractorSearchConditions\n\n # here are defaults values, all contained in a constant.\n # Thanks to this, everyone that looks at that class knows\n # what to expect as default values with this object.\n #\n DEFAULTS = {\n search_terms: :general,\n page: 1,\n page_size: 50, # those values are hard to find\n miles_radius: 15 # in the code you posted... not anymore !\n }.freeze\n\n def initialize( params = {} )\n # the magic happen here. We have default values, \n # but let the caller override them :\n options = DEFAULTS.merge( params || {} ) \n filters = options.delete( :filters ){ {} }\n\n assign_attributes( options )\n filters.each{|name, value| apply_filter( name, value )}\n end\n\n # use the attributes accessor to assign all values.\n # the benefit here is that each accessor encapsulates\n # rules about what is a valid value to assign, how to coerce it, etc.\n # one could also easily filter which attributes can be assigned this way,\n # à la \"attr_accessible\"\n #\n def assign_attributes( attributes )\n attributes.each{|attr,value| public_send \"#{attr}=\", value }\n end\n\n # example of custom writer with safety nets all over the place :\n # \n def page=( value )\n return @page if value.blank?\n @page = value.to_i\n rescue NoMethodError \n raise ArgumentError, \"invalid value '#{value}' for page\"\n end\n\n # we can do something somewhat similar with filters :\n #\n def apply_filter( name, value )\n public_send \"#{name}_filter\", value\n rescue NoMethodError\n raise ArgumentError, \"unknown filter '#{name}'\"\n end\n\n # example of filter :\n #\n def proximity_filter( value )\n self.mile_radius = value\n # this seems dumb, but would be really useful if you have complex behavior\n # like multiparameter filters, etc. \n end\n\nend\n</code></pre>\n\n<h2>What ? but this is far more complex !</h2>\n\n<p>yes... and no.</p>\n\n<ul>\n<li><p>This implementation provides <strong>encapsulation</strong> of data and behavior, and ensures that your object always initializes with default, sensible values, in a consistent state. This is the heart of OOP! </p></li>\n<li><p>This also means you won't have to repeat this code over and over if you need it in another controller : in other words, <strong>reusability</strong>. </p></li>\n<li><p>this is a lot of logic, but <strong>you're doing many things</strong> ! In fact, if you want this to be pure, outrageously OO code, you would have to create one object for each responsibility (SRP) :</p>\n\n<ul>\n<li>extract parameters from a hash </li>\n<li>map them to a set of attributes</li>\n<li>coerce all values and guard against meaningless ones</li>\n<li>etc.</li>\n</ul></li>\n<li><p>For now, you've stuffed a lot of logic in the controller. This works for small projects, but can quickly become a code swamp in bigger ones. The whole process you perform should have a dedicated place to live ! That's why many people (me included) would use some sort of <code>ContractorSearch</code> object that would represent... a search (duh) and that you would be able to manipulate like, say, an ActiveModel object. A (bit outdated) example of such approach can be seen in <a href=\"http://railscasts.com/episodes/111-advanced-search-form\" rel=\"nofollow\">railscasts #111</a>. This even allows you to easily save your searches !</p></li>\n<li><p>i admit i have a tendency to overengineer. My implementation may be too much, but you get the spirit...</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T17:36:58.073",
"Id": "50723",
"Score": "0",
"body": "First of all thank you!\nI changed my method based on your comment.\nI also added the view. Here is the behaviour. The user can access to the page and then apply filter if the default results are not good enough.\nBut I want to avoid logic in my view as much as possible, that's why I instantiate the params in the controller and I also want the inputs to be populated.\n\nWhat do you think ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T17:42:36.920",
"Id": "50724",
"Score": "0",
"body": "i'm still editing my answer, I'll come back to you in a few minutes"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T17:58:40.653",
"Id": "50725",
"Score": "0",
"body": "wow, i may have gone over the board now. Sorry if its too long"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T18:04:07.420",
"Id": "50727",
"Score": "0",
"body": "as to your question, you should really see the [railscasts #11](http://railscasts.com/episodes/111-advanced-search-form-revised) i linked in my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T18:11:36.107",
"Id": "50728",
"Score": "0",
"body": "one more word : with rails 3+, our `apply_filter` method can simply add scopes over a base relation. I usually have such a method, with 'optional' scopes that return an unchanged relation if a blank param is passed. This way you can chain them at will..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T18:13:27.130",
"Id": "50729",
"Score": "0",
"body": "This is actually a pretty awesome answer!\nI wish I could give more than one upvote!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T12:06:43.147",
"Id": "31791",
"ParentId": "31770",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "31791",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T23:29:00.040",
"Id": "31770",
"Score": "1",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Improve a list of if"
}
|
31770
|
<p><strong>Background</strong></p>
<p>In C++ unlike other OOP languages, we do not have a Base Class from where All Classes are derived. I understand in MFC and pre STL, some Compilers did had a similar model, so lets leave it out of the discussion and focus on what the standard provides. </p>
<p>In C++11, <code>auto</code> was introduced to derive the type from rvalue just another way of type deduction of templates. This was a huge relief when one has to write long list of types with all template parameters.</p>
<p>Using Naked Pointers were prone to errors so Smart Pointers were introduced as a remedy for the unavoidable evil.</p>
<p><strong>Use Case</strong></p>
<p>I have a function which should return something that would indicate Null Object when no data was found or if it found needs to return the data. I would like to know, if C++11 has an elegant way of writing the below code, considering, the template types are painful to read.</p>
<p><strong>Code</strong></p>
<pre><code>std::unique_ptr<std::tuple<tstring, int, tstring> > CCOMErrorHandler::PopError()
{
unique_ptr<std::tuple<tstring, int, tstring> > error = nullptr;
if (!m_lstErrors.empty())
{
error = std::unique_ptr<std::tuple<tstring, int, tstring> >(new std::tuple<tstring, int, tstring>(m_lstErrors.front()));
if (error)
{
m_lstErrors.pop_front();
}
}
return(error);
}
</code></pre>
<p>One option is to use a <code>typedef</code> or macro replacement, but generally am not a big FAN as that keeps polluting namespace though you may have to use to few times in your code often only once.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-06T13:22:29.410",
"Id": "504585",
"Score": "0",
"body": "Does `std::optional` serve your purpose nowadays?"
}
] |
[
{
"body": "<p>The first question is, why are you using pointers in the first place here? Allocation with <code>new</code> should only be used when required. Perhaps it is in this case, but I'd rethink your design. Are the errors polymorphic? If so, why? If not, why do you need to use pointers?</p>\n\n<p>Many STL containers use either an error-code approach, that is, they return a <code>std::pair<T, bool></code>, where the <code>bool</code> represents success/failure, or they deal\ndirectly with iterators, and return an iterator to <code>end()</code> in the case of failure. Depending on the type of <code>m_lstErrors</code>, this could be a possibility (although obviously this won't work for a container adapter like <code>std::stack</code>). </p>\n\n<p>Though it is not contained in the C++ standard library at the moment (it is slated for inclusion in C++14), <code>std::optional</code> was basically made for this purpose. In fact, it can be written using only C++11 features (and there's a reference implementation you could use <a href=\"https://github.com/akrzemi1/Optional/blob/master/optional.hpp\" rel=\"noreferrer\">here</a>). Boost also contains a <code>boost::optional</code> type, although this lacks things such as move semantics and safe (explicit) bool conversion (although other than that, it is very similar in nature). This would change the code to look like this:</p>\n\n<pre><code>std::optional<std::tuple<tstring, int, tstring>> CCOMErrorHandler::PopError()\n{\n typedef std::tuple<tstring, int, tstring> tuple_type;\n std::optional<tuple_type> error;\n if(!m_lstErrors.empty()) {\n error = *m_lstErrors.front();\n m_lstError.pop_front();\n }\n return error;\n}\n</code></pre>\n\n<p><a href=\"http://en.cppreference.com/w/cpp/utility/optional\" rel=\"noreferrer\">cppreference</a> has an API reference for <code>std::optional</code>. </p>\n\n<p>As for the complaint about template types, you can always wrap them in another namespace to help prevent pollution:</p>\n\n<pre><code>namespace mynamespace\n{\nnamespace detail\n{\n typedef std::tuple<tstring, int, tstring> error_type;\n typedef std::optional<error_type> optional_error;\n}\n\ndetail::optional_error CCOMErrorHandler::PopError()\n{\n //...\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T16:31:48.873",
"Id": "50719",
"Score": "0",
"body": "+1: For introducing me to std::optional, and reminding me to use namespace. **The first question is, why are you using pointers in the first place here?** Just, to have a unified return irrespective of presence or absence of data.Pointers works well here. Various containers have their own error-code approach, but generally (ex. for sequences) I would have to end up returning iterators, and may not always be valid outside the context (as in my example). Unless `std::optional` was there in the stdlib, I don't see extra mileage in using it from what I have now."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T16:13:00.407",
"Id": "31798",
"ParentId": "31777",
"Score": "5"
}
},
{
"body": "<p>I feel like you're facing a conundrum but you painted yourelf in that corner. You have a function that you specifically called <code>PopError</code> and then you realize that it may not pop an actual error because there may be no error to pop. You're trying to force a different style from how you're expected to do. I would suggest the following :</p>\n<pre><code>bool CCOMErrorHandler::HasError()\n{\n return !m_lstErrors.empty();\n}\n\nauto CCOMErrorHandler::PopError()\n{\n auto error = *m_lstErrors.front();\n m_lstError.pop_front();\n return error;\n}\n</code></pre>\n<p>Confirming you got a "null" object or whether something exists to begin with may feel the same but I'd say the second way is the way you're expected to program in C++ because that's the API you get from the STL and you will have the same amount of code anyway.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-06T12:44:49.233",
"Id": "255686",
"ParentId": "31777",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T03:13:40.577",
"Id": "31777",
"Score": "3",
"Tags": [
"c++"
],
"Title": "Null Object Pattern for STL Types"
}
|
31777
|
<pre><code>import bwi.prog.utils.TextIO;
public class MinMidMax {
public static void main(String[] args) {
int a,b,c;
int greatest, mid, smallest;
TextIO.putln("Enter three numbers");
TextIO.put("a=");
a = TextIO.getInt();
TextIO.put("b=");
b = TextIO.getInt();
TextIO.put("c=");
c = TextIO.getlnInt();
greatest = Math.max(a, Math.max(b,c));
smallest = Math.min(a, Math.min(b,c));
if (a < greatest && a > smallest )
mid = a;
else if (b < greatest && b > smallest )
mid = b;
else
mid = c;
if(a<b && a<c && b<c){ // a<b<c
TextIO.put("\n");
TextIO.putln("ordered:");
TextIO.putf("%d<%d<%d\n",smallest, mid, greatest);
TextIO.putf("%s<%s<%s\n","a", "b", "c");
}
else if(a<c && a<b && c<b){ // a<c<b
TextIO.put("\n");
TextIO.putln("ordered:");
TextIO.putf("%d<%d<%d\n",smallest, mid, greatest);
TextIO.putf("%s<%s<%s\n","a", "c", "b");
}
else if(b<a && b<c && a<c){ // b<a<c
TextIO.put("\n");
TextIO.putln("ordered:");
TextIO.putf("%d<%d<%d\n",smallest, mid, greatest);
TextIO.putf("%s<%s<%s\n","b", "a", "c");
}
else if(b<c && b<a && c<a){ // b<c<a
TextIO.put("\n");
TextIO.putln("ordered:");
TextIO.putf("%d<%d<%d\n",smallest, mid, greatest);
TextIO.putf("%s<%s<%s\n","b", "c", "a");
}
else if(c<a && c<b && a<b){ // c<a<b
TextIO.put("\n");
TextIO.putln("ordered:");
TextIO.putf("%d<%d<%d\n",smallest, mid, greatest);
TextIO.putf("%s<%s<%s\n","c", "a", "b");
}
else if (c<b && c<a && b<a){ //c<b<a
TextIO.put("\n");
TextIO.putln("ordered:");
TextIO.putf("%d<%d<%d\n",smallest, mid, greatest);
TextIO.putf("%s<%s<%s\n","c", "b", "a");
}
else if ( a==b && b==a && a>c && b > c){ // c<a=b
TextIO.put("\n");
TextIO.putln("ordered:");
TextIO.putf("%d<%d=%d\n",c, a, b);
TextIO.putf("%s<%s=%s","c", "a", "b");
}
else if ( a==b && b==a && a<c && b < c){ //a=b<c
TextIO.put("\n");
TextIO.putln("ordered:");
TextIO.putf("%d=%d<%d\n",a, b, c);
TextIO.putf("%s=%s<%s","a", "b", "c");
}
else if ( a==c && c==a && a>b && c > b){ //b<a=c
TextIO.put("\n");
TextIO.putln("ordered:");
TextIO.putf("%d<%d=%d\n",b, a, c);
TextIO.putf("%s<%s=%s","b", "a", "c");
}
else if ( a==c && c==a && a<b && c<b){ //a=c<b
TextIO.put("\n");
TextIO.putln("ordered:");
TextIO.putf("%d=%d<%d\n",a, c, b);
TextIO.putf("%s=%s<%s","a", "c", "b");
}
else if ( a<b && a<c && b==c && c==b){ //a<b=c
TextIO.put("\n");
TextIO.putln("ordered:");
TextIO.putf("%d<%d=%d\n",a, b, c);
TextIO.putf("%s<%s=%s","a", "b", "c");
}
else if ( b==c && c==b && c<a && b< a) // b=c<a
{
TextIO.put("\n");
TextIO.putln("ordered:");
TextIO.putf("%d=%d<%d\n",b, c, a);
TextIO.putf("%s=%s<%s","b", "c", "a");
}
else if (a == b && a == c && b == c && b == a && c==b && c==a) //a=b=c
{
TextIO.put("\n");
TextIO.putln("ordered:");
TextIO.putf("%d=%d=%d\n",smallest, mid, greatest);
TextIO.putf("%s=%s=%s","a", "b", "c");
}
else if (a < b && a < c && b == c && c==b) //a<b=c
{
TextIO.put("\n");
TextIO.putln("ordered:");
TextIO.putf("%d<%d=%d\n",smallest, mid, greatest);
TextIO.putf("%s<%s=%s","a", "b", "c");
}
else if (b<a && b<c && a == b && b == a) //b<a=c
{
TextIO.put("\n");
TextIO.putln("ordered:");
TextIO.putf("%d<%d=%d\n",smallest, mid, greatest);
TextIO.putf("%s<%s=%s","b", "a", "c");
}
else if (c<a && c<b && a == b && b == a) //c<a=b
{
TextIO.put("\n");
TextIO.putln("ordered:");
TextIO.putf("%d<%d=%d\n",smallest, mid, greatest);
TextIO.putf("%s<%s=%s","c", "b", "a");
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>This will achieve the same goal in much less code.</p>\n\n<pre><code>import bwi.prog.utils.TextIO;\nimport java.util.*;\n\npublic class MinMidMax {\n\n public static void main(String[] args) { \n Map<Integer, Character> vars = new TreeMap<Integer, Character>();\n // get input\n TextIO.putln(\"Enter three numbers\"); \n for (Character c = 'a'; c <= 'c'; c++) {\n TextIO.putf(\"%s=\", c);\n vars.put(TextIO.getInt(), c);\n }\n // print the result\n StringBuilder sbValues = new StringBuilder(\"\\nordered:\\n\");\n StringBuilder sbVars = new StringBuilder();\n for (Map.Entry<Integer, Character> e : vars.entrySet()) {\n sbValues.append(e.getValue());\n sbValues.append(\"\\t<\");\n sbVars.append(e.getKey());\n sbVars.append(\"\\t<\");\n }\n sbVars.setLength(sb.length() - 2);\n sbValues.setLength(sb.length() - 2);\n TextIO.putln(sbValues);\n TextIO.putln(sbVars);\n }\n}\n</code></pre>\n\n<p>The <code>TreeMap</code> class automatically sorts its keys, and iterating through them is relatively trivial.</p>\n\n<p>Not that <code>StringBuilder</code> has been used to build strings for later output, so you can remove the remaining <code>\\t<</code> at the end.</p>\n\n<p>The <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/package-summary.html\" rel=\"nofollow\">java.util</a> package can make your life much easier. </p>\n\n<p>Note that this also supports an arbitrary amount of inputs, just change <code>c <= 'c'</code> to any character greater than <code>'c'</code> on the ASCII table.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T05:14:45.273",
"Id": "50683",
"Score": "0",
"body": "I would use a `TreeMap<Integer,Character>` instead. `TreeMap` automatically keeps its keys sorted, and doesn't require an explicit `Collections.sort()`. Also, using `Character` avoids the `\"\"+c` hack."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T05:18:02.117",
"Id": "50684",
"Score": "1",
"body": "You also don't need `items` — you can just get it from `vars.keySet()`, which is guaranteed to be a `SortedSet` if `vars` is a `TreeMap`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T05:19:19.967",
"Id": "50685",
"Score": "0",
"body": "The `Map` doesn't handle duplicate values well at all, though!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T05:40:29.997",
"Id": "50686",
"Score": "0",
"body": "@200_success Modified to address first two comments. Changed to `TreeMap<Integer, Character>` and used resulting `entrySet()` with `StringBuilder`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T04:43:24.557",
"Id": "31780",
"ParentId": "31778",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T04:25:07.843",
"Id": "31778",
"Score": "0",
"Tags": [
"java",
"sorting"
],
"Title": "Sorting three numbers"
}
|
31778
|
<p>I have written a memory pool (<code>pool_allocator</code>) that was described in a book I am reading (<em>Game Engine Architecture</em>). The interface is pretty basic:</p>
<ul>
<li>The constructor: <code>pool_allocator(std::size_t count, std::size_t block_size, std::size_t alignment);</code>.</li>
<li><code>void* allocate();</code>, which returns a pointer to a memory location with (at least) the requested alignment.</li>
<li><code>void free(void* block);</code> which returns the block to the pool.</li>
</ul>
<p>The general design is not complex, either. The constructor uses <code>operator new()</code> to allocate a chunk of memory, and that memory is treated as a linked list - any calls to <code>allocate</code> and <code>free</code> operate on the head of the list.</p>
<p>However, this is the first time I have ever given alignment any real consideration, and apparently if I use enough <code>{static,reinterpret}_cast</code>s, I start to question that the Earth is round. I would be grateful for comments. My main concerns are:</p>
<ul>
<li>Is alignment handled properly? I think <code>align_head()</code> is okay, but what about <code>minimum_alignment()</code> and <code>padding()</code>?</li>
<li>Are the <code>reinterpret_cast</code> and <code>static_cast</code> calls used properly, or are there better alternatives? I understand that they are necessary when handling raw data, but I am out of my comfort zone here.</li>
</ul>
<p>If you want to go the extra mile and point out other deficiencies (which is more than welcome), keep in mind that in the current design it is not the responsibility of this object to handle error conditions or construct objects, just manage a chunk of memory.</p>
<pre><code>class pool_allocator {
public:
typedef void* pointer_type;
public:
pool_allocator(std::size_t count, std::size_t block_size, std::size_t alignment)
: m_data(nullptr)
, m_head(nullptr)
, m_blocks(count)
, m_block_size(block_size)
, m_padding(0)
{
// each block must be big enough to hold a pointer to the next
// so that the linked list works
if (m_block_size < sizeof(pointer_type)) {
m_block_size = sizeof(pointer_type);
}
// each block must meet the alignment requirement given as well
// as the alignment of pointer_type.
alignment = minimum_alignment(alignof(pointer_type), alignment);
// find the padding required for sequential blocks:
m_padding = padding(m_block_size, alignment);
// allocate a chunk of memory
m_data = operator new((m_block_size + m_padding) * m_blocks + alignment);
// align the head pointer
align_head(alignment);
// initialize the list
initialize_list();
}
pool_allocator(pool_allocator const&) = delete;
pool_allocator& operator=(pool_allocator const&) = delete;
virtual ~pool_allocator()
{
operator delete(m_data);
}
// grab one free block from the pool
pointer_type allocate()
{
if (m_head == nullptr) {
return nullptr;
}
else {
pointer_type result = m_head;
m_head = *(static_cast<pointer_type*>(result));
return result;
}
}
// return the block to the pool
void free(pointer_type block)
{
*(static_cast<pointer_type*>(block)) = m_head;
m_head = block;
}
private:
// align_head: calculates the offset from the beginning of the
// allocated data chunk (m_data) to the first aligned location
// and stores it as the void* m_head
void align_head(std::size_t alignment)
{
std::uintptr_t raw_address = reinterpret_cast<std::uintptr_t>(m_data);
std::uintptr_t c_alignment = static_cast<std::uintptr_t>(alignment);
std::uintptr_t offset = c_alignment - (raw_address & (c_alignment - 1));
m_head = reinterpret_cast<pointer_type>(raw_address + offset);
}
// initialize_list: fills the first sizeof(void*) bytes of
// each block in the data chunk with a pointer to the next
void initialize_list()
{
std::uintptr_t current = reinterpret_cast<std::uintptr_t>(m_head);
std::uintptr_t block_size = static_cast<std::uintptr_t>(m_block_size + m_padding);
for (std::size_t block = 0; block < m_blocks; ++block) {
std::uintptr_t next = current + block_size;
*(reinterpret_cast<pointer_type*>(current)) = reinterpret_cast<pointer_type>(next);
current = next;
}
// make sure the last block points nowhere
current -= block_size;
*(reinterpret_cast<pointer_type*>(current)) = nullptr;
}
// minimum_alignment: calculate the least commmon multiple of
// a and b and return that value
std::size_t minimum_alignment(std::size_t a, std::size_t b)
{
std::size_t ta = a;
std::size_t tb = b;
while (tb != 0) {
std::size_t tr = tb;
tb = ta % tr;
ta = tr;
}
return (a / ta) * b;
}
// padding: calculate the smallest multiple of padding that can
// contain block_size
std::size_t padding(std::size_t block_size, std::size_t alignment)
{
std::size_t multiplier = 0;
while (multiplier * alignment < block_size) {
++multiplier;
}
return multiplier * alignment - block_size;
}
private:
pointer_type m_data;
pointer_type m_head;
std::size_t m_blocks;
std::size_t m_block_size;
std::size_t m_padding;
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-05T15:47:41.507",
"Id": "106421",
"Score": "0",
"body": "Shouldn't you try to implement the allocator interface? http://en.wikipedia.org/wiki/Allocator_(C%2B%2B)"
}
] |
[
{
"body": "<p>I think you have some fundamental misunderstandings about alignment (and you can simplify your code a lot):</p>\n\n<h3>3.11 Alignment</h3>\n\n<blockquote>\n <p>3: Alignments are represented as values of the type std::size_t. Valid alignments include only those values returned by an alignof expression for the fundamental types plus an additional implementation-defined set of values, which may be empty. <strong>Every alignment value shall be a non-negative integral power of two.</strong></p>\n</blockquote>\n\n<p>So you can the alignment requirements of a type from <code>alignof()</code>. This value is a power of 2.</p>\n\n<blockquote>\n <p>5: Alignments have an order from weaker to stronger or stricter alignments. Stricter alignments have larger alignment values. An address that satisfies an alignment requirement also satisfies any weaker valid alignment requirement.</p>\n</blockquote>\n\n<p>If something satisfies the alignments for a larger alignment. Then it automatically satisfies alignment requirements for smaller values.</p>\n\n<p>Thus if memory is aligned for an object of size <code>N</code>. Then it is also correctly aligned for objects that are smaller than 'N'.</p>\n\n<h3>18.6.1.1 Single-object forms [new.delete.single]</h3>\n\n<blockquote>\n <p><strong>void* operator new(std::size_t size);</strong><br>\n 1: Effects: The allocation function (3.7.4.1) called by a new-expression (5.3.4) to allocate size bytes of storage suitably aligned to represent any object of that size.</p>\n</blockquote>\n\n<p>Thus using new to allocate memory for a space of size 'M' means the memory returned will also be aligned for objects of size 'M'. This also means that it aligned for all objects that are smaller than 'M'. Thus for your block of memory that will hold multiple objects of type 'N' such that `M = Count*alignof(N)' it is automatically aligned for all objects of type 'N'.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T15:28:16.563",
"Id": "50931",
"Score": "0",
"body": "Thank you - both your points were helpful (and new) to me. Possibly relevant note: the part of the book which prompted this exercise was talking about aligning objects an unaligned chunk of memory, and I just square-pegged in `operator new` in place of a fictional `allocateUnaligned()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-05T15:56:13.227",
"Id": "106423",
"Score": "0",
"body": "Are you sure about this: \"\"\"Thus if memory is aligned for an object of size N. Then it is also correctly aligned for objects that are smaller than 'N'.\"\"\" I think that a compiler could let `char[100]` have 1 as alignment while `int` could have 4."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-05T17:02:44.863",
"Id": "106447",
"Score": "0",
"body": "@EmanuelePaolini: Yes. Because the `operator new` does not know the type is char. It is asked to allocate a chunk of memory 100 bytes in size (see 18.6.1.1). Thus it needs to be aligned for something of size 100. If it is aligned for something for size 100 it is also aligned for something of size 4 (see 3.11 para 5)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T03:04:07.803",
"Id": "31879",
"ParentId": "31779",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "31879",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T04:37:54.593",
"Id": "31779",
"Score": "4",
"Tags": [
"c++",
"c++11",
"memory-management"
],
"Title": "Memory Pool and Block Alignment"
}
|
31779
|
<p>I am learning java and browsing posts on CodeReview and StackOverflow.</p>
<p>In my text <strong>Introduction to Java Programming- Y Daniel Liang</strong> it states: </p>
<blockquote>
<p>The wildcard import imports all classes in a package by using ...<br>
The information for the classes in an imported package is not read in
at compile time or runtime unless the class is used in the program.
The import statement simply tells the compiler where to locate the
classes. There is no performance difference between a specific and a
wildcard import declaration.</p>
</blockquote>
<p>These are two examples:</p>
<p><a href="https://codereview.stackexchange.com/questions/25424/how-ho-make-this-code-more-simple-and-optimized">This question:</a> <strong>(1)</strong> </p>
<pre><code>import java.util.ArrayList;
import java.util.List;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Bounds;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TitledPane;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;
</code></pre>
<p><a href="https://codereview.stackexchange.com/a/2540/29649">This answer:</a> <strong>(2)</strong></p>
<pre><code>import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
</code></pre>
<p>Could these be written as: </p>
<p><strong>(1)</strong> </p>
<pre><code>import java.util.*
import javafx.beans.*
import javafx.collections.*
import javafx.geometry.*
import javafx.scene.*
import javafx.stage.*
</code></pre>
<p>and </p>
<p><strong>(2)</strong></p>
<pre><code>import java. util.*
</code></pre>
<p><strong>Are there exceptions to using the wildcard for importing?<br>
What is considered the best practice when specifying imports?</strong></p>
<p><em>I am not sure if this is best posted on code review or stackoverflow</em></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T07:21:52.047",
"Id": "50697",
"Score": "5",
"body": "I'm not sure, but I think this question would be better suited for Programmers."
}
] |
[
{
"body": "<p>I prefer not to use star imports, because they can lead to ambiguities. Read more here: <a href=\"https://stackoverflow.com/a/147461/660143\">https://stackoverflow.com/a/147461/660143</a></p>\n\n<p>There is no consensus about whether star import are good or bad. My IDE organizes the imports for me, so I don't care if there are a lot of import statements in my code. But that's my personal opinion.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T07:15:19.653",
"Id": "50695",
"Score": "3",
"body": "There is no consensus about whether star import are good or bad. My IDE organizes the imports for me, so I don't care if there are a lot of import statements in my code. But that's my personal opinion."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T06:58:32.797",
"Id": "31783",
"ParentId": "31782",
"Score": "3"
}
},
{
"body": "<p>First, let's acknowledge that this is a subjective question. However, in my opinion, it is constructive enough to be on topic for this site.</p>\n\n<p>I would treat the standard Java library differently than your own packages or third-party packages. Everyone recognizes classes from the standard Java library, such as <code>BufferedReader</code>, <code>PrintWriter</code>, and <code>IOException</code>. There is therefore no value in importing those individually; it just clutters the code. Everyone who has worked with Java will know that those classes belong to the <code>java.io</code> package, unambiguously. Anyone who writes classes whose names conflict with those well known classes will be soundly beaten up, so name conflicts with <code>java.</code> classes just don't happen in practice.</p>\n\n<p>With third-party libraries, it makes sense to import more specifically. Programmers encountering those classes could use some help to figure out which packages they belong to. Name clashes <em>could</em> happen. That said, star imports for third-party libraries would be a judgement call. I would suggest importing individual classes up to some number of classes (around 4) per package; beyond that, a star import might be sensible. I would try to avoid star-importing more than one such package, though, to mitigate against the documentation-searching and name clash concerns. (If you feel the urge to star-import multiple packages, your class is probably doing too much anyway and should be split up.)</p>\n\n<p>With code that you have written yourself for the same or a closely related project, go ahead and star-import related packages, judiciously. If you're working with the source code, you'll be familiar with the related code in neighbouring packages anyway. If it fails to compile because of a name clash, you can fix it yourself.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T09:05:45.663",
"Id": "50705",
"Score": "0",
"body": "By all means, feel free to [wait](http://meta.codereview.stackexchange.com/q/772/9357) for responses to roll in before you decide to accept."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-26T06:12:47.883",
"Id": "179633",
"Score": "0",
"body": "The problem with this is that you assume the programmer writes imports themselves (since AFAIK no IDE can do what you describe). I guess that without the possibility to do selective star imports automaticaly, the arguments against stars imports IMHO prevail. The times when I knew what class is where are long gone and I don't care, that's Eclipse's job."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T08:07:29.917",
"Id": "31786",
"ParentId": "31782",
"Score": "7"
}
},
{
"body": "<p>You have a misconception </p>\n\n<pre><code>import java.util.concurrent.ArrayBlockingQueue;\nimport java.util.concurrent.BlockingQueue;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.atomic.AtomicInteger;\n</code></pre>\n\n<p>can't be write like </p>\n\n<pre><code>import java.util.*;\n</code></pre>\n\n<p><code>*</code>(wildcard) only imports all the classes from the package, but it doesn't import all the packages inside the package, if that was possible then we can just say</p>\n\n<pre><code>import java.*;\n</code></pre>\n\n<p>But that's not right.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T16:08:57.063",
"Id": "50716",
"Score": "0",
"body": "that is precisely why I wrote this question.. +1 ty"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T06:14:22.753",
"Id": "415261",
"Score": "0",
"body": "@YvetteColomb its not clear that's what you're asking. I needed to see Anirban's comment to understand this constraint"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T16:00:22.930",
"Id": "31797",
"ParentId": "31782",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T06:39:20.697",
"Id": "31782",
"Score": "3",
"Tags": [
"java",
"beginner"
],
"Title": "Using the wildcard when importing packages"
}
|
31782
|
<p>In our Rails 3.2.13 app (Ruby 2.0.0 + Postgres on Heroku), we are often retreiving a large amount of Order data from an API, and then we need to update or create each order in our database, as well as the associations. A single order creates/updates itself plus approx. 10-15 associcated objects, and we are importing up to 500 orders at a time.</p>
<p>The below code works, but I fear it's not as efficient as it could be in terms of speed. Creating/updating 500 records takes approx. 1 minute!</p>
<p>Below is the code I would like reviewed:</p>
<pre><code>def add_details(shop, shopify_orders)
shopify_orders.each do |shopify_order|
get_order = Order.where(:order_id => shopify_order.id.to_s, :shop_id => shop.id)
if get_order.blank?
order = Order.create(:order_id => shopify_order.id.to_s, :shop_id => shop.id)
else
order = get_order.first
end
order.update_details(order,shopify_order,shop) #This calls update_attributes for the Order
ShippingLine.add_details(order, shopify_order.shipping_lines)
LineItem.add_details(order, shopify_order.line_items)
Taxline.add_details(order, shopify_order.tax_lines)
Fulfillment.add_details(order, shopify_order.fulfillments)
Note.add_details(order, shopify_order.note_attributes)
Discount.add_details(order, shopify_order.discount_codes)
billing_address = shopify_order.billing_address rescue nil
if !billing_address.blank?
BillingAddress.add_details(order, billing_address)
end
shipping_address = shopify_order.shipping_address rescue nil
if !shipping_address.blank?
ShippingAddress.add_details(order, shipping_address)
end
payment_details = shopify_order.payment_details rescue nil
if !payment_details.blank?
PaymentDetail.add_details(order, payment_details)
end
end
end
def update_details(order,shopify_order,shop)
order.update_attributes(
:order_name => shopify_order.name,
:order_created_at => shopify_order.created_at,
:order_updated_at => shopify_order.updated_at,
:status => Order.get_status(shopify_order),
:payment_status => shopify_order.financial_status,
:fulfillment_status => Order.get_fulfillment_status(shopify_order),
:payment_method => shopify_order.processing_method,
:gateway => shopify_order.gateway,
:currency => shopify_order.currency,
:subtotal_price => shopify_order.subtotal_price,
:Subtotal_tax => shopify_order.total_tax,
:total_discounts => shopify_order.total_discounts,
:total_line_items_price => shopify_order.total_line_items_price,
:total_price => shopify_order.total_price,
:total_tax => shopify_order.total_tax,
:total_weight => shopify_order.total_weight,
:taxes_included => shopify_order.taxes_included,
:shop_id => shop.id,
:email => shopify_order.email,
:order_note => shopify_order.note
)
end
</code></pre>
<p>So as you can see, we are looping through each order, finding out if it exists or not (then either loading the existing Order or creating the new Order), and then calling update_attributes to pass in the details for the Order. After that we create or update each of the associations. Each associated model looks very similar to this:</p>
<pre><code> class << self
def add_details(order, tax_lines)
tax_lines.each do |shopify_tax_line|
taxline = Taxline.find_or_create_by_order_id(:order_id => order.id)
taxline.update_details(shopify_tax_line)
end
end
end
def update_details(tax_line)
self.update_attributes(:price => tax_line.price, :rate => tax_line.rate, :title => tax_line.title)
end
</code></pre>
<p>I've looked into the activerecord-import gem but unfortunately it seems to be more geared towards creation of records in bulk and not update as we require.</p>
<p>Any suggestions on how this code can be improved? How would you go about improving this based on your experience?</p>
<p>Many many thanks in advance.</p>
<p><strong>UPDATE:</strong> </p>
<p>The database is performing quite well as it should, 500 orders with 10-15 associated objects each is about 5500-8000 queries. This is completed in about a minute, so it's handling roughly 100 queries per seconds.. robust enough. Just hoping there is a way that we can reduce the amount of queries needed to accomplish the creation/update of all that data.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T21:00:25.757",
"Id": "50742",
"Score": "0",
"body": "It's hard to understand what you are actually doing there. Did you monitor what (and how many) database statement get executed when you import an order? That could give you a clue where the time is spend."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T14:06:19.650",
"Id": "50777",
"Score": "0",
"body": "@iltempo Thanks for the comment. We are basically consuming an API for data, and then writing that data into our DB. This is done in a background job, but the initial import done when a new user has installed our saas app requires them waiting for it to complete.. this is why we want to \"speed up\" the process as much as possible. I have updated the above to show the current database activity."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-21T10:47:56.460",
"Id": "110103",
"Score": "0",
"body": "You can adapt it to work with updates: https://gist.github.com/jackrg/76ade1724bd816292e4e"
}
] |
[
{
"body": "<p>You can reduce the amount of queries by putting it into a transaction:</p>\n\n<pre><code>ActiveRecord::Base.transaction do\n ...\nend\n</code></pre>\n\n<p>This wont reduce the amount of queries but will do them all at once which will save it doing the commit step for each time it has to do the query. Note, that if one of them fails, the transaction will normally be rolled back.</p>\n\n<p>Bulk importing is also another method:</p>\n\n<p><a href=\"https://github.com/zdennis/activerecord-import\">https://github.com/zdennis/activerecord-import</a></p>\n\n<p>This may not work in your situation as you need to know if there is data there already.</p>\n\n<p>You could also improve your code design to check for the order only once, instead of doing <code>find_or_create_by_order_id</code>, do this at the start and then send it to the other objects,</p>\n\n<p>for example: </p>\n\n<pre><code>order = Order.find_or_create_by_order_id(:order_id => order.id)\norder.shipping_line = shopify_order.shipping_lines\norder.line_item = shopify_order.line_item\norder.fulfillment = shopify_order.fulfillment\n\norder.save!\n\nClass Order < ActiveRecord::Base\n has_many :shopping_line\n ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T21:28:29.160",
"Id": "51246",
"Score": "1",
"body": "Thanks for the great ideas, adding the transaction reduced the overall processing time by about 50%! Will implement your other suggestions as well once I have a little more time, but this is a great improvement already. Appreciate it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T21:30:20.513",
"Id": "51247",
"Score": "1",
"body": "Ps. activerecord-import won't work unfortunately but I've since come accross upsert, which may be a good middle road: [https://github.com/seamusabshere/upsert](https://github.com/seamusabshere/upsert)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-22T10:52:20.467",
"Id": "218759",
"Score": "0",
"body": "BTW activerecord-import has some limited support for batch updating based on MySQL DUPLICATE KEY, but I think it requires all columns to be updated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-30T21:13:50.827",
"Id": "249519",
"Score": "0",
"body": "Here's the docs on the activerecord-import feature mahemoff mentioned: [On Duplicate Key Update](https://github.com/zdennis/activerecord-import/wiki/On-Duplicate-Key-Update)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T01:36:11.577",
"Id": "32051",
"ParentId": "31784",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "32051",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T07:35:39.407",
"Id": "31784",
"Score": "7",
"Tags": [
"performance",
"ruby",
"ruby-on-rails",
"postgresql"
],
"Title": "Faster way to update/create of a large amount of records?"
}
|
31784
|
<p>I have a function that processes a large amount of data. I call this function as part of a wider process via a command line script in which many similar but shorter jobs are conducted in sequence.</p>
<p>I have something like this:</p>
<pre><code>import time
def initialise_foo():
"""do something quickly"""
time.sleep(0.1)
def initialise_bar():
"""do something else quickly"""
time.sleep(0.1)
def load_data(n_items):
"""do another thing quickly"""
return range(n_items)
def process_datum(datum, sleep):
""""do something with datum that takes a while"""
time.sleep(sleep)
def cleanup():
"""do a final thing quickly"""
time.sleep(0.1)
</code></pre>
<p>My problem is that I want my script to provide feedback on progress and I was considering converting my data processor into an iterator and using yield to emit progress information.</p>
<p>I can do this but there is a long wait with no feedback...</p>
<pre><code>def process_data1(data, sleep):
"""loop over a lot of data"""
for item in data:
process_datum(item, sleep)
def main1(n_items, sleep):
print("initialising foo")
initialise_foo()
print("initialising bar")
initialise_bar()
print("loading data")
mydata = load_data(n_items)
print("processing data")
process_data1(mydata, sleep)
print("cleaning up")
cleanup()
print("done")
</code></pre>
<p>So what about this?</p>
<pre><code>def process_data2(data, sleep, report_frequency):
"""loop over a lot of data"""
for i, item in enumerate(data):
process_datum(item, sleep)
if not (i % report_frequency):
yield i
def main2(n_items, sleep, report_frequency):
print("initialising foo")
initialise_foo()
print("initialising bar")
initialise_bar()
print("loading data")
mydata = load_data(n_items)
print("processing data")
for i in process_data2(mydata, sleep, report_frequency):
print("%i items processed" % i)
print("cleaning up")
cleanup()
print("done")
</code></pre>
<p>run it like this.</p>
<pre><code>if __name__ == "__main__":
print ("\nwithout progress")
main1(100, 0.01)
print ("\nwith progress")
main2(100, 0.01, 10)
</code></pre>
<p>Does this look like a reasonable approach? Any comments on how I have coded this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T15:41:59.093",
"Id": "50715",
"Score": "1",
"body": "Alternatively, you could pass in an object like a file or something and write progress to that, perhaps."
}
] |
[
{
"body": "<p>I see three basic options you have, to structure progress feedback:</p>\n\n<ol>\n<li><code>yield</code></li>\n<li>a callback function</li>\n<li>inline, hard-coded feedback</li>\n</ol>\n\n<p>Using <code>yield</code>, as you've shown, is one approach. Ensure you are familiar with Python's implementation of <code>yield</code> and iterables and generators, since several languages share the <code>yield</code> keyword superficially but have subtle implementation differences that might surprise you if, for example, you're used to C#'s <code>yield</code>. Here's <a href=\"http://users.softlab.ece.ntua.gr/~ttsiod/yieldDifferences.html\">a reference</a> on that -- it's subtle but worth reading. Essentially, in Python when your function yields, it returns a generator which can be usefully assigned to a variable, capturing iteration to that point, but you may or may not want to do that.</p>\n\n<p>So there is fundamentally nothing wrong with using <code>yield</code> for this job. It carries the big advantage of separating pure computing from progress IO. </p>\n\n<p>A decent alternative to <code>yield</code> which is easy to understand is a callback function. If you passed a callable as a final parameter to your <code>process_data</code> function then a block of code can be executed, instead of a <code>yield</code> or hardcoded inline feedback, also separating processing from feedback.</p>\n\n<p>One advantage a callback approach carries is it allows communication <em>back</em> to the <code>process_data</code> function which could be used to pause or halt processing. For example, if your callback function is aware of the console or UI, then while updating progress it can also monitor buttons or keys and return a value to the <code>process_data</code> function. This could indicate, for example, that the user wants to abort processing and this doesn't pollute the <code>process_data</code> function with awareness of specific UI or IO. So a callback would also work well and allow you to pass a <code>lambda</code> block or full function in Python. (Languages without a <code>yield</code> facility may have no choice but to use callbacks.)</p>\n\n<p>Example code:</p>\n\n<pre><code>def process_data(data, sleep, report_frequency, report_callback=None):\n for ...\n ...\n if not (i % report_frequency): # or whatever criteria\n if report_callback:\n if report_callback(i) == USER_ABORT: # or other codes, by convention\n return\n</code></pre>\n\n<p>Please let me also address what I see as a big, very practical, issue with the code defining <code>report_frequency</code> in terms of data elements or loop iterations. </p>\n\n<p>I have see two problems with this pattern of progress tracking:</p>\n\n<ol>\n<li><p>It's difficult to know in advance what a good value of <code>report_frequency</code> is, when it's expressed in loop iterations. Trial and error can quickly get you into the ballpark, but that leaves problem #2.</p></li>\n<li><p>Depending on the nature of your computation, the <code>process_datum</code> function may not run in constant time. For example, it may take longer as you get deeper into the dataset, if numbers are getting larger and depending on what you're calculating. What I'm getting at is there may not be a constant number of loop iterations per second.</p></li>\n</ol>\n\n<p>So I'll propose a better way for you to think of <code>report_frequency</code>. Use <em>seconds</em>, not iterations or data elements. Time is likely what you had in mind, anyways. It's natural to want to see an update every X seconds, regardless of how many loop iterations that is. This eliminates both problems and is especially useful when your <code>process_datum</code> function does not run in constant time. </p>\n\n<p>Your code:</p>\n\n<pre><code>def process_data2(data, sleep, report_frequency):\n \"\"\"loop over a lot of data\"\"\"\n for i, item in enumerate(data):\n process_datum(item, sleep)\n if not (i % report_frequency):\n yield i \n</code></pre>\n\n<p>Can become this: (I'm putting the <code>yield</code> vs inline vs callback issue aside for the moment, to illustrate the concept)</p>\n\n<pre><code>def process_data3(data, sleep, report_frequency):\n \"\"\"loop over a lot of data\"\"\"\n t_updlast = datetime.now()\n t_update = t_updlast + timedelta(seconds=report_frequency) \n for i, item in enumerate(data):\n if datetime.now() >= t_update:\n print(\"%6.2f%%\\n\" % (i*100.0/len(data)))\n t_update = datetime.now() + timedelta(seconds=report_frequency)\n process_datum(item, sleep)\n</code></pre>\n\n<p>Now you'll see a report every <code>report_frequency</code> seconds that looks like:</p>\n\n<pre><code>56.12%\n56.83%\n...\n</code></pre>\n\n<p>And this simplifies how you call <code>process_data3</code> from <code>main</code>. By dropping the <code>yield</code>, you simply call the following from <code>main</code>, without wrapping it in a <code>for</code> loop:</p>\n\n<pre><code>process_data3(mydata, sleep, report_frequency)\n</code></pre>\n\n<p>And now that you're in the domain of measuring time, <em>if</em> your <code>process_datum</code> function runs in constant time, you can add a fairly simple calculation for \"estimated time to completion\". I'll leave that as an exercise for you. :-)</p>\n\n<p>Remember to add this at the top of your module:</p>\n\n<pre><code>from datetime import datetime, timedelta\n</code></pre>\n\n<p>Sorry for the long answer and <code>timedelta</code> diversion. I hope this is helpful. Good luck!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-05T13:41:28.020",
"Id": "54249",
"Score": "1",
"body": "Nice answer, I agree that using time to determine the feedback is a great approach. However, my question was about the use of yield for this kind of feedback. The caller of my function may want to process the feedback in another way other than printing. I would like to know if yield is a sensible approach and what other approaches I might take."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-05T19:15:52.470",
"Id": "54335",
"Score": "0",
"body": "@GraemeStuart, thanks, that's fair feedback! I did fixate on your example code's use of iteration-based progress measurement because I've seen that pattern fail many times in practical terms. I will edit my answer shortly to address your (real) question about the suitability of `yield`. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-06T11:36:48.377",
"Id": "54426",
"Score": "0",
"body": "Great thanks. I hadn't considered a callback! I will mull it over. Looks like there are advantages. If my process_data function knows what to expect from the callback then it can indeed be used to control the data processing as well as to provide feedback. Thanks again. If I don't get any more answers then this will be marked as accepted."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-03T17:25:43.997",
"Id": "33746",
"ParentId": "31789",
"Score": "8"
}
},
{
"body": "<p>Use A generator as a callback function. A generator is absolutely perfect for this. Using your example I'll demonstrate</p>\n\n<pre><code>def process_datum(item):\n import random\n import time\n # Sleep for some randomly small time to mimic processing the item\n time.sleep(random.random() / 100.0)\n\n\ndef process_data(data, callback=None):\n if callback is not None: # Prime the generator\n next(callback)\n\n for i, item in enumerate(data):\n process_datum(item)\n if callback is not None:\n callback.send(float(i) / len(data))\n\n if callback is not None: # Close the generator\n callback.close()\n\n\ndef callback(report_frequency):\n counter = 0\n while True:\n progress = yield\n counter += 1\n if counter % report_frequency:\n print(\"Progress: %s%%\" % (progress * 100.0,))\n\n\ndef main():\n data = range(1000)\n process_data(data, callback(10))\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>The great thing about this is that you can make your call back function as complicated or as simple as you like, it also has access to the local scope as well so, if you want to pass arguments (like I did i.e. report_frequency), you can pass it to the generator initialiser, instead of having to do something like</p>\n\n<pre><code>def process_data(data, callback_function, callback_function_args, callback_function_kwargs):\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-10T17:24:28.173",
"Id": "471276",
"Score": "0",
"body": "This is such a cool pattern. It takes me a while to figure it out each time I read it, but it's pretty elegant."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-13T10:28:50.773",
"Id": "141222",
"ParentId": "31789",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "33746",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T10:22:22.480",
"Id": "31789",
"Score": "12",
"Tags": [
"python",
"console",
"iteration"
],
"Title": "Progress report for a long-running process using 'yield'"
}
|
31789
|
<p>I am new in haskell and for start I choosed to write simple grep. Now I want to ask if there is some simplier/shorter way to write it. For example if there is any way to avoid recursion.</p>
<pre><code>parseLines :: String -> [String] -> Int -> IO ()
parseLines _ [] _ = return ()
parseLines pattern (x:xs) line = do
when (isInfixOf pattern x) $ putStrLn $ (show line) ++ ": " ++ x
parseLines pattern xs (line+1)
processFile :: String -> String -> IO ()
processFile _ [] = return ()
processFile pattern file = do
exists <- doesFileExist file
if not exists
then putStrLn $ file ++ ": file does not exists"
else do
putStrLn file
content <- readFile file
parseLines pattern (lines content) 0
processFiles :: String -> [String] -> IO ()
processFiles _ [] = return ()
processFiles pattern (x:xs) = do
processFile pattern x
processFiles pattern xs
main = do
args <- getArgs
processFiles (head args) (tail args)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T17:07:53.073",
"Id": "50721",
"Score": "0",
"body": "Since you're actually not doing any regexps, I believe this can hardly be called a \"grep\". This is just some searching utility."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T18:00:40.257",
"Id": "50726",
"Score": "0",
"body": "regexps are next level"
}
] |
[
{
"body": "<p>Here's the updated code. The notes are following after.</p>\n\n<pre><code>import Control.Monad\nimport Data.List\nimport System.Directory\nimport System.Environment\n\nsearch :: String -> String -> [(Int, String)]\nsearch searchString content = do\n (lineNumber, lineText) <- zip [0..] $ lines content\n if isInfixOf searchString lineText\n then return (lineNumber, lineText)\n else mzero\n\nprocessFile :: String -> String -> IO ()\nprocessFile searchString file = do \n exists <- doesFileExist file\n if not exists\n then error $ file ++ \": file does not exist\"\n else do\n putStrLn file\n content <- readFile file\n forM_ (search searchString content) $ \\(lineNumber, lineText) -> do\n putStrLn $ show lineNumber ++ \": \" ++ lineText\n\nmain :: IO ()\nmain = do\n args <- getArgs\n case args of\n searchString : fileNames | not $ null fileNames -> do\n forM_ fileNames $ processFile searchString\n _ -> error \"Not enough arguments\"\n</code></pre>\n\n<h3>Notes:</h3>\n\n<ol>\n<li><p>In Haskell it's idiomatic to isolate pure code from IO-interactions as much as possible. So first we isolate the <code>search</code> function by accumulating most of the non-IO logic in it. In its implementation I'm utilizing a <code>Monad</code> and <code>MonadPlus</code> instances for list, so don't be surprised by the <code>do</code>-notation used in a non-<code>IO</code> context. Alternatively a List Comprehension syntax could be used, but I'm just not a fan of it. This could also be solved using <code>map</code> and <code>filter</code> and whatnot.</p></li>\n<li><p><a href=\"http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Monad.html#v%3aforM_\" rel=\"nofollow\"><code>forM_</code></a> helps us loop in monads without recursion.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T17:07:19.680",
"Id": "31804",
"ParentId": "31795",
"Score": "0"
}
},
{
"body": "<p>I see these areas where your code could be improved:</p>\n\n<ol>\n<li><p><code>processFiles</code> can be expressed very simply using <code>mapM_</code> from <code>Control.Monad</code>:</p>\n\n<pre><code>processFiles :: String -> [String] -> IO ()\nprocessFiles pattern = mapM_ (processFile pattern)\n</code></pre></li>\n<li>All your functions are in the <code>IO</code> monad. This goes a bit against Haskell's philosophy to keep side effects to minimum.</li>\n<li><code>parseLines</code> requires the whole file to be read into the memory. This could be solved by using lazy IO, but I'd strongly discourage you from doing so.</li>\n</ol>\n\n<p>One possibility to solve 2. and 3. is to use <a href=\"https://www.fpcomplete.com/user/snoyberg/library-documentation/conduit-overview\" rel=\"nofollow\">conduits</a>. This may seem as somewhat complex subject, but the idea is actually very intuitive. A conduit is something that reads input a produces output, using some particular monad. This allows to break your program into very small, reusable components, each doing a single particular task. This makes it easier to debug, test and maintain.</p>\n\n<p>For example, your code could be refactored as follows. (First some required imports.)</p>\n\n<pre><code>import Control.Monad\nimport Control.Monad.IO.Class\nimport Data.ByteString (unpack)\nimport Data.Conduit\nimport qualified Data.Conduit.Binary as C\nimport qualified Data.Conduit.List as C\nimport Data.List (isInfixOf)\nimport System.Environment (getArgs)\nimport System.Directory (doesFileExist)\nimport System.IO\n\nsourceFileLines :: (MonadResource m) => FilePath -> Source m String\nsourceFileLines file = bracketP (openFile file ReadMode) hClose loop\n where\n loop h = do\n eof <- liftIO (hIsEOF h)\n unless eof (liftIO (hGetLine h) >>= yield >> loop h)\n</code></pre>\n\n<p>This function takes a file name and creates a <code>Source</code> - a conduit that takes no input, but produces output. It reads a file line by line and sends each line down the pipeline using <a href=\"http://hackage.haskell.org/packages/archive/conduit/1.0.7.4/doc/html/Data-Conduit.html#v%3ayield\" rel=\"nofollow\"><code>yield</code></a>. Using <a href=\"http://hackage.haskell.org/packages/archive/conduit/1.0.7.4/doc/html/Data-Conduit.html#v%3abracketP\" rel=\"nofollow\"><code>bracketP</code></a> we ensure that the file will get closed no matter what happens to the pipeline.</p>\n\n<pre><code>numLines :: (Monad m) => Conduit a m (Int, a)\nnumLines = C.scanl step 1\n where\n step x n = (n + 1, (n, x))\n</code></pre>\n\n<p>This component built using <a href=\"http://hackage.haskell.org/packages/archive/conduit/1.0.7.4/doc/html/Data-Conduit-List.html#v%3ascanl\" rel=\"nofollow\"><code>scanl</code></a> is very simple. It just sends its input to the output, and keeps the count along the way. Notice that this conduit doesn't need any <code>IO</code>, it works with any monad.</p>\n\n<p>Now it's easy to filter a stream of numbered lines with a pattern:</p>\n\n<pre><code>parseLines :: (Monad m) => String -> Conduit String m (Int, String)\nparseLines pattern = numLines =$= C.filter f\n where\n f (_, x) = isInfixOf pattern x\n</code></pre>\n\n<p>This function fuses two conduits together. The first one numbers lines, the second filters them according to the pattern.</p>\n\n<pre><code>printMatch :: (MonadIO m) => Sink (Int, String) m ()\nprintMatch = C.mapM_ (\\(n, x) -> liftIO $ putStrLn $ show n ++ \": \" ++ x)\n</code></pre>\n\n<p>In <code>printMatch</code> we separate the logic that prints out the output. For each pair it receives it prints the line number and its content.</p>\n\n<p>Combining and running these conduits is then easy:</p>\n\n<blockquote>\n<pre><code>runResourceT $ sourceFileLines file $= parseLines pattern $$ printMatch\n</code></pre>\n</blockquote>\n\n<p>(<code>runResourceT</code> is needed because of <code>bracketP</code>.) So the rest of the program would look like</p>\n\n<pre><code>processFile :: String -> String -> IO ()\nprocessFile _ [] = return ()\nprocessFile pattern file = do \n exists <- doesFileExist file\n if not exists\n then putStrLn $ file ++ \": file does not exists\"\n else do\n putStrLn file\n runResourceT $ sourceFileLines file $= parseLines pattern $$ printMatch\n\nprocessFiles :: String -> [String] -> IO ()\nprocessFiles pattern = mapM_ (processFile pattern)\n\nmain = do \n args <- getArgs\n processFiles (head args) (tail args)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T20:06:35.417",
"Id": "31815",
"ParentId": "31795",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "31815",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T15:33:11.447",
"Id": "31795",
"Score": "3",
"Tags": [
"haskell"
],
"Title": "Haskell grep simplification"
}
|
31795
|
<p>More information, documentation and samples are available at <a href="http://knockoutjs.com" rel="nofollow">http://knockoutjs.com</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T16:18:49.947",
"Id": "31801",
"Score": "0",
"Tags": null,
"Title": null
}
|
31801
|
<p><a href="http://coolwx.com/buoydata/data/curr/all.html" rel="nofollow">http://coolwx.com/buoydata/data/curr/all.html</a> provides weather data
from ships (or maybe buoys) at sea, but the date is given as "25/18" (meaning the 18th
hour of the 25th day of the month, all times GMT). </p>
<p>I need to convert this to a full timestamp ("2013-09-25
18:00:00"). All reports are in the near past. One glitch: if today is the
1st, and the report is "31/18" for example, it's referring to the 31st
of last month. </p>
<p>Here's my solution, which I feel is kludgey. Can it be improved? </p>
<pre><code>sub ship2time {
my(@now) = gmtime(time());
# assumed given as "foo/bar";
my($day,$hour) = split(/\//, $_[0]);
# today's date (GMT)
my($today) = strftime("%d", @now);
# if the given day is in the past (or very near future) it's this month
if ($day <= $today+1) {
return strftime("%Y-%m-$day $hour:00:00", @now);
}
# otherwise, we're referring to last month (eg, today is the 1st,
# report says 31st)
my($year, $month) = split(/\-/, strftime("%Y-%m", @now));
$month--;
if ($month < 0) {$year--; $month=12;}
return "$year-$month-$day $hour:00:00";
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T06:53:08.643",
"Id": "50754",
"Score": "2",
"body": "The link you gave as an example has month name in the first line (_Offshore Data at 06Z Sep 26_) - can you use it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T15:47:47.787",
"Id": "50789",
"Score": "0",
"body": "Wow, that's embarrassing. I always just ignored the header lines. I also didn't realize all the reports were on the same day/hour. You're right."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T16:15:07.793",
"Id": "50795",
"Score": "0",
"body": "Plus, there's a timestamp file available here: http://coolwx.com/buoydata/data/curr/timestamp - I think it'll be easier if you download both data and timestamp files and make your life easier and code more elegant :) You can parse the timestamp with this with `%Y%m%d%H`, i.e.: `perl -MTime::Piece -E 'say Time::Piece->strptime(\"2013092616\", \"%Y%m%d%H\")->datetime'` (outputs `2013-09-26T16:00:00`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T18:47:36.103",
"Id": "50817",
"Score": "0",
"body": "I never though to look at the virtual directory http://coolwx.com/buoydata/data/curr/ but there's a lot of info there, thanks. Turn your comment into an answer and I'll approve it."
}
] |
[
{
"body": "<p>There's a timestamp file available here: <a href=\"http://coolwx.com/buoydata/data/curr/timestamp\" rel=\"nofollow\">http://coolwx.com/buoydata/data/curr/timestamp</a>, so I think it'll be easier if you download and parse both data and timestamp files. </p>\n\n<p>You can parse the timestamp with this with <code>%Y%m%d%H</code> pattern, for example using core <a href=\"https://metacpan.org/module/Time%3a%3aPiece\" rel=\"nofollow\"><code>Time::Piece</code></a> module and its <a href=\"https://metacpan.org/module/Time%3a%3aPiece#Date-Parsing\" rel=\"nofollow\"><code>strptime</code></a> function: </p>\n\n<pre><code>use Time::Piece;\nmy $time = Time::Piece->strptime(\"2013092616\", \"%Y%m%d%H\"); # Time::Piece object, see docs\nsay $time->datetime; # outputs: 2013-09-26T16:00:00\n</code></pre>\n\n<p>See documentation for more formatting methods of <code>Time::Piece</code> object.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T19:19:39.927",
"Id": "31865",
"ParentId": "31809",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "31865",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T18:51:17.237",
"Id": "31809",
"Score": "1",
"Tags": [
"perl",
"datetime"
],
"Title": "More elegant way to get timestamp from day/hour? (Perl)"
}
|
31809
|
<p>I've started coding C++ again after a 6 month break to prepare for a class I'm taking this quarter. I found this idea and thought it would be fun to try and code.</p>
<p>I originally started with input as a string, and wanted to split it into two <code>int</code>s at <code>.</code>, but this way seemed easier. Then came the rounding errors. This is why I multiply by such a large number, and 100 was still giving me incorrect values. I'm really just looking for any feedback on ways I could improve my code, stylistically or otherwise. </p>
<pre><code>cout << "Welcome to Dollar Break Down!" << endl; //print welcome message
cout << "Please enter a dollar amount: "; // prompt for input of a dollar amount
double amt; // var to store the amount
cin >> amt; // read in and store amount
cout << endl; // spacing
int dollars = amt; // dollars = (int)amt ex: int(45.97) = 45
// compute dollars
dollars / 100 == 1 ? // check if bill amount is single or plural
cout << dollars / 100 << " hundred" << endl : // print singe
cout << dollars / 100 << " hundreds" << endl; // print plural
dollars = dollars % 100; // compute remainder after removing bill amount
dollars / 50 == 1 ?
cout << dollars / 50 << " fifty" << endl : // repeat for each bill type
cout << dollars / 50 << " fifties" << endl;
dollars = dollars % 50;
dollars / 20 == 1 ?
cout << dollars / 20 << " twenty" << endl :
cout << dollars / 20 << " twenties" << endl;
dollars = dollars % 20;
dollars / 10 == 1 ?
cout << dollars / 10 << " ten" << endl :
cout << dollars / 10 << " tens" << endl;
dollars = dollars % 10;
dollars / 5 == 1 ?
cout << dollars / 5 << " five" << endl :
cout << dollars / 5 << " fives" << endl;
dollars = dollars % 5;
dollars / 1 == 1 ?
cout << dollars / 1 << " one" << endl:
cout << dollars / 1 << " ones" << endl;
cout << endl; // spacing between dollars and cents
dollars = amt; // reset dollars to amt for cents calculation
amt *= 10000; // multiply to remove rounding errors
dollars *= 10000; // same thing
int cents = (amt - dollars) / 100; // compute cents without rounding errors
// compute cents
cents / 25 == 1 ?
cout << cents / 25 << " quarter" << endl :
cout << cents / 25 << " quarters" << endl;
cents = cents % 25;
cents / 10 == 1 ?
cout << cents / 10 << " dime" << endl :
cout << cents / 10 << " dimes" << endl;
cents = cents % 10;
cents / 25 == 1 ?
cout << cents / 5 << " nickel" << endl :
cout << cents / 5 << " nickels" << endl;
cents = cents % 5;
cents / 25 == 1 ?
cout << cents / 1 << " penny" << endl :
cout << cents / 1 << " pennies" << endl;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T19:13:13.683",
"Id": "50731",
"Score": "0",
"body": "Where's `main()`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T19:30:24.427",
"Id": "50732",
"Score": "3",
"body": "Why are you using `?` here as oposed to `if`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-01T19:25:35.397",
"Id": "59769",
"Score": "0",
"body": "Because it looks cleaner (to me) since the format is if one bill then singular, else plural and I preferred the look over if else statements, I did it both ways and liked how this way looked better."
}
] |
[
{
"body": "<p>Stylistically:</p>\n\n<ul>\n<li>just write <code>std::</code> instead of <code>using namespace std;</code> (which you didn't show but was implicit)</li>\n<li>use a regular <code>if()</code> instead of the ternary operator <code>?</code> </li>\n<li>use compound assignment operators like <code>dollars %= 10;</code> instead of <code>dollars = dollars % 10;</code></li>\n<li>I'm not a big fan of end-of-line comments, but at the very least, try and put them inside the 80 column mark (most editors will show a marker)</li>\n</ul>\n\n<p>Furthermore, it's a good exercise to make your code more general:</p>\n\n<ul>\n<li>put the bills <code>(1, 5, 10, 20, 50, 100)</code> and their strings in a <code>std::map</code>, and write your code as a loop over that map. This way you can start to test with only small bills, and then expand to the general problem</li>\n<li>a propos, where are your tests?</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T00:17:03.483",
"Id": "50750",
"Score": "0",
"body": "+1 good stuff. An array is good, but I think a map could work here as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T08:49:24.767",
"Id": "51009",
"Score": "0",
"body": "@Jamal good point! Updated."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T21:25:10.547",
"Id": "31823",
"ParentId": "31811",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "31823",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T19:04:07.297",
"Id": "31811",
"Score": "3",
"Tags": [
"c++",
"integer"
],
"Title": "Breaking down a dollar amount into bill and coin denominations"
}
|
31811
|
<p>I am new to C++ and with my basic knowledge of the language, I have attempted to create a simple console application filled with lots of useful functions involving math related stuff.</p>
<p>The following is the only version of it that I have created thus far: (also available <a href="https://gist.github.com/NickKartha/6387434" rel="nofollow">here</a>).</p>
<pre><code>#include<iostream>
#include<cmath>
#include<cstdlib>
using namespace std;
string cmd;
bool moduleRun = true;
//Decorations
void finline(string appName){cout<<"Quiting "<<appName<<" ... ";}
void h(string title, char type){
int l = title.length();
for(int i = 0; i < 2*(l + 1); i++){
cout<< type;
if( i == l /*|| i == 2 * l + 1*/ ){ cout << "\n"; }
if( i == l ){ cout << " " << title << "\n"; }
}
}
//End of Decorations
//Modules
//Basic 2 number Calculator Module
void calculator(){
char op;
double n1,n2;
h("Calculator", '-');
cout<< "\n Perform an operation on 2 numbers using basic operators.\n eg: 2+2, 4*3, 5%4, 6/7 etc \t\t[ Type '0x 0' to exit ]\n\n";
while(moduleRun){
cin>> n1 >> op >> n2;
switch(op){
//case '%' :
case '+' : cout<<n1 + n2 ; break;
case '-' : cout<< n1 - n2 ; break;
case 'x' : if(n1 == 0 && n2 == 0){ finline("c4lql80r"); moduleRun = false;}
case '*' : cout<< n1 * n2 ; break;
case '/' : cout<< n1/n2; break;
case '^' : cout<< pow(n1,n2); break;
case '<' : (n1<n2)?cout<<"True":cout<<"False"; break;
case '>' : (n1>n2)?cout<<"True":cout<<"False"; break;
case '=' : (n1==n2)?cout<<"True":cout<<"False"; break;
default :
if(op == '%'){int N1 = floor(n1); int N2 = floor(n2); cout << N1 % N2;}
else{cout<< "That operation is not available";}
}
if(moduleRun)cout<< "\n\n";
}
}
//Functions Module
bool isPrime(long int n) {
if (n == 2) { return true; }
if (n < 2 || !(n&1)) { return false; }
long double l = floor(pow(n, 0.5));
for (long int i = 3; i <= l; i += 2) { if (n % i == 0) {return false;}}
return true;
}
long double sum(int n){
int arr[n];
long double total = 0;
for(int i = 0; i<n; i++){
cout<<i + 1;
(i==0)?cout<<"st":(i==1)?cout<<"nd":(i==2)?cout<<"rd":cout<<"th";
cout<<">> ";
cin>>arr[i];
total+=arr[i];
}
return total;
}
long double mean(int n){ return ( sum(n) / n ); }
long double prod(int n){
int arr[n];
long double product = 1;
for(int i = 0; i<n; i++){
cout<<i + 1;
(i==0)?cout<<"st":(i==1)?cout<<"nd":(i==2)?cout<<"rd":cout<<"th";
cout<<">> ";
cin>>arr[i];
product*=arr[i];
}
cout<<"Product = ";
return product;
}
long double factorial(int n){ //max is 16!
int fact = 1;
for(int i = 1; i<=n; i++){fact*=i;}
return fact;
}
//Sequence&Series functions
long int fibterm(int n) { long int term = (n < 2) ? n : fibterm(n - 1) + fibterm(n - 2); return term;};
void fib(int n){ for(int i = 0; i<=n ; i++) cout<<fibterm(i)<<" "; }
long int fibsum(int n){
long int total = 0;
for(int i = 0; i<=n; i++){total+=fibterm(i);} //Please find a formula to reduce processing
return total;
}
long int lucasterm(int n){ long int term = (n == 1)? 2: (n == 2)? 1: lucasterm(n - 1) + lucasterm(n - 2); return term; }
void lucas( int n ){ for( int i = 0; i<=n ; i++ ) cout << lucasterm(i)<<" "; }
long int lucassum(double n){
long int total = 0;
for(int i = 1; i<=n; i++){total+=lucasterm(i);} //Please find a formula to reduce processing
return total;
}
long int oddterm(int n){ return 2*(n-1);}
void odd(int n){ for( int i = 0; i<=n ; i++ ) cout << oddterm(i)<<" "; }
long int oddsum(int n){return pow(n,2);}
void prime(int n){ //prints n primes
int p = 0, i = 1;
while(p<=n){
if(isPrime(i)){
cout<<i<<" ";
p++;
}
i++;
}
}
//End of Sequence and series functions
void functions(){
string &func = cmd;
double param;
h("Scientific Functions", '-');
cout<<"\n eg: log 20, sin 60, cosh 40, atan 80, etc \n [ Type 'func 101' for a list of all available functions & '0x 0' to exit]\n";
while(moduleRun){
cin>> func >> param;
//Trigo
if(func == "sin") cout<< sin(param);
else if(func == "cos") cout<< cos(param);
else if(func == "tan") cout<< tan(param);
else if(func == "sinh") cout<< sinh(param);
else if(func == "cosh") cout<< cosh(param);
else if(func == "tanh") cout<< tanh(param);
else if(func == "asin") cout<< asin(param);
else if(func == "acos") cout<< acos(param);
else if(func == "atan") cout<< atan(param);
//Scientific
else if(func == "exp") cout<< exp(param);
else if(func == "log") cout<< log10(param);
else if(func == "ln") cout<< log(param);
//Sequence&Series fuAnctions
else if(func == "fib") fib(param);
else if(func == "fib.term") cout<< fibterm(param);
else if(func == "fib.sum") cout << fibsum(param);
else if(func == "lucas") lucas(param);
else if(func == "lucas.term") cout<< lucasterm(param);
else if(func == "lucas.sum") cout << lucassum(param);
else if(func == "odd")odd(param);
else if(func == "odd.term")oddterm(param);
else if(func == "odd.sum")oddsum(param);
//Other
else if(func == "sum"){cout<<"Total = "<<sum(param);}
else if(func == "prod" || func == "product" || func == "multiply"){cout<< prod(param);}
else if(func == "mean" || func == "average" || func == "avg"){cout << "Arithmetic Mean = "<<mean(param);}
else if(func == "fact" || func == "factorial"){cout<< factorial(param);}
else if(func == "isprime") (isPrime(param))? cout<<"Yes, it is prime":cout<<"No, it's not prime";
//ModuleSupport
else if(func == "function" || func == "functions" || func == "func"){
cout<< "\nTrig Functions:\n sin,cos,tan,sinh,cosh,tanh,asin,acos,atan\n\nScientific Functions:\nexp,log,ln\n";
}
else if(func == "exit" || func == "0x" || func == "0 x"){
moduleRun = false;
finline("Sc13nt1fic funct10n5");
}
else {
cout<< "function not available.\n";
}
cout<<"\n\n";
}
}
//End of Functions Module
void converter(){
double n, pi = 3.141592653589793;
string u1, u2;
h("Converter",'-');
cout<<"\n eg: 2m to km, 92cm to km, 34 deg to rad, etc \nWARNING: HIGHLY EXPERIMENTAL\n\n";
while(moduleRun){
cin>>n>>u1;
cout<<"to ";
cin>>u2;
if(u1 == u2){cout<< n;}
//Length
else if(u1 == "mm" || u1 == "millimetre"){
if(u2 == "cm" || u1 == "centimetre" ) cout << ( n * pow(10,-1) );
else if( u2 == "dm" || u1 == "decimetre" ) cout << ( n * pow(10,-2) );
else if( u2 == "m" || u1 == "metre") cout << ( n * pow(10,-3) );
else if( u2 == "dam" || u1 == "decametre") cout << ( n * pow(10,-4) );
else if(u2 == "hm" || u1 == "hectometre") cout << (n * pow(10,-5));
else if(u2 == "km" || u1 == "kilometre") cout << (n * pow(10,-6));
}
else if( u1 == "cm" ){
if(u2 == "mm" || u1 == "millimetre") cout << (n * 10);
else if(u2 == "dm" || u1 == "decimetre" ) cout << (n * pow(10,-1));
else if(u2 == "m") cout<< (n * pow(10,-2));
else if(u2 == "dam") cout<< (n * pow(10,-3));
else if(u2 == "hm") cout<< (n * pow(10,-4));
else if(u2 == "km") cout<< (n * pow(10,-5));
}
else if( u1 == "dm" ){
if(u2 == "mm") cout << (n * pow(10,2));
else if(u2 == "cm") cout << (n * 10);
else if(u2 == "m") cout << (n * pow(10,-1));
else if(u2 == "dam") cout << (n * pow(10,-2));
else if(u2 == "hm") cout << (n * pow(10,-3));
else if(u2 == "km") cout << (n * pow(10,-4));
}
else if( u1 == "dm" ){
if(u2 == "mm") cout << (n * pow(10,2));
else if(u2 == "cm") cout << (n * 10);
else if(u2 == "m") cout << (n * pow(10,-1));
else if(u2 == "dam") cout << (n * pow(10,-2));
else if(u2 == "hm") cout << (n * pow(10,-3));
else if(u2 == "km") cout << (n * pow(10,-4));
}
else if( u1 == "m"){
if(u2 == "mm") cout << (n * pow(10,3));
else if(u2 == "cm") cout << (n * pow(10,2));
else if(u2 == "dm") cout << (n * 10);
else if(u2 == "dam") cout << (n * pow(10,-1));
else if(u2 == "hm") cout << (n * pow(10,-2));
else if(u2 == "km") cout << (n * pow(10,-3));
}
else if( u1 == "dam"){
if(u2 == "mm") cout << (n * pow(10,4));
else if(u2 == "cm") cout << (n * pow(10,3));
else if(u2 == "dm") cout << (n * pow(10,2));
else if(u2 == "m") cout << (n * 10);
else if(u2 == "hm") cout << (n * pow(10,-1));
else if(u2 == "km") cout << (n * pow(10,-2));
}
else if( u1 == "hm"){
if(u2 == "mm") cout << (n * pow(10,5));
else if(u2 == "cm") cout << (n * pow(10,4));
else if(u2 == "dm") cout << (n * pow(10,3));
else if(u2 == "m") cout << (n * pow(10,2));
else if(u2 == "da") cout << (n * 10);
else if(u2 == "km") cout << (n * pow(10,-1));
}
else if( u1 == "km"){
if(u2 == "mm") cout << (n * pow(10,6));
else if(u2 == "cm") cout << (n * pow(10,5));
else if(u2 == "dm") cout << (n * pow(10,4));
else if(u2 == "m") cout << (n * pow(10,3));
else if(u2 == "da") cout << (n * pow(10,2));
else if(u2 == "hm") cout << (n * 10);
}
//Mass
else if( u1 == "mg"){
if(u2 == "cg") cout << (n * pow(10,-1));
else if( u2 == "dg") cout << (n * pow(10,-2));
else if( u2 == "g") cout << (n * pow(10,-3));
else if( u2 == "dag") cout << (n * pow(10,-4));
else if( u2 == "hg") cout << (n * pow(10,-5));
else if( u2 == "kg") cout << (n * pow(10,-6));
}
else if( u1 == "cg" ){
if(u2 == "mg") cout << (n * 10);
else if( u2 == "dg") cout << (n * pow(10,-1));
else if( u2 == "g") cout << (n * pow(10,-2));
else if( u2 == "dag") cout << (n * pow(10,-3));
else if( u2 == "hg") cout << (n * pow(10,-4));
else if( u2 == "kg") cout << (n * pow(10,-5));
}
else if( u1 == "dg" ){
if(u2 == "mg") cout << (n * pow(10,2));
else if( u2 == "cg") cout << (n * 10);
else if( u2 == "g") cout << (n * pow(10,-1));
else if( u2 == "dag") cout << (n * pow(10,-2));
else if( u2 == "hg") cout << (n * pow(10,-3));
else if( u2 == "kg") cout << (n * pow(10,-4));
}
else if( u1 == "dg" ){
if(u2 == "mg") cout << (n * pow(10,2));
else if( u2 == "cg") cout << (n * 10);
else if( u2 == "g") cout << (n * pow(10,-1));
else if( u2 == "dag") cout << (n * pow(10,-2));
else if( u2 == "hg") cout << (n * pow(10,-3));
else if( u2 == "kg") cout << (n * pow(10,-4));
}
else if( u1 == "g"){
if(u2 == "mg") cout << (n * pow(10,3));
else if( u2 == "cg") cout << (n * pow(10,2));
else if( u2 == "dg") cout << (n * 10);
else if( u2 == "dag") cout << (n * pow(10,-1));
else if( u2 == "hg") cout << (n * pow(10,-2));
else if( u2 == "kg") cout << (n * pow(10,-3));
}
else if( u1 == "dag"){
if(u2 == "mg") cout << (n * pow(10,4));
else if( u2 == "cg") cout << (n * pow(10,3));
else if( u2 == "dg") cout << (n * pow(10,2));
else if( u2 == "g") cout << (n * 10);
else if(u2 == "hg") cout << (n * pow(10,-1));
else if(u2 == "kg") cout << (n * pow(10,-2));
}
else if( u1 == "hg"){
if(u2 == "mg") cout << (n * pow(10,5));
else if(u2 == "cg") cout << (n * pow(10,4));
else if(u2 == "dg") cout << (n * pow(10,3));
else if(u2 == "g") cout << (n * pow(10,2));
else if(u2 == "dg") cout << (n * 10);
else if(u2 == "kg") cout << (n * pow(10,-1));
}
else if( u1 == "kg" ){
if(u2 == "mg") cout << (n * pow(10,6));
else if(u2 == "cg") cout << (n * pow(10,5));
else if(u2 == "dg") cout << (n * pow(10,4));
else if(u2 == "g") cout << (n * pow(10,3));
else if(u2 == "dg") cout << (n * pow(10,2));
else if(u2 == "hg") cout << (n * 10);
}
//Angular measure
else if ( u1 == "deg" || u1 == "degrees"){ if( u2 == "radians" || u2 == "rad") cout << (n*pi/180);}
else if ( u1 == "radians" || u1 == "rad"){ if(u2 == "deg" || u2 == "degrees") cout << (n*180/pi);}
else{
cout <<"\n conversion not available from "<< u1 << " to";
moduleRun = false;
}
cout<<" "<<u2<<"\n\n";
if(!moduleRun){finline("c0nv3rt3r");}
}
}
void quad(){
int a,b,c;
h("Quadratic Solver", '-');
cout<<"\n Solves the value for x in a quadratic of the form ax^2 + bx + c = 0\n";
cout<<"\nEnter the coefficient of x^2 >> ";
cin>>a;
cout<<"\nEnter the coefficient of x >> ";
cin>>b;
cout<<"\nEnter the numerical value >> ";
cin>>c;
double d = pow(b,2) - (4*a*c);
if( d < 0 ){ cout<<"\nThere are no real roots possible"; }
else if(d == 0){ cout<<"\nThe root is "<<(-1*b)/(2*a);}
else{ cout<<"\nThe roots are "<< (sqrt(d) - b) / (2 * a) << " & " << (-1*( sqrt(d) + b )) / ( 2 * a ); }
}
//Games Module
bool play = true;
bool gameRun = true;
void solve(){
h("Solve",'*');
int sel, qn = 0, score = 0;
double ans;
char op[4];
op[0] = '+'; op[1] = '-'; op[2] = '*'; op[3] = '/';
while(gameRun){
++qn;
double a = floor(rand()%100), b = floor(rand()%100);
sel = rand()%4; //#Rand(0 to 3)
if(sel == 3){a = b*(rand()%10);}
cout<<"\n\n"<<a << op[sel] << b << '\n';
cin>>ans;
switch(sel){
case 0:
if( ans == (a + b) ){ cout<< "You are correct"; score++;}
else{cout<<"Wrong the answer was "<< a + b;}
break;
case 1:
if( ans == (a - b) ){ cout<< "Absolutely Right"; score++;}
else{cout<<"Wrong the answer was "<< a - b;}
break;
case 2:
if( ans == (a * b) ){ cout<< "You are correct"; score++;}
else{cout<<"Wrong the answer was "<< a * b;}
break;
case 3:
if( ans == (a / b) ){ cout<< "Absolutely Right"; score++;}
else{cout<<"Wrong the answer was "<< a / b;}
break;
default: cout<<"\n!!An unexpected error has occured!!";
}
if(qn>100){
if(score>=50){cout<<"\nGood Job, You've won";}
else{cout<<"\nYou can do better";}
cout<< "\nYour score is "<< score;
cout<< "\n\n Do you wish to play again(y/n)? ";
cin>> cmd;
if(cmd == "n" || cmd == "no"){cout<<"\nThank you for playing."; gameRun = false;}
else{score = 0; qn = 0;}
}
}
}
void guessthenumber(){
h("Guess the number",'*');
cout<<"\nTry to guess the super random number that the computer has chosen\n\n";
while(gameRun){
bool play = true;
int number = rand(), tries = 0, guess;
while(play){ // loop to allow repeted guessing
cin>>guess;
tries++;
if(guess>number){cout<<"The number is smaller\n";}
else if(guess<number){cout<<"The number is larger\n";}
else if(guess==number){
play = false;
cout << "\nYou win, that was the number\n It only took you "<<tries<<" tries\n";
cout << "\nDo you wish to play again?(y/n) ";
cin>>cmd;
if( cmd =="n" || cmd =="no"){gameRun = false;} //ends game loop
else{ cout<<"\nGuess the new number\n"; }
}
}
}
}
void games(){
h("The Games Module", '-');
cout<<"\nThe available games are :\n Solve - Solve a 101 little arithmatic problems\n 'GuessTheNumber' - Try to guess the number that the computer has picked.";
while(moduleRun){
if(!gameRun){cout<<"\nChoose a new game\n";}
gameRun = true;
cout<<"\ngames>";
cin>>cmd;
if(cmd == "guessthenumber"){ guessthenumber(); }
else if(cmd == "solve"){ solve(); }
else if(cmd=="exit" || cmd =="quit"){ moduleRun = false; }
else{cout<<"!Game not Available";}
}
}
//End of Games Module
int main(){
bool ProgramRun = true;
h("The Math Thingy v0.01 by Nick K.",'=');
cout<<"\n Type 'calc' to initialize calculator \n & 'cmdlist' for a list of commands\n";
while(ProgramRun){
if(!moduleRun){cout<<"Enter new command";}
moduleRun = true;
cout << "\n>>";
cin >> cmd;
if( cmd == "cmdlist" || cmd=="commands" ){
cout << "\n\tcalc - Starts Arithmetic Calculator\n\tconv - Convert values to different units\n\tfunc - Scientific functions including sin, cos & tan\n\tquad - Finds the roots of a Quadratic Equation of the form ax^2 + bx + c = 0\n\tgames - Activates the games module\n\n";
}
else if( cmd == "calc" || cmd == "calculator" ){ calculator(); }
else if( cmd == "func" ){functions();}
else if( cmd == "conversions" || cmd == "conv" ){ converter(); }
else if(cmd == "quad"){ quad(); }
else if( cmd == "games" ){ games(); }
else if( cmd == "exit" || cmd == "quit" || cmd == "0x0"){ ProgramRun = false; }
else{ cout<<"Invalid command\n"; }
}
}
</code></pre>
<hr>
<p><strong>Things I would like addressed</strong>:</p>
<ul>
<li>Ways to optimize and clean the code</li>
<li>Mistake and errors in my programming practices</li>
<li>Anything else which needs to corrected</li>
<li>The <a href="https://gist.github.com/NickKartha/6387434#file-maththingy-cpp-L180" rel="nofollow">converter function</a> is what significantly takes the most space in my program. How can I successfully decrease the amount of code for this function? I realize that I should, in some way, implement arrays fo this purpose but with my current knowledge of arrays in this language, I am not in a position to do so. I am in the process of learning more about them and in the meantime, I would appreciate the proposal of any method of optimally condensing the required code.<br> <sub>(Note: I am willing conduct research into any topic on my own . All I ask for is to be pointed in the right direction)</sub></li>
</ul>
|
[] |
[
{
"body": "<p>The command pattern is your friend.<br>\nYou can then use a std::map to convert a user input string to a command during execution.</p>\n\n<pre><code>#include <map>\n#include <string>\n#include <functional>\n#include <cmath>\n#include <iostream>\n\nint main(int argc, char* argv[])\n{\n std::map<std::string, std::function<double(double)>> commands;\n\n commands[\"sin\"] = [](double d) {return std::sin(d);};\n commands[\"cos\"] = [](double d) {return std::cos(d);};\n //... etc.\n\n std::string command = argv[1];\n double value = std::atof(argv[2]);\n std::cout << commands[command](value) << \"\\n\";\n}\n</code></pre>\n\n<p>Your conversions can be done by a matrix:</p>\n\n<pre><code> Unit\n m c <none> d h k\n mili 0 1 2 3 4 5\n cente -1 0 1 2 3 4\n <none> -2 -1 0 1 2 3\n deca -3 -2 -1 0 1 2\n hecto -4 -3 -2 -1 0 1\n kilo -5 -4 -3 -2 -1 0\n</code></pre>\n\n<p>So the table above defines the power conversion from one unit to another.</p>\n\n<pre><code> int conversion[6][6] = {{0,1,2,3,4,5}, {-1,0,1,2,3,4}, .... };\n std::map<std::string, int> data = {{ \"m\", 0 }, {\"c\", 1}, {\"\", 2}, {\"d\", 3}, {\"h\", 4}, {\"k\", 5}};\n\n std::string srcType = \"d\"; // src deca\n std::string dstType = \"k\"; // kilo\n int src = data[srcType];\n int dst = data[dstType];\n int result = n * pow(10, conversion[src][dst]);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T04:14:45.890",
"Id": "31885",
"ParentId": "31813",
"Score": "6"
}
},
{
"body": "<ul>\n<li><p>Try not to get into the habit of using <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\"><code>using namespace std</code></a>.</p></li>\n<li><p>The \"decorations\" don't seem that useful and only clutters the code, so I'd remove them. Don't worry about making the output look super nice (especially in a console environment). Just focus on keeping the computational implementation nice. You can, however, keep this simple by utilizing some functionality from the <a href=\"http://en.cppreference.com/w/cpp/header/iomanip\" rel=\"nofollow noreferrer\"><code><iomanip></code></a> library.</p></li>\n<li><p>Do not use global variables:</p>\n\n<pre><code>string cmd;\nbool moduleRun = true;\n</code></pre>\n\n<p>Your code is already quite lengthy, and having these global will make maintenance painful if they end up being used unknowingly. They should be used <em>locally</em> and passed to functions as needed.</p></li>\n<li><p>It appears that you're getting the square root here:</p>\n\n<pre><code>long double l = floor(pow(n, 0.5));\n</code></pre>\n\n<p>Why not just use <code>std::sqrt()</code>?</p>\n\n<pre><code>long double l = std::floor(std::sqrt(n));\n</code></pre>\n\n<p>I'd also recommend renaming <code>l</code> to something actually accurate. Single-character variables, except as loop counters, add no context to its use, decreasing readability and maintainability (what if you completely forgot what it's for?).</p></li>\n<li><p>This is hard to read:</p>\n\n<pre><code>(i==0)?cout<<\"st\":(i==1)?cout<<\"nd\":(i==2)?cout<<\"rd\":cout<<\"th\";\n</code></pre>\n\n<p>If you cannot shorten it, at least rearrange it in a (slightly) more readable manner:</p>\n\n<pre><code>(i == 0)\n? cout << \"st\"\n: (i == 1)\n? cout << \"nd\"\n: (i == 2)\n? cout << \"rd\"\n: cout << \"th\";\n</code></pre>\n\n<p>But this complexity can suggest that using ternary is <em>not</em> preferred. Whether or not you can make this simpler, it may be beneficial to put this into its own function. This is <em>not</em> <code>prod()</code>'s primary purpose, so having a separate function will make that purpose clearer. It will also help maintain the <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">separation of concerns</a> design principle.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T04:18:23.790",
"Id": "48539",
"ParentId": "31813",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "48539",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T19:51:38.210",
"Id": "31813",
"Score": "6",
"Tags": [
"c++",
"optimization",
"beginner",
"mathematics",
"console"
],
"Title": "Simple mathematical console application"
}
|
31813
|
<p>I have an element where the <a href="http://jscrollpane.kelvinluck.com/" rel="nofollow noreferrer"><code>jScrollPane</code></a> is being used to provide custom scrollbars for an extensive text. The idea behind the code is to change the image beside the text each time the user reaches a certain amount of scroll while reading the text.</p>
<p>To have the code flexible, I've prepared a method to detect the number of images available and from there establish the trigger points for the image change. This is all based on the text wrapper height.</p>
<p>Can't this be simplified, thus reducing the amount of code, perhaps in such reduction, have it improved?</p>
<h2>HTML structure</h2>
<pre><code><div id="imageWrap">
<img data-index="1" src="..." class="active" />
<img data-index="2" src="..." />
<img data-index="3" src="..." />
</div>
</code></pre>
<h2>jQuery/JavaScript code</h2>
<pre><code>$imagesWrap = $('#imageWrap');
if ($imagesWrap.size()==1) {
//target all images and count them
var $targets = $imagesWrap.find('> img'),
total = $targets.size();
//for each found, set the CSS z-index
$targets.each(function(){
var $this = $(this),
index = $this.data('index');
//revert order
$this.css({
'z-index': total-index
});
});
var $scrollSpy = $('.jspPane'), //the element to spy
height = $scrollSpy.height(), //its height
stepsTrigger = parseInt(height/total), //trigger at "every" this distance
currentPos = 0; //current position (active image)
setInterval(function(){
//ascertain current position (insure positive number)
currentPos = Math.abs(parseInt($scrollSpy.css('top'), 10));
//ascertain the target image
var img = Math.round(currentPos/stepsTrigger),
id = img==0 ? 1 : img,
$tgt = $('img[data-index="'+id+'"]');
//if different from the already active
if (!$tgt.hasClass('active')) {
$imagesWrap.find('.active').removeClass('active').hide();
$tgt.fadeIn().addClass('active');
}
}, 100);
}
</code></pre>
|
[] |
[
{
"body": "<p>I'd like to address a couple of style concerns over simplification.</p>\n\n<ol>\n<li><p>Purely for debugging if you have function expressions then name them.</p>\n\n<p>eg. \n setInterval(function(){</p>\n\n<p>could become</p>\n\n<pre><code>setInterval(function _scrollDetectionInterval(){\n</code></pre>\n\n<p>When debugging the call stack will now show you at a glance what this function is (especially helpful if you have multiple).</p></li>\n<li><p>you have define variables outside of the scope you are using them.</p>\n\n<pre><code>var $scrollSpy = $('.jspPane'), //the element to spy\nheight = $scrollSpy.height(), //its height\nstepsTrigger = parseInt(height/total), //trigger at \"every\" this distance\ncurrentPos = 0; //current position (active image)\n</code></pre>\n\n<p>This doesn't make sense unless you aren't going to change them again or you will be using them else where. Assuming this is all the code here I would at least put the <code>currentPos</code> inside the interval function scope. </p></li>\n<li><p>you have a <code>data-index=\"1\"</code> attribute on your elements. Is this actually needed? jQuery has an index you can use in the <a href=\"http://api.jquery.com/each/\" rel=\"nofollow\">.each()</a> method. just change your function to </p>\n\n<pre><code>$targets.each(function(index){\n</code></pre>\n\n<p>unless I am missing something it should work. You can also then change the line</p>\n\n<pre><code>$tgt = $('img[data-index=\"'+id+'\"]');\n</code></pre>\n\n<p>to</p>\n\n<pre><code>$tgt = $targets.eq(Math.max(0, img - 1));\n</code></pre>\n\n<p>there is a lot going on in this line. <code>$targets.eq(</code> uses the 0-based index of the element in the array. <code>Math.max(</code> ensures it will never be less than 0.</p></li>\n</ol>\n\n<p>The code will only work if there is one image wrapper on the page. If you are looking to extend this to multiple here is how i would change it:</p>\n\n<pre><code>$('.someImageWrapClass')\n .each(function _eachWrapper() \n {\n var $parentWrapper = $(this);\n\n //target all images and count them\n var $targets = $parentWrapper.find('> img'),\n total = $targets.size();\n\n //for each found, set the CSS z-index\n $targets.each(function _eachImage(index){\n //revert order\n $(this).css({\n 'z-index': total - index\n });\n });\n\n var $scrollSpy = $('.jspPane'), //the element to spy\n height = $scrollSpy.height(), //its height\n stepsTrigger = parseInt(height/total); //trigger at \"every\" this distance\n\n setInterval(function _scrollDetection()\n {\n //current position (active image)\n //ascertain current position (ensure positive number)\n var currentPos = Math.abs(parseInt($scrollSpy.css('top'), 10));\n\n //ascertain the target image\n var img = Math.round(currentPos/stepsTrigger)\n $tgt = $targets.eq(Math.max(0, img -1));\n\n //if different from the already active\n if (!$tgt.hasClass('active'))\n {\n $targets.removeClass('active').hide();\n $tgt.fadeIn().addClass('active');\n }\n\n }, 100);\n });\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T02:32:31.033",
"Id": "31830",
"ParentId": "31816",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "31830",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T20:07:44.840",
"Id": "31816",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "Custom function to scroll spy on the jScrollPane plugin"
}
|
31816
|
<p>Here is my implementation of John Conway's Game of Life in Python:</p>
<pre><code>from copy import deepcopy
def countSurrounding(board, row, cell):
SURROUNDING = ((row - 1, cell - 1),
(row - 1, cell ),
(row - 1, cell + 1),
(row , cell - 1),
(row , cell + 1),
(row + 1, cell - 1),
(row + 1, cell ),
(row + 1, cell + 1))
count = 0
for row, cell in SURROUNDING:
if isInRange(board, row, cell) and board[row][cell] == True:
count += 1
return count
def isInRange(board, row, cell):
return 0 <= row < len(board) and 0 <= cell < len(board[0])
def nextGeneration(board):
nextBoard = deepcopy(board)
for row in range(len(board)):
for cell in range(len(board[0])):
if board[row][cell] == True and countSurrounding(board, row, cell) not in (2, 3):
nextBoard[row][cell] = False
elif board[row][cell] == False and countSurrounding(board, row, cell) == 3:
nextBoard[row][cell] = True
return nextBoard
def printBoard(board):
for row in board:
for cell in row:
if cell == True:
print("#", end = "")
else:
print(".", end = "")
print()
print()
def main():
board = [[False, False, False, False, False, False, False, False, False],
[False, False, False, True , False, False, False, False, False],
[False, True , False, True , False, False, False, False, False],
[False, False, True , True , False, False, False, False, False],
[False, False, False, False, False, False, False, False, False],
[False, False, False, False, False, False, False, False, False],
[False, False, False, False, False, False, False, False, False],
[False, False, False, False, False, False, False, False, False],
[False, False, False, False, False, False, False, False, False]]
for i in range(10):
printBoard(board)
board = nextGeneration(board)
main()
</code></pre>
<p>Can anyone suggest any improvements to optimize my code?</p>
<p>Thanks</p>
|
[] |
[
{
"body": "<p>Firstly read <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">http://www.python.org/dev/peps/pep-0008/</a> and be Pythonic.\nYou will be amazed how your code will get improve, write the new one as a new file and compare them.</p>\n\n<p>This is a huge brick of False bools on your board list.\nYou can easily and cleanly populate this list by using <strong>list comprehensions</strong></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T22:22:16.687",
"Id": "31826",
"ParentId": "31817",
"Score": "2"
}
},
{
"body": "<h3>1. Comments on your code</h3>\n\n<ol>\n<li><p>You have no guard on the call to <code>main()</code>. This makes it harder to debug the program using the interactive interpreter: as soon as the module is imported, it call <code>main()</code> and starts running. <a href=\"http://docs.python.org/3/library/__main__.html\" rel=\"noreferrer\">Better to put a guard in place</a>:</p>\n\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre></li>\n<li><p>This program consists of persistent state (the board) together with a set of operations on that state. It is therefore crying out to be implemented in the form of a <em>class</em>. See section 3 for how you might do this.</p></li>\n<li><p>It's horribly tedious to watch the progress of the cellular automaton coming out on the terminal. This is the kind of program that really requires the use of a graphics toolkit like <a href=\"http://www.pygame.org/docs/\" rel=\"noreferrer\">PyGame</a> to draw and animate it. See section 4 for how you might do this.</p></li>\n<li><p>It's almost never necessary to compare values explicitly against <code>True</code> or <code>False</code>. Instead of:</p>\n\n<pre><code>if cell == True:\n</code></pre>\n\n<p>you can write:</p>\n\n<pre><code>if cell:\n</code></pre>\n\n<p>and instead of:</p>\n\n<pre><code>if board[row][cell] == False:\n</code></pre>\n\n<p>you can write:</p>\n\n<pre><code>if not board[row][cell]:\n</code></pre></li>\n<li><p>Giant blocks of values like this are hard to input and hard to check.</p>\n\n<pre><code>board = [[False, False, False, False, False, False, False, False, False],\n [False, False, False, True , False, False, False, False, False],\n [False, True , False, True , False, False, False, False, False],\n [False, False, True , True , False, False, False, False, False],\n [False, False, False, False, False, False, False, False, False],\n [False, False, False, False, False, False, False, False, False],\n [False, False, False, False, False, False, False, False, False],\n [False, False, False, False, False, False, False, False, False],\n [False, False, False, False, False, False, False, False, False]]\n</code></pre>\n\n<p>It would be better to draw a \"picture\" and write a bit of code to decode it into the values you want:</p>\n\n<pre><code>glider = '''..o\n o.o\n .oo'''\n</code></pre>\n\n<p>See the <code>paste</code> method in section 3 below for how to decode this kind of picture.</p></li>\n</ol>\n\n<h3>2. Suggestions</h3>\n\n<ol>\n<li><p>When you have a program like this that operates on a two-dimensional array of cells, it often simplifies matters if you represent the two-dimensional array as a one-dimensional list. Then a cell can be represented by a single number instead of a pair; lookups are of the form <code>array[cell]</code> instead of <code>array[x][y]</code>, and adjacent cells may be found by simple arithmetic operations.</p></li>\n<li><p>It's a feature of the game of Life that, most of the time, very few cells are changing. You can take advantage of this fact to speed up the update operation. Instead of examining all cells to see if they need updating, maintain a set of cells that need to be looked at. Whenever you change a cell from live to dead or vice versa, add it, and all its neighbours, to the set. In the update operation, look only at those cells that were added to the set in the course of the previous update operation.</p>\n\n<p>This means that you don't have to copy out the whole world each update: you only need a copy of the information (liveness and neighbour count) relating to the cells in the set.</p></li>\n<li><p>Similarly, rather than count the number of live neighbours each time you update a cell, you could maintain an array containing these neighbour counts and update the array whenever a cell changes.</p></li>\n</ol>\n\n<h3>3. Revised code</h3>\n\n<pre><code>from itertools import product\n\nclass Life(object):\n def __init__(self, width, height):\n self.width = width\n self.height = height\n cells = (width + 2) * (height + 2)\n self.live = [False] * cells\n self.in_bounds = [True] * cells\n self.neighbours = [0] * cells\n for i in range(width + 2):\n self.in_bounds[i] = self.in_bounds[-i] = False\n for j in range(height):\n k = (j + 1) * (width + 2)\n self.in_bounds[k - 1] = self.in_bounds[k] = False\n self.neighbourhood = [y * (width + 2) + x\n for x, y in product((-1, 0, 1), repeat=2)\n if x or y]\n self.needs_update = set()\n\n def cell(self, x, y):\n \"\"\"Return the cell number corresponding to the coordinates (x, y).\"\"\"\n return (self.width + 2) * (y + 1) + x + 1\n\n def set(self, p, value):\n \"\"\"Set cell number 'p' to 'value' (True=live, False=dead).\"\"\"\n if value != self.live[p] and self.in_bounds[p]:\n self.live[p] = value\n self.needs_update.add(p)\n adjust = 1 if value else -1\n for n in self.neighbourhood:\n n += p\n if self.in_bounds[n]:\n self.neighbours[n] += adjust\n self.needs_update.add(n)\n\n def update(self, steps=1):\n \"\"\"Update the world by 'steps' generations (default: 1).\"\"\"\n for _ in range(steps):\n u = [(p, self.live[p], self.neighbours[p]) for p in self.needs_update]\n self.needs_update = set()\n for p, live, neighbours in u:\n if live and not 2 <= neighbours <= 3:\n self.set(p, False)\n elif not live and neighbours == 3:\n self.set(p, True)\n\n def paste(self, s, x, y):\n \"\"\"Decode 's' as a life pattern (o = live, any other character = dead)\n and paste it with top left corner at (x, y).\n\n \"\"\"\n for j, line in enumerate(s.strip().splitlines()):\n for i, char in enumerate(line.strip()):\n self.set(self.cell(x + i, y + j), char == 'o')\n</code></pre>\n\n<p>Note:</p>\n\n<ol>\n<li>It would be possible to combine the <code>live</code>, <code>in_bounds</code> and <code>neighbours</code> arrays into one, perhaps using bit twiddling to combine the values (the neighbour count fits into 4 bits and the other two arrays are one bit each). I've left it as three separate arrays for simplicity here.</li>\n</ol>\n\n<h3>4. Animation</h3>\n\n<p>Here's a quick implementation in <a href=\"http://www.pygame.org/docs/\" rel=\"noreferrer\">Pygame</a>:</p>\n\n<pre><code>import pygame\nfrom pygame.constants import KEYUP, MOUSEBUTTONDOWN, MOUSEMOTION, QUIT, \\\n K_p, K_q, K_s, K_ESCAPE, K_SPACE\n\nclass PygameLife(Life):\n def __init__(self, width, height,\n background=pygame.Color(240, 240, 255),\n foreground=pygame.Color('black'),\n cell_size=4):\n super(PygameLife, self).__init__(width, height)\n self.background = background\n self.foreground = foreground\n self.cell_size = cell_size\n\n def draw(self):\n screen = pygame.display.get_surface()\n screen.fill(self.background)\n c = self.cell_size\n for x in range(self.width):\n for y in range(self.height):\n if self.live[self.cell(x, y)]:\n screen.fill(self.foreground, pygame.Rect(x * c, y * c, c, c))\n pygame.display.flip()\n\n def screen_cell(self, pos):\n \"\"\"Return the cell number corresponding to screen position 'pos', or\n None if the position is out of bounds.\n\n \"\"\"\n x, y = pos\n x //= self.cell_size\n y //= self.cell_size\n if 0 <= x < self.width and 0 <= y < self.height:\n return self.cell(x, y)\n return None\n\n def run(self):\n pygame.init()\n pygame.display.set_mode((self.width * self.cell_size,\n self.height * self.cell_size))\n paused = False\n drawing = False\n running = True\n while running:\n for event in pygame.event.get():\n t = event.type\n if t == QUIT or t == KEYUP and event.key in (K_q, K_ESCAPE):\n running = False\n elif t == KEYUP and event.key in (K_p, K_SPACE):\n paused = not paused\n elif t == KEYUP and event.key in (K_s,):\n self.update()\n elif t == MOUSEBUTTONDOWN and event.button == 1:\n paused = True\n p = self.screen_cell(event.pos)\n drawing = not self.live[p]\n self.set(p, drawing)\n elif t == MOUSEMOTION and event.buttons[0]:\n paused = True\n self.set(self.screen_cell(event.pos), drawing)\n if paused:\n pygame.display.set_caption('Paused (press SPACE to run)')\n else:\n pygame.display.set_caption('Life')\n self.update()\n self.draw()\n pygame.quit()\n</code></pre>\n\n<p>And here's <a href=\"https://en.wikipedia.org/wiki/Bill_Gosper\" rel=\"noreferrer\">Bill Gosper's</a> <a href=\"http://www.conwaylife.com/wiki/Gosper_glider_gun\" rel=\"noreferrer\">glider gun</a> in action:</p>\n\n<pre><code>>>> glider_gun = '''\n........................o...........\n......................o.o...........\n............oo......oo............oo\n...........o...o....oo............oo\noo........o.....o...oo..............\noo........o...o.oo....o.o...........\n..........o.....o.......o...........\n...........o...o....................\n............oo......................'''\n>>> p = PygameLife(100, 60)\n>>> p.paste(glider_gun, 8, 1)\n>>> p.run()\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/VDuNV.png\" alt=\"Glider gun\"></p>\n\n<h3>5. Advanced topic</h3>\n\n<p>Typical Life patterns contain many repeated objects. For example, the output of a glider gun contains many gliders, all of which behave identically. It would be nice to be able to exploit this repetition so that the evolution of a glider (or any other repeated pattern) could be computed just once, with the result appearing at all the necessary places in the world.</p>\n\n<p>Making this idea precise and turning it into an algorithm leads to Bill Gosper's <a href=\"https://en.wikipedia.org/wiki/Hashlife\" rel=\"noreferrer\">Hashlife</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T20:53:56.863",
"Id": "31952",
"ParentId": "31817",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T20:12:16.237",
"Id": "31817",
"Score": "4",
"Tags": [
"python",
"game-of-life"
],
"Title": "Python - Game Of Life"
}
|
31817
|
<p>Could someone help me shorten this code, please?</p>
<pre><code>while cd == "monday":
if cp == "0":
for v in mon.values():
print(v)
break
break
elif cp == "1":
print(mon[1])
break
elif cp == "2":
print(mon[2])
break
elif cp == "3":
print(mon[3])
break
elif cp == "4":
print(mon[4])
break
elif cp == "5":
print(mon[5])
break
cd = False
while cd == "tuesday":
if cp == "0":
for v in tues.values():
print(v)
break
break
elif cp == "1":
print(tues[1])
break
elif cp == "2":
print(tues[2])
break
elif cp == "3":
print(tues[3])
break
elif cp == "4":
print(tues[4])
break
elif cp == "5":
print(tues[5])
break
cd = False
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T20:20:29.057",
"Id": "52111",
"Score": "0",
"body": "What are `cp`, `cd`, `mon`, and `tues`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T20:21:48.597",
"Id": "52112",
"Score": "0",
"body": "Also, why do you have `while` loops if they stop after the first iteration? As soon as they run through, `cd` becomes `False` and the loop breaks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T20:22:34.267",
"Id": "52113",
"Score": "0",
"body": "What is your intention here/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T20:23:49.600",
"Id": "52114",
"Score": "0",
"body": "cp = choice_period, cd = choice_day, mon is monday, and tues is tuesday. Also, you have the option to restart it, but i only put the part that i needed to be cleaned up."
}
] |
[
{
"body": "<p>I'm considering the code only for \"monday\"</p>\n\n<pre><code>while cd == \"monday\": \n for i in range(0, 6):\n if cp == str(i):\n print(mon[i])\n break\nbreak\ncd = false\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T20:50:29.067",
"Id": "50740",
"Score": "0",
"body": "Where is the code when `cp == \"0\"`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T20:59:15.743",
"Id": "50741",
"Score": "0",
"body": "@JeffVanzella sorry I didn't get your point. See [this](http://ideone.com/Lc5vAW)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T21:24:39.203",
"Id": "50744",
"Score": "0",
"body": "@JeffVanzella and [this](http://ideone.com/uMoRKd) also"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T20:48:49.213",
"Id": "31821",
"ParentId": "31818",
"Score": "-1"
}
},
{
"body": "<p>Let's proceed step by step :</p>\n\n<ul>\n<li>WTF are these while loops for ?!</li>\n</ul>\n\n<p>If we enter the first while block then by definition <code>cd == \"monday\"</code>. Now either we encounter a <code>break</code> and we exit the loop and <code>cd</code> still has the same value or we execute <code>cd = False</code> and we exit the loop and <code>cd</code> is now False. As a summary : it doesn't matter what happens, we exit after a single iteration - it looks like an if to me. A similar arguments holds for the second while.</p>\n\n<pre><code>if cd == \"monday\":\n if cp == \"0\":\n for v in mon.values():\n print(v)\n break\n elif cp == \"1\":\n print(mon[1])\n elif cp == \"2\":\n print(mon[2])\n elif cp == \"3\":\n print(mon[3])\n elif cp == \"4\":\n print(mon[4])\n elif cp == \"5\":\n print(mon[5])\n else:\n cd = False\nelif cd == \"tuesday\":\n if cp == \"0\":\n for v in tues.values():\n print(v)\n break\n elif cp == \"1\":\n print(tues[1])\n elif cp == \"2\":\n print(tues[2])\n elif cp == \"3\":\n print(tues[3])\n elif cp == \"4\":\n print(tues[4])\n elif cp == \"5\":\n print(tues[5])\n else:\n cd = False\n</code></pre>\n\n<p>You may wonder why I used <code>elif</code> instead of <code>if</code> for the second loop. The reason is the fact that if <code>cd == \"Monday\"</code> at the beginning, the value would either stay the same or become <code>False</code>, thus `cd != \"Tuesday\".</p>\n\n<ul>\n<li>WTF are the for loops for ?!</li>\n</ul>\n\n<p>As you break in the first iteration, there is no point in using for. I'd need to know much about the object you are using to simplify stuff.</p>\n\n<ul>\n<li>Why so much duplicated code ?!</li>\n</ul>\n\n<p>Avoid any duplicated code. It's hard to write, to read and impossible to maintain.</p>\n\n<pre><code>if cd in (\"monday\",\"tuesday\"):\n day = mon if cd == \"monday\" else tues\n if cp == \"0\":\n for v in day.values():\n print(v)\n break\n elif cp in (\"1\",\"2\",\"3\",\"4\",\"5\"):\n print(day[int(cp)])\n else:\n cd = False\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T21:32:31.920",
"Id": "31824",
"ParentId": "31818",
"Score": "3"
}
},
{
"body": "<p>You could simplify your code to look something like this (warning: I didn't test my code, so you should double-check to make sure it functions identically to the original)</p>\n\n<pre><code>days_map = {\n \"monday\": mon,\n \"tuesday\": tues\n}\n\nday = days_map[cd]\nif cp == \"0\":\n print(day.values()[0])\nelse:\n print(day[int(cp)])\n</code></pre>\n\n<p>Several notes:</p>\n\n<p>In your code, you use a while loop, but in every case, immediately break out of it, either by literally using <code>break</code> or by making the conditional false. What you want instead is an \"if\" statement. However, because the \"if\" statements are almost identical, you can simplify it completely by replacing it with a call to a dict. </p>\n\n<p>(In case you aren't familiar with what dicts are, they're really nifty data structures that make life insanely easier. As you can see, they helped turn a large chunk of code into just 10 or so lines! Here's a link to <a href=\"http://www.codecademy.com/courses/python-beginner-en-pwmb1\">CodeAcademy</a> which gives an introduction to them))</p>\n\n<p>I'm assuming that <code>mon</code> and <code>tues</code> are dicts of some kind -- I made another dict (<code>days_map</code>) to refer to them. This is a common technique in Python -- whenever you have a large amount of <code>if</code> and <code>elif</code> statements, check to see if you can somehow fold things into a dictionary so you can need to make only a single call.</p>\n\n<p>Your for loop is also redundant. If you have a break immediately after, then it's equivalent to simply printing the first value.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T20:32:45.567",
"Id": "52116",
"Score": "0",
"body": "user2816683 looks like a python beginner, i don't think that he learn dictionaries so far."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T20:37:22.793",
"Id": "52117",
"Score": "0",
"body": "That's true -- I didn't think of that. I added a link in my answer with more info."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T20:24:38.083",
"Id": "32583",
"ParentId": "31818",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T20:27:56.670",
"Id": "31818",
"Score": "3",
"Tags": [
"python"
],
"Title": "Repetitive days of the week code"
}
|
31818
|
<h2>Problem Description</h2>
<blockquote>
<p>Write a program to find the maximum number of rectangles that can be
formed both horizontal and vertical with the help of a given n number
of coordinate(x,y) points. [x,y points will always be positive].</p>
<p>The method getRectangleCount takes 1 input parameter which is an int
array called <code>coOrdinates</code>. </p>
<p>The method <code>getRectangleCount</code> takes the coordinates as a 2D integer
array and returns the maximum number of rectangles as an integer.</p>
<pre><code>public int getRectangleCount(int[][] coOrdinates)
</code></pre>
<p>There is no need to count the rectangles that can be created from the
overlapping rectangles.</p>
</blockquote>
<h2>Example</h2>
<blockquote>
<p><strong>Input :</strong> <code>int coordinates[][] = { {1,1}, {7,1}, {1,4}, {1,5}, {7,4}, {7,5} }</code></p>
<p><strong>Output :</strong> Returns 3</p>
<p><strong>Explanation:</strong></p>
<p>Three rectangles can be formed.</p>
<p>First -</p>
<pre><code> (1,4)----(7,4)
| |
| |
(1,1)----(7,1)
</code></pre>
<p>Second -</p>
<pre><code> (1,5)----(7,5)
| |
| |
(1,1)----(7,1)
</code></pre>
<p>Third -</p>
<pre><code> (1,5)----(7,5)
| |
| |
(1,4)----(7,4)
</code></pre>
</blockquote>
<hr>
<h2>My Concerns</h2>
<ol>
<li>Is it readable? Is it maintainable? I intentionally didn't comment in the code because I want to see if the code is self-explanatory or not. </li>
<li><code>for</code> inside <code>for</code> inside <code>if</code> inside.... you get the picture... Is it nasty?</li>
<li>Can it be optimized, as it is from a programming challenge, time is a factor.</li>
</ol>
<h2>My Solution</h2>
<p>You can browse the <a href="https://github.com/tintinmj/Aspiration2020/blob/master/src/infosys/aspiration/practice/countrectangle/CountRectangle.java" rel="nofollow">GitHub Project</a> for more info.</p>
<pre><code>public int getRectangleCount(int [][]coOrdinates) {
// exception handling part coded here... forget about it
final int MIN_POINTS_TO_CREATE_RECTANGLE = 4;
// can't make a rectangle with less than 4 points
if(coOrdinates.length < MIN_POINTS_TO_CREATE_RECTANGLE)
return 0;
final Point []points = new Point[coOrdinates.length];
for(int i = 0; i < coOrdinates.length; i++)
points[i] = new Point(coOrdinates[i][0], coOrdinates[i][1]);
Arrays.sort(points); // points are sorted like (1,1) (1,3) (3,1) (3,3)....
int rectangleCount = 0;
for(int i = 0; i < points.length; i++) {
Point leftDown = points[i];
for(int j = i+1; j < points.length; j++) {
Point leftUp = points[j];
if(leftDown.getX() == leftUp.getX()) {
for(int k = j+1; k < points.length; k++) {
Point rightDown = points[k];
Point probableRightUp = new Point(rightDown.getX(), leftUp.getY());
if((leftDown.getY() == rightDown.getY())
&&
probableRightUp.existsIn(points)) {
rectangleCount++;
}
}
}
}
}
return rectangleCount;
}
</code></pre>
<p>I also have a custom <code>Point</code> class that implements <code>Comparable<Point></code>. <code>Point</code> overrides <code>compareTo()</code> method like following</p>
<pre><code>@Override
public int compareTo(Point p) {
if(Integer.compare(this.getX(),p.getX()) == 0)
{
return Integer.compare(this.getY(), p.getY());
}
return Integer.compare(this.getX(),p.getX());
}
</code></pre>
<p>and method <code>existsIn(Point []graph)</code> works like as you think. It returns <code>true</code> if <code>this</code> exists in the <code>graph</code> else <code>false</code>. </p>
<p>Yes I will create a <code>Points</code> collection class later and will move <code>existsIn(Point []graph)</code>. I will also change the signature to </p>
<pre><code>public static boolean existsIn(Point []graph, Point toCheck) // Promise I will ;)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T20:47:20.860",
"Id": "50738",
"Score": "0",
"body": "`coOrdinates` should be `coordinates`; see: http://en.wikipedia.org/wiki/Coordinate_system"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T20:49:45.340",
"Id": "50739",
"Score": "0",
"body": "Stylistically, prefer `int[][] ` (space after brackets) over `int [][]` (space before brackets); see: http://stackoverflow.com/a/129188/59087 and http://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html"
}
] |
[
{
"body": "<p>On the whole it's not at all bad, I find it readable and I'm sure that it does the job (one caveat to this is how does it handle cases where you have multiple instances of the same point e.g. {{1,1},{1,1},{1,2},{2,1}}), a few things that you could do to improve it..</p>\n\n<ul>\n<li>For uniqueness and sorting consider using a <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/TreeSet.html\" rel=\"nofollow\">TreeSet</a>, this will have an impact on the rest of your algorithm though as you can no longer rely on iterating using an index (see below).</li>\n<li>As @DaveJarvis says, it is preferable to have the square brackets immediately following the type - as they form a part of the type (2D array of ints vs int).</li>\n<li><code>final int MIN_POINTS_TO_CREATE_RECTANGLE = 4;</code> If this is the only piece of code to care that a rectangle has four corners it is fine to define it in method scope. If other methods might care, or if there is any chance it might need to be publicly visible then move it up to class level.</li>\n<li>My personal preference is to always use braces even for one line conditionals. It makes your code slightly longer, but I find it more readable and it reduces the chances of bugs down the line (when someone wants to make it a two+ line conditional). This may relate to the question around Point uniqueness as you may consider adding a test for uniqueness (or using a Set) which would then make your conditional code longer. </li>\n<li>Small things like breaking both the creation and sorting of the <code>Point[]</code> into new methods. It is almost trivial in this case but it will make your code easier to read, more testable and it lends itself to extensibility down the line (if for example you wanted to have different creation <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow\">strategy</a> down the line).</li>\n<li><code>leftDown</code>, <code>leftUp</code> and <code>rightDown</code> do not add anything to your algorithm, instead consider naming <code>i</code>,<code>j</code>, and <code>k</code> more sensibly.</li>\n<li>If <code>leftDown.getX() < leftUp.getX()</code> you know you have reached a point where no other matches can ever be found. To fix this you can use a while loop instead </li>\n</ul>\n\n<p>e.g</p>\n\n<pre><code>int j = i + 1;\n//don't forget to handle index out of bounds\nwhile (points[i].getX() == points[j++].getX()) { }\n</code></pre>\n\n<ul>\n<li>Similarly you can be sure that if <code>k == points.length - 1</code> then you are not going to find a match.</li>\n<li>Your <code>k</code> iteration is pointless if <code>leftDown.getY() != rightDown.getY()</code> so that test should move up and delay your creation of probableRightUp.</li>\n<li>Your compareTo method can be made a little neater, either write the result of the initial compare to a variable and return it immediately if non-zero, or consider doing the comparison yourself </li>\n</ul>\n\n<p>e.g</p>\n\n<pre><code>@Override\npublic int compareTo(Point p) {\n if (this.getX() < p.getX()) { \n return -1;\n } \n if (this.getX() > p.getX()) { \n return 1; \n }\n //and for Y\n ...\n return 0;\n}\n</code></pre>\n\n<p>-. When you are coding your <code>existsIn</code> method start thinking in templates. Sure it's not necessary now, but it costs nothing to write <code>public static <T> boolean existsIn(T[] array, T element)</code> and you've got a utility function you can use forever.</p>\n\n<p>One thing that would concern me about this method is the <a href=\"http://en.wikipedia.org/wiki/Cyclomatic_complexity\" rel=\"nofollow\">Cyclomatic Complexity</a> due to the number of loops and conditionals. Consider how you could break things down, e.g The content of your <code>k</code> loop can be broken out into code which finds/verifies the rectangle is complete. As a rule each method should have a role as discrete as possible, again this makes things more testable and more readable (when coupled with sensible naming).</p>\n\n<hr>\n\n<p>So using a TreeSet. Your initial code becomes:</p>\n\n<pre><code>final SortedSet<Point> points = new TreeSet<Point>(/* comparator goes here */);\n\nfor(int i = 0; i < coOrdinates.length; i++) {\n Point p = new Point(coOrdinates[i][0], coOrdinates[i][1]);\n points.add(p);\n}\n</code></pre>\n\n<p>Your iterations would need to evolve to use the SortedSet#tailSet or SortedSet#subSet methods. Both of these are just new views on the same data so they are cheap operations. </p>\n\n<p>A pseudo approach:</p>\n\n<pre><code>for (Point leftDown : points) {\n //You would pull this into a new method\n SortedSet<Point> potentialLeftUp = points.subSet(leftDown, new Point(leftDown.getX(), somePrecalculatedMaxY);\n\n for (Point leftUp : potentialLeftUp) {\n //no testing needed as you know it shares X\n\n //now build subset (potentialRightDown) where X > leftDown.getX and Y == leftDown.getY (this will be more manual as you are X sorted)\n\n for (Point rightDown : potentialRightDown) {\n //build probableRightUp\n if (points.contains(probableRightUp) {\n //increment count\n }\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T13:08:56.563",
"Id": "50772",
"Score": "0",
"body": "Q1. How to rename `i`,`j`,`k` more sensible way?\n\nQ2. What do you mean by `somePrecalculatedMaxY`?\n\nLike the idea of SortedSet I will consider this now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T13:34:58.537",
"Id": "50775",
"Score": "1",
"body": "@tintinmj regarding `i`,`j` and `k` I only meant that you could call them by something indicative of their role. `i` could be `lowerLeftIndex` now it is clearer when you remove `Point leftDown = points[i]` and replace all uses of `leftDown` with `points[lowerLeftIndex]` maintaining some readability. `somePrecalculatedMaxY` good reading, the `subSet` method is intelligent when generating the new view in that it honors the ordering (when X > leftDown.getX() it will end the subset). The value of Y here is not critical, so you could use Integer.MAX_INT with no efficiency consequences."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T09:36:21.020",
"Id": "31845",
"ParentId": "31819",
"Score": "2"
}
},
{
"body": "<p>Assuming you count rectangle by exhaustion (case by cases), you'll never be able to have a complexity smaller than the number of rectangles.</p>\n\n<p>My feeling is that the highest number of \"rectangles per point\" is obtained when working on a grid of width n (n*n points).</p>\n\n<p>Indeed, in that case, we have :</p>\n\n<ul>\n<li>1 = 1*1 rectangle of size n</li>\n<li>4 = 2*2 rectangles of size n-1</li>\n<li>9 = 3*3 rectangles of size n-2</li>\n<li>...</li>\n<li>(n-1)*(n-1) rectangles of size 1</li>\n</ul>\n\n<p>for a total of (n-1)<em>n</em>(2*n-1)/6.\nThis tells us that the current strategy won't be able to be better than O(n^3).</p>\n\n<p>Now, what you could do to is maintain 2 arrays instead of one :</p>\n\n<ul>\n<li>A1 sorted by (x,y) - this is O(n*log(n))</li>\n<li>A2 sorted by (y,x) - this is O(n*log(n))</li>\n</ul>\n\n<p>Then do something like :</p>\n\n<pre><code> - foreach p1 in A1:\n | find first p2 such that p1.x = p2.x (and p1.y < p2.y) using binary search in A1\n | find last p3 such that p1.x = p3.x using binary search in A1\n | find first p4 such that p1.y = p4.y (and p1.x < p4.x) using binary search in A2\n | find last p5 such that p1.y = p4.y using binary search in A2\n | if (p2 exists and p4 exists):\n | foreach p6 in (p2..p3):\n | foreach p7 in (p4..p5):\n | if (find p8 such that p8.y = p6.y and p8.x = p7.x using binary search in A1 or A2):\n | rectangle++\n</code></pre>\n\n<p>This solution is symetric in terms of <code>x</code> and <code>y</code>.</p>\n\n<p>Its complexity seems to be ~ n^3*log(n) in the worst case (points are a grid) which is not too far from the optimal.</p>\n\n<p>The complexity is ~ n*log(n) in cases where no more than 2 points are on the same horizontal or vertical line.</p>\n\n<p>Tiny optimisations would be starting the binary search in the smallest possible range :</p>\n\n<ul>\n<li>looking for p2 from p1 onward</li>\n<li>looking for p3 from p2 onward</li>\n<li>looking for p5 from p4</li>\n<li>looking for p8 from p3 or p5.</li>\n</ul>\n\n<p>Now, assuming you want to keep the solution with a single sorted array :</p>\n\n<ul>\n<li>you could break if \"if(leftDown.getX() == leftUp.getX()) {\" wasn't verified as it seems that we went too far.</li>\n<li><code>existsIn</code> could be given an additional parameter to limit the space we are using for the lookup.</li>\n<li>I think the interface would be clearer if the function was to take an array of point (and maybe having a different function converting from coordinates to points).</li>\n<li>I am not sure there is any point in having a special case for array with a length smaller than 4 as they would be handled properly and very quickly anyway.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T12:51:32.170",
"Id": "50771",
"Score": "0",
"body": "A1 and A2 don't even need to be sorted. They could just be `HashMap<Integer, HashSet<Integer> >`, giving you O(_n_) instead of O(_n_ log _n_)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T09:53:04.210",
"Id": "31847",
"ParentId": "31819",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "31845",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T20:37:02.877",
"Id": "31819",
"Score": "5",
"Tags": [
"java",
"optimization",
"coordinate-system"
],
"Title": "Get Rectangle Count from Given List of Co-ordinates"
}
|
31819
|
<p>I am trying to write a <code>SynchronizationContext</code> in C# that represents a message queue, to be pumped from a main loop.</p>
<p><em>Edit</em>: I see that I have forgotten to say - I need the message loop executions to be done a single, pre-determined thread. (In my case I want to push updates to an OpenGL context.)</p>
<p>Here is the class I have written:</p>
<pre><code>public class SingleThreadedSynchronizationContext : SynchronizationContext
{
private sealed class WorkItem
{
private readonly SendOrPostCallback _callback;
private readonly object _state;
private readonly ManualResetEventSlim _reset;
public WorkItem (SendOrPostCallback callback, object state, ManualResetEventSlim reset)
{
if (callback == null)
throw new ArgumentNullException ("callback");
_callback = callback;
_state = state;
_reset = reset;
}
public void Execute ()
{
_callback (_state);
if (_reset != null) {
_reset.Set ();
}
}
}
private readonly ConcurrentQueue<WorkItem> _workItems = new ConcurrentQueue<WorkItem> ();
private readonly Thread _executingThread;
public SingleThreadedSynchronizationContext (Thread executingThread)
{
if (executingThread == null)
throw new ArgumentNullException ("executingThread");
_executingThread = executingThread;
}
internal bool HasWorkItems {
get {
return !_workItems.IsEmpty;
}
}
private WorkItem ExecuteAndReturnNextWorkItem ()
{
WorkItem currentItem;
if (_workItems.TryDequeue (out currentItem)) {
currentItem.Execute ();
}
return currentItem;
}
private void ExecuteNextWorkItem ()
{
ExecuteAndReturnNextWorkItem ();
}
public override void Post (SendOrPostCallback d, object state)
{
_workItems.Enqueue (new WorkItem (d, state, null));
}
public override void Send (SendOrPostCallback d, object state)
{
if (Thread.CurrentThread == _executingThread) {
WorkItem requestedWorkItem = new WorkItem (d, state, null);
_workItems.Enqueue (requestedWorkItem);
WorkItem executedWorkItem = null;
do {
executedWorkItem = ExecuteAndReturnNextWorkItem ();
} while (executedWorkItem != null && executedWorkItem != requestedWorkItem);
} else {
using (var reset = new ManualResetEventSlim ()) {
_workItems.Enqueue (new WorkItem (d, state, reset));
reset.Wait ();
}
}
}
}
</code></pre>
<p>And here is a (everything additional removed) example of my main loop:</p>
<pre><code>class MainClass
{
public static void Main (string[] args)
{
var synchronizationContext = new CustomSynchronizationContext ();
SynchronizationContext.SetSynchronizationContext (synchronizationContext);
while (true) {
// Do something else in my loop;
while (synchronizationContext.HasWorkItems) {
synchronizationContext.ExecuteNextWorkItem ();
}
}
}
</code></pre>
<p>It is my first attempt at doing something on that level in the CLR concerning threading, so I wonder whether I have made any mistake in writing it, or done some other kind of mispractice (e.g. wrong class, etc.).</p>
|
[] |
[
{
"body": "<ol>\n<li>You don't need to implement <code>Dispose</code> pattern if you have no unmanaged resources to dispose. Unless you get paid per line of code, that is :)</li>\n<li><p>You should not dispose objects you did not create (unless you implement a wrapper). In your case, you should not dispose reset event in <code>WorkItem</code> class, since you did not create it there. Instead, you should use</p>\n\n<pre><code>using(var reset = new ManualResetEventSlim())\n{\n _workItems.Enqueue (new WorkItem (d, state, reset));\n ...\n}\n</code></pre></li>\n<li><p>this code:</p>\n\n<pre><code>while (true) \n{\n synchronizationContext.Send(_ => Console.WriteLine(\"Hello!\"), null)\n\n while (synchronizationContext.HasWorkItems) {\n synchronizationContext.ExecuteWorkItem ();\n }\n}\n</code></pre>\n\n<p>will hang your application. You should either remove resetEvent from <code>Send</code> method and simply execute all queued <code>WorkItem</code>s there (bad approach) or move this loop:</p>\n\n<pre><code> while (synchronizationContext.HasWorkItems) {\n synchronizationContext.ExecuteWorkItem ();\n }\n</code></pre>\n\n<p>to sepatrate thread (better approach). Might look like:</p>\n\n<pre><code>public sealed class CustomSynchronizationContext : SynchronizationContext, IDisposable\n{\n public CustomSynchronizationContext()\n {\n _thread = new Thread(() => \n {\n while(true)\n {\n _itemQueuedEvent.WaitOne();\n if (_disposed) return;\n ExecuteWorkItem();\n }\n });\n _thread.Start();\n }\n\n ........\n}\n</code></pre>\n\n<p>You will probably encounter some synchronization issues, but nothing that can not be solved.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T20:53:22.373",
"Id": "50824",
"Score": "0",
"body": "Thank you for the comment. I completely agree on 1 and 2. However, concerning item 3, I had forgotten to mention that I want all the work items to execute on a specific thread. I believe that the correct solution in that case would be to execute all `WorkItem`s when `Send` is called synchronously from the correct thread."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T05:35:03.037",
"Id": "50868",
"Score": "0",
"body": "@JeanHominal, well, yes, either that, or you can dispatch `Execute` method calls to the thread you need using wpf dispatcher. Or some other dispatcher (there is plenty available on the net), if you dont want a wpf dependency. Depending on what other code this thread executes, this might improve performance."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T07:31:26.600",
"Id": "31843",
"ParentId": "31820",
"Score": "3"
}
},
{
"body": "<p>A sycnhronisation context is still a powerful and meaningful API, since <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskscheduler.fromcurrentsynchronizationcontext?view=netframework-4.8\" rel=\"nofollow noreferrer\">task schedulers rely on them</a>. However, I have some concerns with your implementation.</p>\n<h3>Exception Management</h3>\n<p>You have no exception management in place.</p>\n<ul>\n<li><code>Post</code> requires the <em>synchronization context</em> to handle the exception.</li>\n<li><code>Send</code> requires the exception to be propagated up to the caller.</li>\n</ul>\n<p>As a consequence, any exception short-circuits signaling threads that are awaiting completion of the callback.</p>\n<blockquote>\n<pre><code>public void Execute ()\n{\n _callback (_state); // <- on error\n if (_reset != null) {\n _reset.Set (); // <-- this will not be called\n }\n}\n</code></pre>\n</blockquote>\n<hr />\n<h3>Proposed Solution</h3>\n<p>Simplify the work item. Extract threading flow from it.</p>\n<pre><code> private sealed class WorkItem\n {\n private readonly SendOrPostCallback _callback;\n private readonly object _state;\n\n public WorkItem(SendOrPostCallback callback, object state)\n {\n if (callback == null)\n throw new ArgumentNullException("callback");\n\n _callback = callback;\n _state = state;\n }\n\n public void Execute()\n {\n _callback(_state);\n }\n }\n</code></pre>\n<p>Let <code>Post</code> and <code>Send</code> have distinct exception management.</p>\n<pre><code> public override void Post(SendOrPostCallback d, object state)\n {\n _workItems.Enqueue(new WorkItem(arg => \n {\n try\n {\n d(arg);\n }\n catch (Exception error)\n {\n // TODO handle internally, but don't propagate it up the stack\n }\n\n }, state));\n }\n\n public override void Send(SendOrPostCallback d, object state)\n {\n if (Thread.CurrentThread == _executingThread)\n {\n // Execute inline\n new WorkItem(d, state).Execute();\n }\n else\n {\n Exception executionException = null;\n using (var signal = new ManualResetEventSlim())\n {\n _workItems.Enqueue(new WorkItem(arg =>\n {\n try\n {\n d(arg);\n }\n catch (Exception error)\n {\n executionException = error;\n }\n finally\n {\n signal.Set();\n }\n\n }, state));\n\n signal.Wait();\n }\n if (executionException != null)\n {\n throw new TargetInvocationException("failure executing the callback", executionException);\n }\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-04T14:31:35.180",
"Id": "221654",
"ParentId": "31820",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "31843",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T20:42:18.790",
"Id": "31820",
"Score": "10",
"Tags": [
"c#",
".net",
"multithreading"
],
"Title": "Basic, single-threaded implementation of SynchronizationContext"
}
|
31820
|
<p><code>User</code> and <code>Role</code> are just examples; also, code is sparse on purpose (i.e. for demonstration purposes only).</p>
<p>Thoughts? (e.g. good, bad, etc.)</p>
<p><strong>Interfaces</strong></p>
<pre><code>public interface IEntity
{
int Id { get; }
}
public interface IUser
: IEntity
{
string Username { get; }
string Email { get; }
ICollection<IRole> Roles { get; }
}
public interface IRole
: IEntity
{
string Name { get; }
ICollection<IUser> Users { get; }
}
public interface IContext<TEntity>
: IDisposable
where TEntity : class, IEntity
{
IDbSet<TEntity> Entities();
int SaveChanges();
}
public interface IUserContext<TUser>
: IContext<TUser>
where TUser : class, IUser
{
}
public interface IRoleContext<TRole>
: IContext<TRole>
where TRole : class, IRole
{
}
public interface IRepository<TEntity>
: IDisposable
where TEntity : class, IEntity
{
TEntity Find(int id);
IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> filter);
void Add(TEntity entity);
void Remove(TEntity entity);
}
public interface IUserRepository<TUser>
: IRepository<TUser>
where TUser : class, IUser
{
}
public interface IRoleRepository<TRole>
: IRepository<TRole>
where TRole : class, IRole
{
}
public interface IUnitOfWork<TUser, TRole>
: IDisposable
where TUser : class, IUser
where TRole : class, IRole
{
IUserRepository<TUser> Users();
IRoleRepository<TRole> Roles();
int SaveChanges();
}
</code></pre>
<p><strong>Classes</strong></p>
<pre><code>public abstract class Entity
: IEntity
{
public virtual int Id { get; set; }
}
public class User
: Entity, IUser
{
private ICollection<IRole> _roles;
public string Username { get; set; }
public string Email { get; set; }
public virtual ICollection<IRole> Roles
{
get { return _roles ?? (_roles = new Collection<IRole>()); }
set { _roles = value; }
}
}
public class Role
: Entity, IRole
{
private ICollection<IUser> _users;
public string Name { get; set; }
public virtual ICollection<IUser> Users
{
get { return _users ?? (_users = new Collection<IUser>()); }
set { _users = value; }
}
}
public abstract class Context<TContext, TEntity>
: DbContext, IContext<TEntity>
where TContext : DbContext
where TEntity : class, IEntity
{
static Context()
{
Database.SetInitializer<TContext>(null);
}
protected Context()
: this("name=DefaultConnection")
{
}
protected Context(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
public virtual IDbSet<TEntity> Entities()
{
return Set<TEntity>();
}
}
public class UserContext<TUser>
: Context<UserContext<TUser>, TUser>, IUserContext<TUser>
where TUser : class, IUser
{
public UserContext()
{
}
public UserContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
}
public class RoleContext<TRole>
: Context<RoleContext<TRole>, TRole>, IRoleContext<TRole>
where TRole : class, IRole
{
public RoleContext()
{
}
public RoleContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
}
public abstract class Repository<TEntity>
: IRepository<TEntity>
where TEntity : class, IEntity
{
private readonly IContext<TEntity> _context;
private bool _disposed;
protected Repository(IContext<TEntity> context)
{
_context = context;
_disposed = false;
}
public virtual TEntity Find(int id)
{
return _context.Entities().Find(id);
}
public virtual IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> filter = null)
{
return filter != null
? _context.Entities().Where(filter)
: _context.Entities();
}
public virtual void Add(TEntity entity)
{
_context.Entities().Add(entity);
}
public virtual void Remove(TEntity entity)
{
_context.Entities().Remove(entity);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
_context.Dispose();
}
_disposed = true;
}
}
~Repository()
{
Dispose(false);
}
}
public class UserRepository<TUser>
: Repository<TUser>, IUserRepository<TUser>
where TUser : class, IUser
{
public UserRepository()
: this(new UserContext<TUser>())
{
}
public UserRepository(IUserContext<TUser> context)
: base(context)
{
}
}
public class RoleRepository<TRole>
: Repository<TRole>, IRoleRepository<TRole>
where TRole : class, IRole
{
public RoleRepository()
: this(new RoleContext<TRole>())
{
}
public RoleRepository(IRoleContext<TRole> context)
: base(context)
{
}
}
public class UnitOfWork<TUser, TRole>
: IUnitOfWork<TUser, TRole>
where TUser : class, IUser
where TRole : class, IRole
{
private readonly IUserContext<TUser> _userContext;
private readonly IRoleContext<TRole> _roleContext;
private readonly IUserRepository<TUser> _userRepository;
private readonly IRoleRepository<TRole> _roleRepository;
private bool _disposed;
public UnitOfWork()
: this(new UserContext<TUser>(), new RoleContext<TRole>())
{
}
public UnitOfWork(IUserContext<TUser> userContext, IRoleContext<TRole> roleContext)
{
_userContext = userContext;
_roleContext = roleContext;
_userRepository = new UserRepository<TUser>(_userContext);
_roleRepository = new RoleRepository<TRole>(_roleContext);
_disposed = false;
}
public IUserRepository<TUser> Users()
{
return _userRepository;
}
public IRoleRepository<TRole> Roles()
{
return _roleRepository;
}
public int SaveChanges()
{
return _userContext.SaveChanges() + _roleContext.SaveChanges();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
_userContext.Dispose();
_roleContext.Dispose();
_userRepository.Dispose();
_roleRepository.Dispose();
}
_disposed = true;
}
}
~UnitOfWork()
{
Dispose(false);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>This seems about right.</p>\n\n<p>There is only one thing I'd like to point out.</p>\n\n<p>I'd change this:</p>\n\n<pre><code>public interface IEntity {\n int Id { get; }\n}\n\npublic class Entity : IEntity {\n public virtual int Id { get; set; }\n}\n</code></pre>\n\n<p><strong>All</strong> your entities are assumed to have <strong>only one Id</strong>, ruling out <strong>every</strong> composite key.</p>\n\n<p>Let's think about this common scenario:</p>\n\n<p>User.cs</p>\n\n<pre><code>public class User {\n public int Id { get; set; }\n public string Username { get; set; }\n}\n</code></pre>\n\n<p>Email.cs</p>\n\n<pre><code>public class Email {\n public int Id { get; set; }\n public string Address { get; set; }\n}\n</code></pre>\n\n<p>UserEmail.cs</p>\n\n<pre><code>public class UserEmail {\n public int UserId { get; set; }\n public int EmailId { get; set; }\n public bool IsPrimary { get; set; } //Adding this prop requires to map this entity.\n}\n</code></pre>\n\n<p>Given your base entity and entity interface you won't be able to handle composite keys.\nAlso, keep in mind that Entity Framework will handle by itself the many to many relationships as long as the table contains no more than the Id's, when you add any other property you will have to add that entity to your project.</p>\n\n<p>My advice is to move the Id to every entity, if you need/want to keep your base entity interface and class as a constraint, you could, but you dont really need the interface <strong>and</strong> the class.</p>\n\n<p>Like:</p>\n\n<p><code>\n<del>public interface IEntity {</del><br>\n <del>int Id { get; }</del><br>\n<del>}</del><br>\n</code><br>\n<code>\npublic class Entity <del>: IEntity</del> {<br>\n <del>public virtual int Id { get; set; }</del><br>\n}<br>\n</code><br>\n<code>\npublic class User : Entity, IUser {<br>\n public int Id { get; set; }<br>\n // ...<br>\n}\n</code></p>\n\n<h2>EDIT:</h2>\n\n<h3>IProvider.cs</h3>\n\n<pre><code>internal interface IProvider {\n MyContext DbContext { get; set; }\n\n IRepository<T> GetGenericRepository<T>()\n where T : class;\n\n T GetCustomRepository<T>(Func<MyContext, object> factory = null)\n where T : class;\n}\n</code></pre>\n\n<h3>Provider.cs</h3>\n\n<pre><code>internal class Provider : IProvider {\n private readonly Factory _factory;\n protected Dictionary<Type, object> Repositories { get; private set; }\n public MyContext DbContext { get; set; }\n\n internal Provider() {\n _factory = new Factory();\n Repositories = new Dictionary<Type, object>(); }\n\n protected virtual T MakeRepository<T>(\n Func<MyContext, object> factory, MyContext dbContext) {\n var f = factory ?? _factory.GetRepositoryFactory<T>();\n if (f == null) throw new NotSupportedException(typeof(T).FullName);\n var repo = (T)f(dbContext);\n Repositories[typeof(T)] = repo;\n return repo; }\n\n public IRepository<T> GetGenericRepository<T>() where T : class {\n return GetCustomRepository<IRepository<T>>(\n _factory.GetRepositoryFactoryForEntityType<T>()); }\n\n public virtual T GetCustomRepository<T>(Func<MyContext, object> factory = null)\n where T : class {\n object repoObj;\n Repositories.TryGetValue(typeof(T), out repoObj);\n if (repoObj != null) { return (T)repoObj; }\n return MakeRepository<T>(factory, DbContext); }\n\n public void SetRepository<T>(T repository) {\n Repositories[typeof(T)] = repository; }\n}\n</code></pre>\n\n<h3>Factory.cs</h3>\n\n<pre><code>internal class Factory {\n private readonly IDictionary<Type, Func<MyContext, object>> _factories;\n\n public Factory() { _factories = GetFactories(); }\n\n public Factory(IDictionary<Type, Func<MyContext, object>> factories) {\n _factories = factories; }\n\n private IDictionary<Type, Func<MyContext, object>> GetFactories() {\n return new Dictionary<Type, Func<MyContext, object>>\n { { typeof(ILogRepository),\n context => new LogRepository(context) },\n { typeof(IExtendedRepository),\n context => new ExtendedRepository(context) } }; }\n\n protected virtual Func<MyContext, object> DefaultEntityRepositoryFactory<T>()\n where T : class {\n return dbContext => new Repository<T>(dbContext); }\n\n public Func<MyContext, object> GetRepositoryFactory<T>() {\n Func<MyContext, object> factory;\n _factories.TryGetValue(typeof(T), out factory);\n return factory; }\n\n public Func<MyContext, object> GetRepositoryFactoryForEntityType<T>()\n where T : class {\n return GetRepositoryFactory<T>() ?? DefaultEntityRepositoryFactory<T>(); } }\n</code></pre>\n\n<h3>IRepository.cs</h3>\n\n<pre><code>public interface IRepository<T> : IDisposable\n where T : class\n{\n IList<T> All();\n IList<T> Find(Func<T, bool> f);\n T Add(T t);\n T Update(T t);\n T Remove(T t);\n}\n</code></pre>\n\n<h3>Repository.cs</h3>\n\n<pre><code>internal class Repository<T> : IRepository<T> where T : class\n{\n internal MyContext Context;\n\n public Repository(MyContext context) { Context = context; }\n\n public IList<T> All() { return Context.Set<T>().ToList(); }\n\n public IList<T> Find(Func<T, bool> f) {\n return Context.Set<T>().Where(f).ToList();\n }\n\n public T Add(T t) { /* add but don't save */ }\n\n public T Update(T t) { /* update but don't save */ }\n\n public T Remove(T t) { /* remove but don't save */ }\n\n public void Dispose() { /* dispose context */ }\n}\n</code></pre>\n\n<h3>ILogRepository.cs</h3>\n\n<pre><code>public interface ILogRepository : IDisposable\n{\n IList<Log> All();\n IList<Log> Find(Func<Log, bool> f);\n}\n</code></pre>\n\n<h3>LogRepository.cs</h3>\n\n<pre><code>internal class LogRepository : ILogRepository\n{\n internal DepofisContext Context;\n\n public LogRepository(DepofisContext context)\n {\n Context = context;\n }\n\n public IList<Log> All()\n {\n return Context.Logs.ToList();\n }\n\n public IList<Log> Find(Func<Log, bool> f)\n {\n return Context.Logs.Where(f).ToList();\n }\n\n public void Dispose()\n {\n Context.Dispose();\n }\n}\n</code></pre>\n\n<h3>IExtendedRepository.cs</h3>\n\n<pre><code>public interface IExtendedRepository : IRepository<Extend>\n{\n Extend NewMethod(Extend t);\n}\n</code></pre>\n\n<h3>ExtendedRepository.cs</h3>\n\n<pre><code>internal class ExtendedRepository : Repository<Extend>\n{\n public ExtendedRepository(MyContext context)\n : base(context) { }\n\n public Extend NewMethod(Extend t)\n {\n return t;\n }\n}\n</code></pre>\n\n<h3>IUnitOfWork.cs</h3>\n\n<pre><code>internal interface IUnitOfWork : IDisposable\n{\n int Save();\n}\n</code></pre>\n\n<h3>UnitOfWork.cs</h3>\n\n<pre><code>public class UnitOfWork : IUnitOfWork\n{\n private MyContext Context { get; set; }\n internal IProvider Provider { get; set; }\n\n private IRepository<T> GetGenericRepository<T>() where T : class {\n return Provider.GetGenericRepository<T>();\n }\n private T GetCustomRepository<T>() where T : class {\n return Provider.GetCustomRepository<T>(); \n }\n private void CreateContext() { Context = new MyContext(); }\n\n public UnitOfWork() {\n CreateContext();\n if (Provider == null) Provider = new Provider();\n Provider.DbContext = Context;\n }\n\n public IRepository<User> Users { \n get { return GetGenericRepository<User>(); } }\n public IRepository<Role> Roles { \n get { return GetGenericRepository<Role>(); } }\n public ILogRepository Logs { \n get { return GetCustomRepository<ILogRepository>(); } }\n public IExtendedRepository Extends { \n get { return GetCustomRepository<IExtendedRepository>(); } }\n\n public int Save() { return Context.SaveChanges(); }\n public void Dispose() { /* dispose context */ }\n}\n</code></pre>\n\n<p>As for the usage:</p>\n\n<pre><code>using(var uow = new UnitOfWork()) {\n var users = uow.Users.All();\n\n // do magic stuff here ;)\n\n uow.Save(); // don't forget to save\n}\n</code></pre>\n\n<p>Now the uow have these methods:</p>\n\n<ul>\n<li>uow.Users\n<ul>\n<li>.All()</li>\n<li>.Find(q=>q.UserId == 1)</li>\n<li>.Add(new User())</li>\n<li>.Update(user)</li>\n<li>.Remove(user)</li>\n</ul></li>\n<li>uow.Logs\n<ul>\n<li>.All()</li>\n<li>.Find(q=>q.LogId == 1)</li>\n</ul></li>\n<li>uow.Extends\n<ul>\n<li>Same methods as uow.Users</li>\n<li>.NewMethod(extend)</li>\n</ul></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T16:32:33.437",
"Id": "50796",
"Score": "0",
"body": "Excellent point (i.e. composites) Esteban; thank you, I appreciate your feedback. I'm not clear on how moving Id to all derived entities helps (Is there some entity framework side effect I am unaware of? You made reference to entity framework's handling of many-to-many relationships, did I miss/misunderstand some key point?). If I may ask, what are your thoughts on my use of generics for all data access objects (i.e. context, repository, and unit of work)? I did this to be able to use any entity implementing an interface (e.g. stubs, mocks, etc.) - is this overkill do you think?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T22:03:45.097",
"Id": "50837",
"Score": "0",
"body": "I've updated que answer, the code I provided is a modified version of John Papa's CodeCamper, you can find it on GitHub."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T14:22:34.017",
"Id": "50917",
"Score": "0",
"body": "Got your message, thanks for getting back to me; I'll look at this over the weekend - I appreciate your feedback."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T14:40:54.213",
"Id": "50921",
"Score": "0",
"body": "This code is going to take a while to digest; thanks for posting it, it'll be something I reference and learn [from] over time - I appreciate it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T15:21:15.617",
"Id": "50927",
"Score": "0",
"body": "Glad I could help, if you need anything just ask, no worries, it took me a while to fully grasp these two patterns together."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T17:05:08.973",
"Id": "50947",
"Score": "0",
"body": "Cool, thanks again and have a good weekend :-)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T03:45:46.223",
"Id": "31833",
"ParentId": "31822",
"Score": "1"
}
},
{
"body": "<p>You should not dispose the context in the Repository's dispose method, because it has been injected via the constructor and you have no information if you can safely dispose it or not. If the same context has been passed into another repository then you would break it by disposing it.</p>\n\n<p>Please read this for a full explanation and an example how to do it the correct way: <a href=\"https://dusted.codes/dont-dispose-externally-created-dependencies\" rel=\"nofollow\">https://dusted.codes/dont-dispose-externally-created-dependencies</a></p>\n\n<p>In short you can re-factor the code to use a factory, so that you are in charge of creating and disposing a context object.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-23T13:44:32.133",
"Id": "120872",
"ParentId": "31822",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T20:57:27.023",
"Id": "31822",
"Score": "4",
"Tags": [
"c#",
"design-patterns",
"entity-framework"
],
"Title": "Unit of Work and Repository Design Pattern Implementation"
}
|
31822
|
<pre><code>def execute(parameterName : scala.Boolean = { /* compiled code */ })
</code></pre>
<p>When calling this method, you can go with</p>
<pre><code>someobject.execute(true)
</code></pre>
<p>or</p>
<pre><code>someobject.execute(parameterName = true)
</code></pre>
<p>If you use the former, IntelliJ pops up a recommendation stating that Boolean arguments should be named. But doesn't this introduce an unnecessary dependency on the name of the parameter? Essentially the name of the parameter becomes part of the interface.</p>
<p>If I then change the name of <code>parameterName</code> in <code>execute()</code> to something else, I potentially break a lot of code that is using the execute method.</p>
<p>I understand that it improves readability a bit (you can look at the code and see which Boolean is being set to true without having to look at the called method). But is it enough of an advantage?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T21:53:19.597",
"Id": "50832",
"Score": "0",
"body": "This is really a question for the Programmers affiliate site. You're asking about a concept, with single line examples, not for a review of some functioning code. You'd get more attention and better answers on the Programmers site, as well. Mind you, you'd probably also find the question closed, because it has been asked so many times before. http://stackoverflow.com/questions/1240739/boolean-parameters-do-they-smell http://programmers.stackexchange.com/questions/147977/is-it-wrong-to-use-a-boolean-parameter-to-determine-behavior"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T23:17:02.937",
"Id": "50846",
"Score": "0",
"body": "Noted about using Programmers - but the questions you've linked aren't really the same. This is about the best practice of calling a function with a boolean variable, not a question as to whether the boolean should be there in the first place."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T23:24:40.233",
"Id": "50848",
"Score": "4",
"body": "This question appears to be off-topic because it does not actually ask for review of code."
}
] |
[
{
"body": "<p>IDEA's Scala plugin has always been lacking quality compared to other products of Jetbrains. The company develops a direct competitor language to Scala named Kotlin, so I think it's simply an issue of their priorities. In a couple of years of posting dozens of bugs related to Scala plugin on their tracker I've grown accustomed not to trust anything that this plugin says or does. </p>\n\n<p>Your case is an example of how it tries to be too smart. You've given a good enough reason to report this on their bugtracker, and, of course, not to follow that ridiculous advice.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T21:47:55.650",
"Id": "50831",
"Score": "3",
"body": "The Eclipse Scala IDE does the same thing, fyi. http://misto.ch/detecting-and-naming-boolean-parameters/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T21:56:28.457",
"Id": "50834",
"Score": "0",
"body": "Good point. Although I still believe that it's quite a ridiculous suggestion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T21:58:15.910",
"Id": "50835",
"Score": "0",
"body": "It's a bit like the grammar checker in Word, which always highlights *which* and *that*, because they are often misused, without being able to detect whether they are actually being misused in this instance."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T23:40:57.473",
"Id": "31828",
"ParentId": "31827",
"Score": "3"
}
},
{
"body": "<p>Personally, I think it's a reasonable suggestion.</p>\n\n<ul>\n<li>If you change the parameter name in a way that changes its meaning, it's a good thing that the code using the old name doesn't compile anymore.</li>\n<li>If you change the parameter name, keep the meaning the same and all your code is in the same solution, then your IDE should be able to rename all usages at the same time.</li>\n<li>If you change the parameter name, keep the meaning the same, but your code is not all in the same solution (e.g. when you're writing a library used by third parties), then somebody could be using this practice, no matter what you use. So, the name is already part of the interface, no matter what you use.</li>\n</ul>\n\n<p>There is a middle ground where all your code is not in the same solution, but you have control over all of it (e.g. by specifying coding guidelines for your company). In this case, you might decide that it's an unnecessary dependency. But in all the other cases, I think that using named parameter often makes sense.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T00:27:06.370",
"Id": "50856",
"Score": "2",
"body": "I'd argue with your points. If a function's parameter changes its meaning it's a sure sign that the function does a different thing, which means that it's rather more appropriate to change the function's name instead. Depending on IDE to keep a project manageable can't be a good idea either. IMO this whole thing is an example of an overcomplication without any real practical benefit."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T23:34:01.107",
"Id": "31875",
"ParentId": "31827",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "31828",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-25T22:39:47.800",
"Id": "31827",
"Score": "7",
"Tags": [
"scala"
],
"Title": "Whether or not to name Boolean parameters in Scala"
}
|
31827
|
<p>While responding to a SO question, I wrote the following method to convert a flat key structure to a hierarchical one as given below</p>
<p>In</p>
<pre><code>{
property1: 'value1',
property2.property3: 'value2',
property2.property7: 'value4',
property4.property5.property6: 'value3',
}
</code></pre>
<p>Out</p>
<pre><code>{
property1: 'value1',
property2: {
property3: 'value2',
property7: 'value4'
},
property4: {
property5: {
property6: 'value3'
}
}
}
</code></pre>
<p>Converter:</p>
<pre><code>function convert(obj) {
var res = {}, i, j, splits, ref, key;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
splits = i.split('.');
ref = res;
for (j = 0; j < splits.length; j++) {
key = splits[j];
if (j == splits.length - 1) {
ref[key] = obj[i];
} else {
ref = ref[key] = ref[key] || {};
}
}
};
}
return res;
}
</code></pre>
<p>Can this be improved?</p>
<p>Demo: <a href="http://jsfiddle.net/arunpjohny/xFS9u/1/" rel="nofollow">Fiddle</a></p>
|
[] |
[
{
"body": "<p>The main complexity of this function arises from using a <strong>plain for-in loop</strong> to loop over object keys - this adds two extra indentation levels instead of just one level if one were to use a higher-level looping construct. So I would use some library function or create something like:</p>\n\n<pre><code>function eachKeyValue(obj, fun) {\n for (var i in obj) {\n if (obj.hasOwnProperty(i)) {\n fun(i, obj[i]);\n }\n }\n}\n</code></pre>\n\n<p>Within this loop, there's <strong>another low-level for-loop</strong>, which I would again replace, say... with an <code>Array.forEach</code> method.</p>\n\n<p>Now, in your code the loop goes over all the parts of the key, <strong>checking each time whether it's the last part.</strong> Instead of this, I would first remove the last part, loop over all the other parts to ensure all these are initialized, and then simply assign the value to the last position.</p>\n\n<p>With some additional <strong>improvements to variable names</strong>, I would write it as such:</p>\n\n<pre><code>function convert(obj) {\n var result = {};\n eachKeyValue(obj, function(namespace, value) {\n var parts = namespace.split(\".\");\n var last = parts.pop();\n var node = result;\n parts.forEach(function(key) {\n node = node[key] = node[key] || {};\n });\n node[last] = value;\n });\n return result;\n}\n</code></pre>\n\n<p>This code has just 2 levels of nesting compared to the original 4.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T14:59:59.577",
"Id": "31857",
"ParentId": "31831",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T03:04:48.480",
"Id": "31831",
"Score": "4",
"Tags": [
"javascript"
],
"Title": "Convert flat object keys to hierarchical one"
}
|
31831
|
<p>I wrote a script that will eventually go onto a Raspberry Pi. It takes a picture then uploads it to Twitter every 15 minutes from 5:30-9:00pm. </p>
<p>It works fine as is, but I feel I need to organize this as a class. I was wondering if someone could point me in the right direction on how to take my functions and make it into a class.</p>
<p>Just to be clear, I have basic knowledge on how classes work. I'm just confused about how I could get all of my functions to work within a class.</p>
<pre><code>#Take care of imports
import pyimgur
import json
import requests
from requests_oauthlib import OAuth1
from twython import Twython
from apscheduler.scheduler import Scheduler
import logging
logging.basicConfig()
#Imgur credentials
CLIENT_ID = "----"
#Twitter credentials
consumer_key = '----'
consumer_secret = '----'
access_token = '-----'
access_token_secret = '----'
user_id = "----"
################################
##### FUNCTIONS ################
################################
#Optional: Upload an image to imgur and grab the link to tweet it. Bypassing twitpic
def upload_to_imgur():
#path to image
path = "/pathtopicture"
#upload to imgur
im = pyimgur.Imgur(CLIENT_ID)
uploaded_image = im.upload_image(PATH, title="Uploaded with PyImgur")
#print various test things
#print(uploaded_image.title)
#print(uploaded_image.datetime)
#print(uploaded_image.link)
imgur_link = uploaded_image.link
#Upload a tweet or a media tweet to twitter
def upload_to_twitter():
# #upload simple tweet
twitter = Twython(consumer_key, consumer_secret, access_token, access_token_secret)
twitter.update_status(status="tweet text goes here")
#
# OR upload a media tweet
#
# photo = open('/pathtopicture', 'rb')
# twitter.update_status_with_media(status='tweetText', media=photo)
#
# OR upload to imgur then tweet link
#
# upload_to_imgur()
# twitter.update_status(status=imgur_link)
#
#Destroy a tweet from twitter
def destroy_tweet():
#URL for the destroy request
destroy_url = 'https://api.twitter.com/1.1/statuses/user_timeline.json?user_id=---&count=1'
#authentication
auth = OAuth1(consumer_key, consumer_secret, access_token, access_token_secret)
#Request twitter for JSON response
r =requests.get(destroy_url, auth=auth)
#Grab most recent tweet ID from JSON response
tweet_id=r.json()[0]['id_str']
#Set what twitter means
twitter = Twython(consumer_key, consumer_secret, access_token, access_token_secret)
#Destroy the latest tweet
twitter.destroy_status(id=tweet_id)
#Every 15 minutes from 5:30-9:00pm tweet a picture and upload to twitter.
def start_scheduler():
#initialize
sched = Scheduler()
#All fo the schedulers
#Scheduler at 5:30
@sched.cron_schedule(day_of_week='mon-sat', hour=17, minute=30)
def scheduled_job():
destroy_tweet()
upload_to_twitter()
#Scheduler at 5:45
@sched.cron_schedule(day_of_week='mon-sat', hour=17, minute=45)
def scheduled_job():
destroy_tweet()
upload_to_twitter()
#Scheduler at 6:00
@sched.cron_schedule(day_of_week='mon-sat', hour=18)
def scheduled_job():
destroy_tweet()
upload_to_twitter()
#Scheduler at 6:15
@sched.cron_schedule(day_of_week='mon-sat', hour=18, minute=15)
def scheduled_job():
destroy_tweet()
upload_to_twitter()
#Scheduler at 6:30
@sched.cron_schedule(day_of_week='mon-sat', hour=18, minute=30)
def scheduled_job():
destroy_tweet()
upload_to_twitter()
#Scheduler at 6:45
@sched.cron_schedule(day_of_week='mon-sat', hour=18, minute=45)
def scheduled_job():
destroy_tweet()
upload_to_twitter()
#Scheduler at 7:00
@sched.cron_schedule(day_of_week='mon-sat', hour=19)
def scheduled_job():
destroy_tweet()
upload_to_twitter()
#Scheduler at 7:15
@sched.cron_schedule(day_of_week='mon-sat', hour=19, minute=15)
def scheduled_job():
destroy_tweet()
upload_to_twitter()
#Scheduler at 7:30
@sched.cron_schedule(day_of_week='mon-sat', hour=19, minute=30)
def scheduled_job():
destroy_tweet()
upload_to_twitter()
#Scheduler at 7:45
@sched.cron_schedule(day_of_week='mon-sat', hour=19, minute=45)
def scheduled_job():
destroy_tweet()
upload_to_twitter()
#Scheduler at 8:00
@sched.cron_schedule(day_of_week='mon-sat', hour=20)
def scheduled_job():
destroy_tweet()
upload_to_twitter()
#Scheduler at 8:15
@sched.cron_schedule(day_of_week='mon-sat', hour=20, minute=15)
def scheduled_job():
destroy_tweet()
upload_to_twitter()
#Scheduler at 8:30
@sched.cron_schedule(day_of_week='mon-sat', hour=20, minute=30)
def scheduled_job():
destroy_tweet()
upload_to_twitter()
#Scheduler at 8:45
@sched.cron_schedule(day_of_week='mon-sat', hour=20, minute=45)
def scheduled_job():
destroy_tweet()
upload_to_twitter()
#Scheduler at 9:00
@sched.cron_schedule(day_of_week='mon-sat', hour=21)
def scheduled_job():
destroy_tweet()
upload_to_twitter()
#start scheduler
sched.start()
#loop
while True:
pass
#Start the script
start_scheduler()
</code></pre>
|
[] |
[
{
"body": "<p>I think that defining a function inside of a function definition body is bad practice.\nFor example you can have a class called <code>Scheduler</code> and define each function inside that class.</p>\n\n<p>I will leave the rest for the more expirienced people.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T03:53:49.167",
"Id": "31834",
"ParentId": "31832",
"Score": "1"
}
},
{
"body": "<p>Repeating the scheduled jobs is not necessary. A sufficiently complex <a href=\"https://pythonhosted.org/APScheduler/cronschedule.html\" rel=\"nofollow\">cron-style expression</a> should do:</p>\n\n<pre><code>@sched.cron_schedule(hour='17-20', minute='0-45/15')\ndef scheduled_job():\n destroy_tweet()\n upload_to_twitter()\n</code></pre>\n\n<p>The downside of this is that it, unlike your original code, will not be triggered at 9:00.</p>\n\n<p>Even if that's not acceptable, your original code need not repeat itself so much. After defining <code>scheduled_job</code> without the <code>sched.cron_schedule</code> decorator, you can still schedule that as a job within a <code>for</code> loop, which would be much cleaner, e.g.:</p>\n\n<pre><code>for hour in range(17, 21):\n for minute in [0, 15, 30, 45]:\n sched.add_cron_job(scheduled_job, hour=hour, minute=minute)\n</code></pre>\n\n<p>This would also allow for adding the special 9:00 case.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T06:06:45.203",
"Id": "31839",
"ParentId": "31832",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T03:41:47.097",
"Id": "31832",
"Score": "2",
"Tags": [
"python",
"twitter"
],
"Title": "Uploading a picture to Twitter over a period of time"
}
|
31832
|
<p>I attempted to write a read-only dictionary, containing primes:</p>
<pre><code>#inspired by http://ceasarjames.wordpress.com/2011/07/10/the-quadratic-sieve/
class PrimeDict(dict):
def __init__(self):
super(PrimeDict,self).__setitem__(2,2)
self.previous_max = 2
def __setitem__(self, key, value):
return self.__getitem__(key) #it's a read-only dict
def __delitem__(self, key):
return self.__getitem__(key) #it's a read-only dict
def __find_primes(self,n):
if n < self.previous_max: return
sieve = range(self.previous_max,n)
for x in self.keys():
i = x * ((self.previous_max - 1)//x + 1)
while i < n:
sieve[i - self.previous_max] = 0
i += x
index = self.previous_max
while index <= n ** 0.5:
if sieve[index-self.previous_max]:
i = index ** 2
while i < n:
sieve[i-self.previous_max] = 0
i += index
index += 1
self.previous_max = n
for x in sieve:
if x:
super(PrimeDict,self).__setitem__(x,x)
def __getitem__(self,key):
key = int(key)
if key>= self.previous_max:
self.__find_primes((key+1))
try:
return super(PrimeDict,self).__getitem__(key)
except:
return False
</code></pre>
<p><a href="https://gist.github.com/aausch/6709819" rel="nofollow">https://gist.github.com/aausch/6709819</a></p>
<p>Is there any way for me to make this class definition cleaner and/or shorter?</p>
|
[] |
[
{
"body": "<h3>1. Comments on your code</h3>\n\n<ol>\n<li><p>No docstrings! What does your class do and how am I supposed to use it? Also, no <a href=\"http://docs.python.org/3/library/doctest.html\" rel=\"nofollow\">doctests</a>.</p></li>\n<li><p>Wouldn't it be more natural for this class to be a <em>set</em> of primes, rather than a <em>dictionary</em> mapping primes to <code>True</code> and other keys to <code>False</code>?</p></li>\n<li><p>There's only one set of primes, so this is a rare opportunity to make use of the <a href=\"http://en.wikipedia.org/wiki/Singleton_pattern\" rel=\"nofollow\">Singleton pattern</a>. That is, each call to <code>PrimeDict()</code> ought to return the <em>same</em> object.</p></li>\n<li><p>By implementing <code>__setitem__</code> like this:</p>\n\n<pre><code>def __setitem__(self, key, value):\n return self.__getitem__(key) #it's a read-only dict\n</code></pre>\n\n<p>you give callers the false impression that this operation succeeded:</p>\n\n<pre><code>>>> p = PrimeDict()\n>>> p[1] = True\n>>> # looks good, but:\n>>> p[1]\nFalse\n</code></pre>\n\n<p>Instead, you should raise an exception:</p>\n\n<pre><code>def __setitem__(self, key, value):\n raise TypeError(\"'PrimeDict' object doesn't support item assignment\")\n</code></pre>\n\n<p>Similarly for <code>__delitem__</code>:</p>\n\n<pre><code>def __delitem__(self, key):\n raise TypeError(\"'PrimeDict' object doesn't support item deletion\")\n</code></pre></li>\n<li><p>By deriving your class from Python's <code>dict</code>, you make all of the <code>dict</code> methods available. This means that a caller might accidentally bypass your attempt to make the dictionary read-only, by calling some other method that you haven't overridden. For example:</p>\n\n<pre><code>>>> p = PrimeDict()\n>>> p.update({1: True})\n>>> p[1]\nTrue\n</code></pre>\n\n<p>The thing to do is not to subclass <code>dict</code>, but to subclass <a href=\"http://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping\" rel=\"nofollow\"><code>collections.abc.Mapping</code></a> and have the actual dictionary be a member variable. Or, if you take my suggestion in point 2 above, subclass <a href=\"http://docs.python.org/3/library/collections.abc.html#collections.abc.Set\" rel=\"nofollow\"><code>collections.abc.Set</code></a> and have the actual set as a member variable. I'll show how to do this in my revised code in section 2 below.</p></li>\n<li><p>The method <code>__find_primes</code> has a <a href=\"http://docs.python.org/3/tutorial/classes.html#private-variables\" rel=\"nofollow\">private name</a>. Why do you do that? The intended use of private names in Python is to \"avoid name clashes of names with names defined by subclasses\" but that's obviously not necessary here. All that the private name achieves here is to make your code a bit harder to debug:</p>\n\n<pre><code>>>> p = PrimeDict()\n>>> p.__find_primes(10)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'PrimeDict' object has no attribute '__find_primes'\n>>> p._PrimeDict__find_primes(10)\n>>> p\n{2: 2, 3: 3, 5: 5, 7: 7}\n</code></pre></li>\n<li><p>You start out by adding 2 to the set of primes and then set <code>self.previous_max = 2</code>. But it would be simpler to start out with the empty set of primes and <code>self.previous_max = 1</code>. The <a href=\"https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow\">sieve of Eratosthenes</a> is self-starting.</p></li>\n<li><p>Instead of:</p>\n\n<pre><code>i = index ** 2\nwhile i < n:\n sieve[i-self.previous_max] = 0\n i += index\n</code></pre>\n\n<p>make use of Python's <a href=\"http://docs.python.org/3/library/stdtypes.html#range\" rel=\"nofollow\"><code>range</code></a> function, and write:</p>\n\n<pre><code>for i in range(index ** 2, n, index):\n sieve[i - self.previous_max] = 0\n</code></pre></li>\n<li><p>The code in <code>__find_primes</code> has to subtract <code>self.previous_max</code> from the array index every time it looks up something in <code>sieve</code>. It would be more efficient to do this subtraction once when setting up the loop bounds. For example, instead of the code that I suggested above:</p>\n\n<pre><code>for i in range(index ** 2, n, index):\n sieve[i - self.previous_max] = 0\n</code></pre>\n\n<p>you could write:</p>\n\n<pre><code>for i in range(index ** 2 - self.previous_max, n - self.previous_max, index):\n sieve[i] = 0\n</code></pre></li>\n<li><p>The line:</p>\n\n<pre><code>key = int(key)\n</code></pre>\n\n<p>can raise <code>ValueError</code>. Wouldn't it be better to return <code>False</code> if <code>key</code> can't be converted to an integer?</p></li>\n</ol>\n\n<h3>2. Revised code</h3>\n\n<pre><code>try:\n from collections.abc import Set\nexcept ImportError:\n from collections import Set # Python 3.2 or earlier\n\nclass PrimeSet(Set):\n \"\"\"A PrimeSet object acts like the set of prime numbers:\n\n >>> p = PrimeSet()\n >>> 2 in p\n True\n >>> 4 in p\n False\n\n The object sieves for primes as needed. When iterated over, it\n yields the primes found so far:\n\n >>> 30 in p\n False\n >>> list(p)\n [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\n\n \"\"\"\n # Singleton pattern: there is only one set of primes.\n instance = None\n def __new__(cls):\n if cls.instance is None:\n cls.instance = super(PrimeSet, cls).__new__(cls)\n return cls.instance\n\n def __init__(self):\n super(PrimeSet, self).__init__()\n self.max = 1 # Highest number sieved to so far.\n self.set = set() # Set of primes up to self.max.\n\n def __iter__(self):\n return iter(self.set)\n\n def __len__(self):\n return len(self.set)\n\n def __contains__(self, key):\n try:\n key = int(key)\n except ValueError:\n return False\n if key > self.max:\n self.find_primes(key)\n return key in self.set\n\n def find_primes(self, n):\n \"\"\"Sieve for primes from self.max + 1 up to and including n.\"\"\"\n if n <= self.max:\n return\n sieve = [True] * (n - self.max)\n for p in self:\n for i in range(p - 1 - self.max % p, len(sieve), p):\n sieve[i] = False\n for p, isprime in enumerate(sieve):\n if isprime:\n p += self.max + 1\n self.set.add(p)\n for i in range(p * p - self.max - 1, len(sieve), p):\n sieve[i] = False\n self.max = n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T17:56:53.730",
"Id": "50811",
"Score": "0",
"body": "2. <-- it's a dictionary mapping primes to themselves; there's no space wasted mapping non-primes to false. I figured a dictionary lookup is faster than a test for inclusion in a set."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T21:53:30.130",
"Id": "50833",
"Score": "0",
"body": "I wasn't concerned about wasted space. My point is that the set of primes is a more natural idea than its characteristic function, and so representing it by a Python set seems more natural to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T21:59:17.143",
"Id": "50836",
"Score": "0",
"body": "yeah, i'll definitely re-name the class a \"set\" instead of a \"dictionary\", but i'm still not convinced it's a good idea to store all of the \"false's\" in there. it's probably easier to convince me to use a set data-structure as the underlying store, but i'm not there yet on that one"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T22:19:24.487",
"Id": "50839",
"Score": "1",
"body": "Point 2 is about appropriate *interface* for an object representing the prime numbers (should it be set-like or dictionary-like?), not about the implementation. My implementation suggestion is that you use a Python set, which of course has no values (`False` or otherwise), just keys."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T11:02:14.167",
"Id": "31848",
"ParentId": "31835",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "31848",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T04:26:31.057",
"Id": "31835",
"Score": "3",
"Tags": [
"python",
"primes",
"hash-map"
],
"Title": "Prime number dictionary"
}
|
31835
|
<p>I've taken all the advice from <a href="https://codereview.stackexchange.com/questions/31451/craps-game-rules-and-code">here</a> and have created a Craps class and gameplay. I just wanted to ask for more advice on how to optimize my code.</p>
<pre><code>#include <iostream>
#include <cmath> // atan(), fabs()
#include "Craps.h"
using namespace std;
int main(int argc, char* argv[])
{
int choice;
Craps game;
do {
cin>> choice;
if(!cin)
{
cin.clear();
cin.ignore(200,'\n');
cout<<"\n please inter int number \n\n";
}
switch (choice) {
case 1:
game.Play();
break;
case 2:
break;
default:
break;
}
} while (choice != 2);
return 0;
}
#include <iostream>
//#include <catdlib>
#include <ctime>
#include <string>
using namespace std;
class Craps
{
public:
void DisplayInstruction();
void Play();
int DiceRoll();
private:
int random;
};
void Craps::DisplayInstruction(){
cout<<"DisplayInstruction"<<endl;
}
int Craps::DiceRoll()
{
int die1 = (rand() + time(0)) % 6+1 ;
int die2 = (rand() + time(0)) % 6+1 ;
int sum = die1 + die2;
return sum;
}
void Craps::Play()
{
bool won = false;
bool lost = false;
string anyKey;
int myPoint = 0;
int sumeOfDice = DiceRoll();
switch (sumeOfDice)
{
case 7:
won= true;
break;
case 11:
won= true;
break;
case 2:
lost = true;
break;
case 3:
lost = true;
break;
case 12:
lost = true;
break;
default:
myPoint = sumeOfDice;
cout<< myPoint <<endl;
break;
}
while (won == false && lost ==false) {
sumeOfDice = DiceRoll();
if(sumeOfDice == myPoint)
{
won = true;
}
else
if(sumeOfDice == 7)
{
lost = true;
}
}
if (won == true)
{
cout<<"player win"<<endl;
}
else
{
cout<<"player lose "<<endl;
}
}
#endif /* defined(__Craps__Craps__) */
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Try to refrain from using <code>using namespace std</code></a>, especially in a program like this. If you were to put it in the header, you could introduce bugs due to issues such as name-clashing.</p></li>\n<li><p>Your comments next to <code><cmath></code> suggests that you're using it, but I don't see these functions used anywhere. No need to include this library.</p></li>\n<li><p><code>#include</code> headers before libraries to prevent unwanted dependency:</p>\n\n<pre><code>#include \"Craps.h\" // header won't be forced to use <iostream>\n#include <iostream>\n</code></pre></li>\n<li><p>Naming convention states that functions should start lowercase:</p>\n\n<pre><code>thisIsAFunction();\nthis_is_also_a_function();\n</code></pre></li>\n<li><p><code>DisplayInstruction()</code> is a needless function as it only displays one line of text. Functions shouldn't be created just for that. In general, functions that don't do anything with the data members are best as free functions (non-member functions).</p></li>\n<li><p>The dice functionality should have its own class, allowing the <code>Craps</code> class to maintain object(s) of it as needed. This will also ensure <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">separation of concerns</a>. You may refer to <a href=\"https://codereview.stackexchange.com/questions/31571/review-of-dice-class\">my implementation</a> to get an idea for this.</p></li>\n<li><p>You didn't seed <code>std::rand()</code> with <code>std::srand()</code>. This will cause <code>rand()</code> to produce the <a href=\"https://stackoverflow.com/a/7343909/1950231\">same random numbers each time</a>. <em>Put this at the top of <code>main()</code> only</em>:</p>\n\n<pre><code>// this requires <cstdlib> and <ctime>\n// use nullptr instead if using C++11\nstd::srand(static_cast<unsigned int>(std::time(NULL)));\n</code></pre>\n\n<p><em>However</em>, if you're using C++11, you should no longer use <code>rand</code>. I'll quote <a href=\"https://codereview.stackexchange.com/a/39098/22222\">one of my answers</a>:</p>\n\n<blockquote>\n <p><strong>You should refrain from using <code>rand</code> altogether in C++11 as it is <a href=\"http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful\" rel=\"nofollow noreferrer\">considered harmful</a>. Instead, utilize C++11's <a href=\"http://en.cppreference.com/w/cpp/header/random\" rel=\"nofollow noreferrer\"><code><random></code></a>\n library.</strong></p>\n \n <p>You also no longer need <code><ctime></code> and should use C++11's\n <a href=\"http://en.cppreference.com/w/cpp/chrono\" rel=\"nofollow noreferrer\"><code><chrono></code></a>. From this library, you can obtain a seed for a PRNG\n with this:</p>\n\n<pre><code>auto chrono_seed = std::chrono::system_clock::now().time_since_epoch().count();\n</code></pre>\n</blockquote></li>\n<li><p>The <code>switch</code> in <code>Play()</code> could be its own function, specifically of type <code>bool</code>. As it isn't working with a data member, it can be a free function. If you go this route, then each <code>case</code> will need a <code>return true</code> or <code>return false</code>. The <code>default</code> will also need to handle errors resulting from an invalid <code>case</code> value, such as by throwing an exception.</p></li>\n<li><p>You never use <code>anyKey</code> anywhere, so remove it.</p></li>\n<li><p>Tested <em>conditions</em> could be shortened like this:</p>\n\n<pre><code>if (condition) // if (condition == true)\nif (!condition) // if (condition == false)\n</code></pre></li>\n<li><p>Tested <em>streams</em> can be shortened like <a href=\"https://stackoverflow.com/questions/6791520/if-cin-x-as-a-condition\">this</a>:</p>\n\n<pre><code>if (!(cin >> choice)) // cin >> choice;\n // if (!cin) \n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T05:14:07.263",
"Id": "31838",
"ParentId": "31836",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "31838",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T04:45:14.700",
"Id": "31836",
"Score": "2",
"Tags": [
"c++",
"optimization",
"classes",
"game"
],
"Title": "Craps game rules and code: version 2"
}
|
31836
|
<p>I want you to pick my code apart and give me some feedback on how I could make it better or simpler. This code converts a binary tree to a doubly linked list (in order).</p>
<pre><code>public class BinaryTreeToLinkedList {
private TreeNode root;
private static class TreeNode {
TreeNode left;
TreeNode right;
int item;
public TreeNode(TreeNode left, TreeNode right, int item) {
this.left = left;
this.right = right;
this.item = item;
}
}
private TreeNode appendDLL (TreeNode left, TreeNode right) {
if (left == null) return right;
if (right == null) return left;
// get last element of left linkedlist
TreeNode leftLast = left.left;
TreeNode rightLast = right.left;
leftLast.right = right;
right.left = leftLast;
// now we form the list into circular again.
rightLast.right = left;
left.left = rightLast;
return left;
}
private TreeNode postOrder(TreeNode node) {
if (node == null) {
return null;
}
TreeNode leftList = postOrder(node.left);
TreeNode rightList = postOrder(node.right);
// convert the current node into doubly LL
node.left = node;
node.right = node;
// hook current node.
leftList = appendDLL (leftList, node);
// hook right side linkedlist
leftList = appendDLL (leftList, rightList);
return leftList;
}
public void convertToLinkedList() {
root = postOrder(root);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T16:50:17.860",
"Id": "50797",
"Score": "0",
"body": "Your question says inorder, but your code says postorder."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T17:39:43.973",
"Id": "50803",
"Score": "0",
"body": "Thats not a fault, we need a postorder traversal to fetch inorder linkedlist."
}
] |
[
{
"body": "<p>Your code certainly seems to do the job (assuming that the tree is only a root node with two branches; otherwise you will need to implement some recursion). It doesn't \"feel\" very Java-esque, but you've said in your previous questions/comments that you don't really want critique of method and variable names, so I'll try to avoid that.</p>\n\n<pre><code>if (left == null) return right;\nif (right == null) return left;\n</code></pre>\n\n<p>This code will return <code>null</code> if I pass in <code>null</code> for both <code>left</code> and <code>right</code>. Is that intentional? It's unclear from the way you've written your code that that would be the desired result. When I think about it, it makes sense that the method would return <code>null</code> in this scenario, but I'm not sure if you understood that consequence when you coded it, just based on the style.</p>\n\n<pre><code>if (node == null) {\n return null;\n}\n</code></pre>\n\n<p>You should try to use consistent style in your code. If you're going to put these checks and return statements at the beginning, either put them on the same line as the <code>if()</code> statement or don't. It doesn't matter which you do, as long as you do the same thing throughout. Makes your code much more readable and easier to maintain.</p>\n\n<pre><code>// get last element of left linkedlist\nTreeNode leftLast = left.left;\nTreeNode rightLast = right.left;\n\nleftLast.right = right;\nright.left = leftLast;\n\n// now we form the list into circular again.\nrightLast.right = left;\nleft.left = rightLast;\n\nreturn left;\n</code></pre>\n\n<p>This entire block is very difficult to scan. What it does isn't readily apparent by the way you've named all your variables. For example <code>rightLast</code> sounds like the rightmost node in the tree, but in fact it's the <em>left</em> node of the right node in the tree. Then with all the subsequent processing, it's very confusing without stepping through line-by-line to get a better understanding. Consider renaming your variables to be more meaningful. In my opinion, the most beautiful and elegant code is self-documenting.</p>\n\n<p>Also, if you were looking for ways to further improve the code's functionality (besides adding recursion), you might look into <a href=\"http://docs.oracle.com/javase/tutorial/java/generics/types.html\" rel=\"nofollow\">generic types</a> so that your nodes can hold any data, rather than just an <code>int</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T17:42:47.597",
"Id": "50805",
"Score": "0",
"body": "Thanks, but `rightLast` is right most node of tree. Remaining part is a very Helpful feedback."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T19:11:26.953",
"Id": "50818",
"Score": "0",
"body": "@JavaDeveloper Is it? This line where you declare it seems to say that it's the `left` node of the current node's `right` node... (`TreeNode rightLast = right.left;`)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T18:27:02.373",
"Id": "51033",
"Score": "0",
"body": "Its my bad terminology. right is actually circular linkedlist obtained from right subtree."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T13:26:36.053",
"Id": "31852",
"ParentId": "31841",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "31852",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T06:10:10.213",
"Id": "31841",
"Score": "4",
"Tags": [
"java",
"algorithm",
"linked-list",
"tree",
"converting"
],
"Title": "Convert tree to circular doubly linked list"
}
|
31841
|
<p>The first line of the input stream contains integer n. The second line contains <code>n (1 <= n <= 1000)</code> integers <code>{ a[1], a[2], a[3], ... , a[n] }, abs(a[i]) < 10^9</code>. </p>
<p>Find the longest alternating subsequence <code>{ a[i1], a[i2].. , a[ik] }</code> of the sequence <code>a</code> that is the subsequence such that <code>i1 < i2 < ... < ik</code>, every two adjacent elements are different, and every three adjacent elements <code>a[i' - 1], a[i'], a[i' + 1]</code> meet one of the following conditions: <code>(a[i' - 1] < a[i'] && a[i'] > a[i' + 1]) || (a[i' - 1] > a[i'] && a[i'] < a[i' + 1])</code> where k is maximized. </p>
<p>The output stream should contain the subsequence <code>{ a[i1], a[i2].. , a[ik] }</code>. </p>
<p><strong>Important condition.</strong> If there are several subsequences that satisfy this condition you need to choose the subsequence with the minimum i1. From all subsequences with the same i1 you need to choose the one with minimum i2. And so on.</p>
<p>For example:</p>
<p>1) <code>n = 13, a = { 8, 7, 4, 3, 2, 5, 6, 9, 8, 7, 3, 2, 4}</code>. </p>
<p>Output is <code>{ 8, 7, 9, 3, 4}</code>.</p>
<p>2) <code>n = 10, a = { 1, 4, 2, 3, 5, 8, 6, 7, 9, 10}</code>.</p>
<p>Output is <code>{ 1, 4, 2, 8, 6, 7}</code>.</p>
<p>A short explanation of my algorithm on example:</p>
<p>8, 7, 4, 3, 2, 5, 6, 9, 8, 7, 3, 2, 4</p>
<p>---|----1----|--|---2--|-|---3-----|-|4|</p>
<p>In this case there are 4 subsequence: 2 decreasing (1, 3) and 2 increasing (2, 4). So the maximum number of elements in the longest alternating subsequence will be 5 (number of subcequencws + 1, because of the first element, which is always included in the begining of longest alternating subsequence). Now we need to find the optimal elements, that satisfy important condition. </p>
<p>At every iterarion of the main cycle I have to subsequence: increasing and decreasing (seq[0] and seq[1], one of them is current), which I change with every iteration. </p>
<p>For example, </p>
<p>1) seq[1] = {7, 4, 3, 2} and seq[0] = {5, 6, 9} , seq[1] is current; </p>
<p>2) seq[0] = {5, 6, 9} is current, seq[1] = {8, 7, 3, 2}; </p>
<p>3) seq[1] = {8, 7, 3, 2} is current, seq[0] = 4. </p>
<p>In each iteration I choose an element in current subsequence according to these rules:</p>
<p>1) if the current subsequence is decreasing, than choose the leftmost element in seq[1][i] ( i >=<em>currentLimiter</em> ), which is less than some element in increasing subsequence seq[0][j], and remember the current position <em>currentLimiter</em>=j of seq[0][j]; </p>
<p>For the case of seq[1] = {7, 4, 3, 2} and seq[0] = {5, 6, 9}, where seq[1] is current, element 7 is selected, as 7 < 9, and the <em>currentLimiter</em> = 2 (index of 9). </p>
<p>2) if the current subsequence is increasing, than choose the leftmost element in seq[0][i] ( i >=<em>currentLimiter</em> ), which is greater than some element in decreasing subsequence seq[1][j], and remember the current position <em>currentLimiter</em>=j of seq[1][j];</p>
<p>For the case of seq[0] = {5, 6, 9}, seq[1] = {8, 7, 3, 2}, where seq[0] is current, element 9 is selected, as we can search only from index 2 (<em>currentLimiter</em> = 2) and 9 > 8, and the <em>currentLimiter</em> = 0 (index of 8).</p>
<p>There is my solution for this problem:</p>
<pre><code>std::vector<long long> findLongestAlternantSequence(std::vector<long long> &inputArray)
{
if (inputArray.size() == 1 || inputArray.size() == 2)
return inputArray;
std::vector<int> arrayOfDifferences;
for (size_t i = 0; i < inputArray.size() - 1; ++i)
{
//if the next element greater than current, add 1 to arrayOfDifferences
//else add 0. So we have array of markers, that shows whether
//the sequence encreases or decreases
arrayOfDifferences.push_back((inputArray[i] - inputArray[i + 1] > 0) ? 1 : 0);
}
std::vector<long long> longestAlternantSequence;
//seq - vector of 2 subsequences (increasing and decreasing)
//seq[0] will be filled with increasing subsequence
//seq[1] will be filled with decreasing subsequence
std::vector< std::vector<long long> > seq;
std::vector<long long> v1;
std::vector<long long> v2;
seq.push_back(v1);
seq.push_back(v2);
int currentVal = arrayOfDifferences[0];
// pointer to the current element of input sequence
size_t pos = 0;
// pointer to the element of increasing/decreasing subsequence
// from which I can search for the next element
size_t currLimiter = 0;
// the first element is always result sequence
longestAlternantSequence.push_back(inputArray[0]);
while (pos < arrayOfDifferences.size())
{
seq[currentVal].clear();
//fill current subsequence seq[currentVal] with new elements
//of increasing or decreasing subsequence
// currentVal can be 0 or 1; 0 indicates that the current subsequence
// is increasing, 1- decresing
while (pos < arrayOfDifferences.size() && currentVal == arrayOfDifferences[pos])
{
seq[currentVal].push_back(inputArray[pos + 1]);
++pos;
}
currentVal = (currentVal + 1) % 2;
if (currentVal == 1)
{
if (seq[1].size() != 0)
{
int k = 0;
int s = currLimiter;
while ( s < seq[1].size() && seq[1][s] >= seq[0][k])
{
++k;
if ( k == seq[0].size())
{
k = 0;
++s;
}
}
if (s < seq[1].size())
{
longestAlternantSequence.push_back(seq[1][s]);
}
currLimiter = k;
}
}
else
{
if (seq[0].size() != 0)
{
int k = 0;
int s = currLimiter;
while (s < seq[0].size() && seq[0][s] <= seq[1][k])
{
++k;
if ( k == seq[1].size())
{
k = 0;
++s;
}
}
if (s < seq[0].size())
{
longestAlternantSequence.push_back(seq[0][s]);
}
currLimiter = k;
}
}
}
// push the element of the last subsequence
longestAlternantSequence.push_back(seq[(currentVal + 1) % 2][currLimiter]);
return longestAlternantSequence;
}
</code></pre>
<p>I've spent a lot of time on this problem, but still not convinced that I solved it correctly. I will be grateful if you specify my mistakes and find the tests for which my program is wrong.</p>
|
[] |
[
{
"body": "<p>Your approach is not very idiomatic. It is very hard to read, and reason-about. Spotting mistakes is not easy. I will not even attempt it, as I think some major rewriting should be your first priority. I think your current approach of trying to solve the entire problem in one big function is a big part of the reason why you had to work so long on it! Of course, algorithms are hard, but you can use well-known building blocks to build larger ones.</p>\n\n<p>I would try to mimic the Standard Library / Boost as much as possible. This means using divide-and-conquer to split your problem up into manageable pieces, each of which are easy to reason about without knowing too much of the rest of the problem.</p>\n\n<ul>\n<li>top-level function should be a function template taking bidirectional iterators arguments instead of a container, and returning a pair of iterators instead of a container. This makes the algorithm usable with other data types and avoids unnecessary copying. </li>\n</ul>\n\n<p>i.e. like this:</p>\n\n<pre><code>template<class BidirIt>\nstd::pair<BidirIt, BidirIt> \nfind_longest_alternating_subsequence(BidirIt first, BidirIt last)\n</code></pre>\n\n<ul>\n<li>because you are iterating 3 elements in lock-step, I would use a <code>boost::zip_iterator</code> from the Boost.Iterator library. This will tie the adjacent elements into a <code>boost::tuple</code> from the Boost.Tuple library. I would let your top-level function delegate to a <code>find_longest_alternating_subsequence_helper</code> that takes such <code>zip_iterator</code>s. </li>\n</ul>\n\n<p>i.e. define the starting iterators of the helper function like this:</p>\n\n<pre><code>auto first_triple_it = boost::make_zip_iterator(\n boost::make_tuple(first, std::next(first), std::next(first, 2))\n);\n\nauto last_triple_it = boost::make_zip_iterator(\n boost::make_tuple(std::prev(last, 2), std::prev(last), last)\n);\n</code></pre>\n\n<ul>\n<li>use a function object predicate <code>is_alternating_triple</code> that takes a <code>zip_iterator</code> to formally define the alternating condition that you are looking for</li>\n</ul>\n\n<p>i.e. like </p>\n\n<pre><code>struct is_alternating_triple\n{\n template<class TripleIt>\n bool operator()(TripleIt it) const\n {\n auto const& e0 = it.get<0>(); \n auto const& e1 = it.get<1>();\n auto const& e2 = it.get<2>();\n\n return (\n ((e0 < e1) && (e1 > e2)) ||\n ((e0 > e1) && (e1 < e2))\n )\n }\n};\n</code></pre>\n\n<ul>\n<li>Let's look back what these suggestions would achieve: you can repeatedly use a simple one-dimensional search over triples to find elements satisfying a predicate, and compute whether the length of the last sequence was larger than the maximum so far. This suggests using <code>std::find_if</code> and <code>std::find_if_not</code> from the Standard Library in order to find the beginning and end of each alternating sequence.</li>\n</ul>\n\n<p>i.e. a main loop inside <code>find_longest_alternating_subsequence_helper</code> like this</p>\n\n<pre><code>// init max sequence found so far\nfor (auto it = first_triple_it; it != last_triple_it; /* NO ++it here, see loop*/) {\n auto seq_beg = std::find_if(it, last_triple_it, is_alternating_triple);\n if (res == last_triple_it) // no matches found, we're done\n // return max sequence found\n\n // OK, we are at a start of a new sequence, find the end of it\n auto seq_end = std::find_if_not(seq_beg, last_triple_it, is_alternating_triple);\n if (std::distance(seq_beg, seq_end) > max_length_so_far)\n // update max sequence so far \n it = seq_end; // instead of ++it, see comment inside loop\n}\n// return max sequence found\n</code></pre>\n\n<p>From these suggestions, it's easy to compose a general, flexible and almost certainly correct algorithm. Each step can be reasoned about in isolation. There is very little room for off-by-one errors. There is no unecessary copying of large vectors, just tuples of iterators.</p>\n\n<p>Regarding your question for test cases: I would start with some simple stuff. Sequences with 0, 1 or 2 elements. Sequences with only alternating elements. Sequences with no alternating elements, etc. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T18:22:38.767",
"Id": "31948",
"ParentId": "31842",
"Score": "2"
}
},
{
"body": "<p>There are two bugs related to consecutive equal entries:</p>\n\n<ul>\n<li>According to the problem specification, the result needs to be strictly alternating — <em>a<sub>i</sub></em> and <em>a<sub>i+1</sub></em> may not be equal to each other. For the input <code>{ 8, 8, 8 }</code>, the output should be <code>{ 8 }</code>. Your algorithm produces <code>{ 8, 8 }</code>.</li>\n<li>A two-element input is not a trivial base case. For the input <code>{ 5, 5 }</code>, you cannot immediately return the input as the output.</li>\n</ul>\n\n<p>I'll make the trivial observation that the <code>inputArray</code> parameter should be <code>const</code>. Just call it <code>input</code>; the \"Array\" adds nothing of value, and in any case, it's a <code>std::vector</code>, not an array.</p>\n\n<p>Wherever you say <code>(n + 1) % 2</code> to map 0 to 1 and vice versa, you can just say <code>!n</code>.</p>\n\n<p>That said, I can make absolutely no sense of how your code works. It appears to work correctly for all sequences I tried, except for the bugs mentioned above. If you could describe its theory of operation, I think I would like to give it a proper review.</p>\n\n<p>I've written an implementation that makes sense to me. I'll admit that it does not perform nearly as efficiently as yours.</p>\n\n<pre><code>std::vector<T> altSubsequence(const std::vector<T> &input) {\n if (input.size() <= 1)\n return input;\n\n const size_t DESCENDING = 0, ASCENDING = 1;\n std::vector<size_t> subsequenceLength[] = {\n std::vector<size_t>(input.size(), 1),\n std::vector<size_t>(input.size(), 1)\n };\n std::vector<size_t> nextElement[] = {\n std::vector<size_t>(input.size(), 0),\n std::vector<size_t>(input.size(), 0)\n };\n size_t maxSubsequenceLength[] = { 1, 1 };\n\n for (int i = input.size() - 1; i >= 0; --i) {\n for (size_t dir = DESCENDING; dir <= ASCENDING; dir++) {\n for (size_t j = i + 1; j < input.size(); j++) {\n if ((dir == DESCENDING) ? (input[i] > input[j])\n : (input[i] < input[j])) {\n if (subsequenceLength[dir][i] <= subsequenceLength[!dir][j]) {\n subsequenceLength[dir][i] = 1 + subsequenceLength[!dir][j];\n nextElement[dir][i] = j;\n\n if (subsequenceLength[dir][i] > maxSubsequenceLength[dir]) {\n maxSubsequenceLength[dir] = subsequenceLength[dir][i];\n }\n if (subsequenceLength[dir][i] == 1 + maxSubsequenceLength[!dir]) {\n break;\n }\n }\n }\n }\n }\n }\n\n std::vector<T> result;\n // Which direction to start?\n size_t dir = (subsequenceLength[DESCENDING][0] > subsequenceLength[ASCENDING][0]) ? DESCENDING :\n (subsequenceLength[ASCENDING][0] > subsequenceLength[DESCENDING][0]) ? ASCENDING :\n (nextElement[DESCENDING][0] < nextElement[ASCENDING][0]) ? DESCENDING : ASCENDING;\n size_t i = 0;\n do {\n result.push_back(input[i]);\n i = nextElement[dir][i];\n dir = !dir;\n } while (i != 0);\n return result;\n}\n</code></pre>\n\n<h2>Explanation</h2>\n\n<p>This solution is based on dynamic programming. We want to know, that is the longest descending-first alternating subsequence if the input only consisted of elements <em>input</em><sub><em>i</em></sub>, <em>input</em><sub><em>i</em> + 1</sub>, …, <em>input</em><sub><em>n</em></sub>, and what is the longest ascending-first subsequence, that starts with <em>input</em><sub><em>i</em></sub>? We start with <em>i</em> = <em>n</em>, where obviously the maximum subsequence length is 1. Then we consider <em>i</em> = <em>n</em> - 1 to see how it might be incorporated into an existing optimal sequence, etc., until <em>i</em> = 0, at which point we will know what the optimal sequence looks like.</p>\n\n<p>Example:</p>\n\n<blockquote>\n <p><em>input</em> = { 8, 7, 4, 3, 2, 5, 6, 9, 8, 7, 3, 2, 4 }</p>\n</blockquote>\n\n<ol>\n<li>Considering just the last element { 4 }, the longest alternating descending-first subsequence has length 1, and the longest ascending-first subsequence also has length 1.</li>\n<li>Considering { 2, 4 }, the longest descending-first subsequence is { 2 }, which has length 1. The longest ascending-first subsequence is { 2, 4 }, which has length 2.</li>\n<li>Considering { 3, 2, 4 }, the longest descending-first subsequence is { 3, 2, 4 } — it can connect to the 2-element ascending-first we found in step 2. The longest ascending-first subsequence anchored by 3 is { 3, 4 } — it connects to the descending-first subsequence found in step 1.</li>\n<li>Considering { 7, 3, 2, 4 }, the longest descending-first subsequence is { 7, 3, 4 } — it connects to the 2-element ascending-first we found in step 3. (How do we know? Of the subsequent elements smaller than 7, we find the one that is the start of the longest ascending-first sequence that is known to exist.) The longest ascending-first subsequence is { 7 } — there is no element larger than 7.</li>\n<li>Considering { 8, 7, 3, 2, 4 }, the longest descending-first subsequence is { 8, 3, 4 } — it connects to the 3-element ascending-first we found in step 3. (How do we know? Of the subsequent elements smaller than 3, we find the one that is the start of the longest ascending-first sequence that is known to exist, favouring { 8, 3, 4 } over { 8, 2, 4 } because 3 is an earlier entry.) The longest ascending-first subsequence is { 8 } — there is no element larger than 8.</li>\n<li>Considering { 9, 8, 7, 3, 2, 4 }, the longest descending-first subsequence is { 9, 3, 4 } — it connects to the 2-element ascending-first we found in step 3. The longest ascending-first subsequence is { 9 } — there is no element larger than 9.</li>\n<li>Considering { 6, 9, 8, 7, 3, 2, 4 }, the longest descending-first subsequence that starts with 6 is { 6, 3, 4 } — it connects to the 2-element ascending-first we found in step 3. (We walk consider elements 3, 2, and 4, which are all smaller than 6. Of those, 3 is the one that starts the longest known ascending-first sequence.) The longest ascending-first subsequence is { 6, 9, 3, 4 } — connecting to the 3-element descending-first subsequence found in step 6.</li>\n<li>Considering { 5, 6, 9, 8, 7, 3, 2, 4 }, the longest descending-first subsequence that starts with 5 is { 5, 3, 4 } — it connects to the 2-element ascending-first we found in step 3. The longest ascending-first subsequence is { 5, 9, 3, 4 } — connecting to the 3-element descending-first subsequence found in step 6.</li>\n<li>Considering { 2, 5, 6, 9, 8, 7, 3, 2, 4 }, the longest descending-first sequence is { 2 }. The longest ascending-first sequence is { 2, 9, 3, 4 }.</li>\n<li>Considering { 3, 2, 5, 6, 9, 8, 7, 3, 2, 4 }, the longest descending-first sequence is { 3, 2, 9, 3, 4 }. The longest ascending-first sequence is { 3, 5, 3, 4 } — connecting to the descending-first sequence found in step 8.</li>\n<li>Considering { 4, 3, 2, 5, 6, 9, 8, 7, 3, 2, 4 }, the best descending-first sequence is { 4, 3, 2, 9, 3, 4 }. The best ascending-first sequence is { 4, 6, 3, 4 } — connecting to the descending-first sequence found in step 7.</li>\n<li>Considering { 7, 4, 3, 2, 5, 6, 9, 8, 7, 3, 2, 4 }, the best descending-first sequence is { 7, 4, 6, 3, 4 }. The best ascending-first sequence is { 7, 9, 3, 4 } (using step 6).</li>\n<li>Considering all input { 8, 7, 4, 3, 2, 5, 6, 9, 8, 7, 3, 2, 4 }, the best descending-first sequence is { 8, 7, 9, 3, 4 } (using step 12). The best ascending-first sequence is { 8, 9, 3, 4 } (using step 6).</li>\n<li>The descending-first sequence is longer, so it wins.</li>\n</ol>\n\n<p>Why do we work backwards from the end? Because the problem, as stated, favours earlier elements. The first element of the input will always be included in the result. Therefore, when we finally reach the first element, we have our answer.</p>\n\n<p>In the code, the two <code>subsequenceLength</code> vectors store the length of the longest descending-first and ascending-first anchored at element <em>i</em>. The <code>nextElement</code> vectors contain the indexes that tell us how those chains are constructed. Each of the two <code>maxSubsequenceLength</code> just contains the maximum value of <code>subsequenceLength</code>, as a shortcut to prevent the algorithm from being fully O(<em>n</em><sup>2</sup>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T08:17:40.250",
"Id": "51214",
"Score": "0",
"body": "Thank you for finding these bugs! I've added some explanations to my algorithm. It is not easy to follow I suppose. So ask questions if something is not clear."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T18:37:06.163",
"Id": "31991",
"ParentId": "31842",
"Score": "4"
}
},
{
"body": "<p>You have essentially implemented a greedy algorithm. Each time you detect a change in the trend, you add an element to the result. It's just that your code for finding which element to add is hard to follow because the cryptic variable names lack meaning. Also, I think it is useful to introduce a class representing a monotonic run, just like you described in your explanation.</p>\n\n<p>Your greedy strategy seems to work, although I can't prove that it's correct.</p>\n\n<p>Here's my implementation of what you described, with fixes for the bugs I noted in my other answer. I think you'll find it more expressive than your original.</p>\n\n<pre><code>#include <assert.h>\n#include <vector>\n\n//////////////////////////////////////////////////////////////////////\n\n/**\n * This class represents a monotonically non-increasing (trendtype = DN)\n * or monotonically non-decreasing (trendtype = UP) run of elements in\n * a vector.\n */\ntemplate<typename T>\nclass MonotonicRun {\n public:\n typedef enum trendtype { DN = 0, UP = 1 } trendtype;\n\n /**\n * begin and end should point to either:\n * - the front of the vector,\n * - just past the back of the vector,\n * - a local extremum\n */\n MonotonicRun(const std::vector<T> &vector,\n typename std::vector<T>::const_iterator begin,\n typename std::vector<T>::const_iterator end) :\n // C++11 constructor delegation\n MonotonicRun(vector, begin, end, trendForInitialRun(vector, begin, end)) {\n }\n\n MonotonicRun(const std::vector<T> &vector,\n typename std::vector<T>::const_iterator begin,\n typename std::vector<T>::const_iterator end,\n trendtype trend) :\n vector(&vector),\n b(begin),\n e(end),\n t(trend) {\n }\n\n inline typename std::vector<T>::const_iterator begin() const {\n return b;\n }\n\n inline void begin(typename std::vector<T>::const_iterator b) {\n this->b = b;\n }\n\n inline typename std::vector<T>::const_iterator end() const {\n return e;\n }\n\n inline trendtype trend() const {\n return t;\n }\n\n inline bool hasNext() const {\n return begin() != vector->end();\n }\n\n MonotonicRun<T> next() const {\n assert(hasNext());\n typename std::vector<T>::const_iterator it;\n T e;\n switch (trend()) {\n case DN:\n for (it = end(), e = *it; it != vector->end() && *it >= e; ++it) {\n e = *it;\n }\n return MonotonicRun(*vector, end(), it, UP);\n case UP:\n for (it = end(), e = *it; it != vector->end() && *it <= e; ++it) {\n e = *it;\n }\n return MonotonicRun(*vector, end(), it, DN);\n }\n }\n\n private:\n static trendtype trendForInitialRun(const std::vector<T> &vector,\n typename std::vector<T>::const_iterator begin,\n typename std::vector<T>::const_iterator end) {\n assert(begin == vector.begin());\n if (end == vector.end()) {\n // This is the initial and only run. Construct a degenerate\n // run; its trendtype won't matter since it only serves to\n // signal the end of iteration.\n return DN;\n } else if (*begin < *end) {\n return DN;\n } else if (*begin > *end) {\n return UP;\n }\n // If *end == *begin, then then we failed to locate all consecutive\n // repeating elements when constructing this run.\n assert(false);\n }\n\n const typename std::vector<T> *vector;\n typename std::vector<T>::const_iterator b, e;\n trendtype t;\n};\n\n//////////////////////////////////////////////////////////////////////\n\ntemplate<typename T>\nstd::vector<T> longestAlternatingSubsequence(const std::vector<T> &input) {\n if (input.size() <= 1) {\n return input;\n }\n std::vector<T> result;\n\n // Construct an initial run consisting of the first element. If any\n // immediately following elements are equal to it, include those too.\n typename std::vector<T>::const_iterator it;\n for (it = input.begin(); it != input.end() && *it == input.front(); ++it);\n MonotonicRun<T> thisRun(input, input.begin(), it);\n\n do {\n MonotonicRun<T> nextRun = thisRun.next();\n\n // Find the earliest element of this run that will let us accommodate\n // the next run.\n typename std::vector<T>::const_iterator thisIt, nextIt;\n for (thisIt = thisRun.begin(); thisIt != thisRun.end(); ++thisIt) {\n for (nextIt = nextRun.begin(); nextIt != nextRun.end(); ++nextIt) {\n if ( ((thisRun.trend() == thisRun.DN) && (*thisIt < *nextIt)) || \n ((thisRun.trend() == thisRun.UP) && (*thisIt > *nextIt)) ) { \n nextRun.begin(nextIt); \n goto PUSH_RESULT; \n } \n }\n }\n assert(!nextRun.hasNext());\n thisIt = thisRun.begin();\n\n PUSH_RESULT: result.push_back(*thisIt);\n thisRun = nextRun;\n } while (thisRun.hasNext());\n\n return result;\n}\n</code></pre>\n\n<p>I would also observe that the code should be templatized, becaused there is no reason to be limited to <code>long long</code> only. Any type would work, as long as it supports the comparison operators.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T00:09:57.443",
"Id": "32101",
"ParentId": "31842",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "31991",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T07:19:06.500",
"Id": "31842",
"Score": "7",
"Tags": [
"c++",
"algorithm"
],
"Title": "The longest alternating sequence in C++"
}
|
31842
|
<p>I am working on a small method that saves uploaded images and records the images in a database.</p>
<pre><code>public function setEventImages($event_id){
foreach($_FILES['event-images']['tmp_name'] as $tmp_name){
$imgName = $this->imgPath . $this->random_name . $_FILES['event-images']['name'];
move_uploaded_file($tmp_name, $imgName);
$stmt = $this->dbh->prepare("INSERT INTO adrenaline_junkies_uk_event_images (event_image_name, event_id) VALUES (?,?)");
$stmt->bindParam(1, $imgName, PARAM_STR);
$stmt->bindValue(2, $event_id, PARAM_INT);
$stmt->execute();
}
}
</code></pre>
<p>How can this be made more efficient?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T20:46:37.910",
"Id": "83829",
"Score": "0",
"body": "Are you sure you want to store images in the database? I have always opted for storing the path to the image in the database, but left the images as flat files. There are plenty of reasons both for and against. (There are many debates about it on StackOverflow http://stackoverflow.com/questions/815626/to-do-or-not-to-do-store-images-in-a-database)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-10-21T05:36:42.977",
"Id": "271884",
"Score": "0",
"body": "can you please post full code ?"
}
] |
[
{
"body": "<p>I don't think your code will work as expected. This:</p>\n\n<pre><code> foreach($_FILES['event-images']['tmp_name'] as $tmp_name){\n</code></pre>\n\n<p>tells me that <code>$_FILES['event-images']['tmp_name']</code> is an array (i.e., you're handling multiple files upload). But, in that case, <code>$_FILES['event-images']['name']</code> should also be an array, so the concatenation will fail here:</p>\n\n<pre><code> $imgName = $this->imgPath . $this->random_name . $_FILES['event-images']['name'];\n</code></pre>\n\n<p>As for PDO, why do you prepare the same SQL query over and over again? I'd put the <code>prepare</code> statement before the loop, so that this work is done only once per upload.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T13:51:31.160",
"Id": "50776",
"Score": "0",
"body": "I assumed I was looping through each image by using this foreach statement?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T14:30:47.717",
"Id": "50781",
"Score": "0",
"body": "You are, but `$_FILES['event-images']['name']` is still an array. Try to do such a loop and just print the values of `$tmp` and `$_FILES['event-images']['name']`. Of course, to test this, you need to upload at least two files. As for PDO, see Example 1 in [`prepare` documentation](http://php.net/manual/en/pdo.prepare.php): you need only one preparation for multiple executes."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T13:48:54.523",
"Id": "31854",
"ParentId": "31853",
"Score": "0"
}
},
{
"body": "<p>Yes, there certainly is. Prepared statements can be reused, over and over again. The way your code works is: it's creating the same prepared statement over and over again, and binds the new parameters right after doing so, why not move the <code>prepare</code> call outside of the loop?</p>\n\n<pre><code>$stmt = $this->dbh->prepare(\"INSERT INTO adrenaline_junkies_uk_event_images (event_image_name, event_id) VALUES (?,?)\");\nforeach($_FILES['event-images']['tmp_name'] as $tmp_name)\n{ \n $imgName = $this->imgPath . $this->random_name . $_FILES['event-images']['name'];\n move_uploaded_file($tmp_name, $imgName);\n $stmt->bindParam(1, $imgName, PARAM_STR);\n $stmt->bindValue(2, $event_id, PARAM_INT);\n $stmt->execute();\n //done for now, to re-use a statement, close its cursor first?\n //though this is done implicitly, best do it ASAP\n //especially when using SELECT + PDOStatement::fetch in a loop\n $stmt->closeCursor();\n}\n</code></pre>\n\n<p>For a start, that saves you the trouble of that <code>prepare</code> call in the loop, increasing readability and, if all goes well, it'll also improve performance a bit.</p>\n\n<p>Now, I do have some other niggles with your code, like this statement:</p>\n\n<pre><code>$imgName = $this->imgPath . $this->random_name . $_FILES['event-images']['name'];\n</code></pre>\n\n<p>Now, I don't know how your <code>$_FILES</code> array is structured, but <a href=\"http://php.net/manual/en/reserved.variables.files.php\" rel=\"nofollow noreferrer\">check some of the contributed notes on the man page</a> there are quite a few snippets that deal with <code>$_FILES</code> arrays recursively.</p>\n\n<p>Another thing, and this is really a detail, is that you don't seem to be using <em>transactions</em>. When you're in the process of inserting images, one by one, and you reach a point where your script fails (either through timeout or another reason), you might end up with partially inserted data. That's not great. Transactions are an easy way to avoid this:</p>\n\n<pre><code>try\n{\n $this->dbh->beginTransaction();//start transaction here\n $stmt = $this->dbh->prepare(\"INSERT INTO adrenaline_junkies_uk_event_images (event_image_name, event_id) VALUES (?,?)\");\n foreach($_FILES['event-images']['tmp_name'] as $tmp_name)\n {\n $imgName = $this->imgPath . $this->random_name . $_FILES['event-images']['name'];\n move_uploaded_file($tmp_name, $imgName);\n $stmt->bindParam(1, $imgName, PARAM_STR);\n $stmt->bindValue(2, $event_id, PARAM_INT);\n $stmt->execute();\n }\n $this->dbh->commit();//ok, all was well, commit inserted data\n}\ncatch (PDOException $e)\n{\n $this->dbh->rollBack();//undo inserts, because not all of them were successful.\n throw $e;//rethrow, let caller deal with the exception\n}\n</code></pre>\n\n<p>Now this is looking better, I do believe. But like I said in the comments, <a href=\"http://php.net/manual/en/pdostatement.bindparam.php\" rel=\"nofollow noreferrer\"><code>bindParam</code> uses <em>references</em></a>:</p>\n\n<pre><code>public bool PDOStatement::bindParam ( mixed $parameter , mixed &$variable [, int $data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] )\n ^^ & => reference\n</code></pre>\n\n<p>, which (in a loop) can lead to unexpected behaviour from time to time, so I'd rather pass my values to <code>PDOStatement::execute</code>, if I were you:</p>\n\n<pre><code> foreach($_FILES['event-images']['tmp_name'] as $tmp_name)\n {\n $imgName = $this->imgPath . $this->random_name . $_FILES['event-images']['name'];\n move_uploaded_file($tmp_name, $imgName);\n $stmt->execute(array($imgName, $event_id));\n }\n</code></pre>\n\n<p>But for completeness' sake, here's the same thing using <code>bindParam</code> outside of the loop:</p>\n\n<pre><code>$stmt = $this->dbh->prepare(\"INSERT INTO adrenaline_junkies_uk_event_images (event_image_name, event_id) VALUES (?,?)\");\n$imgName = null;\n$stmt->bindParam(1, $imgName, PARAM_STR);\n//$event_id might fail, because this var is argument\n$stmt->bindParam(2, $event_id, PARAM_INT);\n//if it fails, try:\n$eventId = &$event_id;\n$stmt->bindParam(2, $eventId, PARAM_INT);\nforeach($_FILES['event-images']['tmp_name'] as $tmp_name)\n{ \n $imgName = $this->imgPath . $this->random_name . $_FILES['event-images']['name'];\n move_uploaded_file($tmp_name, $imgName);\n $stmt->execute();\n}\n</code></pre>\n\n<p>Lastly: You're using both <code>bindParam</code> and <code>bindValue</code> as though they both do the same thing. Now at first glance, they do, but be weary of references. <a href=\"https://stackoverflow.com/questions/17459521/what-is-better-in-a-foreach-loop-using-the-symbol-or-reassigning-based-on-k/18464019#18464019\">read this, to see why references in loops are risky</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T14:25:14.050",
"Id": "50779",
"Score": "0",
"body": "You can even move those bindParam calls outside of the foreach :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T14:30:09.683",
"Id": "50780",
"Score": "1",
"body": "@Pinoniq: That would imply using references, and IMO, it's best to avoid those in a loop (dangling references can cause unexpected behaviour)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T12:56:17.550",
"Id": "50915",
"Score": "1",
"body": "Thanks for this, learnt some new things, especially placing outside foreach and passing an array into the execute instead of binding, interesting."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T14:17:24.937",
"Id": "31855",
"ParentId": "31853",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "31855",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T13:26:51.180",
"Id": "31853",
"Score": "3",
"Tags": [
"php",
"pdo",
"image"
],
"Title": "Saving and uploading images in a database"
}
|
31853
|
<p>I've been looking into empty abstract classes and from what I have read, they are generally bad practice. I intend to use them as the foundation for a small search application that I am writing. I would write the initial search provider and others would be allowed to create their own providers as well. My code's intent is enforce relationships between the classes for anyone who would like to implement them.</p>
<p>Can someone chime in and describe why or why not this is still a bad practice and what, if any, alternatives are available?</p>
<pre><code>namespace Api.SearchProviders
{
public abstract class ListingSearchResult
{
public abstract string GetResultsAsJSON();
}
public abstract class SearchParameters
{
}
public interface IListingSearchProvider
{
ListingSearchResult SearchListings(SearchParameters p);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T17:01:02.383",
"Id": "50798",
"Score": "2",
"body": "Both your `abstract` `class`es listed could be `interface`s. And the second one could be a custom `[Attribute]`."
}
] |
[
{
"body": "<p>To build on @Jesse C. Slicer's comment above: interfaces are for defining contracts, whereas abstract classes are meant to add some base implementation code. An abstract class without any implementation code does not add anything an interface does not already provide. Even worse, it blocks inheriting from other (potentially useful) classes.</p>\n\n<p>Relationships can be defined either way.</p>\n\n<p>You are free to provide an abstract class to callers which takes care of some of the base functionality, or you can extract an abstract base class during a later re-factoring pass if you like, but your API should still stick to the interfaces as much as possible.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T17:31:03.837",
"Id": "31861",
"ParentId": "31856",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T14:50:03.870",
"Id": "31856",
"Score": "2",
"Tags": [
"c#",
"interface"
],
"Title": "Empty abstract class enforce structure"
}
|
31856
|
<p>I am currently using the following to convert <code>[url=][/url]</code> to an <a href="http://en.wikipedia.org/wiki/HTML" rel="nofollow">HTML</a> link:</p>
<pre><code>s = message.replace(/\[url=([^\]]+)\]\s*(.*?)\s*\[\/url\]/gi, "<a href='$1'>$2</a>")
</code></pre>
<p>That work's fine.</p>
<p>I then added on another replace function using a regular expression to replace <code>www</code> with <code>http://www</code> like so:</p>
<pre><code>s = message.replace(/\[url=([^\]]+)\]\s*(.*?)\s*\[\/url\]/gi, "<a href='$1'>$2</a>")
.replace(/www/g, "http://www");
</code></pre>
<p>This is probably not the best/efficient method and also does not support <code>https://</code> which is not a priority at the moment, but it is something I would like to include at some point. What could I do to improve the regular expression?</p>
<p>I asked this on Stack Overflow. However, I was informed that the type of question was not really fit for there, which I understand.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T16:04:24.547",
"Id": "50791",
"Score": "0",
"body": "No full review, but perhaps a useful pointer: [Do NOT try parsing with regular expressions](http://kore-nordmann.de/blog/do_NOT_parse_using_regexp.html) and [Q: Best way to parse bbcode (Stack Overflow)](http://stackoverflow.com/questions/488963/best-way-to-parse-bbcode)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T16:08:23.933",
"Id": "50793",
"Score": "0",
"body": "@ojdo - thanks for the info. I will definitely bare this in mind"
}
] |
[
{
"body": "<p>Like <em>ojdo</em> has pointed out, using plain regexes to parse something like BBCode is too complicated of a route to take.</p>\n\n<p>It would be too long of a task to educate you on building proper parsers, but here's a short simplified example, of how one would go on parsing something like BBCode.</p>\n\n<h2>First tokenize</h2>\n\n<p>First off, we transform the input text into some higher level data structure which we can then work on more easily. For the BBCode, let's tokenize the input into begin tags, end tags, and text in between:</p>\n\n<pre><code>function tokenize(input) {\n var m;\n var tokens = [];\n while (input.length > 0) {\n if ((m = input.match(/^\\[([a-z]+)(=([^\\]]+))?\\]/i))) {\n // start tag [foo=*]\n tokens.push({type: m[1].toLowerCase() + \"_start\", argument: m[3], raw: m[0]});\n }\n else if ((m = input.match(/^\\[\\/([a-z]+)\\]/i))) {\n // end tag [/foo]\n tokens.push({type: m[1].toLowerCase() + \"_end\", raw: m[0]});\n }\n else {\n // text between tags (this regex always matches)\n m = input.match(/^\\[?[^\\[]*/);\n tokens.push({type: \"text\", raw: m[0]});\n }\n // skip forward\n input = input.slice(m[0].length);\n }\n return tokens;\n}\n</code></pre>\n\n<p>Given an input like <code>\"[URL=google.com]click here[/URL]\"</code>, the <code>tokenize</code> function produces an array of tokens like this:</p>\n\n<pre><code>[\n { type: 'url_start', argument: 'google.com', raw: '[URL=google.com]' },\n { type: 'text', raw: 'click here' },\n { type: 'url_end', raw: '[/URL]' }\n]\n</code></pre>\n\n<h2>Then produce HTML</h2>\n\n<p>Normally one would now transform this list of tokens into a tree structure, but as the BBCode-to-HTML conversion is very one-to-one, we don't really need to, and can pass the list of tokens directly to another function that converts it to HTML:</p>\n\n<pre><code>function tokensToHtml(tokens) {\n var output = \"\";\n for (var i=0; i<tokens.length; i++) {\n var tok = tokens[i];\n\n if (tok.type === \"url_start\") {\n var url = tok.argument;\n // prepend URL-s with http:// if needed\n if (!/^https?:\\/\\//.test(url)) {\n url = \"http://\" + url;\n }\n output += \"<a href='\" + escapeHtml(url) + \"'>\";\n }\n else if (tok.type === \"url_end\") {\n output += \"</a>\";\n }\n else {\n // anything else is a text token or an unknown tag\n // which we also treat just as text\n output += escapeHtml(tok.raw);\n }\n }\n return output;\n}\n\nfunction escapeHtml(str) {\n return str.replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;');\n}\n</code></pre>\n\n<p>As can be see, we simply replace each token with corresponding HTML. When writing out the <code><a href=...</code> we also take care of prepending the <code>http://</code> as needed. Additionally we escape all HTML special chars in URL and within rest of the text - using a little <code>escapeHtml</code> utility function.</p>\n\n<p>To tie it all together:</p>\n\n<pre><code>function bbCodeToHtml(input) {\n return tokensToHtml(tokenize(input));\n}\n</code></pre>\n\n<p>It should be fairly obvious how to extend the <code>tokensToHtml</code> to support additional BBCode tags.</p>\n\n<p>One missing feature is to automatically append close tags if one would input something like <code>\"[URL=google.com]bla bla\"</code>. This is left as an exercise for the reader :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T18:57:35.377",
"Id": "31862",
"ParentId": "31859",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "31862",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T15:42:40.723",
"Id": "31859",
"Score": "2",
"Tags": [
"javascript",
"regex"
],
"Title": "JavaScript HTTP regular expression"
}
|
31859
|
<p>So I really want to have something similar to <a href="http://msdn.microsoft.com/en-us/library/dd233226.aspx">discriminated unions</a> in C#.</p>
<p>One way to do it is to use a visitor pattern, but it takes half a life to write all broilerplate code by hands.
There is another way that would allow me writing a bit less code, but it is based on delegates.</p>
<p>Consider the analogue of <a href="http://msdn.microsoft.com/en-us/library/dd233245.aspx">Options from F#</a>:</p>
<pre><code>public abstract class Optional<TValue>
{
public abstract TResult Resolve<TResult>(Func<TValue, TResult> someHandler, Func<String, TResult> noneHandler);
}
public class Some<TValue> : Optional<TValue>
{
public Some(TValue value)
{
this.Value = value;
}
public TValue Value { get; private set; }
public override TResult Resolve<TResult>(Func<TValue, TResult> someHandler, Func<String, TResult> noneHandler)
{
return someHandler(this.Value);
}
}
public class None<TValue> : Optional<TValue>
{
public None(String message)
{
this.Message = message;
}
public String Message { get; private set; }
public override TResult Resolve<TResult>(Func<TValue, TResult> someHandler, Func<String, TResult> noneHandler)
{
return noneHandler(this.Message);
}
}
public class Demo {
public Optional<Uri> ParseAbsoluteUri(String whateverUrl)
{
if (Uri.IsWellFormedUriString(whateverUrl, UriKind.Absolute))
{
var uri = new Uri(whateverUrl, UriKind.Absolute);
return new Some<Uri>(uri);
}
else
{
return new None<Uri>("Given URL is not absolute.");
}
}
public String ProcessUrl(String whateverUrl)
{
var uriOpt = this.ParseAbsoluteUri(whateverUrl);
var result = uriOpt.Resolve(uri => "Hey, your URL \"" + uri + "\" looks nice!", message => "Sorry, the URI that you gave looks bad: " + message);
return result;
}
public void Test()
{
Trace.WriteLine(this.ProcessUrl("http://google.com"));
Trace.WriteLine(this.ProcessUrl("Not url at all"));
/* output:
Hey, your URL "http://google.com/" looks nice!
Sorry, the URI that you gave looks bad: Given URL is not absolute.
*/
}
}
</code></pre>
<ol>
<li><p>Each delegate is essentially a class that the C# compiler makes to wrap the pointer to a function. So with the excessive use of such approach will I hit any sort of problems? (Bloating the size of the assembly for example?)</p></li>
<li><p>Delegates aren't the fastest things in the galaxy, especially multicasts ones, this approach uses them heavily.</p></li>
<li><p>Making a call to a virtual method lessens (if not eliminates at all) a chance for JIT inlining.</p></li>
</ol>
<p>So all in all I am a bit scared to go all the way this way due to performance concerns. I would like to know what you think of this.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T20:56:44.440",
"Id": "50826",
"Score": "1",
"body": "Options don't have a message, this is more like `Choice<T, string>`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T21:00:40.973",
"Id": "50828",
"Score": "1",
"body": "If you have performance concerns, *measure* your code in realistic situations. Only can answer whether the performance is good enough, because we don't know how exacly would you use this code or what \"good enough\" is for you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T21:08:28.173",
"Id": "50830",
"Score": "0",
"body": "I am with you about measuring the code. I cannot measure the performance until I write some code and when I measure *some* code won't give me an overall picture of how it would look like in a real project. With this in mind, basically what you are saying is that I should use it everywhere in a real project and see what happens. Sure thing that would answer the question. Is there anything we can tell about this approach before jumping into it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T22:17:30.490",
"Id": "50838",
"Score": "3",
"body": "I've been doing this for ~2 years now. ( http://bugsquash.blogspot.com/2012/01/encoding-algebraic-data-types-in-c.html ) Unless you're writing super high-performance code, you're fine. It doesn't have any real perf impact in my code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T22:23:02.090",
"Id": "50840",
"Score": "0",
"body": "Also, you'll want to make the type **closed**. Otherwise you can't really check totality."
}
] |
[
{
"body": "<p>This looks very well crafted. I don't know <a href=\"/questions/tagged/f%23\" class=\"post-tag\" title=\"show questions tagged 'f#'\" rel=\"tag\">f#</a> and I'm not really into <em>functional programming</em>, but I can enumerate everything I like about this code:</p>\n\n<ul>\n<li>Type parameter names are descriptive: <code>TValue</code> and <code>TResult</code> are perfect.</li>\n<li>The interface for <code>Optional<TValue></code> is <em>segregated</em>; it's very focused and specialized, which makes it highly reusable... which is a nice feature for an <code>abstract</code> class.</li>\n<li>Usage of <code>this</code> qualifier is consistent.</li>\n</ul>\n\n<p>Well as I enumerated these points I <em>did</em> find a few minor nitpicks:</p>\n\n<ul>\n<li>Usage of <code>this</code> qualifier is redundant.</li>\n<li>Usage of <code>String</code> could be replaced with C# language alias <code>string</code> (but then again usage of <code>String</code> is beautifully consistent).</li>\n</ul>\n\n<p>And as I enumerated these minor nitpicks I <em>did</em> find one tiny little thing that could be improved: the <code>Message</code> property in the derived types is only assigned through the constructor, using the <code>private</code> setter. I'd make it <code>readonly</code> and change the auto-property for a get-only property:</p>\n\n<pre><code>public None(String message)\n{\n _message = message;\n}\n\nprivate readonly String _message;\npublic String Message { get { return _message; } }\n</code></pre>\n\n<p>...and this is where I'm clashing with <code>this</code> - I prefer prefixing private fields with an underscore and avoid <code>this</code> altogether, you might have it like this instead:</p>\n\n<pre><code>public None(String message)\n{\n this.message = message;\n}\n\nprivate readonly String message;\npublic String Message { get { return this.message; } }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T15:41:06.093",
"Id": "46936",
"ParentId": "31864",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T19:07:51.550",
"Id": "31864",
"Score": "8",
"Tags": [
"c#",
"f#"
],
"Title": "Discriminated-unions in C#"
}
|
31864
|
<p>So I'm implementing a linked list in Java, and so far it looks like this:</p>
<pre><code>public class List <T> {
private class Node {
T value;
Node next;
}
private Node node_at(int n) {
Node seeker = front;
for (int i = 0; i < n; i++) {
seeker = seeker.next;
}
return seeker;
}
Node front;
int length;
public int length() {
return length;
}
public void insert(int index, T o) {
if (index == 0) {
Node n = new Node();
n.value = o;
n.next = node_at(0);
front = n;
} else {
Node n1 = node_at(index-1);
Node n2 = new Node();
n2.next = n1.next;
n1.next = n2;
n2.value = o;
}
length++;
}
public void append(T o) {
Node n = node_at(length);
n.value = o;
n.next = new Node();
length++;
}
public void append(List<T> l) {
node_at(length-1).next = l.front; // specific area of interest
length += l.length;
}
public T at(int n) {
Node seeker = node_at(n);
return seeker.value;
}
List() {
length = 0;
front = new Node();
}
}
</code></pre>
<p>The line that I marked <code>specific area of interest</code> is effectively cutting off a node (the last node in the receiver), leaving it homeless. Is that node going to get garbage collected?</p>
|
[] |
[
{
"body": "<p>Yes, in theory. That depends on when the garbage collector decides to run. (There are lots of great explanations about <a href=\"https://stackoverflow.com/a/18297597/1435657\">how finicky it is</a> on Stack Overflow.) But it will become <em>eligible</em> for garbage collection and is gone for all intents and purposes. Data becomes eligible for garbage collection when no references to it exist, and, assuming <code>node_at(length-1).next</code> is the only reference to it, the <code>Node</code> then qualifies once you change that reference.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T23:57:38.737",
"Id": "50852",
"Score": "0",
"body": "What would happen if I had 100 or so items in my list, and then I did `front = new Node();`? Would it take a long time for the GC to find all the objects and destroy them since the last element wouldn't become eligible for destruction until every other element before it was destroyed? And if so is there a better way for me to delete the contents of my list?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T00:00:06.740",
"Id": "50853",
"Score": "0",
"body": "@anthropomorphic The GC in general is pretty smart. My guess would be that it would immediately \"know\" that all 100 of those `Node`s were \"dead\", but I don't know for sure. It also wouldn't bother even attempting to reclaim the memory until the memory was needed, or if the JVM was just hanging out, not doing much, with spare clock cycles. Haha"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T00:02:20.297",
"Id": "50854",
"Score": "0",
"body": "@anthropomorphic Actually, [here's a SO question about exactly that](http://stackoverflow.com/questions/6935579/garbage-collection-orphaned-linkedlist-links)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T23:53:16.193",
"Id": "31876",
"ParentId": "31868",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "31876",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T20:02:17.127",
"Id": "31868",
"Score": "4",
"Tags": [
"java",
"linked-list",
"garbage-collection"
],
"Title": "Linked List in Java (Garbage Collection)"
}
|
31868
|
<blockquote>
<p>A palindromic number reads the same both ways. The largest palindrome
made from the product of two 2-digit numbers is 9009 = 91 × 99.</p>
<p>Find the largest palindrome made from the product of two 3-digit
numbers.</p>
</blockquote>
<p>How would you improve the following code?</p>
<p>I'm looking specifically for:</p>
<ul>
<li>performance optimizations </li>
<li>ways to shorten the code </li>
<li>more "pythonic" ways to write it</li>
</ul>
<hr>
<pre><code> def is_palindrome(num):
return str(num) == str(num)[::-1]
def fn(n):
max_palindrome = 1
for x in range(n,1,-1):
if x * n < max_palindrome:
break
for y in range(n,x-1,-1):
if is_palindrome(x*y) and x*y > max_palindrome:
max_palindrome = x*y
elif x * y < max_palindrome:
break
return max_palindrome
print fn(999)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T01:16:49.767",
"Id": "51050",
"Score": "1",
"body": "whenever a `product` or `combination` or `permutation` is mentioned, i'd check `itertools` first"
}
] |
[
{
"body": "<p>It looks good to me.</p>\n\n<p>You could break from the inner loop even if x*y == max to avoid 1) an additional useless iteration 2) checking if it is a palindrome. Also it would remove some code testing the value of the product.</p>\n\n<p>I think you could change the limits of the inner loop to consider only y smaller or equal to x. If you do so, you can break out of the outer loop if x*x < max.</p>\n\n<p><strong>Edit :</strong></p>\n\n<p>Some more details. My second optimisation tips is not a really a good tip, it's not a bad tip neither.</p>\n\n<p>Here is the function before and after taking my second comment into action. Also, some more basic code has been added for benchmarking purposes.</p>\n\n<pre><code>def fn(n):\n itx,ity = 0, 0\n max_palindrome = 1\n for x in range(n,1,-1):\n itx+=1\n if x * n < max_palindrome:\n break\n for y in range(n,x-1,-1):\n ity+=1\n if is_palindrome(x*y) and x*y > max_palindrome:\n max_palindrome = x*y\n elif x * y < max_palindrome:\n break\n print \"1\", n,itx,ity,max_palindrome\n return max_palindrome\n\ndef fn2(n):\n itx,ity = 0, 0\n max_palindrome = 1\n for x in range(n,1,-1):\n itx+=1\n if x * x <= max_palindrome:\n break\n for y in range(x,1,-1):\n ity+=1\n if x*y <= max_palindrome:\n break\n if is_palindrome(x*y):\n max_palindrome = x*y\n break\n print \"2\", n,itx,ity,max_palindrome\n return max_palindrome\n</code></pre>\n\n<p>Now, when running the following tests :</p>\n\n<pre><code>for n in [99,999,9999,99999,999999]:\n assert fn(n) == fn2(n)\n</code></pre>\n\n<p>fn is sometimes in a pretty epic way, sometimes just worse...</p>\n\n<pre><code>fn n itx ity result\n1 99 10 38 9009\n2 99 6 29 9009\n1 999 93 3242 906609\n2 999 48 6201 906609\n1 9999 100 4853 99000099\n2 9999 51 2549 99000099\n1 99999 339 50952 9966006699\n2 99999 171 984030 9966006699\n1 999999 1000 498503 999000000999\n2 999999 501 250499 999000000999\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T22:33:54.197",
"Id": "50842",
"Score": "1",
"body": "are you sure the second optimization is correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T23:43:27.167",
"Id": "50851",
"Score": "0",
"body": "Assuming x goes from n to 0 and y goes from x to 0, I think we have the following property: 1) for a given x, x*y is decreasing 2) if x*x <= max, x*y <= x*x <= max."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T01:11:19.757",
"Id": "50858",
"Score": "0",
"body": "y is in the range [n..x-1]. y*x > x*x for y > x"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T03:38:06.330",
"Id": "50863",
"Score": "0",
"body": "This is why I think you could/should change the range you are using for y and consider only 0 <= y <= x except if you have a reason not to."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T04:40:10.653",
"Id": "50866",
"Score": "1",
"body": "that's a change which leads to an incorrect algorithm (as written above, it would miss some of the larger palindromes, including the correct solution). It would be an effective optimization if i was writing an algorithm looking for the smallest palindrome, though"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T22:49:44.997",
"Id": "51108",
"Score": "1",
"body": "I've added more details about what I had in mind."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T13:48:32.780",
"Id": "51161",
"Score": "0",
"body": "Both the functions you are testing above are incorrect. Remove your optimization from my version of the function, and test that against your version."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T14:06:02.760",
"Id": "51164",
"Score": "0",
"body": "I am not sure which optimisation you are talking about. I've tried copy pasting your version and I do get the same results. Please let me know if I've missed something."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T14:15:17.983",
"Id": "51165",
"Score": "0",
"body": "sorry, misread the code, your algorithms are correct"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T19:38:17.610",
"Id": "51189",
"Score": "0",
"body": "No worries. Can my answer be upvoted so that it doesn't get a negative reputation whilst being mostly right ?"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T22:24:31.960",
"Id": "31871",
"ParentId": "31869",
"Score": "1"
}
},
{
"body": "<p>The function <code>is_palindrome</code> converts <code>num</code> to a string twice. You might consider:</p>\n\n<pre><code>def is_palindrome(n):\n \"\"\"Return True if n is a palindrome; False otherwise.\"\"\"\n s = str(n)\n return s == s[::-1]\n</code></pre>\n\n<p>And then for the main loop I would write:</p>\n\n<pre><code>from itertools import product\nmax(x * y for x, y in product(range(1000), repeat=2) if is_palindrome(x * y))\n</code></pre>\n\n<p>This runs in less than a second so I think it is not worth putting lots of effort into optimizing it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T22:40:14.607",
"Id": "31872",
"ParentId": "31869",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "31872",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-26T21:23:09.750",
"Id": "31869",
"Score": "2",
"Tags": [
"python",
"optimization",
"project-euler"
],
"Title": "Project Euler #4 - Largest Palindrome Product"
}
|
31869
|
<p>I have the following code (it looks long but it's not too bad):</p>
<pre><code>function evaluate_cards(hand){
var hand_length = hand.length;
var num_of_sets = 0;
var num_of_runs = 0;
var cards_in_run = 0;
var suit = '';
var buckets = {
three_bucket: [],
four_bucket: [],
five_bucket: [],
six_bucket: [],
seven_bucket: [],
eight_bucket: [],
nine_bucket: [],
ten_bucket: [],
j_bucket: [],
q_bucket: [],
k_bucket: [],
w_bucket: [] //bucket for wilds
}
for(var i = 0; i < hand_length; i++){
if(hand[0].is_wild){
buckets.w_bucket.push(hand.splice(0, 1));
}else if(hand[0].value == 3){
buckets.three_bucket.push(hand.splice(0, 1));
}else if(hand[0].value == 4){
buckets.four_bucket.push(hand.splice(0, 1));
}else if(hand[0].value == 5){
buckets.five_bucket.push(hand.splice(0, 1));
}else if(hand[0].value == 6){
buckets.six_bucket.push(hand.splice(0, 1));
}else if(hand[0].value == 7){
buckets.seven_bucket.push(hand.splice(0, 1));
}else if(hand[0].value == 8){
buckets.eight_bucket.push(hand.splice(0, 1));
}else if(hand[0].value == 9){
buckets.nine_bucket.push(hand.splice(0, 1));
}else if(hand[0].value == 10){
buckets.ten_bucket.push(hand.splice(0, 1));
}else if(hand[0].value == 11){
buckets.j_bucket.push(hand.splice(0, 1));
}else if(hand[0].value == 12){
buckets.q_bucket.push(hand.splice(0, 1));
}else if(hand[0].value == 13){
buckets.k_bucket.push(hand.splice(0, 1));
}
}
for(var k in buckets){
if(buckets.hasOwnProperty(k)){
if(buckets[k].length >= 3 && buckets[k] != buckets.w_bucket){
num_of_sets++;
}else if(buckets.w_bucket.length > 0 && buckets[k].length == 2){
buckets[k].push(buckets.w_bucket.shift());
num_of_sets++;
}else if(buckets[k].length < 3 && buckets.w_bucket.length > 1){
for(var i = 0; i < buckets.w_bucket.length; i++){
buckets[k].push(buckets.w_bucket.shift());
}
if(buckets[k].length >= 3){
num_of_sets++;
}
}else if(num_of_sets == 0){
if(buckets[k].length > 0){
if(suit == ''){
suit = buckets[k][0].suit;
}else if(suit == buckets[k][0].suit){
cards_in_run++;
}else{
suit = '';
}
if(cards_in_run != 0 && cards_in_run < 3 && buckets.w_bucket.length != 0){
cards_in_run++;
}
}
if(cards_in_run >= 3){
num_of_runs++;
cards_in_run = 0;
}
}
}
}
return {'runs':num_of_runs, 'sets': num_of_sets};
}
</code></pre>
<p>It's based off of the second answer to this question on <a href="https://gamedev.stackexchange.com/questions/49302/determining-poker-hands">game-dev.se</a>. There are two major differences, however.</p>
<ol>
<li>There are wilds in my game, which makes finding things like runs much more difficult.</li>
<li>Most sets/runs are going to be 3 or four cards but could be up to 5 cards, obviously anything 6 and over can be divided (set or run has to be a minimum of 3 cards).</li>
</ol>
<p>The following is passed a hand will determine almost all sets of three cards, but only a few runs. </p>
<p>My request is that it be reviewed for optimization and where my logic goes wrong with runs. I'm totally open to any suggestions. </p>
|
[] |
[
{
"body": "<p>Your sorting of cards to buckets takes a lot of code, which is because the names of your buckets don't match with the names of cards. The cards have just numeric values (10, 11), while buckets are named with words (ten_bucket, j_bucket). I would represent the cards as such:</p>\n\n<pre><code>{kind: 3, suit: \"club\"},\n{kind: 10, suit: \"heart\"},\n{kind: \"K\", suit: \"spade\"},\n{wild: true},\n</code></pre>\n\n<p>And then I could write a much simpler algorithm for putting them to buckets:</p>\n\n<pre><code>var wilds = [];\nvar kinds = {3:[], 4:[], 5:[], 6:[], 7:[], 8:[], 9:[], 10:[], J:[], Q:[], K:[]};\n\nhand.forEach(function(card) {\n if (card.wild) {\n wilds.push(card);\n } else {\n kinds[card.kind].push(card);\n }\n});\n</code></pre>\n\n<p>I'm also handling the wild cards as a completely separate category, which makes it much easier to check if we have three-of-a-kind:</p>\n\n<pre><code>for (var k in kinds){\n if (kinds.hasOwnProperty(k)){\n if (kinds[k].length + wilds.length >= 3) {\n // Yes, we have a three-of-a-kind\n }\n }\n}\n</code></pre>\n\n<h2>Checking for runs</h2>\n\n<p>A basic check for runs is quite simple. You just loop through all the buckets in order and check for the longest sequence without holes:</p>\n\n<pre><code>function longest_run() {\n var count = 0;\n var max_run = 0;\n [\"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\", \"K\"].forEach(function(k) {\n if (kinds[k].length >= 1) {\n count += 1;\n } else {\n if (count > max_run) {\n max_run = count;\n }\n count = 0;\n }\n });\n return max_run;\n}\n</code></pre>\n\n<p>But taking the wild cards into account complicates the whole thing considerably. Now it really becomes a question of combinatorics. A brute-force approach would be to try using the wildcards in each of the empty positions. This can be optimized of course, but <strong>I suggest you turn to StackOverflow</strong> with this question - some math-minded people might be able to provide you with a better algorithm over there.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T19:48:47.700",
"Id": "50953",
"Score": "0",
"body": "Thanks, I hadn't thought of that, though my card structure was already set up for me to do so. Do you have any thoughts on checking for runs? That's really where my logic has an issue."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T11:00:34.580",
"Id": "51149",
"Score": "0",
"body": "I've updated the answer with an example for finding runs, though further discussion of this is better suited for StackOverflow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T14:39:34.980",
"Id": "51169",
"Score": "0",
"body": "There's not much benefit to having an array of `{wild: true}` objects over having a simple integer count."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T07:57:21.720",
"Id": "31890",
"ParentId": "31878",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "31890",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T02:20:39.230",
"Id": "31878",
"Score": "3",
"Tags": [
"javascript",
"playing-cards"
],
"Title": "JavaScript card game and hand evaluation"
}
|
31878
|
<p>This is a class I implemented that can be thought of as a highly specialized version of <code>std::list<></code> for pointers. It provides the additional feature that the elements can be removed in constant time with the element alone. This is accomplished with an <code>std::unordered_map<></code> to associate list elements with their <code>iterator</code>.</p>
<p>I would appreciate any suggestions for improvement. I am particularly keen to know if there is a better way to enforce that the template parameter has to be a pointer type. The class currently does not work for <code>std::unique_ptr<></code>, so any thoughts on what needs to be done on that front would be great. Also, if there is just a plain better way of doing the same thing, I would welcome those thoughts as well.</p>
<pre><code>template <typename, typename> class ptr_list;
class ptr_list_helper {
template <typename, typename> friend class ptr_list;
typedef std::true_type true_type;
template <typename T> struct is_ptr : std::is_pointer<T> {};
template <typename T> struct is_ptr<std::shared_ptr<T>> : true_type {};
template <typename T> struct is_ptr<std::unique_ptr<T>> : true_type {};
struct void_ptr {
void *p_;
void_ptr (void *p = 0) : p_(p) {}
template <typename T>
operator T * () const { return static_cast<T *>(p_); }
template <typename T>
operator const T * () const { return static_cast<T *>(p_); }
bool operator < (const void_ptr &p) const { return p_ < p.p_; }
bool operator == (const void_ptr &p) const { return p_ == p.p_; }
};
struct const_void_ptr {
const void *p_;
const_void_ptr (const void *p = 0) : p_(p) {}
template <typename T>
operator const T * () const { return static_cast<T *>(p_); }
bool operator < (const const_void_ptr &p) const { return p_ < p.p_; }
bool operator == (const const_void_ptr &p) const { return p_ == p.p_; }
};
template <typename T>
struct hash {
std::ptrdiff_t operator () (T p) const {
return reinterpret_cast<std::ptrdiff_t>(p.p_);
}
};
template <typename T> struct traits;
template <typename T> struct traits<T *> {
typedef std::list<void_ptr> ListImpl;
typedef T Type;
typedef T *RealPtrType;
typedef T *RefType;
static RealPtrType get (RefType ptr) { return ptr; }
};
template <typename T> struct traits<const T *> {
typedef std::list<const_void_ptr> ListImpl;
typedef T Type;
typedef const T *RealPtrType;
typedef const T *RefType;
static RealPtrType get (RefType ptr) { return ptr; }
};
template <typename T> struct traits<std::shared_ptr<T>> {
typedef std::list<std::shared_ptr<T>> ListImpl;
typedef T Type;
typedef T *RealPtrType;
typedef const std::shared_ptr<T> &RefType;
static RealPtrType get (RefType ptr) { return ptr.get(); }
};
template <typename T> struct traits<std::unique_ptr<T>> {
typedef std::list<std::unique_ptr<T>> ListImpl;
typedef T Type;
typedef T *RealPtrType;
typedef const std::unique_ptr<T> &RefType;
static RealPtrType get (RefType ptr) { return ptr.get(); }
};
template <typename PtrType, typename Allocator> struct impl {
typedef traits<PtrType> Traits;
typedef typename Traits::ListImpl ListImpl;
typedef typename ListImpl::iterator SelfType;
typedef typename ListImpl::const_iterator ConstSelfType;
typedef typename Traits::Type Type;
typedef const_void_ptr KeyPtrType;
typedef hash<KeyPtrType> MapHash;
typedef std::equal_to<KeyPtrType> MapEqual;
typedef std::pair<const KeyPtrType, SelfType> MapPair;
typedef typename Allocator::template rebind<MapPair>::other
MapAllocator;
typedef std::unordered_map<KeyPtrType, SelfType,
MapHash, MapEqual, MapAllocator> SelfMap;
typedef typename Traits::RefType RefType;
static const Type * get (RefType p) { return Traits::get(p); }
class Iterator {
friend class ptr_list<PtrType, Allocator>;
ConstSelfType self_;
bool eq (const Iterator &i) const { return self_ == i.self_; }
public:
Iterator () : self_() {}
Iterator (SelfType s) : self_(s) {}
Iterator (ConstSelfType s) : self_(s) {}
operator RefType () const { return *self_; }
RefType operator -> () const { return *self_; }
Type & operator * () const { return **self_; }
const Iterator & operator ++ () { ++self_; return *this; }
const Iterator & operator -- () { --self_; return *this; }
Iterator operator ++ (int) { return self_++; }
Iterator operator -- (int) { return self_--; }
Iterator next () const { ConstSelfType s(self_); return ++s; }
Iterator prev () const { ConstSelfType s(self_); return --s; }
operator bool () const { return *self_; }
bool operator == (const Iterator &i) const { return eq(i); }
bool operator != (const Iterator &i) const { return !eq(i); }
};
class Rotareti {
Iterator iter_;
Iterator cur () const { return iter_.prev(); }
bool eq (const Rotareti &i) const { return iter_ == i.iter_; }
public:
Rotareti () : iter_() {}
Rotareti (Iterator i) : iter_(i) {}
operator RefType () const { return cur(); }
RefType operator -> () const { return cur(); }
Type & operator * () const { return *cur(); }
const Rotareti & operator ++ () { --iter_; return *this; }
const Rotareti & operator -- () { ++iter_; return *this; }
Rotareti operator ++ (int) { return iter_--; }
Rotareti operator -- (int) { return iter_++; }
Rotareti next () const { return iter_.prev(); }
Rotareti prev () const { return iter_.next(); }
operator bool () const { return cur(); }
bool operator == (const Rotareti &i) const { return eq(i); }
bool operator != (const Rotareti &i) const { return !eq(i); }
Iterator base () const { return iter_; }
};
};
};
template <typename PtrType, typename Allocator = std::allocator<PtrType>>
class ptr_list {
static_assert(ptr_list_helper::is_ptr<PtrType>::value,
"ptr_list requires pointer type");
static_assert(std::is_copy_constructible<PtrType>::value,
"ptr_list requires copying");
typedef typename ptr_list_helper::template impl<PtrType, Allocator> Traits;
typedef typename Traits::Type Type;
typedef typename Traits::RefType RefType;
typedef typename Traits::ListImpl ListImpl;
typedef typename Traits::SelfMap SelfMap;
ListImpl impl_;
SelfMap selfmap_;
static const Type * ptr (RefType p) { return Traits::get(p); }
ptr_list & replace (const ptr_list &l, bool clear_map = false) {
if (clear_map) selfmap_.clear();
impl_ = l.impl_;
for (auto x = impl_.begin(); x != impl_.end(); ++x) {
selfmap_[ptr(*x)] = x;
}
return *this;
}
public:
typedef typename Traits::Iterator iterator;
typedef typename Traits::Rotareti reverse_iterator;
typedef iterator const_iterator;
typedef reverse_iterator const_reverse_iterator;
typedef PtrType value_type;
typedef RefType reference;
typedef typename ListImpl::size_type size_type;
typedef typename ListImpl::difference_type difference_type;
typedef typename ListImpl::pointer pointer;
typedef typename ListImpl::const_pointer const_pointer;
typedef Allocator allocator_type;
ptr_list () : impl_(), selfmap_() {}
ptr_list (const ptr_list &l) : impl_(), selfmap_() { replace(l); }
ptr_list & operator = (const ptr_list &l) { return replace(l, true); }
allocator_type get_allocator () const { return impl_.get_allocator(); }
iterator begin () const { return impl_.begin(); }
iterator end () const { return impl_.end(); }
const_iterator cbegin () const { return impl_.cbegin(); }
const_iterator cend () const { return impl_.cend(); }
reverse_iterator rbegin () const { return end(); }
reverse_iterator rend () const { return begin(); }
const_reverse_iterator crbegin () const { return cend(); }
const_reverse_iterator crend () const { return cbegin(); }
void clear () { selfmap_.clear(); impl_.clear(); }
iterator find (RefType p) const {
auto x = selfmap_.find(ptr(p));
return (x != selfmap_.end() ? x->second : end());
}
iterator insert (iterator where, RefType p) {
typename SelfMap::iterator x = selfmap_.find(ptr(p));
if (x == selfmap_.end()) {
typename SelfMap::value_type v(ptr(p), impl_.end());
x = selfmap_.insert(v).first;
} else {
impl_.erase(x->second);
}
auto w = selfmap_.find(ptr(where));
return x->second = ((w != selfmap_.end())
? impl_.insert(w->second, p)
: impl_.insert(impl_.end(), p));
}
iterator erase (RefType p) {
auto x = selfmap_.find(ptr(p));
if (x == selfmap_.end()) return end();
selfmap_.erase(x);
return impl_.erase(x->second);
}
RefType front () const { return begin(); }
RefType back () const { return end().prev(); }
void push_front (RefType p) { insert(begin(), p); }
void push_back (RefType p) { insert(end(), p); }
void pop_front () { erase(front()); }
void pop_back () { erase(back()); }
bool empty () const { return impl_.empty(); }
bool contains (RefType p) const { return find(p) != end(); }
size_type size () const { return impl_.size(); }
size_type max_size () const { return impl_.max_size(); }
void swap (ptr_list &other) {
selfmap_.swap(other.selfmap_);
impl_.swap(other.impl_);
}
void splice (iterator where, ptr_list &other) {
auto i = other.impl_.begin();
while (i != other.impl_.end()) {
PtrType x(*i++);
insert(where, x);
}
other.clear();
}
void remove (RefType p) { erase(p); }
template <typename Predicate> void remove_if (Predicate p) {
auto i = impl_.begin();
while (i != impl_.end()) {
PtrType x(*i++);
if (p(x)) remove(x);
}
}
void reverse () { impl_.reverse(); }
void sort () { impl_.sort(); }
template <typename Compare> void sort (Compare c) { impl_.sort(c); }
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T13:53:18.213",
"Id": "51072",
"Score": "0",
"body": "Have you tried [Boost.MultiIndex](http://www.boost.org/doc/libs/1_54_0/libs/multi_index/doc/index.html)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T16:47:24.290",
"Id": "51081",
"Score": "0",
"body": "@TemplateRex: Never heard of it before now. So, my class is like a `multi_index_container` of pointers that has a `hashed_unique` index?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T16:50:54.047",
"Id": "51083",
"Score": "0",
"body": "Actually, the pointers are an implementation detail that Boost abstracts away. I'll write a proper answer later tonight."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T17:25:33.903",
"Id": "51085",
"Score": "0",
"body": "@TemplateRex: Looking forward to it, but realize I need it to be a container of pointers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T18:34:02.650",
"Id": "51088",
"Score": "0",
"body": "Which is the fundamental requirement? To have a `std::list<T*>`, and to add `O(1)` removal on top of that? Or, to have a `std::multiset<T>`, and to add bidirectional iteration on top of that? I just want to make sure that your pointer requirement is actually required or if you think you need that to efficiently implement the removal."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T19:07:08.583",
"Id": "51090",
"Score": "0",
"body": "@TemplateRex: The intention of the data structure is to replace homegrown lists where the item is defined to have its own next and previous pointers (the item is its own iterator). This is used in cases where the item is managed, but is itself an active component that has some say on how it is managed. So the item itself needs to be able to remove itself from the list efficiently."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T19:50:22.900",
"Id": "51092",
"Score": "0",
"body": "@TemplateRex: Also, this is not a `multiset`, the pointer is only allowed to be added to the list once."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T19:53:33.530",
"Id": "51093",
"Score": "0",
"body": "OH, so you have unique elements in your list?"
}
] |
[
{
"body": "<p>I think this problem screams out for Boost.MultiIndex. It allows to add multiple indices to a container. In your case, you seem to want both a <code>std::list<T></code> and a <code>std::unordered_set</code> interface. In Boost.MultiIndex, these index types are called <code>sequenced</code> and <code>hashed_unique</code>. A simple template definition would be </p>\n\n<pre><code>template<class T>\nusing my_container = multi_index_container<\n T,\n indexed_by<\n sequenced<>,\n hashed_unique< identity<T> >,\n >\n>;\n</code></pre>\n\n<p>The <a href=\"http://www.boost.org/doc/libs/1_54_0/libs/multi_index/doc/index.html\" rel=\"nofollow\">documentation</a> of Boost.MultiIndex is one of the best of all the Boost libraries, so you should be able to work out how to iterate over this container, and how to insert/erase elements. The library will guarantee you amortized <code>O(1)</code> insertion/erasure, as well as bidirectional iteration and <code>O(1)</code> splicing and <code>O(N log N)</code> sorting. </p>\n\n<p>If you wonder how this is implemented, there is a <a href=\"http://www.boost.org/doc/libs/1_54_0/libs/multi_index/doc/performance.html#simulation\" rel=\"nofollow\">special section</a> about that in the docs. I think that this is much better than to build your own container. Writing proper containers (with correct complexity, exception safety, resource management and move semantics) is very hard. Leveraging high-quality libraries should be your first priority.</p>\n\n<p>BTW, here's a somewhat related <a href=\"http://timday.bitbucket.org/lru.html\" rel=\"nofollow\">in-depth discussion</a> of various ways to write an LRU-cache, starting with using combinations of STL containers and ending with Boost.Bimap (which is a special case of Boost.MultIndex). It shows how many of the pointer manipulations of hand-written solutions are quite intricate to get correct and efficient.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T20:25:32.307",
"Id": "31995",
"ParentId": "31886",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T06:51:17.380",
"Id": "31886",
"Score": "3",
"Tags": [
"c++",
"c++11",
"pointers"
],
"Title": "list class for pointers with constant time item removal"
}
|
31886
|
<p>I want to know how I can improve this piece of JS with respect to best practices/performance.</p>
<p><strong>JS</strong></p>
<pre><code>var treeGroupTypes, treeType, leftLeafClass, rightLeafClass;
treeGroupTypes = ["tree-group-small", "tree-group-avg", "tree-group-large", "tree-group-large", "tree-group-avg", "tree-group-small", "tree-group-small", "tree-group-avg", "tree-group-large", "tree-group-large", "tree-group-avg", "tree-group-small"];
treeType = ["small-tree", "avg-tree", "large-tree"];
leftLeafClass = "left-leaf";
rightLeafClass = "right-leaf";
//Both the above arrays have css classes in them, and then the 2 variables as well. Basically the whole js codes builds some trees and appends leaves to them.
buildTrees(treeGroupTypes, treeType, leftLeafClass, rightLeafClass);
buildTrees: function (treeGroupTypes, treeType, leftLeafClass, rightLeafClass) {
for (j = 0; j < treeGroupTypes.length; j++) {
var treeGroup;
treeGroup = $(document.createElement("div"));
treeGroup.addClass(treeGroupTypes[j]).appendTo(".trees")
for (i = 0; i < treeType.length; i++) {
var leftLeaf, rightLeaf, leftIcon, rightIcon;
leftLeaf = $(document.createElement("span"));
rightLeaf = leftLeaf.clone();
leftIcon = $(document.createElement("i"));
rightIcon = leftIcon.clone();
leftLeaf.addClass(leftLeafClass).append(leftIcon);
rightLeaf.addClass(rightLeafClass).append(rightIcon);
var tree = $(document.createElement("div"));
tree.addClass(treeType[i]).appendTo(treeGroup);
leftLeaf.appendTo(tree);
if (treeGroupTypes[j] == "tree-group-large" && treeType[i] == "large-tree") {
for (l = 1; l < 4; l++) {
var more = rightLeaf.clone();
more.css("top", (tree.height() / 4) * l).appendTo(tree)
}
}
else if (treeGroupTypes[j] == "tree-group-avg" && treeType[i] == "large-tree") {
for (l = 1; l < 3; l++) {
var more = rightLeaf.clone();
more.css("top", ((tree.height() / 3) * l) + 10).appendTo(tree)
}
}
else {
rightLeaf.css("top", tree.height() / 3).appendTo(tree)
}
}
}
}
</code></pre>
<p><strong>CSS required:</strong></p>
<p>There are 3 tree groups - avg, large, small, as per height, shown in the Fiddle. By group, it means it has 3 trees in this together and those 3 trees in each group are further sub divided as large-tree, avg-tree, small-tree.</p>
<pre><code>.trees { padding:0 10px;}
.tree-group-avg {margin:0 8px; display:inline-block;}
.tree-group-avg div {position:relative; display:inline-block; margin:0 10px 0 0; background:#83919F; width:2px; vertical-align:bottom;}
.tree-group-avg .large-tree { height:120px; }
.tree-group-avg .avg-tree { height:90px;}
.tree-group-avg .small-tree { height:60px;}
.tree-group-large {margin:0 8px; display:inline-block;}
.tree-group-large div {position:relative; display:inline-block; margin:0 10px 0 0; background:#83919F; width:2px; vertical-align:bottom;}
.tree-group-large .large-tree { height:150px; }
.tree-group-large .avg-tree { height:120px;}
.tree-group-large .small-tree { height:90px;}
.tree-group-small {margin:0 8px; display:inline-block;}
.tree-group-small div {position:relative; display:inline-block; margin:0 10px 0 0; background:#83919F; width:2px; vertical-align:bottom;}
.tree-group-small .large-tree { height:90px; }
.tree-group-small .avg-tree { height:60px;}
.tree-group-small .small-tree { height:30px;}
</code></pre>
<p>Below are the leaf classes which are attached to tree, left leaf class means it will be on left side of tree and right leaf on right side</p>
<pre><code>.left-leaf i{width:10px; height:10px; border-radius:0 10px 0 10px; display:inline-block; background:#ACCF37; position:relative;behavior: url(css/PIE.htc); }
.left-leaf {position:absolute; left:-10px;}
.right-leaf i{width:10px; height:10px; border-radius:10px 0 10px 0; display:inline-block; background:#ACCF37; position:relative; behavior: url(css/PIE.htc);}
.right-leaf {position:absolute;}
</code></pre>
<p><strong>HTML:</strong></p>
<pre><code><section class="trees"></section>
</code></pre>
<p><a href="http://jsfiddle.net/5NrfQ/" rel="nofollow">jsfiddle</a></p>
|
[] |
[
{
"body": "<p>I am using color codes for clarity of my explanation, not suggesting you use them in the code.</p>\n\n<p><img src=\"https://i.stack.imgur.com/sdd25.png\" alt=\"trees\"></p>\n\n<p>As the image is static. Just use a set code.</p>\n\n<p>You have 5 tree heights:<br>\nred, green, yellow, blue (=orange), purple </p>\n\n<pre><code>Tree.size 1 2 3 4 5 \n</code></pre>\n\n<p>You have 5 left leaf, 4 right leaf </p>\n\n<pre><code>leaf.left 1 2 3 4 5 \nleaf.right 1 2 3 4 \n\nred tree = .size1 + leaf.left1 + leaf.right1.\ngreen tree = .size2 + leaf.left2 + leaf.right2 //..etc\n</code></pre>\n\n<p>Using the classes in css. </p>\n\n<pre><code> red tree\n green tree\n yellow tree\n space\n green tree\n yellow tree\n blue tree\n space //..etc\n</code></pre>\n\n<p>You know how to code, just use the above algorithm.</p>\n\n<p>To change the width of the trunks, just add change to format accordingly.</p>\n\n<p>Honestly, your ability to loop shows you have a talent, and put a lot of thought into your code. But in this case, where you are producing a static image, it is over complicated and unnecessary. Save your code for situations, where you require user input; I am sure it could be modified to be useful for a more dynamic website.</p>\n\n<p>You can achieve the same result using css and no js. I think the use of js is an overkill. With websites, if you can achieve the same result will good css, I think (my opinion) that it is the better way to go. Back in the day js was treated suspiciously and often disabled on web browser, but this is less so the case now. However, I would recommend, that if you can achieve the same result using css, I wouldn't code such a thing using js. </p>\n\n<p>Personally, I would reserve js for client side validation, or interaction in a dynamic website. Not for producing a static image.</p>\n\n<p>My opinion.</p>\n\n<p><em>Edit</em><br>\nAlso, you have a lot of nested looping going on.. and I haven't addressed that in this answer, I am sure that could be optimised.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T09:27:20.700",
"Id": "50884",
"Score": "0",
"body": "well, just to confirm, that when you say use a set code, would you mean just use html/css with the above mentioned algo to create the image, instead of doing it through js."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T09:30:41.930",
"Id": "50885",
"Score": "0",
"body": "@whyAto8 yes, I just edited my answer to address this and why I wouldn't use js.. sorry, I should've been more explicit from the outset.. I think you are very capable, but sometimes restraint and a simpler method is better.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T09:31:02.387",
"Id": "50886",
"Score": "0",
"body": "As I said, keep your code.. it will be useful for something else, I am sure"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T09:38:54.273",
"Id": "50895",
"Score": "0",
"body": "Thanks a lot for that info. My first attempt at doing this was only through html/css and no js, but then I thought of that I would end up writing a lot of html elements for this, so would it make sense to use js and loop it through. I did raise a question on this :http://stackoverflow.com/questions/18975586/html-or-js-to-create-large-amount-of-similar-html-tags-in-a-page , hence I went ahead with js solution. I am still kindda confused, what to do. I am ready with both the solutions though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T09:42:11.707",
"Id": "50898",
"Score": "0",
"body": "@whyAto8 this is one answer, one opinion.. why don't you try to write it (or part of it) using css, and see if it seems less complicated.. I am happy to come back to this with you and look at coding it.. I just have to go now"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T09:42:49.600",
"Id": "50899",
"Score": "0",
"body": "@whyAto8 my daughter turned 12 yesterday and we are preparing for her birthday party tomorrow.. but I will pop in again in a few hours :) let me know how u are getting on"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T09:44:30.917",
"Id": "50900",
"Score": "0",
"body": "I agree with this http://stackoverflow.com/a/18975747/2776866 in this case you are creating a static image.."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T09:19:04.343",
"Id": "31894",
"ParentId": "31892",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T08:30:40.853",
"Id": "31892",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "Drawing a picture of some trees using JavaScript"
}
|
31892
|
<p>Just want to know if this is safe way to clone arrays and plain objects avoiding infinite loops trigger by circular refrences:</p>
<pre><code>//
!(( function ( methodName, dfn ) {
// add global 'clone' method identifier
this[methodName] = dfn();
} ).call(
self,
"clone",
function () {
var _api = {
// two arrays to keep track of what was cloned
originalValues : [],
clonedValues : [],
clone : function ( input ) {
throw new Error(
"Failed to clone value: " + input + "."
);
},
ownEach : function ( obj, func ) {
for ( var p in obj ) {
obj.hasOwnProperty( p )
&& func.call( obj, p, obj[p] );
}
return obj;
}
};
// helper functions
function corstr( o ) {
return Object.prototype.toString.call( o );
}
function corslice( args, i1, i2 ) {
return Array.prototype.slice.call( args, i1, i2 );
}
function isArray( o ) {
return corstr( o ) === "[object Array]";
}
function isObject( o ) {
return corstr( o ) === "[object Object]";
}
function bind( obj, fn ) {
return function () {
return fn.apply( obj, corslice( arguments ) );
};
}
function override( obj, method_v1, method_v2 ) {
var coreMethod = obj[method_v1];
return obj[method_v1] = function () {
return method_v2.apply(
this,
[ bind( this, coreMethod ) ]
.concat( corslice( arguments ) )
);
};
}
//
// build up clone method
// handles arrays and objects
override(
_api,
"clone",
function ( oldMethod, input ) {
var cloned, isarray = false;
if (
isArray( input )
&& ( isarray = true, cloned = [] )
|| isObject( input )
&& ( cloned = {} )
) {
_api.originalValues.push( input );
_api.clonedValues.push( cloned );
isarray
&& (
input
.forEach(
function ( val ) {
cloned.push( _api.clone( val ) );
}
),
true
)
|| (
_api.ownEach(
input,
function ( prop, val ) {
cloned[prop] = _api.clone( val );
}
)
);
return cloned;
} else {
return oldMethod( input );
}
}
);
// copies anything else
override(
_api,
"clone",
function ( oldMethod, input ) {
// here checks if value has been already cloned
// and returns it if it has
var k;
if ( ( k = _api.originalValues.indexOf( input ) ) != -1 ) {
return _api.clonedValues[k];
}
if (
!isArray( input )
&& !isObject( input )
) {
_api.originalValues.push( input );
_api.clonedValues.push( input );
return input;
} else {
return oldMethod( input );
}
}
);
return function ( value ) {
var out = _api.clone( value );
// empties arrays after _api.clone() func is done
_api.originalValues.length
= _api.clonedValues.length
= 0;
return out;
};
}
));
// test
var o = [];
var clon;
o.push( o );
o.push( { p : o } );
clon = clone( o );
console.log( o );
console.log( clon );
console.log( 'o === clon -> ' , o === clon );
console.log( 'o[0] === clon[0] -> ' , o[0] === clon[0] );
console.log( 'o[1] === clon[1] -> ' , o[1] === clon[1] );
console.log( 'o[1].p === clon[1].p -> ', o[1].p === clon[1].p );
//
// [[...], Object { p=[2]}]
// [[...], Object { p=[2]}]
// o === clon -> false
// o[0] === clon[0] -> false
// o[1] === clon[1] -> false
// o[1].p === clon[1].p -> false
//
</code></pre>
|
[] |
[
{
"body": "<p><strong>What the tin says</strong></p>\n\n<p>Your code seems to track all cloned objects, so that it will find circular references, so it should be bullet proof indeed.</p>\n\n<p><strong>The goggles!</strong></p>\n\n<pre><code>!(( function ( methodName, dfn ) {\n // add global 'clone' method identifier\n this[methodName] = dfn();\n} ).call(\nself,\n\"clone\",\nfunction () {\n</code></pre>\n\n<ul>\n<li>There seems to be no good reason to negate the outcome of that function</li>\n<li>Splitting function parameters over different lines should be avoided unless it makes your code more readable, that is definitely not the case here! You do this several times in the code.</li>\n</ul>\n\n<p>Also this:</p>\n\n<pre><code> _api.originalValues.length\n = _api.clonedValues.length\n = 0;\n</code></pre>\n\n<p>looks so much better as</p>\n\n<pre><code>_api.originalValues.length = _api.clonedValues.length = 0;\n</code></pre>\n\n<p>finally, stuff like this:</p>\n\n<pre><code> && (\n input\n .forEach(\n function ( val ) {\n cloned.push( _api.clone( val ) );\n }\n ),\n true\n )\n</code></pre>\n\n<p>Might have some artistic value, but it makes your code far too hard to grok.</p>\n\n<p><strong>Overkill</strong></p>\n\n<pre><code>clone : function ( input ) {\n throw new Error(\n \"Failed to clone value: \" + input + \".\"\n );\n},\n</code></pre>\n\n<p>I assume you are very proficient in another OO language, but things like creating a useless <code>clone</code> function have absolutely no value in JavaScript, but it can eat up bandwidth and cpu time.</p>\n\n<p><strong>Naming</strong></p>\n\n<ul>\n<li>You are not consistent with lowerCamelCase</li>\n<li>I understand why you call these <code>corstr</code> and <code>corslice</code>, they are still bad names</li>\n<li>Having a function <code>isArray</code> and a <code>var isarray</code> is mildly evil</li>\n</ul>\n\n<p><strong>Checking on Arrays and Objects</strong></p>\n\n<p>I really like this implementation:</p>\n\n<pre><code>function isType(object, type){\n return object != null && type ? object.constructor.name === type.name : object === type;\n}\n</code></pre>\n\n<p>Then you can </p>\n\n<pre><code>if( isType( input , Array ) )\n</code></pre>\n\n<p><strong>Scope</strong></p>\n\n<pre><code>return function ( value ) {\n var out = _api.clone( value );\n // empties arrays after _api.clone() func is done\n _api.originalValues.length\n = _api.clonedValues.length\n = 0;\n return out;\n};\n</code></pre>\n\n<p>is wrong, why should the caller of <code>clone</code> need to worry about <code>originalValues</code> and <code>clonedValues</code> ? These should be part of <code>clone</code> so that no house keeping is required. Then you can simple have</p>\n\n<pre><code>return _api.clone;\n</code></pre>\n\n<p><strong>Advanced Hackery</strong></p>\n\n<ul>\n<li>Assignments inside <code>if</code> statements are cool, but should only be used in personal projects. They are a source of bugs and confusion for other developers.</li>\n<li>Writing you own <code>bind</code> is great, but I would suggest you check out the <code>bind</code> shim of Mozilla.</li>\n</ul>\n\n<p><strong>Finale</strong></p>\n\n<p>I would not want to work with this code until it got beautified and all jshint trouble fixed. It works, but I am certain that a far shorter and far more readable implementation can be written.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-24T22:57:43.463",
"Id": "67189",
"Score": "0",
"body": "I agree, a lot of cleanup can be made, I'm still figuring out the 'best code style' to stick to in JavaScript, because it's very free form and 'do it your self' language. \n\nI needed some sort of confirmation that the aproach: 'check what you got so far cache new values you come accross', successfully handles copying self-references without getting stuck. Code snippet is just part of tree data structure implementation I'm working on, where greatest challenge I faced was cloning nodes wich can hold dozen of direct and indirect cyclic references."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-24T23:08:00.717",
"Id": "67190",
"Score": "0",
"body": "I don't see why scope is wrong as you say, internal clone method does it's job and cleans after itself, returns copied object. Caller doesn't need to care about internal logic because returned wrapper function does that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T22:44:50.283",
"Id": "39696",
"ParentId": "31898",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "39696",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T11:00:20.857",
"Id": "31898",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Bulletproof way to clone Objects & Arrays handling circular references?"
}
|
31898
|
<p>I’m planning on creating a Mortal Kombat-inspired game in JavaScript. I’ve written a basic game engine that manages my game states and creates a game loop.</p>
<p>I just wondered if it could be improved at all? As I’m a web developer by trade and this is my first foray into programming games.</p>
<pre><code>/**
* Game engine.
*/
function GameEngine() {
this.states = new Array();
this.currentState;
this.running = false;
};
GameEngine.prototype.init = function() {
this.running = true;
};
GameEngine.prototype.changeState = function(state) {
this.currentState = state;
};
GameEngine.prototype.isRunning = function() {
return this.running;
};
GameEngine.prototype.handleEvents = function() {
this.currentState.handleEvents(this);
};
GameEngine.prototype.update = function() {
this.currentState.update(this);
};
GameEngine.prototype.draw = function() {
this.currentState.draw(this);
};
/**
* Base game state state.
*/
function GameState() {};
/**
* Intro state.
*/
function IntroState() {};
IntroState.prototype = Object.create(GameState.prototype);
IntroState.prototype.handleEvents = function(game) {
console.log('IntroState::handleEvents');
};
IntroState.prototype.update = function(game) {
console.log('IntroState::update');
};
IntroState.prototype.draw = function(game) {
console.log('IntroState::draw');
};
/**
* Initialises the game.
*/
(function() {
var game = new GameEngine();
var gameLoop;
var frameLength = 500;
game.init();
game.changeState(new IntroState());
gameLoop = setInterval(function() {
game.handleEvents();
game.update();
game.draw();
}, frameLength);
})();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T14:32:44.357",
"Id": "50918",
"Score": "2",
"body": "It's a little hard to code review something this simple it doesn't actually do anything at this moment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T14:36:14.197",
"Id": "50919",
"Score": "0",
"body": "I just wanted to know if I was on the right track. Obviously I’m not going to write a complete game and then post the code here, as that could potentially be tens of thousands of lines of code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T14:37:50.653",
"Id": "50920",
"Score": "0",
"body": "That's understandable, a basic game engine is a loop and a redraw/update system. So yes you are good. You should explore other game engines in javascript and see what they do."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-12T06:39:16.253",
"Id": "52122",
"Score": "0",
"body": "Well the client-code shouldn't have to know about how to setup the game loop. That part should be encapsulated as well. Also, it's a bit verbose and not DRY to type `Constructor.prototype` all the time, you should perhaps do something like `Constructor.prototype = { constructor: Constructor, someFn: function () {}, someOtherFn: function () {} }`. Also have a look at http://www.ibm.com/developerworks/library/wa-objectorientedjs/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-18T17:33:01.937",
"Id": "57811",
"Score": "0",
"body": "@plalx Your comment, combined with Steven's comments could work fine as an answer to this question. If you write it as an answer, I'll give you an upvote (and we will have one less unanswered question)"
}
] |
[
{
"body": "<p>Just a general tip in regard to the comments...</p>\n\n<p>It's not recommended to use <code>/* */</code> comment blocks in your code. The reason for that is because in Javascript, that character pair can occur in regular expression literals as well. Comment blocks are therefore not safe for commenting blocks of code.</p>\n\n<p>A better alternative is to generally stick to line comments (<code>//</code>) whenever possible and save block comments for formal documentation and for commenting out.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-18T17:30:45.330",
"Id": "57809",
"Score": "0",
"body": "I have to disagree with you about this. I see no reason to avoid `/* */` comments just because it can be occur in regex."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-18T18:05:53.100",
"Id": "57819",
"Score": "0",
"body": "@SimonAndréForsberg I agree with you, but this question needs an upvoted answer :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-18T18:10:31.063",
"Id": "57822",
"Score": "2",
"body": "@retailcoder I know, but upvoted answers should be **useful** answers :) Thanks for adding a better one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-18T21:55:13.870",
"Id": "57867",
"Score": "0",
"body": "So you say to avoid comments blocks, then say save them for formal documentation? Be consistent. Also, I’ve never had a problem with comments being interpreted as regular expression literals and vice versa."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-17T00:40:01.557",
"Id": "32791",
"ParentId": "31901",
"Score": "-2"
}
},
{
"body": "<p>There's really not much to say about this code, so I'll quote a comment posted on this question:</p>\n\n<blockquote>\n <p>[...] a basic game engine is a loop and a redraw/update system. So yes you are good. You should explore other game engines in javascript and see what they do. – Steven</p>\n</blockquote>\n\n<p>Just one thing that's itching: you're declaring <code>var frameLength = 500;</code> - I think this is going to bite you later, when you want to adjust frame rate (FPS).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-18T18:05:23.957",
"Id": "35613",
"ParentId": "31901",
"Score": "2"
}
},
{
"body": "<p>My 2 cents:</p>\n\n<ul>\n<li><p>GameEngine is most likely going to be a singleton, so there is no reason to add anything to it's prototype really. You can assign init etc. straight to GameEngine.</p></li>\n<li><p>If you are going to have the GameEngine functions simply execute the currentState functions, you should at least return <code>this</code>, so that the caller can chain calls.</p></li>\n<li><p>I am very ambivalent towards <code>handleEvents</code>, I would simply listen to mouse clicks and keyboard presses in the old school way and update the data model in your <code>GameEngine</code>, then draw the data from the data model every n milliseconds.</p></li>\n<li><p>As retailcoder mentioned, you will probably have to think how you want to maintain a steady fps, just calling those functions every x milliseconds is not going to cut it most likely.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-18T19:24:47.713",
"Id": "35625",
"ParentId": "31901",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T12:15:44.703",
"Id": "31901",
"Score": "6",
"Tags": [
"javascript"
],
"Title": "Simple Game Engine in JavaScript"
}
|
31901
|
<p>I have navigation items that are created dynamically with PHP. I wrote this because I need to add individual classes and fire them individually. My code works, but I want a way of refining it no matter how many items are added to the navigation via the backend. Is there a way of doing this so I don't have to add 20 <code>.slideToggle</code> lines of code? </p>
<pre><code>//Adds a CSS Selector to items we need to target individually
jQuery('#sidr ul li').has('ul').each(function(i){
jQuery(this).addClass('has-sub-'+(i+1));
});
jQuery('#sidr ul li ul').has('li').each(function(i){
jQuery(this).addClass('sub-'+(i+1));
});
//Toggles a 'clicked' CSS Selector and reveals the Sub-Menus
jQuery('li.has-sub-1').click(function(){
jQuery('#sidr ul li ul.sub-1').slideToggle(200);
});
jQuery('li.has-sub-2').click(function(){
jQuery('#sidr ul li ul.sub-2').slideToggle(200);
});
jQuery('li.has-sub-3').click(function(){
jQuery('#sidr ul li ul.sub-3').slideToggle(200);
});
jQuery('li.has-sub-1, li.has-sub-2, li.has-sub-3, li.has-sub-4, li.has-sub-5, li.has-sub-6').click(function(){
jQuery(this).toggleClass('clicked');
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-30T16:43:51.620",
"Id": "53709",
"Score": "1",
"body": "Hi, welcome to CR! If [this post](http://codereview.stackexchange.com/questions/33522/saas-hierarchy-what-should-i-do) is meant as a comment to the accepted answer here, and you don't have enough rep to comment on other posts, know that you can comment on your question and use @JohnMark13 notation to make sure the intended user gets notified of your comment (sorry to ping you like this JohnMark13)."
}
] |
[
{
"body": "<p>I think that all you are looking for is:</p>\n\n<pre><code>//assumes sidr is top level container for menu\n//you should consider adding a generic class to menu items when page is assembled\njQuery('#sidr > ul > li').click(function() {\n $this = jQuery(this);\n $this.find('ul').slideToggle(200);\n});\n</code></pre>\n\n<p>If you cannot rely on a selector (like I used above) to find the elements that you are interested in, or if you cannot add classes to the elements when the page is assembled then you could add the class in code:</p>\n\n<pre><code>jQuery('#sidr ul li').has('ul').addClass('hasSubMenu');\n</code></pre>\n\n<p>Now you can use:</p>\n\n<pre><code>jQuery('.hasSubMenu').click(function() {\n $this = jQuery(this);\n $this.find('ul').slideToggle(200);\n $this.toggleClass('clicked');\n});\n</code></pre>\n\n<p>This also saves re-evaluating the various selectors, which is much more efficient.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T15:12:37.800",
"Id": "31904",
"ParentId": "31902",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "31904",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T14:32:13.040",
"Id": "31902",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "Calling individual classes for navigation items"
}
|
31902
|
<p>Edit: <a href="https://codereview.stackexchange.com/questions/32073/parallel-job-consumer-using-tpl">A second iteration of this problem here.</a></p>
<p>I need to provide a service (either a Windows Service or an Azure Worker Role) which will handle the parallel execution of jobs. These jobs could be anything from importing data to compiling of reports, or to sending out mass notifications, etc. They are generally long-running and are not suitable to run on the web server.</p>
<p><strong>Important factors</strong></p>
<ul>
<li>The solution needs to be a very extensible and maintainable solution, as new job implementations will be created by developers all the time. </li>
<li>The execution of these jobs is to be abstracted away from the client code. All developers need to do is to create the new job and add it to the job data source (database, MSMQ, Azure Queue, etc).</li>
</ul>
<p><strong>Solution</strong></p>
<p>Deriving from <code>AbstractJob</code> and overriding the abstract <code>Execute()</code> method to provide implementation for the new job:</p>
<pre><code>public abstract class AbstractJob
{
public JobState State { get; protected set; }
public AbstractJob()
{
State = JobState.New;
}
protected abstract bool Execute();
public sealed void ExecuteJob()
{
State = JobState.Executing;
try
{
if (Execute())
{
State = JobState.Successful;
}
else
{
State = JobState.Failed;
}
}
catch (Exception)
{
State = JobState.FailedOnException;
}
}
}
public class TestJob : AbstractJob
{
protected override bool Execute()
{
Debug.WriteLine("Test job!");
return true;
}
}
</code></pre>
<p>The following <code>JobConsumer</code> would reside on a Windows Service or Azure Worker Role. <code>IJobSource</code> provides the consumer with jobs. These could be from the database, a MSMQ, an Azure Queue, etc (I have left this implementation out).</p>
<p>Every 5 seconds (this can obviously be configurable), the <code>JobConsumer</code> executes new jobs when there are available cores.</p>
<pre><code>public class JobConsumer
{
public List<AbstractJob> Jobs { get; set; }
public IJobSource JobSource { get; private set; }
public int ParallelExecutionCount { get; set; }
protected List<Task> Tasks { get; set; }
public JobConsumer(IJobSource jobSource, int parallelExecutionCount)
{
JobSource = jobSource;
ParallelExecutionCount = parallelExecutionCount;
}
public void StartConsumer()
{
Task.Factory.StartNew(() =>
{
TaskScheduler currentScheduler = TaskScheduler.Current;
while (true)
{
int availableCores = ParallelExecutionCount - Tasks.Count();
IEnumerable<AbstractJob> newJobs =
JobSource.ReadNewJobs().Take(availableCores);
foreach (var job in newJobs)
{
System.Threading.Tasks.Task task = null;
task = Task.Factory.StartNew(() =>
{
Tasks.Add(task);
}, CancellationToken.None,
TaskCreationOptions.None,
currentScheduler)
.ContinueWith(t =>
{
// Execute job on a new thread
job.ExecuteJob();
})
.ContinueWith(t =>
{
Tasks.Remove(task);
}, currentScheduler);
}
Thread.Sleep(5000);
}
});
}
}
public interface IJobSource
{
public IEnumerable<AbstractJob> ReadNewJobs();
}
</code></pre>
<p>Input, critique and suggestions very welcome!</p>
<p><strong>EDIT:</strong> I am using .NET 4.5</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T15:16:45.520",
"Id": "50925",
"Score": "0",
"body": "I wrote similar code polling a serial port and used the same looping methods you've used. Except I added a timeout error count, which would reset every time it connected successfully. I don't know if you want to count your job errors, to create some system flag??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T15:40:57.240",
"Id": "50933",
"Score": "0",
"body": "What version of .Net are you using?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T15:42:26.930",
"Id": "50934",
"Score": "2",
"body": "Wouldn't it actually be easier to convert the `Execute` to `ExecuteAsync` returning a `Task` and the `AbstractJob` to `IJob`? `Task` carries everything that you put in the `JobState` flag and more (e.g. if it failed, why). Then you could also drop the task creation on consumer side and use either `ConcurrentQueue<T>` or `BlockingCollection<T>` to process the jobs, but that depends on .NET version."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T16:49:14.487",
"Id": "50944",
"Score": "0",
"body": "@PatrykĆwiek I think that unless explicitly mentioned, you can safely assume at least .Net 4.0."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T17:39:26.180",
"Id": "50949",
"Score": "0",
"body": "I am using .NET 4.5 - Sorry for not stipulating."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T17:45:44.587",
"Id": "50950",
"Score": "0",
"body": "@Patryk: Thanks for your comment! The `ExecuteAsync` idea sounds much better. But the reason why I decided on an abstract class is because I am concerned that I may want to include certain properties (like a `SendNotificationOnComplete` flag or `Priority` setting). A priority field would also mean that I couldn't use a `ConcurrentQueue<T>` if I understand correctly. Feel free to formulate an answer :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T19:28:19.013",
"Id": "50952",
"Score": "0",
"body": "@davenewza Depending on how your `Priority` is supposed to work, you might be able to implement it using multiple `ConcurrentQueue`s (or, more likely, multiple `BlockingCollection`s)."
}
] |
[
{
"body": "<ol>\n<li><p>The way you're using <code>TaskScheduler.Current</code> to try to synchronize access to <code>Tasks</code> won't work (unless this code runs under a very specific custom <code>TaskScheduler</code>).</p>\n\n<p>With the default scheduler, a <code>Task</code> can be executed on any <code>ThreadPool</code> thread, which means that multiple threads could access <code>Tasks</code> at the same time. The simplest fix for that is to use <code>lock</code> instead of trying to use <code>TaskScheduler</code> (which will also simplify your code a bit).</p>\n\n<p>Since you seem to be using <code>Tasks</code> just for counting, another option would be to replace it with <code>int</code> field and then use <code>Interlocked.Increment()</code>/<code>Decrement()</code> to modify it.</p></li>\n<li><p>I think you should save the exception that's caught in <code>ExecuteJob()</code> somewhere, so that when you encounter an issue, you can actually diagnose it.</p>\n\n<p>Also, it looks like you're not saving the results of jobs anywhere. I think that's a bad idea, you should have some sort of logging, to see where the problem was when something doesn't work right. (Was the job even scheduled? Did it complete successfully? Etc.)</p>\n\n<p>And I'm not sure you want to differentiate between \"failed\" and \"failed on exception\". When something fails, you usually want to know <em>why</em> it failed, which is what exceptions are for.</p></li>\n<li><p>Why are most of the properties of <code>JobConsumer</code> public? If you want to allow adding a new job to <code>Jobs</code>, but nothing else, then create a method for that.</p>\n\n<p>And why is <code>Tasks</code> protected, when you don't have any virtual methods? The default accessibility should be private (which means you don't need a property anymore and you can use just a field) and you should change that only when you have good reason.</p></li>\n<li><p>The way you use <code>ReadNewJobs()</code> seems to indicate that items are actually consumed only when the enumerable is iterated. That's not a bad idea (<code>BlockingCollection.GetConsumingEnumerable()</code> does the same thing), but it should be documented <em>very clearly</em> that that's what is expected from the method.</p></li>\n<li><p>Since you're on .Net 4.5, you can use <code>await Task.Delay()</code> instead of <code>Thread.Sleep()</code>. This means you would need to make the lambda <code>async</code> and you should probably also use <code>Task.Run()</code> instead of <code>Task.Factory.StartNew()</code> (which is a good idea anyway, because it's shorter).</p></li>\n<li><p>There is no need to spell the name <code>System.Threading.Tasks.Task</code> in full, use just <code>Task</code>.</p></li>\n<li><p>I don't think that the name <code>AbstractJob</code> needs to emphasize that the class is abstract, calling it just <code>Job</code> would work just as well. Another possible name is <code>JobBase</code>.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T06:54:39.533",
"Id": "51121",
"Score": "0",
"body": "Thanks for the great reply. You have made some really helpful point. I have a question. Would you use an abstract `Job` class or an `IJob` interface for implementation of new jobs? I feel that an `IJob` is the more correct choice, but I really want the job to have a `JobState`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T08:45:59.040",
"Id": "51131",
"Score": "0",
"body": "@davenewza You could always do both. But I think that abstract class makes more sense here, because of `ExecuteJob()` (if you used an interface, each implementation would have to repeat the code for that method)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T14:49:07.403",
"Id": "51233",
"Score": "0",
"body": "I have created a second iteration of the above code (and have implemented a lot of your comments). Your feedback/review would be awesome: [post here](http://codereview.stackexchange.com/questions/32073/parallel-job-consumer-using-tpl)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T19:26:53.990",
"Id": "31912",
"ParentId": "31903",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "31912",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T15:04:06.660",
"Id": "31903",
"Score": "3",
"Tags": [
"c#",
"design-patterns",
".net"
],
"Title": "Parallel Job Consumer"
}
|
31903
|
<p>I had an exercise to create two methods for simple queue class, first to delete last element and second to delete element at k position. Particularly I'm not asking for better implementation. Is it good enough and elegant ? What I should change ? I'll post only mentioned methods, rest should be simple enough.</p>
<pre><code>/**
* Deletes node at position k.
*/
public void delete(int k) {
if (k > N || isEmpty()) throw new NoSuchElementException("Cannot delete element at position: " + k);
Node previous = first;
int deleteIndex = 1;
if(k == deleteIndex){ //special case for first element
if(first.next == null)
last = null;
first = first.next;
N--;
return;
}
for (Node node = first; node != null; node = node.next, deleteIndex++) {
if (k == deleteIndex) {
previous.next = node.next;
if (previous.next == null) last = previous; //if deleted element was the last one
N--;
return;
}
previous = node;
}
}
/**
* Deletes last node from the queue.
*/
public void removeLastNode() {
if(isEmpty()) throw new NoSuchElementException("Cannot delete last element from queue");
if (N == 1) { //special case for only one element in queue
first = null;
last = null;
N--;
return;
}
Node previous = null;
for (Node node = first; node != null; node = node.next) {
if (node.next == null) {
previous.next = null;
last = previous;
N--;
}
previous = node;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Well, your code is correct and mostly ok. Except for two things:</p>\n\n<ul>\n<li><p>You have 1-based indexing? Follow the <em>principle of least suprise</em>, and use zero-based indexing like all other data structures as well.</p></li>\n<li><p>Your variable names could be more obvious.</p>\n\n<ul>\n<li><p><code>N</code> seems to be the <code>length</code> or <code>size</code> of your list – use this longer name instead. Also, the name <code>N</code> does not adhere to the best practice that variables and members should start with lowercase characters.</p></li>\n<li><p><code>k</code> is an <code>index</code> – the traditional abbreviation for that is <code>i</code>.</p></li>\n<li><p><code>deleteIndex</code> is not the index which you want to delete. Rather, it is some iteration variable. I'd call it <code>position</code>.</p></li>\n</ul></li>\n</ul>\n\n<p>Then there are some minor style issues.</p>\n\n<ul>\n<li><p>It is advisable to always use <code>if</code> with braces, as it tends to improve readability. If you do not use braces, I would recommend to put the body of the <code>if</code> on the same line. You do this with your <code>isEmpty</code> guards, but not at <code>if (first.next == null)</code>.</p></li>\n<li><p>You have very long lines. I recommend using 80–100 characters. Your longest line seems to be 104 characters long with this intendation, which is too long. (Incidentally, your lines get shorter if you use the <code>if</code> with curlies…).</p></li>\n<li><p>Instead of an <code>NoSuchElementException</code> you should consider an <code>IndexOutOfBoundsException</code>.</p></li>\n</ul>\n\n<p>Some parts of your code could be made more obvious, or structured differently:</p>\n\n<ul>\n<li><p>In <code>delete</code>, you have the test <code>if (first.next == null)</code>, where you actually want to test <code>if (size == 1)</code>.</p></li>\n<li><p>Finding a node at a certain position is so useful that it should have a method of its own. You want a <code>Node previous = nodeAt(i - 1); ...</code> instead of the <code>for</code> loops.</p></li>\n<li><p>If you don't do that, your <code>for</code> loops still have the problem that they do three things between iterations: <code>previous = node; node = node.next; position++</code>. You have put one of these at the end of the loop body, the rest in the increment statement of the <code>for</code> loop. It would have been better to group these together.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T16:56:39.303",
"Id": "31908",
"ParentId": "31906",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "31908",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T15:59:24.590",
"Id": "31906",
"Score": "1",
"Tags": [
"java",
"queue"
],
"Title": "Removing nodes from queue"
}
|
31906
|
<p>I was making a relatively large-scale project in Python as a learning experiment, and in the process I found that it would be useful to have a map (or, in Python, I guess they're called dictionaries) where a value could have multiple keys. I couldn't find much support for this out there, so this is the implementation I ended up going with:</p>
<pre><code>def range_dict(*args):
return_val = {}
for k,v in args:
for i in k:
return_val[i] = v
return return_val
COINS = range_dict((range(1,15), None),
(range(15,30), "1d6x1000 cp"),
(range(30,53), "1d8x100 sp"),
(range(53,96), "2d8x10 gp"),
(range(96,101), "1d4x10 pp"))
</code></pre>
<p>I was told that this wasn't really a good way to achieve what I wanted to do, but I don't really understand <em>why</em>. It works perfectly in my application. What's wrong with this? Is there a better, more Pythonic way to do this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T20:28:43.680",
"Id": "50954",
"Score": "1",
"body": "It's hard to answer if the structure is optimal, because there is no data how many values there are? How many keys per value? How many unique values? Are ranges usual or an exception? Also, which operations are prevailing and so on. Are you optimizing for speed or memory conservation?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T21:23:49.843",
"Id": "50955",
"Score": "1",
"body": "\"I was told that this wasn't really a good way to achieve what I wanted to do\". Well, what *do* you want to do?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T22:32:43.163",
"Id": "50956",
"Score": "0",
"body": "Sorry, I didn't realize what I'm doing was so confusing. Basically, I wanted a dictionary where a value would be mapped to multiple keys. So the numbers 1-14 should map to `None`, 15-30 should map to `1d6x1000 cp`, etc. Thought it was pretty self-explanatory. :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T23:03:46.997",
"Id": "50962",
"Score": "0",
"body": "Yes, that's all clear from your post. But what do you want to *do* with this data structure? It looks like a table in an RPG that you are doing to roll d100 against."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T23:29:44.300",
"Id": "50971",
"Score": "0",
"body": "@JeffGohlke I think you can also use dictionary comprehensions, it's the same as my answer down below but is build like a comprehension dict. List comprehensions are faster than for loop block. Dictionary comprehension should be faster too, I think. Check them out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T00:03:21.993",
"Id": "50973",
"Score": "1",
"body": "@GarethRees Ah, gotcha. Yeah, it's actually a loot generator for D&D 3.5. And the `COINS` variable is actually a dictionary of `range_dict`s, but I just thought that would confuse the example since that's pretty irrelevant. But the way I use it in the code is like `COINS[5][d100()]`, where `5` is the Challenge Rating and `d100()` generates a random number between 1 and 100."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T00:04:35.373",
"Id": "50974",
"Score": "0",
"body": "@dragons And thanks, I will. :) Thanks for your answer as well. Just want to leave the question open for a bit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-09T20:25:11.427",
"Id": "203140",
"Score": "0",
"body": "I know it is a dead topic irregardless, as is mentioned in other answers, your ranges you originally provided were ambiguous. If you roll a 15 is that None or \"1d6x1000 cp\". Same goes for if you \"roll\" a 30, 53 or a 96."
}
] |
[
{
"body": "<p>My attempt, keep in my mind that I'm not close to any of pro's around here.</p>\n\n<pre><code>for i in range(1, 101):\n if i < 15:\n my_coins[i] = None\n if 15 <= i < 30:\n my_coins[i] = '1d6x1000 cp'\n if 30 <= i < 53:\n my_coins[i] = '1d8x100 sp'\n if 53 <= i < 96:\n my_coins[i] = '2d8x10 gp'\n if i >= 96:\n my_coins[i] = '1d4x10 pp'\n</code></pre>\n\n<p>Put it in a function and return <code>my_coins</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T00:12:12.727",
"Id": "50975",
"Score": "0",
"body": "Yeah, I thought of doing this, but I wanted something a bit more concise. And I figured I could create a convenient data structure that just represented the table."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T01:27:00.937",
"Id": "50981",
"Score": "0",
"body": "@JeffGohlke Your original function have 5 parameters. Usualy a good design is to have a up to maximum 4."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T20:53:55.103",
"Id": "31915",
"ParentId": "31907",
"Score": "3"
}
},
{
"body": "<p>If everything wanted with the datasctructure is to be able to generate random coin, it's much easier to do directly by generating random integer number from [1, 100] and then use if-statements to go through choices (ranges).</p>\n\n<p>Another possibility is to have all the values in a list as many times as their range length and use <a href=\"http://docs.python.org/2/library/random.html\" rel=\"nofollow\">random.choice() function</a> to fetch one.</p>\n\n<p>Also, I do not find the original code particularly bad. Write tests, experiment, and you are there.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T06:50:47.603",
"Id": "31933",
"ParentId": "31907",
"Score": "2"
}
},
{
"body": "<h2>1. Comments on your code</h2>\n\n<ol>\n<li><p>No docstrings! What does your code do and how am I supposed to use it?</p></li>\n<li><p>No test cases. This ought to be a good opportunity to use <a href=\"https://docs.python.org/3/library/doctest.html\" rel=\"noreferrer\">doctests</a>.</p></li>\n<li><p>Given that your purpose here is to implement RPG lookup tables, your design seems a bit hard to use. The printed RPG table probably says something like this:</p>\n\n<pre><code>1-8 giant spider\n9-12 skeleton\n13-18 brass dragon\n...\n</code></pre>\n\n<p>but you have to input it like this (adding one to the limit of each range):</p>\n\n<pre><code>range_dict((range(1, 9), \"giant spider\"),\n (range(9, 13), \"skeleton\"),\n (range(13, 18), \"brass dragon\"),\n ...)\n</code></pre>\n\n<p>which would be easy to get wrong.</p></li>\n<li><p>The design also seems fragile, because it doesn't ensure that the ranges are contiguous. If you made a data entry mistake:</p>\n\n<pre><code>d = range_dict((range(1, 8), \"giant spider\"),\n (range(9, 13), \"skeleton\"),\n (range(13, 18), \"brass dragon\"),\n ...)\n</code></pre>\n\n<p>then the missing key would later result in an error:</p>\n\n<pre><code>>>> d[8]\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nKeyError: 8\n</code></pre></li>\n</ol>\n\n<h2>2. An alternative approach</h2>\n\n<p>Here's how I'd implement this lookup table:</p>\n\n<pre><code>from bisect import bisect_left\nfrom collections.abc import Mapping\n\nclass LookupTable(Mapping):\n \"\"\"A lookup table with contiguous ranges of small positive integers as\n keys. Initialize a table by passing pairs (max, value) as\n arguments. The first range starts at 1, and second and subsequent\n ranges start at the end of the previous range.\n\n >>> t = LookupTable((10, '1-10'), (35, '11-35'), (100, '36-100'))\n >>> t[10], t[11], t[100]\n ('1-10', '11-35', '36-100')\n >>> t[0]\n Traceback (most recent call last):\n ...\n KeyError: 0\n >>> next(iter(t.items()))\n (1, '1-10')\n\n \"\"\"\n def __init__(self, *table):\n self.table = sorted(table)\n self.max = self.table[-1][0]\n\n def __getitem__(self, key):\n key = int(key)\n if not 1 <= key <= self.max:\n raise KeyError(key)\n return self.table[bisect_left(self.table, (key,))][1]\n\n def __iter__(self):\n return iter(range(1, self.max + 1))\n\n def __len__(self):\n return self.max\n</code></pre>\n\n<p>Notes on this implementation:</p>\n\n<ol>\n<li><p>The constructor takes the maximum for each range (not the maximum plus one), making data entry less error-prone.</p></li>\n<li><p>The minimum of each range is taken from the end of the previous range, thus ensuring that there are no gaps between ranges.</p></li>\n<li><p>The <a href=\"https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping\" rel=\"noreferrer\"><code>collections.abc.Mapping</code></a> abstract base class provides much of the functionality of a read-only dictionary. The idea is that you supply the <code>__getitem__</code>, <code>__iter__</code> and <code>__len__</code> methods, and the <code>Mapping</code> class supplies implementations of <code>__contains__</code>, <code>keys</code>, <code>items</code>, <code>values</code>, <code>get</code>, <code>__eq__</code>, and <code>__ne__</code> methods for you. (Which you can override if you need to, but that's not necessary here.)</p></li>\n<li><p>I've used <a href=\"https://docs.python.org/3/library/bisect.html#bisect.bisect_left\" rel=\"noreferrer\"><code>bisect.bisect_left</code></a> to efficiently look up keys in the sorted table.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T12:32:02.240",
"Id": "31943",
"ParentId": "31907",
"Score": "9"
}
},
{
"body": "<p>The main drawback to this arrangement is that it's wasteful. For a small case it's not a big deal but for a large range of values you're going to need an equally large range of keys, which will mean both a lot of searching for the right key and also expending memory to store all the keys.</p>\n\n<p>For the specific application the python <a href=\"http://docs.python.org/2/library/bisect.html\" rel=\"nofollow noreferrer\">bisect</a> module is handy. It's great for fast searching through <em>sorted</em> data, so its fast for this kind of lookup table:</p>\n\n<pre><code>import bisect\n\n# Set up the data. Don't do it inside the function, you don't\n# want to do it over and over in the function!\nxp_table = [(0, 0), (15, \"1d6x1000 cp\"), (30, \"1d8x100 sp\"), (53, \"2d8x10 gp\"), (96 ,\"1d4x10 pp\")]\nxp_table.sort() \nkeys = [k[0] for k in xp_table]\n\ndef get_reward(val):\n idx = bisect.bisect_right(keys, val)\n return xp_table[idx][1]\n</code></pre>\n\n<p>A dictionary based solution will still be better for data that doesn't sort, or does not fall into neat ranges.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T01:22:13.033",
"Id": "31966",
"ParentId": "31907",
"Score": "4"
}
},
{
"body": "<p>So, I came across this issue earlier today. Wasn't real thrilled with most of the solutions here, mostly because I wanted to be able to set normal keys, but also set a range of keys all at once when needed, so I came up with this:</p>\n\n<pre><code>class RangedDict(dict):\n \"\"\"\n A dictionary that supports setting items en masse by ranges, but also supports normal keys.\n\n The core difference between this and any other dict is that by passing a tuple of 2 to 3 numeric values, an\n inclusive range of keys will be set to that value. An example usage is:\n\n >>> d = RangedDict({\n ... (1, 5): \"foo\"\n ... })\n >>> print d[1] # prints \"foo\"\n >>> print d[4] # also prints \"foo\"\n >>> print d[5] # still prints \"foo\" because ranges are inclusive by default\n >>> d['bar'] = 'baz'\n >>> print d['bar'] # prints 'baz' because this also works like a normal dict\n\n Do note, ranges are inclusive by default, so 5 is also set. You can control\n inclusivity via the `exclusive` kwarg.\n\n The third, optional, parameter that can be given to a range tuple is a step parameter (analogous to the step\n parameter in xrange), like so: `(1, 5, 2)`, which would set keys 1, 3, and 5 only. For example:\n\n >>> d[(11, 15, 2)] = \"bar\"\n >>> print d[13] # prints \"bar\"\n >>> print d[14] # raises KeyError because of step parameter\n\n NOTE: ALL tuples are strictly interpreted as attempts to set a range tuple. This means that any tuple that does NOT\n conform to the range tuple definition above (e.g., `(\"foo\",)`) will raise a ValueError.\n \"\"\"\n def __init__(self, data=None, exclusive=False):\n # we add data as a param so you can just wrap a dict literal in the class constructor and it works, instead of\n # having to use kwargs\n self._stop_offset = 0 if exclusive else 1\n if data is None:\n data = {}\n\n for k, v in data.items():\n if isinstance(k, tuple):\n self._store_tuple(k, v)\n else:\n self[k] = v\n\n def __setitem__(self, key, value):\n if isinstance(key, tuple):\n self._store_tuple(key, value)\n else:\n # let's go ahead and prevent that infinite recursion, mmmmmkay\n dict.__setitem__(self, key, value)\n\n def _store_tuple(self, _tuple, value):\n if len(_tuple) > 3 or len(_tuple) < 2:\n # eventually, it would be nice to allow people to store tuples as keys too. Make a new class like: RangeKey\n # to do this\n raise ValueError(\"Key: {} is invalid! Ranges are described like: (start, stop[, step])\")\n\n step = _tuple[2] if len(_tuple) == 3 else 1\n start = _tuple[0]\n stop = _tuple[1]\n\n # +1 for inclusivity\n for idx in xrange(start, stop + self._stop_offset, step):\n dict.__setitem__(self, idx, value)\n</code></pre>\n\n<p>It uses tuples to describe ranges, which looks rather elegant, if I do say so myself. So, some sample usage is:</p>\n\n<pre><code>d = RangedDict()\nd[(1, 15)] = None\nd[(15, 25)] = \"1d6x1000 cp\"\n</code></pre>\n\n<p>Now you can easily use <code>d[4]</code> and get what you want.</p>\n\n<p>The astute reader will however notice that this implementation does <strong>not</strong> allow you to use tuples as keys <strong>at all</strong> in your dict. I don't see that as a common use case, or something elegant to do, in general, so I felt it was worth the tradeoff. However, a new class could be made named along the lines of <code>RangeKey(1, 5, step=2)</code> that could be used to key ranges, thus letting you key tuples as well.</p>\n\n<p>I hope a future reader enjoys my code!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-07-29T21:26:32.063",
"Id": "325007",
"Score": "0",
"body": "While I like this approach quite a bit, the inclusiveness of the upper boundary might be surprising to a user. How about making that optional by using `self._end_offset = 1 if inclusive else 0` instead of the constant +1 in `_store_tuple`, with `inclusive=True/False` as parameter to `__init__`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-01T04:18:07.437",
"Id": "325353",
"Score": "0",
"body": "Edited to accommodate that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-01T04:25:43.953",
"Id": "325355",
"Score": "0",
"body": "Can't say I'm a fan of the `exclusive` switch (I mean over using `inclusive`) with a `False` default. Double-negative is usually not straight forward... Any reason why you preferred that combination?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-01T19:32:27.807",
"Id": "325540",
"Score": "0",
"body": "I would argue that `exclusive` isn't really a negative by itself, so this isn't really a double negative. I mostly chose `exclusive` because it was already inclusive by default, and I think a clearer API is one that is opt-IN and not opt-OUT. For example, to me it makes more sense and is more common to pass a Truthy flag to change behavior, rather than a Falsey one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-02T00:01:45.343",
"Id": "325568",
"Score": "1",
"body": "Yeah, I see what you mean. De gustibus non disputandum est ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-06T20:46:51.187",
"Id": "326441",
"Score": "0",
"body": "Definitely one of the toughest parts about software design: creating a common convention and base for naming =)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-10T19:45:12.673",
"Id": "83786",
"ParentId": "31907",
"Score": "6"
}
},
{
"body": "<p>To answer the original question: One drawback of a multi-key map is that more memory is used to store the second key.</p>\n\n<p>However. here is a way to get your desired functionality:</p>\n\n<pre><code>d = { # key is max value\n 5: 'one',\n 10: 'two',\n 15: 'three',\n 20: 'four',\n 25: 'five',\n 30: 'six'}\n\nMINIMUM = 1\n\nfor i in range(10):\n d[[key for key in sorted(d) if key >=random.randint(MINIMUM, max(d))][0]]\n\n'two'\n'four'\n'two'\n'five'\n'three'\n'three'\n'five'\n'four'\n'three'\n'four'\n</code></pre>\n\n<p>You could replace the part sorted(d) with <code>one_off_pre_sorted_keys</code>:</p>\n\n<pre><code>one_off_pre_sorted_keys = sorted(d)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-09T20:14:08.433",
"Id": "110280",
"ParentId": "31907",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "31943",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T16:53:08.803",
"Id": "31907",
"Score": "11",
"Tags": [
"python",
"python-3.x",
"hash-map"
],
"Title": "\"Multi-key\" dictionary"
}
|
31907
|
<p>I'm using using twitter4j to fetch usernames that retweeted me. I'm interested in any feedback that make the code more elegant, and also that might reduce the number of calls I'm making to the Twitter API.</p>
<pre><code>import java.util.ArrayList;
import twitone.structure.BaseTwitterClass;
import twitone.structure.TwitApplicationFactory;
import twitter4j.Paging;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
public class getmyretweeters extends BaseTwitterClass {
public static void main(String[] args) throws TwitterException {
Twitter twitter = TwitApplicationFactory.getjoereddingtonTwitter();
String temp[] = getRetweeters(twitter);
for (String string : temp) {
System.out.println(string);
}
}
public static String[] getRetweeters(Twitter twitter) {
ArrayList<String> names = new ArrayList<String>();
try {
for (Status status : twitter.getUserTimeline(new Paging(1, 200))) {
System.out.println(status.getText());
if (status.getRetweetCount() > 0) {
Thread.sleep(12000);// Because I don't want to breach
// Twitter's rate limits
for (Status rt : twitter.getRetweets(status.getId())) {
names.add(rt.getUser().getScreenName());
}
}
}
} catch (TwitterException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return names.toArray(new String[names.size()]);
}
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>General Notes</strong></p>\n\n<ol>\n<li>Follow Java naming conventions. Class names should have <code>EachWordCapitalized</code>, and variable and method names should be <code>inCamelCase</code>. Also, class names should be nouns, and method names should be verbs.</li>\n<li>For collections, the overarching interface is usually used. (i.e., <code>List<String> names = new ArrayList<String>();</code>) Not really that important in my view, but it adds some style points according to some authorities.</li>\n<li>Most of the <code>int</code> literals should be true constants. So for example, you would have <code>private static final long WAIT_TIME = 12000;</code> at the top of your class, and then call <code>Thread.sleep(WAIT_TIME)</code>. It doesn't matter for this small application, but for large-scale projects this will allow you to change the setting globally just by modifying this one value. Otherwise, you'll be doing a lot of digging through your code, and you're guaranteed to forget to change that one spot it mattered most. Every. Single. Time.</li>\n<li>Why are you bothering to convert the <code>ArrayList<String></code> into a <code>String[]</code> before returning it? You may as well just change the return type of the method to <code>List<String></code>. In general, it's best to avoid primitive arrays and use these data structures. And they can also be used in the enhanced <code>for</code> loop in your <code>main</code> method.</li>\n<li>You should hardly ever swallow <code>Exception</code>s and do nothing about them. Again, it's pretty trivial in this case and doesn't really matter, but if you're looking to develop good programming habits, start logging and doing safety checking and all that now. It'll make your life a lot easier down the road.</li>\n</ol>\n\n<p><sub><em>Also, this method name made me die a little on the inside: <code>getjoereddingtonTwitter()</code></em></sub></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T20:07:21.740",
"Id": "31914",
"ParentId": "31910",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T18:23:04.190",
"Id": "31910",
"Score": "2",
"Tags": [
"java",
"twitter"
],
"Title": "Using twitter4j to fetch usernames that retweeted me"
}
|
31910
|
<p>I want you to pick my code apart and give me some feedback on how I could make it better or more simple. This code finds inorder successor in a binary tree.</p>
<pre><code>public class Successor {
private TreeNode root;
private class TreeNode {
TreeNode left;
TreeNode right;
TreeNode parent;
int item;
TreeNode(TreeNode left, TreeNode right, TreeNode parent, int item) {
this.left = left;
this.right = right;
this.parent = parent;
this.item = item;
}
}
public void makeBinarySearchTree(int[] a) {
for (int i : a) {
addElement(i);
}
}
public void addElement(int element) {
if (root == null) {
root = new TreeNode(null, null, null, element);
} else {
TreeNode prevNode = null;
TreeNode node = root;
while (node != null) {
prevNode = node;
// no definition exists, and for convenience we will stick to this one.
if (element < node.item) {
node = node.left;
} else {
node = node.right;
}
}
if (element < prevNode.item) {
prevNode.left = new TreeNode(null, null, prevNode, element);
} else {
prevNode.right = new TreeNode(null, null, prevNode, element);
}
}
}
private TreeNode search (int x) {
TreeNode node = root;
while (node != null) {
if (x < node.item) {
node = node.left;
} else if (x > node.item) {
node = node.right;
} else {
return node;
}
}
return null;
}
public Integer getSucessor(int val) {
TreeNode node = getInorderSuccessor(search(val));
return node == null ? null : node.item;
}
private TreeNode getInorderSuccessor(TreeNode node) {
if (node == null) return null;
if (node.right != null) {
node = node.right;
while (node.left != null) {
node = node.left;
}
return node;
} else {
while (node.parent != null && node == node.parent.right) {
node = node.parent;
}
return node.parent;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-31T18:01:49.590",
"Id": "53826",
"Score": "1",
"body": "I assume that this is Java, given your Username? I added the tag."
}
] |
[
{
"body": "<ul>\n<li>Please give clear meaningful name. Your class name is <code>Successor</code>... now who's successor? yours? king Luthar's? who's? See the concern. I think <code>BinarySearchTree</code> is the apt. name for the class.</li>\n<li>In <code>makeBinarySearchTree</code> you are creating a Binary Tree, so someone seeing your code will think it as a <em>factory method</em>, so better make it that way.</li>\n<li>You can make your class generic but that's not a big deal for now but in future keep this in head and try to find always general solution for any given problem.</li>\n<li>Someone using your <code>getSucessor</code> method(should be <code>getSuccessor</code>) will always get the inorder-successor. Now what if someday someone want to find preorder-successor or preorder-successor, what will you do then?</li>\n</ul>\n\n<p>Otherwise your code is good and self-documenting.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-31T19:36:34.367",
"Id": "33617",
"ParentId": "31911",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "33617",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T18:49:03.033",
"Id": "31911",
"Score": "2",
"Tags": [
"java",
"tree"
],
"Title": "Finding inorder successor"
}
|
31911
|
<p>I want you to pick my code apart and give me some feedback on how I could make it better or more simple.</p>
<pre><code>class TreeNode {
private TreeNode left;
private TreeNode right;
private TreeNode parent;
int item;
public TreeNode (TreeNode left, TreeNode right, TreeNode parent, int item) {
this.left = left;
this.right = right;
this.parent = parent;
this.item = item;
}
public int getItem() {
return item;
}
public void setItem(int item) {
this.item = item;
}
public TreeNode getLeft() {
return left;
}
public void setLeft(TreeNode left) {
this.left = left;
}
public TreeNode getRight() {
return right;
}
public void setRight(TreeNode right) {
this.right = right;
}
public TreeNode getParent() {
return parent;
}
public void setParent(TreeNode parent) {
this.parent = parent;
}
}
public class Ebay {
private TreeNode root;
public Map<TreeNode, List<TreeNode>> getMap (List<TreeNode> listOfTreeNodes) {
final Map<TreeNode, List<TreeNode>> map = new HashMap<TreeNode, List<TreeNode>>();
for (TreeNode treeNode : listOfTreeNodes) {
if (map.get(treeNode.getParent()) != null) {
map.get(treeNode.getParent()).add(treeNode);
} else {
List<TreeNode> list = new ArrayList<TreeNode>();
list.add(treeNode);
map.put(treeNode.getParent(), list);
}
}
return map;
}
public void soStuff (List<TreeNode> listOfTreeNode) {
final Map<TreeNode, List<TreeNode>> map = getMap (listOfTreeNode);
root = map.get(null).get(0);
constructTree ( map , root);
}
public TreeNode constructTree (Map<TreeNode, List<TreeNode>> map, TreeNode node) {
if (map.containsKey(node)) {
List<TreeNode> list = map.get(node);
node.setLeft(constructTree(map, map.get(node).get(0)));
if (list.size() == 2) {
node.setRight(constructTree(map, map.get(node).get(1)));
}
}
return node;
}
</code></pre>
|
[] |
[
{
"body": "<p>Your <code>TreeNode</code> class is mostly allright. But you have to be careful when handling trees with parent pointers, or the tree could go out of sync, and deteriorate to a weird class. A <code>setParent</code> on its own is silly. The <code>setLeft</code> and <code>setRight</code> should also make sure to set the <code>parent</code> of the new child node:</p>\n\n<pre><code>public void setLeft(TreeNode left) {\n this.left = left;\n left.parent = this;\n}\n</code></pre>\n\n<p>Do not force a user of your class to do this bookkeeping.</p>\n\n<p>Your <code>item</code> is weird. It is the only non-private field, and is an <code>int</code>. Use generics, so that your tree can carry any type.</p>\n\n<p>A usable tree implementation will implement certain collection interfaces like <code>Iterable</code>.</p>\n\n<hr>\n\n<p>Your <code>Ebay</code> class is very weird.</p>\n\n<p>The methods <code>getMap</code> and <code>constructTree</code> are public, but are not very useful outside of that class. Both should also be <code>static</code>.</p>\n\n<p>It is not immediately obvious what <code>soStuff</code> does. In seems to be a constructor, or initializer. Why not name it as such?</p>\n\n<p>You use a <code>HashMap</code>, but do not provide a custom hashing method for <code>TreeNode</code>. While you inherit one from <code>Object</code>, this isn't terribly advisable.</p>\n\n<p>What these three methods do is:</p>\n\n<ul>\n<li>You get a list of <code>TreeNode</code>s which only point to their parent. The task is to link these to a full tree.</li>\n<li>You build a map that maps parent nodes to a list of childs.</li>\n<li>You then assign the first item in each list to <code>parent.left</code>, the 2nd to <code>parent.right</code>, if applicable.</li>\n</ul>\n\n<p>Your solution has the advantage that it builds the tree top-down, recursively, and won't touch any nodes that will not be in the final tree. It comes at the cost of building an entirely unneccessary <code>HashMap</code>. The following implementation assumes that no unrelated nodes are in the input list:</p>\n\n<pre><code>/**\n * Expects a TreeNode collection where each node points to its parent.\n * Builds the full tree and returns the root (which has to have a\n * null parent).\n */\npublic static TreeNode linkToTree(Iterable<TreeNode> nodes) {\n /* Building the tree.\n *\n * At some point, we *will* find the root, thus getting a\n * handle on the tree. If not, \"null\" will be returned, which\n * is a good error case.\n * \n * Each node already knows its parent, so we just add the node\n * as a new child to the parent. We treat a \"null\" slot as empty.\n * First, we fill the left slot, then overwrite the right slot\n * without any checks – last one wins out.\n */\n\n TreeNode root;\n\n for (TreeNode node : nodes) {\n final TreeNode parent = node.getParent();\n\n // try to detect the root node\n if (parent == null) {\n root = node;\n }\n // add this node to the parent's left slot if it's empty\n else if (parent.getLeft() == null) {\n parent.setLeft(node);\n }\n // … else overwrite right slot\n else {\n parent.setRight(node);\n }\n }\n\n return root;\n}\n</code></pre>\n\n<p>What did I do differently?</p>\n\n<ul>\n<li>This method is <code>public static</code>. It is reusable, and does not modify any instance members.</li>\n<li>It takes any <code>Iterable</code>, not just a <code>List</code>. Why be unneccessarily specific?</li>\n<li>It is <em>documented</em>. Note that I have a large comment inside my method explaining why I wrote my code this way, and point out a certain edge case (not finding any root). Inside my <code>if/else</code>, I have smaller comments pointing out what each test <em>means</em>.</li>\n<li>I did not use recursion. While recursion can be very elegant, it is to be avoided on the JVM.</li>\n<li>It uses less memory than your solution, is shorter, and more elegant. Due to all of the comments, the implementation shouldn't be harder to understand than your code, even though the underlying algorithm is slightly more difficult.</li>\n<li>I don't use nondescriptive variable names like <code>map</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T23:42:03.633",
"Id": "31921",
"ParentId": "31916",
"Score": "5"
}
},
{
"body": "<p>Technically this is a binary tree node and not a tree node. In order to make it a tree node, it would have a list of child nodes instead of one left child and one right child. The class could add a list of children or rename <code>TreeNode</code> to <code>BinaryTreeNode</code> for higher cohesion.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-21T18:51:12.960",
"Id": "111427",
"ParentId": "31916",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "31921",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T21:53:54.570",
"Id": "31916",
"Score": "7",
"Tags": [
"java",
"tree"
],
"Title": "Create a tree from a list of nodes with parent pointers only"
}
|
31916
|
<p>Do you have an idea to "transfer" this CSS Code to Javascript (maybe jQuery)?</p>
<pre><code>html { background-color: #B94FC1; }
html:before, html:after { content: ""; height: 100%; width: 100%; position: fixed; z-index: -6; }
html:before { background-image: linear-gradient(to bottom, #5856D6 0%, #C644FC 100%); animation: fgradient 5s linear 0s infinite alternate; }
html:after { background-image: linear-gradient(to bottom, #C643FC 0%, #FF5F37 100%); animation: sgradient 5s linear 0s infinite alternate; }
@keyframes fgradient { 0% { opacity: 1; } 100% { opacity: 0; } }
@keyframes sgradient { 0% { opacity: 0; } 100% { opacity: 1; } }
</code></pre>
<p><a href="http://jsfiddle.net/aMVBk/1/" rel="nofollow">Fiddle.</a></p>
<p>I want a transition from a gradient to an other. My own code works well, but I want try the same with Javascript ;)</p>
<p>Hope somebody can help me.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T22:55:41.130",
"Id": "50960",
"Score": "0",
"body": "CAn you pls put your relevant code into the question"
}
] |
[
{
"body": "<p>using jquery:</p>\n\n<p><strong>html</strong></p>\n\n<pre><code><div class=\"gradient one\"></div>\n<div class=\"gradient two\"></div>\n</code></pre>\n\n<p><strong>css</strong></p>\n\n<pre><code>html { background-color: #B94FC1; } \nbody { margin:0; }\n.gradient { content: \"\"; height: 100%; width: 100%; position: fixed; z-index: -6; }\n.gradient.one { background-image: linear-gradient(to bottom, #5856D6 0%, #C644FC 100%);}\n.gradient.two { background-image: linear-gradient(to bottom, #C643FC 0%, #FF5F37 100%); display:none; }\n</code></pre>\n\n<p><strong>javascript</strong></p>\n\n<pre><code>$(function() {\n fadeToggle( $('.gradient.one') );\n fadeToggle( $('.gradient.two') );\n});\n\nfunction fadeToggle(el) {\n el.fadeToggle(5000,null,function() { fadeToggle(el); });\n}\n</code></pre>\n\n<p>fiddle: <a href=\"http://jsfiddle.net/aMVBk/2/\" rel=\"nofollow\">http://jsfiddle.net/aMVBk/2/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T23:12:47.553",
"Id": "31920",
"ParentId": "31917",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "31920",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T22:22:54.943",
"Id": "31917",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"css"
],
"Title": "CSS gradient transition_in javascript"
}
|
31917
|
<p>Here's my first HTML5 game: a really simple snake. I've never made a game before and haven't had too much experience with JavaScript.</p>
<p><a href="http://jsfiddle.net/NjdWv/1/" rel="noreferrer">Fiddle</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-js lang-js prettyprint-override"><code>$(document).ready(function(){
// SNAKE SETTINGS
var SQR_SIZE = 10;
var FRAMES = 100;
// SNAKE VARIABLES
var snakeSpeed = 50;
var moveCount = 0;
var snakeDirection = 38; //37 - left; 38 - up; 39 - right; 40 - down;
// OTHER VARS
var score = 0;
// TRAIL VARS
var xTrail = new Array();
var yTrail = new Array();
var snakeSize = 0;
// CREATE CANVAS
var c= document.getElementById("snakePlatform");
var ctx=c.getContext("2d");
var canvWidth = c.width;
var canvHeight = c.height;
c.addEventListener('click',function(e){mouseHandle(e.offsetX,e.offsetY);},false);
// SNAKE POSITIONING;
var xSnake;
var ySnake;
var xpos;
var ypos;
resetPositions();
// FOOD POSITIONING
var xFood;
var yFood;
// BUTTON POSITIONS
var buttonPos = new Array();
// GAMESTATE
var gameState = 0;
var preState = gameState;
// ----------- GAME PLAY -----------------------------------------------------------------
menuStart();
var checkGs=self.setInterval(function(){checkGamestate(gameState)},20);
function checkGamestate(s){
if(gameState != preState){
switch(s)
{
case 0:
menuStart();
preState = 0;
break;
case 1:
gameStart();
preState = 1;
break;
case 2:
pgStart();
preState = 2;
break;
default:
};
};
};
// ----------- GAME FUNCTIONS ------------------------------------------------------------
// GAME FLOW
function gameStart(){
var int=self.setInterval(function(){snakeAnimation()},snakeSpeed);
function snakeAnimation(){
if(moveCount == 0){
clear();
drawFirst();
moveFood();
drawFood();
moveCount++;
}else{
clear();
drawScore();
setTrail();
moveSnake(snakeDirection);
drawSnake();
if(wallCollision(xpos,ypos) || snakeCollision(xpos,ypos)){
resetGame();
int=window.clearInterval(int);
gameState=2;
};
if(foodCollision(xpos,ypos)){
addTrail();
clearFood();
drawSnake();
moveFood();
score++;
};
drawFood();
moveCount++;
drawScore();
};
};
};
// SCORE FUNCTIONS
function drawScore(){
ctx.font="25px Arial";
ctx.fillStyle="rgba(0,0,0,0.2)";
ctx.textAlign="center";
ctx.fillText(score,canvWidth/2,canvHeight/2);
};
// SNAKE FUNCTIONS
function drawSnake(){
drawFirst();
drawTrail();
};
function drawFirst(){
ctx.clearRect(0,0,canvWidth,canvHeight);
ctx.fillStyle="rgba(41,99,12,1)";
ctx.fillRect(xpos,ypos,SQR_SIZE,SQR_SIZE);
};
function moveSnake(d){
switch(d)
{
case 37:
xSnake--;
break;
case 38:
ySnake--;
break;
case 39:
xSnake++;
break;
case 40:
ySnake++;
break;
default:
};
xpos = xSnake*SQR_SIZE;
ypos = ySnake*SQR_SIZE;
};
$(document).keydown(function(event){
if(event.which == 37 || event.which == 38 || event.which == 39 || event.which == 40){
if(((event.which%2) == 0 && (snakeDirection%2) != 0)){
snakeDirection = event.which;
}else if(((event.which%2) != 0 && (snakeDirection%2) == 0)){
snakeDirection = event.which;
};
};
});
function resetPositions(){
xSnake = (canvWidth/SQR_SIZE)/2;
ySnake = (canvHeight/SQR_SIZE)/2;
xpos = xSnake*SQR_SIZE;
ypos = ySnake*SQR_SIZE;
};
// TRAIL FUNCTIONS
function addTrail(){
xTrail.push(xTrail[xTrail.length-1]);
yTrail.push(yTrail[yTrail.length-1]);
};
function setTrail(){
var i=xTrail.length;
var xTemp;
var yTemp
while(i>0){
xTrail[i] = xTrail[i-1];
yTrail[i] = yTrail[i-1];
i--;
};
xTrail.pop();
yTrail.pop();
xTrail[0] = xpos;
yTrail[0] = ypos;
};
function drawTrail(){
for(var a=0;a<xTrail.length;a++){
ctx.fillStyle="rgba(0,255,0,1)";
ctx.fillRect(xTrail[a],yTrail[a],SQR_SIZE,SQR_SIZE);
};
};
// FOOD FUNCTIONS
function clearFood(){
ctx.clearRect(xFood,yFood,SQR_SIZE,SQR_SIZE);
};
function moveFood(){
do{
xFood = (Math.floor(Math.random()*((canvWidth/SQR_SIZE)-SQR_SIZE))+1)*SQR_SIZE;
yFood = (Math.floor(Math.random()*((canvHeight/SQR_SIZE)-SQR_SIZE))+1)*SQR_SIZE;
}
while (snakeCollision(xFood,yFood));
};
function drawFood(){
ctx.fillStyle="rgba(255,0,0,1)";
ctx.fillRect(xFood,yFood,SQR_SIZE,SQR_SIZE);
};
// COLLISION CHECKS
function wallCollision(xsource,ysource){
if(xsource == canvWidth || xsource == 0-SQR_SIZE){
return true;
}else if(ysource == canvHeight || ysource == 0-SQR_SIZE){
return true;
};
};
function foodCollision(xsource,ysource){
if(xsource == xFood && ysource == yFood){
return true;
};
};
function snakeCollision(xsource,ysource){
for(var i=0;i<xTrail.length;i++){
if(xsource == xTrail[i] && ysource == yTrail[i]){
return true;
};
};
};
// RESET FUNCTIONS
function resetGame(){
resetPositions();
xTrail = [];
yTrail = [];
moveCount = 0;
};
// ----------- POST GAME FUNCTIONS -------------------------------------------------------
// PG START
function pgStart(){
clear();
ctx.font="25px Arial";
ctx.fillStyle="rgba(0,0,0,1)";
ctx.textAlign="center";
ctx.fillText('GAME OVER',canvWidth/2,canvHeight/2-30);
ctx.font="25px Arial";
ctx.fillStyle="rgba(0,0,0,1)";
ctx.textAlign="center";
ctx.fillText('SCORE: '+score,canvWidth/2,canvHeight/2);
drawButton(getCenterX(100),getCenterY(50)+35,100,50,"Re-Start",1);
};
// ----------- MENU FUNCTIONS ------------------------------------------------------------
// MENU START
function menuStart(){
clear();
drawButton(getCenterX(100),getCenterY(50),100,50,"Start",0);
};
// CLEAR SCREEN
function clear(){
ctx.clearRect(0,0,canvWidth,canvHeight);
};
// DRAW BUTTON
function drawButton(x,y,width,height,string,event){
xCenterButton=x+(width/2);
yCenterButton=y+(height/2);
ctx.fillStyle="rgba(0,0,0,1)";
ctx.fillRect(x-1,y-1,width+2,height+2);
ctx.fillStyle="rgba(242,255,195,1)";
ctx.fillRect(x,y,width,height);
ctx.font="25px Arial";
fontSize = getFontSize();
centerNum = fontSize/4;
ctx.fillStyle="rgba(0,0,0,1)";
ctx.textAlign="center";
ctx.fillText(string,xCenterButton,yCenterButton+centerNum);
buttonPos.push([[x],[y],[x+width],[y+height],[event]]);
};
// BUTTON EVENTS
function eventButton(d){
var buttonInt = parseInt(d);
switch(buttonInt){
case 0: // STARTBUTTON
if(gameState == 0){
gameState = 1;
};
break;
case 1:
if(gameState == 2){
score = 0;
gameState = 1;
};
break;
default:
alert("Error: No button in place.");
};
};
// BUTTON CLICK
function mouseHandle(x,y){
for(var i=0; i<buttonPos.length; i++){
if(x>buttonPos[i][0] && x<buttonPos[i][2]){
if(y>buttonPos[i][1] && y<buttonPos[i][3]){
eventButton(buttonPos[i][4]);
};
};
};
};
// GET FONT SIZE
function getFontSize(){
fontSizeArray = new Array();
fontString = ctx.font;
fInstance = fontString.indexOf("px");
for(var i=0;i<fInstance;i++){
fontSizeArray[i] = fontString[i];
};
fontSize = fontSizeArray.join("");
return fontSize;
};
// CANVAS CENTER
function getCenterX(width){
canvCenter = canvWidth/2;
widthCenter = width/2;
x = canvCenter - widthCenter;
return x;
};
function getCenterY(height){
canvCenter = canvHeight/2;
heightCenter = height/2;
y = canvCenter - heightCenter;
return y;
};
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#snakePlatform{
border:1px solid #000;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<canvas id="snakePlatform" width="400" height="400"></canvas></body></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>It's pretty good for a first game. There are a few things I would change:</p>\n\n<p><strong>1. Dependencies</strong></p>\n\n<p>You use jQuery for two purposes in your code: <code>$(document).ready</code> to trigger the game setup, and <code>$(document).keydown</code> to catch the keyboard events.</p>\n\n<p>However, there really isn't any need to use jQuery for either of these things, so all it does is add to the load time of the page.</p>\n\n<p>You can get rid of the <code>$(document).ready</code> completely if you move the JavaScript down to the bottom of the page (instead of inside the <code><head></code>).</p>\n\n<p>You can replace <code>$(document).keydown(function(event){</code> with <code>document.addEventListener('keydown',function(event){</code>.</p>\n\n<p><strong>2. Objects Namespaces</strong></p>\n\n<p>If you create a single component that uses a lot of JavaScript code, it is often considered best practice to put the code into an object. The biggest benefits of doing this are:</p>\n\n<ol>\n<li>You don't have to worry about other things on the same page conflicting with this code because you (or someone else) gave them the same names. This is particularly important given that some of your variable names <code>c</code>, <code>ctx</code>, etc. are fairly generic and likely to be used again.</li>\n<li><p>You can reuse the same code again and again to create multiple objects on the page without worrying about them interfering with each other. For example, you could create two snake games on a page by doing this:</p>\n\n<pre><code><canvas id=\"snakePlatform1\" width=\"400\" height=\"400\"></canvas>\n<canvas id=\"snakePlatform2\" width=\"400\" height=\"400\"></canvas>\n<script>\n var snake1 = new Snake('snakePlatform1');\n var snake2 = new Snake('snakePlatform2');\n</script>\n</code></pre>\n\n<p><em>Important Note: The code, as it exists now, will not work with more than one snake because it binds the <code>keydown</code> event to the document and this would cause the keystrokes to be sent to both games at once. In order to use more than one, you will need to figure out how to \"focus\" one or the other snake game at a time for keyboard input. Explaining how to do this is beyond the scope of this answer.</em></p></li>\n<li><p>You can expose some of the functionality of the snake game to outside code in a consistent and documented way. For example, you could provide a <code>getScore()</code> method that returns the current score (or a <code>snake.scored</code> event that fires whenever the score changes), a <code>turn(direction)</code> method that allows outside control of the snake, etc. These would be accessed in the example above by calling <code>snake1.getScore()</code>, <code>snake2.turn('DOWN')</code>, etc. You might subscribe to the event using (a jQuery example) <code>$('#snakePlatform1').on('snake.scored', function(score) {...})</code>. The possibilities are endless.</p></li>\n</ol>\n\n<p>It is also best to put this object inside a namespace. For example, instead of calling <code>new Snake('snakePlatform')</code>, you would call <code>new Dominic.Games.Snake('snakePlatform')</code>. This makes it easier to track and maintain code in large projects. While this project is fairly simple and may not need namespaces, it's good to get in the habit of using them unless there is a very good reason not to do so.</p>\n\n<p><strong>3. Enums</strong></p>\n\n<p>Although JavaScript doesn't really have the concept of <code>enum</code> like many other languages, it is often useful to define helper objects that act as enums. Here are the two enums that I would define for this game:</p>\n\n<pre><code>var directions = {\n LEFT: 37,\n UP: 38,\n RIGHT: 39,\n DOWN: 40,\n};\n\nvar states = {\n READY: 0,\n RUNNING: 1,\n OVER: 2,\n};\n</code></pre>\n\n<p>This makes it much easier to see what parts of the code are doing, and therefore makes the code much easier to maintain. For instance, if you don't touch the code for a long time, then come back to it to make some changes, you don't have to relearn what the different numbers you used stand for.</p>\n\n<hr>\n\n<p>I made a jsFiddle with these changes in it at <a href=\"http://jsfiddle.net/PXMAh/\">http://jsfiddle.net/PXMAh/</a>. Each of the sections above is done as a version of the fiddle, so you can add the version number at the end of the URL (last one is <a href=\"http://jsfiddle.net/PXMAh/2/\"><code>...PXMAh/2/</code></a>, back to <a href=\"http://jsfiddle.net/PXMAh/1/\"><code>.../1/</code></a> or <a href=\"http://jsfiddle.net/PXMAh/0/\"><code>.../0/</code></a>) to see the changes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T15:02:17.337",
"Id": "51236",
"Score": "0",
"body": "Thank you for such an in depth and informative answer! Very much appreciated! Also, could I give the canvas a tabIndex and use document.getElementById(id).focus(); to separate each instance of the game?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T19:09:44.327",
"Id": "32039",
"ParentId": "31919",
"Score": "17"
}
},
{
"body": "<p>You did really well with readability and documentation. On the design side, I would personally have the score off to the side and not in the middle, although it isn't that big of a deal. I would also consider slowing down the snake a little bit. I noticed that you use a lot of code for adding length to your snake. If you want to, I would suggest doing this instead of using <code>xTrail</code> and <code>yTrail</code>: </p>\n\n<pre><code>var body = [\n {\n \"x\": 6,\n \"y\": 0\n },\n {\n \"x\": 5,\n \"y\": 0\n },\n {\n \"x\": 4,\n \"y\": 0\n },\n {\n \"x\": 3,\n \"y\": 0\n },\n {\n \"x\": 2,\n \"y\": 0\n },\n {\n \"x\": 1,\n \"y\": 0\n }\n];\n</code></pre>\n\n<p>I used a grid system to go along with the array of body segment objects (row 1, column 1 = <code>1x1</code>). To add/remove segments during movement, I used <code>.unshift()</code> and <code>.pop()</code>.</p>\n\n<p>To draw the segments onto the board, I used a for loop and <code>body[i].x</code> or <code>body[i].y</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-23T20:57:58.870",
"Id": "248176",
"Score": "0",
"body": "Hi! Welcome to Code Review. Good job on your first answer! I hope to see more of these great answers!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-23T17:49:35.817",
"Id": "132883",
"ParentId": "31919",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "32039",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T22:36:35.977",
"Id": "31919",
"Score": "16",
"Tags": [
"javascript",
"jquery",
"game",
"html5",
"snake-game"
],
"Title": "First HTML5 game: Snake"
}
|
31919
|
<p>I want you to pick my code apart and give me some feedback on how I could make it better or more simple.</p>
<pre><code>public class MaxSumPath {
private TreeNode root;
private static class TreeNode {
TreeNode left;
TreeNode right;
int item;
TreeNode (TreeNode left, TreeNode right, int item) {
this.left = left;
this.right = right;
this.item = item;
}
}
private static class TreeInfo {
TreeNode node;
int maxCount;
TreeInfo (TreeNode node, int maxCount) {
this.node = node;
this.maxCount = maxCount;
}
}
public void maxSumPath () {
final TreeInfo treeInfo = new TreeInfo(null, 0);
fetchMaxSumPath(root, treeInfo, root.item);
printPath (root, treeInfo);
}
private void fetchMaxSumPath (TreeNode node, TreeInfo treeInfo, int sumSoFar) {
if (node == null) return;
sumSoFar = sumSoFar + node.item;
if (node.right == null && node.left == null) {
if (sumSoFar > treeInfo.maxCount) {
treeInfo.maxCount = sumSoFar;
treeInfo.node = node;
}
return;
}
fetchMaxSumPath(node.left, treeInfo, sumSoFar);
fetchMaxSumPath(node.right, treeInfo, sumSoFar);
}
private boolean printPath (TreeNode node, TreeInfo treeInfo) {
if (node != null && (node == treeInfo.node || printPath(node.left, treeInfo) || printPath(node.right, treeInfo))) {
System.out.print(node.item + ", ");
return true;
}
return false;
}
}
</code></pre>
<p>Also considering additional storage (<code>TreeInfo</code>), is it right to say that the space complexity is \$O(1)\$?</p>
|
[] |
[
{
"body": "<p>You should have a constructor <code>MaxSumPath(TreeNode root)</code>. Otherwise, there's no way for any other class to call the code.</p>\n\n<p>The <code>TreeNode(left, right, item)</code> constructor is awkward. Consider rearranging the <code>TreeNode</code> constructor arguments to <code>TreeNode(left, item, right)</code> or <code>TreeNode(item, left, right)</code>. I suggest creating a <code>TreeNode(item)</code> constructor as well.</p>\n\n<p>Your <code>TreeInfo</code> could be eliminated by moving its variables into <code>MaxSumPath</code> itself. I'd rename the variables to <code>TreeNode maxLeaf</code> and <code>int maxSum</code>.</p>\n\n<p>In the <code>maxSumPath()</code> method, you call <code>fetchMaxSumPath(root, treeInfo, root.item)</code>. It should be <code>fetchMaxSumPath(root, treeInfo, 0)</code> if you don't want to double-count the root node. (Fortunately, this bug happens not to affect the output.)</p>\n\n<p>The space complexity is actually O(log <em>n</em>) when you take into account the stack used in recursion. The time complexity is O(<em>n</em>), because you visit every node once when discovering the leaf for the path with the maximum sum, and every node again to find that leaf for printing. You might want to use O(log <em>n</em>) space (which, remember, happens anyway due to the recursion stack) to keep track of the best path while discovering the best sum, which lets you avoid the second pass O(<em>n</em>) pass.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T07:57:32.813",
"Id": "51006",
"Score": "0",
"body": "Agree on constructor, agree on the double counting bug."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T07:59:25.387",
"Id": "51007",
"Score": "0",
"body": "Disagree on - keeping a instance variable for max count, because maintining that value will be complicated if new nodes get added or deleting from tree, I would appreciate if you could highlight if my method had pressing drawbacks, in addition to suggestions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T08:00:45.457",
"Id": "51008",
"Score": "0",
"body": "Lastly, agree again on complexity, in addition how much space complexity would TreeInfo add ? would it be O(1) ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T15:48:30.660",
"Id": "51019",
"Score": "1",
"body": "I see no reason to treat what I call `maxLeaf` and `maxSum` any differently from `root`. Either make them all instance variables of `MaxSumPath` (my preferred option), all encapsulated in `TreeInfo`, or pass them all around as local parameters (my least preferred option)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T15:49:55.447",
"Id": "51020",
"Score": "1",
"body": "`TreeInfo` adds O(1) space on top of the O(log _n_) stack that I mentioned, bringing the total space to O(log _n_)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T16:09:22.100",
"Id": "51021",
"Score": "2",
"body": "Correction — O(log _n_) is a best-case scenario, because the tree may not be balanced. It could be O(_n_) in the worst case."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T04:00:28.467",
"Id": "31931",
"ParentId": "31922",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "31931",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T00:36:23.193",
"Id": "31922",
"Score": "3",
"Tags": [
"java",
"algorithm",
"tree"
],
"Title": "Print path (leaf to root) with max sum in a binary tree"
}
|
31922
|
<p>As far as I know (and I don't claim to know much about this!), direct binding to <code>ListView.SelectedItems</code> isn't possible in WPF. I've seen work-arounds involving code-behind which I'm not too crazy about, especially since I'm having a hard time with getting a <code>DelegateCommand</code> to work, and decided to use <code>RoutedCommands</code>. For the following XAML command binding...</p>
<pre><code><UserControl.CommandBindings>
<CommandBinding Command="{x:Static my:ClientSearchSection.AddSelectionCommand}"
CanExecute="CanExecuteAddSelectionCommand"
Executed="ExecuteAddSelectionCommand"/>
</UserControl.CommandBindings>
</code></pre>
<p>...I have the following code-behind:</p>
<pre><code>public static readonly RoutedCommand AddSelectionCommand = new RoutedCommand();
private void CanExecuteAddSelectionCommand(object sender, CanExecuteRoutedEventArgs e)
{
if (Commands != null)
{
Commands.SelectedClients = SearchResultsList.SelectedItems.Cast<ClientViewModel>().ToList();
e.CanExecute = Commands.CanExecuteAddSelectionCommand();
}
e.Handled = true;
}
private void ExecuteAddSelectionCommand(object sender, ExecutedRoutedEventArgs e)
{
Commands.SelectedClients = SearchResultsList.SelectedItems.Cast<ClientViewModel>().ToList();
Commands.OnExecuteAddSelectionCommand();
e.Handled = true;
}
</code></pre>
<p>Where <code>Commands</code> is a get-only private property that returns an interface implemented by the ViewModel, which defines all the <code>CanExecuteXXXX</code> and <code>ExecuteXXXX</code> methods.</p>
<p>Here's how I have it:</p>
<pre><code>private IViewModel _viewModel;
private IClientsSearchSectionCommands Commands { get { return _viewModel as IClientsSearchSectionCommands; } }
public ClientSearchSection()
{
InitializeComponent();
DataContextChanged += ClientsSearchSection_DataContextChanged;
}
void ClientSearchSection_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
_viewModel = e.NewValue as IViewModel;
}
</code></pre>
<hr>
<p>This allows me to implement the command code in the ViewModel, for example:</p>
<pre><code>public bool CanExecuteAddSelectionCommand()
{
return SelectedClients.Count > 0;
}
public void OnExecuteAddSelectionCommand()
{
// whatever needs to happen here, I can access my model as needed
}
</code></pre>
<p>The trick that allows the <code>SelectedItems</code> to work is with this property, exposed by the <code>IClientsSearchSectionCommands</code> interface implemented by the ViewModel:</p>
<pre><code>public IList<ClientViewModel> SelectedClients { get; set; }
</code></pre>
<p>...and the fact that I'm setting them in the commands' <code>CanExecute</code> and <code>Executed</code> handlers.</p>
<p>This works beautifully... but is it weird in any way? [How] could it be done better?</p>
<p>I don't want to dive into <em>behaviors</em> at this point, firstly because I have no clue about them, second, because I'm dragging a more junior developper into WPF & MVVM, coming from WinForms and inline-SQL-in-the-form's-code-behind, so I'd like to know if this code is easy enough to follow...</p>
|
[] |
[
{
"body": "<p>Your approach looks fine to me. Except i would probably use prefix-casting, to get cast exceptions straigt away if something goes wrong, instead of using <code>as</code>.</p>\n\n<p>This can be achieved without modifying code-behind tho. You can bind container's IsSelected property to appropriate item's viewmodel property.</p>\n\n<pre><code><ListView.ItemContainerStyle>\n <Style TargetType=\"ListViewItem\" >\n <Setter Property=\"IsSelected\" Value=\"{Binding IsSelected}\"/>\n </Style>\n</ListView.ItemContainerStyle>\n</code></pre>\n\n<p>Then you can access selected items in your viewmodel by using:</p>\n\n<pre><code>protected IEnumerable<Item> SelectedItems { get { return Items.Where(x => x.IsSelected); } }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T17:21:11.453",
"Id": "51180",
"Score": "0",
"body": "Wow this is amazing - turns out I have those \"item view models\" implementing a `ISelectable` interface so they all have a `IsSelected` property, and with this XAML I can perform that binding at item level, only the designer blue-squigles `{Binding IsSelected}` saying it can't resolve that property.. but it works! Is there a way to make the `ListView.ItemContainerStyle` block understand that the view model it should validate at design-time against is that of `ListView.ItemsSource`? (like `ListView.ItemTemplate` does) ...'cause for a novice dev it's not obvious that it works at run-time!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T06:14:05.560",
"Id": "51209",
"Score": "1",
"body": "@retailcoder, yes, you should either set an actual DataContext in Xaml or specify a design-time DataContext (see http://stackoverflow.com/questions/13863099/can-i-somehow-tell-resharper-about-the-type-of-the-viewmodel for example). Normally it doesn't worth the effort tho."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T13:27:45.857",
"Id": "51228",
"Score": "0",
"body": "I meant this:http://stackoverflow.com/questions/19100882/how-does-this-setter-end-up-working-listview-multiselect/19101155?noredirect=1#comment28241704_19101155"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T07:12:42.217",
"Id": "32017",
"ParentId": "31926",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "32017",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T01:49:54.823",
"Id": "31926",
"Score": "4",
"Tags": [
"c#",
"wpf",
"mvvm"
],
"Title": "ListView MultiSelect, MVVM and RoutedCommands"
}
|
31926
|
<pre><code>from string import punctuation, ascii_lowercase
def is_palindrome(string):
"""Return True if string is a palindrome,
ignoring whitespaces and punctuation.
"""
new = ""
for char in string:
lc = char.lower()
for x in lc:
if x in ascii_lowercase:
new += x
return new[::-1] == new
# string = "Was it a rat I saw?"
# print(is_palindrome(string))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T09:59:03.743",
"Id": "51010",
"Score": "0",
"body": "What should `is_palindrome('èÈ')` be? I mean, you are considering only *ascii* letters, but should we remove from the string any non-ascii letter before the comparison or unicode *letters* should be taken into account?"
}
] |
[
{
"body": "<ul>\n<li>You are unnecessarily importing <code>punctuation</code></li>\n<li>Avoid reassigning module names such as <code>string</code> in your code</li>\n<li>A list comprehension would be a simpler way of filtering out the data you don't want</li>\n</ul>\n\n<hr>\n\n<pre><code>from string import ascii_letters\n\ndef is_palindrome(candidate):\n \"\"\"\n Returns True if candidate is a palindrome, ignoring whitespaces and punctuation.\n \"\"\"\n stripped = [char.lower() for char in candidate if char in ascii_letters]\n return stripped == stripped[::-1]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T03:30:16.417",
"Id": "31929",
"ParentId": "31928",
"Score": "12"
}
},
{
"body": "<p>I think we could build up the new string in a nicer way:</p>\n\n<pre><code>from string import ascii_letters\n\ndef is_palindrome(s):\n new = ''.join(c.lower() for c in s if c in ascii_letters)\n return new[::-1] == new\n</code></pre>\n\n<p>If we wanted to avoid lowercasing and stripping non-letters out of the whole string when the first few characters might be enough to determine if it's a palindrome, we could be lazy about doing the transformation. There's also this nice idea of splitting out the filtering and normalizing into separate logic we could pursue. (see <a href=\"http://nedbatchelder.com/blog/201303/loop_like_a_native.html\" rel=\"nofollow\">Loop like a Native</a>)</p>\n\n<pre><code>from string import ascii_lowercase\nfrom itertools import izip\n\ndef just_lowercase_ascii(s):\n for char in s:\n if char.lower() in ascii_lowercase:\n yield char.lower()\n\ndef is_palindrome(s):\n for char1, char2 in izip(just_lowercase_ascii(reversed(s)), just_lowercase_ascii(s):\n if char1 != char2:\n return False\n return True\n</code></pre>\n\n<p>or</p>\n\n<pre><code>def is_palindrome(s):\n all(c1 == c2 for c1, c2 in izip(just_lowercase_ascii(reversed(s)),\n just_lowercase_ascii(s)\n</code></pre>\n\n<p>edit: didn't change parameter name, but string is bad as other answer points out.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T03:32:00.337",
"Id": "31930",
"ParentId": "31928",
"Score": "4"
}
},
{
"body": "<p>The most readable and fast implementation should be something on the lines of:</p>\n\n<pre><code>from string import ascii_lowercase\n\n\ndef is_palindrome(candidate, letters=set(ascii_lowercase)):\n \"\"\"\n Return True if candidate is a palindrome, ignoring case and\n ignoring all characters not in letters.\n\n The letters paramater defaults to all the ASCII letters.\n\n \"\"\"\n stripped = [char for char in candidate.lower() if char in letters]\n return stripped == list(reversed(stripped))\n</code></pre>\n\n<p>If you are considering only short palindromes(and you probably are if you are not dealing with hundred of characters palindrome strings), using <code>stripped[::-1]</code> should be slightly faster than <code>list(reversed(stripped))</code>, although the latter is more readable.</p>\n\n<p>Note that:</p>\n\n<ul>\n<li>calling <code>.lower()</code> on each character is pretty bad for performances. You can first transform to lowercase and then simply check for <code>ascii_lowercase</code>.\nWhen possible try to avoid useless function calls since they are quite \"heavy\" when in a tight loop</li>\n<li>Use <code>set</code>s when you want to check for membership. Their lookup is constant time, while doing <code>character in some_text</code> might need to scan the whole text.\nThis is especially important in loops since using <code>in</code> on strings might produce a <em>quadratic</em> algorithm, while using <code>set</code>s the algorithm could be linear.</li>\n</ul>\n\n<hr>\n\n<p>Also in your code:</p>\n\n<pre><code>lc = char.lower()\nfor x in lc:\n if x in ascii_lowercase:\n new += x\n</code></pre>\n\n<p>This <code>for</code> loop is useless. <code>lc</code> will always be a single character, hence the <code>for</code> will be executed exactly once, as if the code was:</p>\n\n<pre><code>lc = char.lower()\nif lc in ascii_lowercase:\n new += lc\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T10:12:12.993",
"Id": "31939",
"ParentId": "31928",
"Score": "4"
}
},
{
"body": "<p>The question was mostly answered, however I think it's not entirely correct to exclude digits and it's more optimal to lower case the whole string instead of lower casing it character by character. And also there's should be check for empty strings. So my version looks like this:</p>\n\n<pre><code>from string import digits, ascii_lowercase\n\nchars = digits + ascii_lowercase\n\ndef is_palindrome(s):\n norm = [c for c in s.lower() if c in chars]\n return norm[::-1] == norm != []\n</code></pre>\n\n<p>However in 2013 you probably want to have Unicode version of the function which can looks like this:</p>\n\n<pre><code>from unicodedata import category\n\ndef is_palindrome(u):\n norm = [c for c in u.lower() if category(c)[0] in \"LN\"]\n return norm[::-1] == norm != []\n</code></pre>\n\n<p>Some examples for Unicode version of <code>is_palindrome</code>:</p>\n\n<pre><code>>>> is_palindrome(u\"...\")\nFalse\n>>> is_palindrome(u\"Was it a rat I saw?\")\nTrue\n>>> is_palindrome(u\"А роза упала на лапу Азора.\")\nTrue\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T10:27:19.840",
"Id": "31940",
"ParentId": "31928",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "31929",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T02:57:46.253",
"Id": "31928",
"Score": "6",
"Tags": [
"python",
"strings",
"palindrome"
],
"Title": "is_palindrome function that ignores whitespace and punctuation"
}
|
31928
|
<p>I'm building a text search system for a web application in PHP. I wrote this function that gets the sentences of the text which contains the keywords used by the user and also highlight them (well, surround them with any tags anyway).</p>
<p>I'm measuring an average of 23ms if only the first matches is retrieved, and about 27ms if I choose to get all of the matches. It doesn't seem much, but I'll use it for all search results in a page and many users might be doing a search at the same time.</p>
<p>The function is somewhat long but I heavily commented it:</p>
<pre><code><?php
/**
* Return the highlighted excerpts, given the text and the keywords. This can show
* ALL phrases with keywords or just the first matches (in both cases, no phrase is
* repeated, even containing more than one keyword, but all keywords are highlighted.
*
* @param string $text The text in which to perform the search.
* @param array $keywords A list of keywords to search.
* @param string $prefix The prefix for the highlighting (i.e. the opening tag).
* @param string $suffix The suffix for the highlighting (i.e. the closing tag).
* @param boolean $only_first Whether to show only the first match or all of them.
* @return string A text with the matched keywords an the surrounding phrases, separated
* by ellipsis (...).
*/
function excerpts($text, $keywords, $prefix = '<b>', $suffix = '</b>', $only_first = TRUE)
{
// Replacing null prefix suffix for default values.
if ($prefix === NULL)
{
$prefix = '<b>';
}
if ($suffix === NULL)
{
$suffix = '</b>';
}
// Split the text in an array
$text_array = preg_split("/([^\w]+)/u", $text, NULL, PREG_SPLIT_DELIM_CAPTURE);
$text_array_len = count($text_array);
// Use a lower case version for case insensitive search
// And remove accents to also ignore them.
$map = function($el){
return strtolower(iconv("utf-8", "ascii//TRANSLIT", $el));
};
$lowers = array_map($map, $text_array);
// Have to do the same with the keywords
$keywords = array_map($map, $keywords);
$matches = array();
// Get the keys where the values matches the keywords
if ($only_first)
{
foreach ($keywords as $word)
{
$matches[] = array_search($word, $lowers);
}
}
else
{
foreach ($keywords as $word)
{
$matches = array_merge($matches, array_keys($lowers, $word));
}
}
// The result must be in the same order as the original text
sort($matches);
$result = array();
// Keep track of previous phrases, to check if the current phrase
// is the same as the previous and avoid repeating.
$previous_start = $text_array_len;
$previous_end = 0;
foreach ($matches as $key)
{
// Find the nearest period before this matched key
$first_period = -1;
for ($j = $key - 1; $j >= 0; $j--)
{
if (preg_match('/\./', $text_array[$j]))
{
$first_period = $j;
break;
}
} unset($j);
// Check if we already did this phrase:
if (($first_period + 1) >= $previous_start && ($first_period + 1) <= $previous_end)
{
continue;
}
// Now we set the previous values
$previous_start = $first_period + 1;
$previous_end = $text_array_len - 1;
// Put an ellipsis only if not at the beginning
if ($previous_start != 0)
{
$result[] = ' ... ';
}
// Go from there forward to the next period
for ($j = $previous_start; $j < $text_array_len; $j++)
{
// If it's a period and we already showed the key, stop it
if ($j > $key && (strpos($text_array[$j], '.') !== FALSE))
{
$previous_end = $j;
break;
}
// If it's one keyword, surround it
if (in_array($j, $matches))
{
$result[] = $prefix . $text_array[$j] . $suffix;
}
else
{
$result[] = $text_array[$j];
}
}
}
// This is tricky: it puts the last period of the text
// if we stopped just a bit before
if ($previous_end == ($text_array_len - 2))
{
$result[] = $text_array[$text_array_len - 1];
}
// If we didn't reach the finish, show the ellipsis
elseif ($previous_end < ($text_array_len - 2))
{
$result[]= ' ...';
}
// Bring the array together again to a string
return implode('', $result);
}
</code></pre>
<p>Is there a way to increase performance? Am I overreacting? Can it be more concise and/or more simple?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T05:37:54.553",
"Id": "51002",
"Score": "0",
"body": "Why complicate the wrapping so much? Can't you just use something like this? https://gist.github.com/elclanrs/6738783"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T06:45:21.287",
"Id": "51003",
"Score": "0",
"body": "@elclanrs I use both prefix and suffix because the tag may contain attributes (such as style or class), hence they might be different. But doing the overall wrapping later may be neater. Thanks for the tip."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T04:05:11.877",
"Id": "31932",
"Score": "2",
"Tags": [
"php",
"strings",
"search"
],
"Title": "How to increase concision and performance in a function to retrieve sentences where keywords match?"
}
|
31932
|
<p>I'm not a Javascript expert, so please review this function for me. Also, it could be that there is something in any of the library we're using in our project that can do something similar for me (angular, foundation, jquery, underscore), but I'm not too familiar yet with most of them.</p>
<pre><code>// helper function, parses numeric input also ending with %
/*
[parseNumeric('123') === 123,
parseNumeric('10 abc') === undefined
parseNumeric('10.10%') === 10.1,
parseNumeric(' 10.1000 ') === 10.1,
parseNumeric('10. 01%' ) === undefined,
parseNumeric('10.0 %') === 10] */
function parseNumeric(number) {
if (number === undefined || typeof(number) === 'number') {
return number;
}
// delete trailing zeros and whitespaces between number digits and %,
// leaving % if present
var numberString = number.trim().replace(/\.?0*\s*(\%)?$/g,'$1');
var parsedNumber = parseFloat(number);
if (isNaN(parsedNumber)) {
return undefined;
}
var parsedNumberLength = (parsedNumber+'').length;
if (numberString.length === parsedNumberLength) {
return parsedNumber;
}
if (numberString.charAt(numberString.length - 1) === '%' &&
(numberString.length - 1) === parsedNumberLength) {
return parsedNumber;
}
return undefined;
}
</code></pre>
|
[] |
[
{
"body": "<p>I think it's a bit too much code. If you are already using a regular expression, why not using it to do all the parsing for you?</p>\n\n<pre><code>function parseNumeric(number) {\n var num = number.trim();\n var reOut = /^([-+]?(\\d+\\.?\\d*|\\d*\\.?\\d+))\\s*%?$/.exec(num);\n return reOut ? parseFloat(reOut[1]): undefined;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T00:05:56.303",
"Id": "31962",
"ParentId": "31934",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T07:29:30.677",
"Id": "31934",
"Score": "2",
"Tags": [
"javascript",
"parsing"
],
"Title": "Function to parse floats optionally followed by %, more strict than parseFloat in javascript"
}
|
31934
|
<pre><code>var appname = " - simple notepad",
textarea = document.getElementById("textarea"),
untitled = "untitled.txt" + appname,
filename = "*.txt",
isModified;
document.title = untitled;
textarea.onpaste = textarea.onkeypress = function() {
isModified = true;
};
function confirmNav() { // Confirm navigation
if (isModified) {
var a = window.confirm("You have unsaved changes that will be lost.");
if (a) {
isModified = false;
}
}
}
function New() { // New
confirmNav();
if (!isModified) {
textarea.value = "";
document.title = untitled;
}
textarea.focus();
}
function Open() { // Open
confirmNav();
if (!isModified) {
document.getElementById("selected_file").click();
}
}
function loadFileAsText() { // load file as text
var selected_file = document.getElementById("selected_file").files[0];
var fileReader = new FileReader();
fileReader.onloadend = function(e) {
if (e.target.readyState === FileReader.DONE) {
filename = selected_file.name;
document.title = filename + appname;
textarea.value = e.target.result;
textarea.focus();
}
};
fileReader.readAsText(selected_file);
}
function rename() { // Rename
filename = window.prompt("Name this note:", filename);
if (filename) {
filename = (filename.lastIndexOf(".txt") === -1) ? filename + ".txt" : filename;
document.title = filename + appname;
}
}
function Save() { // Save
rename();
if (filename) {
var blob = new Blob([textarea.value], {
type: "text/plain;charset=utf-8"
});
window.saveAs(blob, filename);
isModified = false;
}
textarea.focus();
}
function Print() { // Print
var prnt_helper = document.getElementById("prnt_helper");
prnt_helper.innerHTML = textarea.value;
window.print();
prnt_helper.innerHTML = "";
textarea.focus();
}
function Help() { // Help
var help = document.getElementById("help_content"),
overlay = document.getElementById("overlay");
function closeHelpAndOverlay() {
help.setAttribute("aria-hidden", "true");
overlay.setAttribute("aria-hidden", "true");
textarea.focus();
}
if (help["aria-hidden"] === "true") {
closeHelpAndOverlay();
} else {
help.setAttribute("aria-hidden", "false");
overlay.setAttribute("aria-hidden", "false");
textarea.blur();
document.getElementById("overlay").onclick = function() {
closeHelpAndOverlay();
};
// document.onkeydown = function(e) { // esc to close help
// if (e.keyCode === 27 || e.which === 27) {
// closeHelpAndOverlay();
// }
// };
}
}
// Confirm close
window.onbeforeunload = function() {
if (isModified) {
return "You have unsaved changes that will be lost.";
}
};
// Keyboard shortcuts
document.onkeydown = function(e) {
var key = e.keyCode || e.which;
if (e.ctrlKey) {
if (e.altKey) {
if (key === 78) {
// Ctrl+Alt+N
New();
}
}
if (key === 79) {
// Ctrl+O
e.preventDefault();
Open();
}
if (key === 83) {
// Ctrl+S
e.preventDefault();
Save();
}
if (key === 80) {
// Ctrl+P
e.preventDefault();
Print();
}
if (key === 191) {
// Ctrl+/
e.preventDefault();
Help();
}
}
if (e.keyCode === 9 || e.which === 9) { // tab
e.preventDefault();
var s = textarea.selectionStart;
textarea.value = textarea.value.substring(0, textarea.selectionStart) + "\t" + textarea.value.substring(textarea.selectionEnd);
textarea.selectionEnd = s + 1;
}
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T07:55:55.007",
"Id": "51004",
"Score": "0",
"body": "Do you have a question, or any specific part of your code you want looked at? Or just anything and everything?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T07:57:07.397",
"Id": "51005",
"Score": "0",
"body": "@Jeremy I'll assume \"anything and everything\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T10:07:45.823",
"Id": "51012",
"Score": "0",
"body": "yea you can say anything, the whole code, the way I coded this stuff. you may suggest me some simpler way if there are... and so on. thanks."
}
] |
[
{
"body": "<p>You can optimize some queries.</p>\n\n<pre><code>var selected_file = document.getElementById(\"selected_file\")\n</code></pre>\n\n<p>Unless your HTML changes considerably (replacing nodes periodically), every call to getElementById() will return the same node. You can access the node more efficiently if you cache the node in a local variable, and use the same local variable throughout your code, instead of looking it up multiple times.</p>\n\n<p>Same with:</p>\n\n<pre><code>// Help\nvar help = document.getElementById(\"help_content\"),\n overlay = document.getElementById(\"overlay\");\n</code></pre>\n\n<p>As long as all these elements exist when your code initializes, you can lookup and store them in variables once, instead of each time Help() (etc) is called. <em>In your code, the performance increase will be very minor, but it can add up in other situations.</em></p>\n\n<hr>\n\n<p>In your keydown block:</p>\n\n<pre><code>if (key === 79) {\n...\nif (key === 83) {\n...\n\n// function rename()\n(filename.lastIndexOf(\".txt\") === -1)\n</code></pre>\n\n<p>You can shave a few bytes by using <code>==</code> instead of <code>===</code>. Since you're comparing primitives, not objects, <code>==</code> and <code>===</code> function equivalently.</p>\n\n<p>Using <code>===</code> (instead of <code>==</code>) is a good practice when you're not sure, but it is unnecessary in the places you are using it.</p>\n\n<hr>\n\n<p>It looks like you didn't update your last check in the keydown callback</p>\n\n<pre><code>if (e.keyCode === 9 || e.which === 9) { // tab\n</code></pre>\n\n<p>Can be rewritten as:</p>\n\n<pre><code>if (key == 9) { // tab\n</code></pre>\n\n<hr>\n\n<pre><code>function confirmNav() { // Confirm navigation\n if (isModified) {\n var a = window.confirm(\"You have unsaved changes that will be lost.\");\n if (a) {\n isModified = false;\n ...\n</code></pre>\n\n<hr>\n\n<p>While nothing is technically wrong here, I'd either like to see the <code>confirm</code> inlined into the <code>if()</code> or a more descriptive variable name. <code>a</code> is meaningless.</p>\n\n<pre><code> if (window.confirm(\"You have unsaved changes that will be lost.\")) {\n // or \n var leavePage = window.confirm(\"You have unsaved changes that will be lost.\");\n if (leavePage) {\n</code></pre>\n\n<hr>\n\n<p>Your code only has three long lines. The longest, at 136 chars:</p>\n\n<pre><code>var s = textarea.selectionStart\ntextarea.value = textarea.value.substring(0, textarea.selectionStart) + \"\\t\" + textarea.value.substring(textarea.selectionEnd);\ntextarea.selectionEnd = s + 1;\n</code></pre>\n\n<p>I compacted it be using the local you already declared, and by adding a second. Now 97 chars:</p>\n\n<pre><code>var sStart = textarea.selectionStart,\n txt = textarea.value;\ntextarea.value = txt.substring(0, sStart) + \"\\t\" + txt.substring(textarea.selectionEnd);\n</code></pre>\n\n<p>I don't think <code>s</code> was a bad variable name (<code>s</code> for selection or start is meaningful), but sStart is more clear.</p>\n\n<hr>\n\n<p>You wrote some lovely, readable, and coherent JavaScript.</p>\n\n<p>Here is everything:</p>\n\n<pre><code>var appname = \" - simple notepad\",\n textarea = document.getElementById(\"textarea\"),\n help = document.getElementById(\"help_content\"),\n overlay = document.getElementById(\"overlay\"),\n selected_file = document.getElementById(\"selected_file\"),\n prnt_helper = document.getElementById(\"prnt_helper\"),\n untitled = \"untitled.txt\" + appname,\n filename = \"*.txt\",\n isModified;\n\ndocument.title = untitled;\n\ntextarea.onpaste = textarea.onkeypress = function() {\n isModified = true;\n};\n\nfunction confirmNav() { // Confirm navigation\n if (isModified) {\n var leavePage = window.confirm(\"You have unsaved changes that will be lost.\");\n if (leavePage) {\n isModified = false;\n }\n }\n}\n\nfunction New() { // New\n confirmNav();\n if (!isModified) {\n textarea.value = \"\";\n document.title = untitled;\n }\n textarea.focus();\n}\n\nfunction Open() { // Open\n confirmNav();\n if (!isModified) {\n selected_file.click();\n }\n}\n\nfunction loadFileAsText() { // load file as text\n var file = selected_file.files[0],\n fileReader = new FileReader();\n fileReader.onloadend = function(e) {\n if (e.target.readyState == FileReader.DONE) {\n filename = file.name;\n document.title = filename + appname;\n textarea.value = e.target.result;\n textarea.focus();\n }\n };\n fileReader.readAsText(file);\n}\n\nfunction rename() { // Rename\n filename = window.prompt(\"Name this note:\", filename);\n if (filename) {\n filename = (filename.lastIndexOf(\".txt\") == -1) ? filename + \".txt\" : filename;\n document.title = filename + appname;\n }\n}\n\nfunction Save() { // Save\n rename();\n if (filename) {\n var blob = new Blob([textarea.value], {\n type: \"text/plain;charset=utf-8\"\n });\n window.saveAs(blob, filename);\n isModified = false;\n }\n textarea.focus();\n}\n\nfunction Print() { // Print\n prnt_helper.innerHTML = textarea.value;\n window.print();\n prnt_helper.innerHTML = \"\";\n textarea.focus();\n}\n\nfunction Help() { // Help\n function closeHelpAndOverlay() {\n help.setAttribute(\"aria-hidden\", \"true\");\n overlay.setAttribute(\"aria-hidden\", \"true\");\n textarea.focus();\n }\n\n if (help[\"aria-hidden\"] == \"true\") {\n closeHelpAndOverlay();\n } else {\n help.setAttribute(\"aria-hidden\", \"false\");\n overlay.setAttribute(\"aria-hidden\", \"false\");\n textarea.blur();\n overlay.onclick = function() {\n closeHelpAndOverlay();\n };\n // document.onkeydown = function(e) { // esc to close help\n // if (e.keyCode == 27 || e.which == 27) {\n // closeHelpAndOverlay();\n // }\n // };\n }\n}\n\n// Confirm close\nwindow.onbeforeunload = function() {\n if (isModified) {\n return \"You have unsaved changes that will be lost.\";\n }\n};\n\n// Keyboard shortcuts\ndocument.onkeydown = function(e) {\n var key = e.keyCode || e.which;\n if (e.ctrlKey) {\n if (e.altKey) {\n if (key == 78) {\n // Ctrl+Alt+N\n New();\n }\n }\n if (key == 79) {\n // Ctrl+O\n e.preventDefault();\n Open();\n }\n if (key == 83) {\n // Ctrl+S\n e.preventDefault();\n Save();\n }\n if (key == 80) {\n // Ctrl+P\n e.preventDefault();\n Print();\n }\n if (key == 191) {\n // Ctrl+/\n e.preventDefault();\n Help();\n }\n }\n if (key == 9) { // tab\n e.preventDefault();\n var sStart = textarea.selectionStart,\n txt = textarea.value;\n textarea.value = txt.substring(0, sStart) + \"\\t\" + txt.substring(textarea.selectionEnd);\n textarea.selectionEnd = sStart + 1;\n }\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T13:51:19.177",
"Id": "51017",
"Score": "0",
"body": "Thank you very very much for such a detailed suggestions and advise...\nI really appreciate it..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T16:20:01.180",
"Id": "51022",
"Score": "0",
"body": "and I'd glad if you take a look at the complete app - https://dl.dropboxusercontent.com/u/92126558/projects/ntpd/notepad.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T23:06:30.663",
"Id": "51046",
"Score": "0",
"body": "Nice, that's a very clean app. I'd recommend other ways to dismiss the Help dialog, esc, or an x in the corner. Now I see why you have the esc code commented. You can move the `closeHelpAndOverlay()` out of `Help()` to a top level function, then you can add another `if` at the end of your main keydown, to handle esc and call `closeHelpAndOverlay()`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T11:51:20.130",
"Id": "31942",
"ParentId": "31935",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "31942",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T07:36:31.037",
"Id": "31935",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Web-based text editor (#2)"
}
|
31935
|
<p>I want you to give me some feedback on how I could make it better or simpler.</p>
<pre><code>public class NonRecursiveTraversal {
private TreeNode root;
private static class TreeNode {
TreeNode left;
TreeNode right;
int item;
TreeNode (TreeNode left, TreeNode right, int item) {
this.left = left;
this.right = right;
this.item = item;
}
}
public void createBinaryTree (Integer[] arr) {
if (arr == null) {
throw new NullPointerException("The input array is null.");
}
root = new TreeNode(null, null, arr[0]);
final Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
final int half = arr.length / 2;
for (int i = 0; i < half; i++) {
if (arr[i] != null) {
final TreeNode current = queue.poll();
final int left = 2 * i + 1;
final int right = 2 * i + 2;
if (arr[left] != null) {
current.left = new TreeNode(null, null, arr[left]);
queue.add(current.left);
}
if (right < arr.length && arr[right] != null) {
current.right = new TreeNode(null, null, arr[right]);
queue.add(current.right);
}
}
}
}
public void preOrder() {
if (root == null) return;
final Stack<TreeNode> stack = new Stack<TreeNode>();
stack.add(root);
while (!stack.empty()) {
TreeNode node = stack.pop();
System.out.print(node.item + " ");
// LIFO
if (node.right != null) stack.push(node.right);
if (node.left != null) stack.push(node.left);
}
}
public void reverseOrder() {
if (root == null) return;
final Stack<TreeNode> stack = new Stack<TreeNode>();
stack.add(root);
while (!stack.empty()) {
TreeNode node = stack.pop();
System.out.print(node.item + " ");
// LIFO
if (node.left != null) stack.push(node.left);
if (node.right != null) stack.push(node.right);
}
}
public void inOrder() {
if (root == null) return;
final Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode node = root;
while (!stack.isEmpty() || node != null) {
if (node != null) {
stack.add(node);
node = node.left;
} else {
node = stack.pop();
System.out.print(node.item + " ");
node = node.right;
}
}
}
public void postOrder () {
if (root == null) return;
final Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode node = root;
while (!stack.isEmpty() || node != null) {
while (node != null) {
if (node.right != null) stack.add(node.right);
stack.add(node);
node = node.left;
}
node = stack.pop();
// (node.right) != null means this node is parent of that tiny subtree
// stack.pop != null ensures it was not the root.
if (node.right != null && !stack.isEmpty() && node.right == stack.peek()) {
TreeNode nodeRight = stack.pop();
stack.push(node);
node = nodeRight;
} else {
System.out.print(node.item + " ");
node = null;
}
}
}
}
</code></pre>
<p>Also, please correct my complexities: time and space both being \$O(n)\$.</p>
|
[] |
[
{
"body": "<p>I would not throw <code>NullPointerException</code>; it indicate that you are trying to use a variable which is null. Throw <code>IllegalArgumentException</code> instead; it indicated that arguments provided are not in a legal state.</p>\n\n<p>And I personally don't like nesting too much loops and conditions. Try to separate them into smaller methods. When you put a block of code into a method, you are documenting it with the method name. Same applies for long conditions.</p>\n\n<p>For example,</p>\n\n<pre><code>node.right != null && !stack.isEmpty() && node.right == stack.peek()\n</code></pre>\n\n<p>takes a while to \"decipher\". When you put it into the method <code>isParentOfSubtree(...)</code>, it is obvious.</p>\n\n<p>Also consider using some logger instead of <code>System.out</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T08:24:26.120",
"Id": "32121",
"ParentId": "31936",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "32121",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T07:51:10.937",
"Id": "31936",
"Score": "3",
"Tags": [
"java",
"algorithm",
"tree"
],
"Title": "Non-recursive tree traversal"
}
|
31936
|
<p>I just wrote my first Java class, and I wanted to share it with you and maybe get some quick check from more experiences coders than I am.</p>
<p>I want to learn OOP, and Java is just the tool I thought was the best to start with (it's very similar to C in syntax, which I'm used to, and it's spreading more and more, day by day).</p>
<p>You can obviously comment on Java bad habits and ways to improve the class, but consider the class structure and the abstraction of the problem I wanted to solve, the separation between in data methods, etc.. as my main point of concern.</p>
<p>Here's the class. The aim is to create a random password generator.</p>
<pre><code>import java.util.Random;
public final class PasswordGenerator {
// DATAS
// characters with which the password will be composed
private static final int charactersSize = 100;
private static char [] characters = new char [charactersSize];
// keep the counts of used characters
private static int charactersCount = 0;
// size of the password to generate
private int passwordSize;
// CONSTRUCTOR
public PasswordGenerator( int passwordSize ) {
// set the password size
this.passwordSize = passwordSize;
// set the characters that will be used to generate the password
initCharacters();
}
// METHODS
// fill the array of characters that will be used to generate the password
private static char [] initCharacters() {
int i = 0;
// add 0-9
for ( int j = 48; j < 58; ++i, ++j, ++charactersCount ) {
characters[i] = (char) j;
}
// add @ + a-z
for ( int j = 64; j < 91; ++i, ++j, ++charactersCount ) {
characters[i] = (char) j;
}
// add A-Z
for ( int j = 97; j < 123; ++i, ++j, ++charactersCount ) {
characters[i] = (char) j;
}
return characters;
}
// generate a random password
public char [] get() {
// initialize the random number generator
Random rnd = new Random();
char [] password = new char [passwordSize];
// choose a random character from the array
for ( int i = 0; i < passwordSize; ++i ) {
password[i] = characters[ rnd.nextInt(charactersCount) ];
}
return password;
}
// DEBUG METHODS
// show the characters the will be used to compose the pass
public void showCharacters() {
for ( int i = 0; i < charactersCount && characters[i] != 0; ++i ) {
System.out.println(characters[i]);
}
}
// MAIN - testing code
public static void main(String[] args) {
int passwordSize = 10;
PasswordGenerator password = new PasswordGenerator( passwordSize );
System.out.println( password.get() );
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T23:37:41.897",
"Id": "51049",
"Score": "3",
"body": "From a security perspective, I hope you're not going to use Random for real passwords. It produces low-quality random numbers. You should use SecureRandom instead for actual applications such as this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-26T16:01:02.327",
"Id": "242157",
"Score": "0",
"body": "Related: http://stackoverflow.com/q/1741160/435605"
}
] |
[
{
"body": "<p>Your code does have its share of C-isms, but we will be able to fix that.</p>\n\n<p>But first, if you are learning Java in order to understand Object Oriented Programming, pick a better language. Java's OO primitives are classes, abstract classes, interfaces and single inheritance. Since Java was designed, the world has moved on, and trait-based OO (instead of interfaces) is all the rage. The Scala language isn't very C-like, but has a wonderful object system. Another interesting language for OO is Ruby with it's metaclasses.</p>\n\n<p>I assume you already know about the difference of <code>static</code> and non-static <em>fields</em> and <em>methods</em>. Whatever is marked as <em>static</em> belongs to the class and is shared among all objects of that class. Your <code>fillCharacters</code> static method only operates on the class level, yet you call it in an object constructor. Instead of refilling the <code>characters</code> each time you make a new generator, initialize that array once.</p>\n\n<p>A horrible C-ism is that you make your <code>characters</code> array fixed size, in the hope that it will be large enough. But you only fill it with 63 characters! This is the way bugs are born. Java has multiple collections (like <code>LinkedList</code>s or <code>ArrayList</code>s) that resize themselves if necessary. I would do something like this:</p>\n\n<pre><code>private static char[] characters = initCharacters();\n\nprivate static char[] initCharacters() {\n final int initialCapacity = 63;\n // a vector is a variable-size array\n final List<Character> chars = new Vector<Character>(initialCapacity);\n\n // add digits 0–9\n for (char c = '0'; c <= '9'; c++) {\n chars.add(c);\n }\n\n // add uppercase A–Z and '@'\n for (char c = '@'; c <= 'Z'; c++) {\n chars.add(c);\n }\n\n // add lowercase a–z\n for (char c = 'a'; c <= 'z'; c++) {\n chars.add(c);\n }\n\n // Copy the chars over to a simple array, now that we know\n // the length. The .toArray method could have been used here,\n // but its usage is a pain.\n\n final char[] charArray = new char[chars.size()];\n\n for (int i = 0; i < chars.size(); i++) {\n charArray[i] = chars.get(i).charValue();\n }\n\n return charArray;\n}\n\nprivate static void showCharacters() {\n System.err.println(\"The following \" + characters.length + \" characters are available: \" + new String(characters));\n}\n</code></pre>\n\n<p>What was that <code>characters.length</code>? Yes, Java keeps book about the size of your arrays, so you don't have to! Keeping extra variables around for the size is error prone. Also note that I allocate various objects in the <code>initCharacters</code> method – the garbage collector will clean up after me.</p>\n\n<p>Because our <code>character</code> array has no unused fields, we don't need the <code>charactersSize</code> and <code>charactersCount</code> variables any longer.</p>\n\n<p>Something that C doesn't have is <em>generics</em>, i.e. parameterized polymorphism. The arguments in angled brackets are type names, which can only be classes. Java has primitive types like <code>char</code> and <code>int</code>. These have corresponding object types like <code>Character</code> and <code>Integer</code>.</p>\n\n<p>Your <code>get</code> method is mostly allright. I'd call it <code>nextPassword</code>, and would rename <code>rnd</code> to <code>random</code>. The algorithm is fine.</p>\n\n<hr>\n\n<p>One thing I'd do differently would be <em>not</em> using much object orientation for this problem. Creating a new <code>PasswordGenerator</code> for different sizes is silly. I'd rather use that functionality like</p>\n\n<pre><code>System.out.println(PasswordGenerator.nextPassword(passwordSize));\n</code></pre>\n\n<p>i.e. use the generation as a static method, and pass the requested size as a parameter.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T17:19:39.220",
"Id": "51024",
"Score": "3",
"body": "+1, nice answer. But have to disagree about Java being a bad language to learn object-oriented principles. I personally think that Scala \"feels\" very dirty and messy, but of course that's subjective."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T21:58:47.930",
"Id": "51549",
"Score": "1",
"body": "Is there any reason you chose to use Vector rather than ArrayList? This topic would suggest you should avoid its use: http://stackoverflow.com/questions/1386275/why-is-java-vector-class-considered-obsolete-or-deprecated"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T10:40:36.547",
"Id": "31941",
"ParentId": "31937",
"Score": "7"
}
},
{
"body": "<p>Here's my take on this. This is actually port of my C# code which does the same, however, as Java doesn't support functional programming aspect of C#, it's a bit less verbose.</p>\n\n<p>I'm using really simple <a href=\"http://en.wikipedia.org/wiki/Fluent_interface\" rel=\"nofollow\">Fluent interface</a> here.</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Random;\n\npublic class PasswordBuilder {\n\nprivate final static Random random = new Random();\n\n// we keep our data in lists. Arrays would suffice as data never changes though.\nprivate final static List<Character> LOWER_CAPS, UPPER_CAPS, DIGITS, SPECIALS;\n\n// stores all templates\nprivate List<Template> templateList = new ArrayList<Template>();\n\n// indicates if we should shuffle the password\nprivate boolean doShuffle;\n\n/**\n * Factory method to create our builder.\n *\n * @return New PasswordBuilder instance.\n */\npublic static PasswordBuilder builder() {\n return new PasswordBuilder();\n}\n\n/**\n * Adds lowercase letters to password.\n *\n * @param count Number of lowercase letters to add.\n * @return This instance.\n */\npublic PasswordBuilder lowercase(int count) {\n templateList.add(new Template(LOWER_CAPS, count));\n return this;\n}\n\npublic PasswordBuilder uppercase(int count) {\n templateList.add(new Template(UPPER_CAPS, count));\n return this;\n}\n\npublic PasswordBuilder digits(int count) {\n templateList.add(new Template(DIGITS, count));\n return this;\n}\n\npublic PasswordBuilder specials(int count) {\n templateList.add(new Template(SPECIALS, count));\n return this;\n}\n\n/**\n * Indicates that the password will be shuffled once\n * it's been generated.\n *\n * @return This instance.\n */\npublic PasswordBuilder shuffle() {\n doShuffle = true;\n return this;\n}\n\n/**\n * Builds the password.\n *\n * @return The password.\n */\npublic String build() {\n // we'll use StringBuilder\n StringBuilder passwordBuilder = new StringBuilder();\n List<Character> characters = new ArrayList<Character>();\n\n // we want just one list containing all the characters\n for (Template template : templateList) {\n characters.addAll(template.take());\n }\n\n // shuffle it if user wanted that\n if (doShuffle)\n Collections.shuffle(characters);\n\n // can't append List<Character> or Character[], so\n // we do it one at the time\n for (char chr : characters) {\n passwordBuilder.append(chr);\n }\n\n return passwordBuilder.toString();\n}\n\n// initialize statics\nstatic {\n LOWER_CAPS = new ArrayList<Character>(26);\n UPPER_CAPS = new ArrayList<Character>(26);\n for (int i = 0; i < 26; i++) {\n LOWER_CAPS.add((char) (i + 'a'));\n UPPER_CAPS.add((char) (i + 'A'));\n }\n\n DIGITS = new ArrayList<Character>(10);\n for (int i = 0; i < 10; i++) {\n DIGITS.add((char) (i + '0'));\n }\n\n // add special characters. Note than other\n // than @, these are in ASCII range 33-43\n // so we could have used the loop as well\n SPECIALS = new ArrayList<Character>() {{\n add('!');\n add('@');\n add('#');\n add('$');\n add('%');\n add('^');\n add('&');\n add('(');\n add(')');\n add('*');\n add('+');\n }};\n}\n}\n</code></pre>\n\n<p>Here's the Template class. This class is used to tell us something like: From list of given characters, take n(count) characters by random.</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.List;\nimport java.util.Random;\n\npublic class Template {\nprivate final List<Character> source;\nprivate final int count;\n\nprivate static final Random random = new Random();\n\npublic Template(List<Character> source, int count) {\n this.source = source;\n this.count = count;\n}\n\npublic List<Character> take() {\n List<Character> taken = new ArrayList<Character>(count);\n for (int i = 0; i < count; i++) {\n taken.add(source.get(random.nextInt(source.size())));\n }\n\n return taken;\n}\n}\n</code></pre>\n\n<p>Last, but not the least, example usage:</p>\n\n<pre><code>PasswordBuilder builder = new PasswordBuilder();\n builder.lowercase(5)\n .uppercase(5)\n .specials(2)\n .digits(2)\n .shuffle();\n // write 100, 14-char shuffled passwords\n for (int i = 0; i < 100; i++) {\n System.out.println(builder.build());\n }\n</code></pre>\n\n<p>This example (hopefully) shows the power of OO. It was not necessary for this to be this complex, you can remove templates and just generate password on the fly, or you can improve them and add more features.</p>\n\n<p>In the end, there are tens of different ways to implement this, but I hope I helped a bit. :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-06T18:12:33.340",
"Id": "51627",
"Score": "0",
"body": "+1, and I am not going to select this as the accepted answer just because due to my poor experience in the world of OOP, I can't get through your code so well as I can read amon's. I really thank you for the example, though. Indeed, the more I read it, the more it makes sense to me, and I already prefer your approach to the one I initially took. Thank you @Alex."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-06T21:29:07.500",
"Id": "51637",
"Score": "1",
"body": "why have you implemented a Fisher-Yates algorithm when there is a Collections.shuffle(List<?> list, Random rnd), available?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-06T21:29:37.410",
"Id": "51638",
"Score": "0",
"body": "check http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#shuffle(java.util.List,%20java.util.Random) for that"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-07T03:26:51.937",
"Id": "51653",
"Score": "0",
"body": "You should by all means accept the other answer, as It's based on your original code. I have just provided a way how would I myself would have implemented it, and of course I'm not claiming it's any better - moreover, it has its downsides. You are correct about Collections.shuffle(), I'll change the code to reflect that (No built-in shuffle in .net, so that was the reason as I hastly ported it )."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T22:08:57.010",
"Id": "31956",
"ParentId": "31937",
"Score": "3"
}
},
{
"body": "<p>@doplumi, some feedback on you solution:</p>\n\n<ol>\n<li>It's not customizable. Hard to change the possible chars.</li>\n<li>You wrote the int value of the chars themselves, like 48. Hard to understand. Documentation can help but we should try to be more explicit in the code. Example: '0'.</li>\n<li>Many indexes in your loops. Hard to follow, especially if some error snuck in.</li>\n</ol>\n\n<p>Implemented one myself as well. As a builder.</p>\n\n<p>Supports password limit, must have characters and how much of them, char ranges and a list of them.</p>\n\n<p>Usage Example:</p>\n\n<pre><code>System.out.println(new PasswordBuilder().addCharsOption(\"!@#$%&*()_-+=[]{}\\\\|:/?.,><\", 1).addRangeOption('A', 'Z', 1).addRangeOption('a', 'z', 0).addRangeOption('0', '9', 1).build());\n</code></pre>\n\n<p>Example result: <code>QU1GY7p+j+-PUW+_</code></p>\n\n<pre><code>System.out.println(new PasswordBuilder().addCharsOption(\"!@#$%&*()_-+=[]{}\\\\|:/?.,><\", 1).addRangeOption('A', 'Z', 1).addRangeOption('a', 'z', 0).addRangeOption('0', '9', 1).setSize(5).build());\n</code></pre>\n\n<p>Example result: <code>%,4NX</code></p>\n\n<p>Implementation:</p>\n\n<pre><code>//Version=1.0\n//Source=https://www.dropbox.com/s/3a4uyrd2kcqdo28/PasswordBuilder.java?dl=0\n//Dependencies=java:7 com.google.guava:guava:18.0 commons-lang:commons-lang:2.6\n\nimport com.google.common.primitives.Chars;\nimport org.apache.commons.lang.ArrayUtils;\n\nimport java.security.SecureRandom;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * Created by alik on 5/26/16.\n */\npublic class PasswordBuilder {\n private int size = 16;\n private List<Character> options = new ArrayList<>();\n private Map<List<Character>, Integer> musts = new java.util.LinkedHashMap<>();\n private SecureRandom secureRandom = new SecureRandom();\n\n public PasswordBuilder() {\n }\n\n public PasswordBuilder setSize(int size) {\n this.size = size;\n return this;\n }\n\n public PasswordBuilder addRangeOption(char from, char to, int mustCount) {\n List<Character> option = new ArrayList<>(to - from + 1);\n for (char i = from; i < to; ++i) {\n option.add(i);\n }\n return addOption(option, mustCount);\n }\n\n public PasswordBuilder addCharsOption(String chars, int mustCount) {\n return addOption(Chars.asList(chars.toCharArray()), mustCount);\n }\n\n public PasswordBuilder addOption(List<Character> option, int mustCount) {\n this.options.addAll(option);\n musts.put(option, mustCount);\n return this;\n\n }\n\n public String build() {\n validateMustsNotOverflowsSize();\n Character[] password = new Character[size];\n\n // Generate random from musts\n for (Map.Entry<List<Character>, Integer> entry : musts.entrySet()) {\n for (int i = 0; i < entry.getValue(); i++) {\n int charIndex = secureRandom.nextInt(entry.getKey().size());\n char c = entry.getKey().get(charIndex);\n addChar(password, c);\n }\n }\n\n // Generate from overall\n for (int i = 0; i < password.length; i++) {\n if (password[i] != null) continue;\n password[i] = options.get(secureRandom.nextInt(options.size()));\n }\n return new String(ArrayUtils.toPrimitive(password));\n }\n\n private void addChar(Character[] password, char c) {\n int i;\n for (i = secureRandom.nextInt(password.length); password[i] != null; i = secureRandom.nextInt(password.length)) {\n }\n password[i] = c;\n }\n\n private void validateMustsNotOverflowsSize() {\n int overallMusts = 0;\n for (Integer mustCount : musts.values()) {\n overallMusts += mustCount;\n }\n if (overallMusts > size) {\n throw new RuntimeException(\"Overall musts exceeds the requested size of the password.\");\n }\n }\n\n public static void main(String[] args) {\n System.out.println(new PasswordBuilder().addCharsOption(\"!@#$%&*()_-+=[]{}\\\\|:/?.,><\", 1).addRangeOption('A', 'Z', 1).addRangeOption('a', 'z', 0).addRangeOption('0', '9', 1).build());\n System.out.println(new PasswordBuilder().addCharsOption(\"!@#$%&*()_-+=[]{}\\\\|:/?.,><\", 1).addRangeOption('A', 'Z', 1).addRangeOption('a', 'z', 0).addRangeOption('0', '9', 1).setSize(5).build());\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-26T16:00:36.903",
"Id": "129380",
"ParentId": "31937",
"Score": "2"
}
},
{
"body": "<p>Its not required to write tons of lines and regex for this purpose now. We can use <a href=\"http://www.passay.org/\" rel=\"nofollow noreferrer\">passey</a> library that generates and validates passwords. Passwords can be alphanumeric or special characters.</p>\n\n<p>For example following methods generates password with alphanumeric and special characters with a minimum length of 8 characters.</p>\n\n<pre><code>public String generateRandomPassword() {\n\n List rules = Arrays.asList(new CharacterRule(EnglishCharacterData.UpperCase, 1),\n new CharacterRule(EnglishCharacterData.LowerCase, 1), new CharacterRule(EnglishCharacterData.Digit, 1),new CharacterRule(EnglishCharacterData.Special, 1));\n\n PasswordGenerator generator = new PasswordGenerator();\n String password = generator.generatePassword(8, rules);\n return password;\n }\n</code></pre>\n\n<p>Reference:\n<a href=\"http://www.devglan.com/corejava/random-password-generator-java\" rel=\"nofollow noreferrer\">Generating random Password in Java</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-05-03T08:19:19.580",
"Id": "308359",
"Score": "1",
"body": "A bit more detail might be warranted, especially since this question has had an accepted answer for about three years. In any case, I don't think the author is still concerned about this code..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-05-03T08:54:24.947",
"Id": "308364",
"Score": "0",
"body": "I have updated the answer with an example"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-05-03T09:01:35.897",
"Id": "308366",
"Score": "1",
"body": "This may be helpful for others who are looking for the random password generator same as I was looking for it and found a better approach to generate it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-05-03T09:11:15.780",
"Id": "308369",
"Score": "1",
"body": "That looks better already. I'm not familiar with the code formatting conventions in Java, but that list of character rules might need some nicer formatting. In addition you should also specifically add the requirements for this to work (passey, if I understand that link correctly)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-05-03T07:37:45.427",
"Id": "162386",
"ParentId": "31937",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "31941",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T08:40:42.417",
"Id": "31937",
"Score": "8",
"Tags": [
"java",
"object-oriented",
"classes",
"random"
],
"Title": "Random password generator"
}
|
31937
|
<p>Since the resources I found to learn are generally out-of-date, I'm having to read a lot of documentation, which makes the learning process somewhat haphazard. The module makes a simple character stack which can be read and written to by multiple processes.</p>
<pre><code>#include<linux/init.h>
#include<linux/module.h>
#include<linux/fs.h>
#include<linux/types.h>
#include<linux/kdev_t.h>
#include<linux/cdev.h>
#include<linux/mutex.h>
#include<asm/uaccess.h>
#define MHELLO_STACK_SIZE 20
static int major;
static dev_t dev;
static struct cdev my_cdev;
static int count;
static DEFINE_MUTEX(lock);
static char stack[MHELLO_STACK_SIZE];
static int head;
static ssize_t hello_read(struct file* f,char* buf,size_t count,loff_t * offset)
{
unsigned int res;
printk(KERN_ALERT"R\n");
mutex_lock(&lock);
if(head<0)
{
mutex_unlock(&lock);
return 0;
}
res=copy_to_user(buf,stack+head,1);
head--;
mutex_unlock(&lock);
return 1;
}
static ssize_t hello_write(struct file* f,const char* buf,size_t count,loff_t * offset)
{
unsigned int res;
printk(KERN_ALERT"W\n");
mutex_lock(&lock);
if(head >= MHELLO_STACK_SIZE-1)
{
mutex_unlock(&lock);
return -ENOSPC;
}
head++;
res=copy_from_user(stack+head,buf,1);
mutex_unlock(&lock);
return 1;
}
static int hello_open(struct inode* inode,struct file* f)
{
mutex_lock(&lock);
count++;
printk(KERN_ALERT"O %d\n",count);
mutex_unlock(&lock);
return 0;
}
static int hello_release(struct inode* inode,struct file* f)
{
mutex_lock(&lock);
count--;
printk(KERN_ALERT"C %d\n",count);
mutex_unlock(&lock);
return 0;
}
const struct file_operations fops=
{
.owner=THIS_MODULE,
.read=hello_read,
.write=hello_write,
.open=hello_open,
.release=hello_release
};
static int hello_init(void)
{
int result=-1;
mutex_init(&lock);
mutex_lock(&lock);
count=0;
head=-1;
result=alloc_chrdev_region(&dev,0,1,"mhello");
if(result<0)
printk(KERN_ALERT"Can't allocate major.\n");
major=MAJOR(dev);
printk(KERN_ALERT"Hello, my major no. is %d.\n",major);
cdev_init(&my_cdev,&fops);
my_cdev.owner=THIS_MODULE;
cdev_add(&my_cdev,dev,1);
mutex_unlock(&lock);
return 0;
}
static void hello_exit(void)
{
mutex_lock(&lock);
unregister_chrdev_region(dev,1);
cdev_del(&my_cdev);
mutex_unlock(&lock);
printk(KERN_ALERT"Goodbye world\n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("foo");
</code></pre>
|
[] |
[
{
"body": "<p>So, this isn't a full answer to your question, but maybe still relevant.</p>\n\n<p>Included with the Linux sources is scripts/checkpatch.pl - which checks for things like coding style compliance, but also warns on use of outdated interfaces.</p>\n\n<p>If you have a checked out (clean) git repository of the kernel, you can simply copy your source file into there and run</p>\n\n<pre><code>linux$ git diff HEAD | scripts/checkpatch.pl -\n</code></pre>\n\n<p>Doing that on the above code does point out a few things not just coding-style related.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T16:01:16.283",
"Id": "31945",
"ParentId": "31938",
"Score": "3"
}
},
{
"body": "<p>My comments below are general C, not specific to Linux kernel development (of which I know nothing).</p>\n\n<ul>\n<li><p>When handling resources like mutexes, I usually think it better to release the resource in only one place. So I would modify your read function to the following:</p>\n\n<pre><code>static ssize_t hello_read(struct file* f, char* buf, size_t count, loff_t * offset)\n{\n ssize_t res = 0;\n mutex_lock(&lock);\n if (head >= 0) {\n copy_to_user(buf, stack + head, 1);\n head--;\n res = 1;\n }\n mutex_unlock(&lock);\n return res;\n}\n</code></pre>\n\n<p>As you can see, I have adjusted the condition and done the copy within the conditional block. Note that the return from <code>copy_to_user</code> should be checked (number of bytes not copied) and presumably the function should use <code>count</code> and <code>offset</code>, in which case these need to be checked before use.</p>\n\n<p>The same comments apply to the <code>hello_write</code> function.</p></li>\n<li><p><code>hello_init</code> continues initialising even after an error in the <code>alloc_chrdev_region</code> call. It also doesn't check the return from cdev_init and cdev_add.</p></li>\n<li><p>Outside of kernel development, it is normal to put spaces after commas, around '=', and (for me) after keywords (if, else, for, while etc). Do kernel developers do things differently?</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-07T08:04:37.900",
"Id": "51667",
"Score": "0",
"body": "https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/Documentation/CodingStyle describes the coding style to be used for Linux kernel code. The only two differences between that and your code I can spot are (1) placement of '*' and (2) indentation depth."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T08:44:17.680",
"Id": "32123",
"ParentId": "31938",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T09:56:17.340",
"Id": "31938",
"Score": "3",
"Tags": [
"c",
"linux",
"kernel"
],
"Title": "Simple Linux char driver"
}
|
31938
|
<blockquote>
<p>There is a char array of n length. The array can have elements only from
any order of R, B, W. You need to sort the array so that order should R,B,W
(i.e. all R will come first followed by B and then W).</p>
<p>Constraints: Time
complexity is O(n) and space complexity should be O(1).</p>
<p>Assumption:
You can assume one swap method is given with signature <code>swap(char[]
arr, int index1, int index2)</code> that swaps number in unit time. Method
given to implement: <code>public sort(char[]array);</code></p>
</blockquote>
<p>Here is my implementation of it. A better solution from anyone is appreciated. Anyone is free to point out any mistakes.</p>
<pre><code>public static void sort(char[] arr){
int rIndex = 0, wIndex = arr.length -1;
for (int i = 0 ; i <= wIndex;){
if ( arr[i] == 'R' ){
swap(arr, i , rIndex ++ );
i ++;
} else if (arr[i] == 'W' ){
swap(arr, i , wIndex -- );
}else{
i ++;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T18:03:36.837",
"Id": "51025",
"Score": "0",
"body": "Does this work? Running it in my head with `\"WRB\"` gives `\"RWB\"`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T18:05:55.267",
"Id": "51026",
"Score": "0",
"body": "It will give RBW for sure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T18:11:59.423",
"Id": "51027",
"Score": "0",
"body": "Ah, I missed the `i <= wIndex` termination."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T18:22:34.500",
"Id": "51030",
"Score": "0",
"body": "Using the actual code on `\"WBRWBRBWRB\"` yields `\"RRBRBBBWWW\"`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T18:27:27.200",
"Id": "51034",
"Score": "0",
"body": "Yes. Thats correct. I will look into issue and fix this. Thank you for pointing out this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T18:58:07.163",
"Id": "51037",
"Score": "0",
"body": "fixed the code :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T19:24:51.933",
"Id": "51038",
"Score": "1",
"body": "Editing the code in place makes it hard to discuss as it invalidates all the comments and possibly answers. This looks about as good as you'll get it I think."
}
] |
[
{
"body": "<p>One quick improvement to your solution would be to use <code>switch(arr[i])</code> instead of the <code>if-else</code> chain.</p>\n\n<p>The only real problem I see <strike>beyond the complexity and non-obviousness of the algorithm</strike> is that it can end up doing a lot of unnecessary swaps<strike>--often in-place. While <code>swap</code> could be written to avoid them, you still pay the cost of the function call.</strike></p>\n\n<p>Another solution is to do it in two passes: first pull all Rs to the left and then all Ws to the right. While it takes twice as long, it's still equivalent to O(n).</p>\n\n<pre><code>public static void sort(char[] arr) {\n int length = arr.length;\n int rIndex = 0, wIndex = length - 1;\n for (int i = 0; i < length; i++) {\n if (arr[i] == 'R') {\n if (i != rIndex) {\n swap(arr, i, rIndex);\n }\n ++rIndex;\n }\n }\n for (int i = length - 1; i >= 0; i--) {\n if (arr[i] == 'W') {\n if (i != wIndex) {\n swap(arr, i, wIndex);\n }\n --wIndex;\n }\n }\n}\n</code></pre>\n\n<p>A more complicated but possibly faster solution would be to walk in from both ends simultaneously instead of scanning from left-to-right. This allows you to pick the better swap and do it only when necessary. I started on it, but it quickly got out of hand.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T18:24:07.477",
"Id": "31950",
"ParentId": "31944",
"Score": "4"
}
},
{
"body": "<p>Basically this is near as good as you can get it.</p>\n\n<p>I would simply suggest</p>\n\n<ul>\n<li>renaming of index variables to clarify their function </li>\n<li>adding a comment that clarifies the algorithm</li>\n<li>use a switch as it yield a clearer structure in this instance.</li>\n</ul>\n\n<p>(note that i've also fiddled with the place of indices to be able to more elegantly formulate the invariants)</p>\n\n<pre><code>public static void sort(char[] arr) {\n // invariants :\n // * each index up to and including lastR contains 'R'\n // * each index equal to or greater than firstW contains 'W'\n // * each index greater than lastR but smaller than i contains B\n // array will be sorted once i == firstW\n int lastR = -1, firstW = arr.length;\n for (int i = 0; i < firstW; ) {\n switch(arr[i]) {\n case 'R':\n swap(arr, i, ++lastR);\n i++;\n break;\n case 'W':\n swap(arr, i, --firstW);\n break;\n default:\n i++;\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T22:03:37.187",
"Id": "31955",
"ParentId": "31944",
"Score": "1"
}
},
{
"body": "<p>You can convert the characters to an order number, and implement a regular sorting algorithm. That way you only need to solve converting the character to a order number, and can use a proven algorithm for the rest.</p>\n\n<p>Here is an example using bubble sort, but you can of course use a more efficient sorting algorithm.</p>\n\n<pre><code>public static int convert(char c) {\n switch (c) {\n case 'R': return 0;\n case 'B': return 1;\n default: return 2;\n }\n}\n\npublic static void sort(char[] arr){\n int cont = true;\n while (cont) {\n cont = false;\n for (int i = 1; i < arr.length; i++) {\n if (convert(arr[i - 1]) > convert(arr[i])){\n swap(arr, i - 1, i);\n cont = true;\n }\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T12:13:22.697",
"Id": "51069",
"Score": "0",
"body": "complexity is needed to be O(1)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T12:23:02.200",
"Id": "51070",
"Score": "0",
"body": "@MohdAdnan: Sorry, I missed that part. The space complexity actually is O(1), but the time complexity isn't O(n)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T12:28:47.407",
"Id": "51071",
"Score": "0",
"body": "Yes I actually meant time complexity O(n)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T22:09:31.767",
"Id": "31957",
"ParentId": "31944",
"Score": "0"
}
},
{
"body": "<p>Don't bother swapping. Just do a <a href=\"http://en.wikipedia.org/wiki/Counting_sort\">counting sort</a>!</p>\n\n<pre><code>public static void sort(char[] arr) {\n // Count occurrences of each letter\n int r = 0, b = 0, w = 0;\n for (char c : arr) {\n switch (c) {\n case 'R': r++; break;\n case 'B': b++; break;\n case 'W': w++; break;\n default: throw new IllegalArgumentException();\n }\n }\n\n // Write out the appropriate repetitions of each letter\n int i = 0;\n while (r-- > 0) arr[i++] = 'R';\n while (b-- > 0) arr[i++] = 'B';\n while (w-- > 0) arr[i++] = 'W';\n}\n</code></pre>\n\n<p>Not only is the code easy to understand, it's also gentle to the cache since you always proceed linearly down the array.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T04:13:21.477",
"Id": "31971",
"ParentId": "31944",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T15:57:45.190",
"Id": "31944",
"Score": "6",
"Tags": [
"java",
"algorithm",
"sorting"
],
"Title": "A character array of arbitary length with 'R', 'B', 'W' is needed to be sorted in that order"
}
|
31944
|
<p>I need some feedback for this set of value-test functions (are they doing what they say they do). Also ways to improve some of them, suggestions to add more test functions, etc.</p>
<pre><code>// Object.test.isnumeric('0x12') -> true, etc.
!(( function ( field, define ) {
this[field] = define();
} ).call(
Object,
"test",
function () {
var _inner = {
corstr:function ( o ) { return Object.prototype.toString.call( o ); },
corePrimitiveTypes : ['[object Undefined]', '[object Null]', '[object Number]', '[object String]', '[object Boolean]'],
emptyValues : [void 0, null, false, 0, ""],
reg:{
SCALAR : /^boolean|number|string$/,
URL : /^(?:[a-z]+:\/\/)?(?:\/)?(?:\.\.\/)*[a-z][\w\-.]*(?:\:\d+)?[\/\w#!:.?+=&%@!\-]+$/i,
EMAIL : /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/,
VALUE_TYPE : /\b(\w+)\]$/
}
};
return {
// #isbool
isbool: function (o) {
return _inner.corstr( o ) === '[object Boolean]';
},
// #isnum
isnum: function (o) {
return isFinite( o ) && _inner.corstr(o) === "[object Number]";
},
// #isnumeric
isnumeric: function (o) {
try {
return isFinite( o = o["valueOf"]() )
&& ( eval( o ) === parseFloat( Number( o ) ) );
} catch(e) {}
return false;
},
// #isunum
isunum: function (n) {
return this.isnum( n ) && ( n >= 0 );
},
// #isint
isint: function ( n ) {
return n === +n && isFinite( n ) && !( n%1 );
},
// #isuint
isuint: function ( n ) {
return this.isint( n ) && ( n >= 0 );
},
// #isfloat
isfloat: function ( n ) {
return +n === n && ( !isFinite(n) || !!( n % 1 ) );
},
// #isprimitive
isprimitive: function ( o ) {
return _inner.corePrimitiveTypes.indexOf( _inner.corstr( o ) ) != -1;
},
// #isstr
isstr: function ( o ) {
return _inner.corstr( o ) === "[object String]";
},
// #isfn
isfn: function (o) {
return typeof o === "function";
},
// #iswin
iswin: function (o) {
return o && o.top && ( o === o.window );
},
// #isarray
isarray: function ( o ) {
return this.isfn( Array.isArray )
? Array.isArray( o )
: _inner.corstr( o ) === '[object Array]';
},
// #isarraylike
isarraylike: function (o) {
if ( !o ) return false;
if ( this.iswin( o ) ) return false;
var len = o.length,
T = this.type( o );
if ( o.nodeType === 1 && len ) return true;
return T === "array" ||
T !== "string" &&
T !== "function" &&
(
len === 0
|| typeof len === "number"
&& len > 0
&& (len - 1) in Object( o )
);
},
// #isplainobj
isplainobj: function (o) {
return _inner.corstr( o ) === "[object Object]";
},
// #isemptyobj
isemptyobj: function ( o ) {
try {
for ( var l in o )
return false;
return true;
} catch( e ) {
return false;
}
},
// #isdata , -> true for: [ {}+ ] structures
isdata: function (o) {
return this.isarray( o )
&& o.every(
function ( v ) {
return this.isplainobj( v );
},
this
);
},
// #isobj
isobj: function (o) {
return o === Object(o);
},
// #isscalar, -> true for: true/false, string, number
isscalar: function ( o ) {
return _inner.reg.SCALAR.test( this.type( o ) );
},
// #isempty, -> true for: undefined, null, 0, "", false, NaN, {}, []
isempty: function ( o ) {
if ( arguments.length === 0 )
return void 0;
var key, i, len, T;
for (
i = 0,
len = _inner.emptyValues.length;
i < len;
i++
) {
if (
o === _inner.emptyValues[i]
|| o !== o
) return true;
}
if ( this.isarray( o ) ) return o.length == 0;
if ( this.isobj( o ) ) return this.isemptyobj( o );
return false;
},
// #isvalid, -> false, for: undefined, null, NaN
isvalid: function ( o ) {
return o !== void 0
&& o !== null
&& ( o === o );
},
// #isdomobj
isdomobj: function (el) {
return this.isobj(el)
&& ( el instanceof Node )
&& (
( el.ownerDocument || el )
.documentElement
.nodeName
.toUpperCase() === "HTML"
);
},
// #isurl
isurl: function ( str ) {
return _inner.reg.URL.test( String( str ) );
},
// #isemail
isemail: function (str) {
return _inner.reg.EMAIL.test( String( str ) );
},
// #isxmlnode
isxmlnode: function ( elm ) {
var docElement =
( elm ? elm.ownerDocument || elm : 0 ).documentElement;
return docElement
? documentElement.nodeName !== "HTML"
: false;
},
// #ishtm
ishtm: function ( input, _testel ) {
return (
_testel = doc.createElement("div"),
_testel.innerHTML = String( input ),
_testel.getElementsByTagName("*").length > 0
);
},
// #type
type : function ( o ) {
if ( o === void 0 )
return "undefined";
var out;
(
( out = this.iswin( o )
&& 'window'
|| _inner.corstr( o )
.match( _inner.reg.VALUE_TYPE )[1]
.toLowerCase()
) === 'number'
)
&& (
isFinite( o ) || ( out = String( o ) )
);
return out;
}
};
//
}
));
</code></pre>
|
[] |
[
{
"body": "<p>Did you run this through a minifier and then prettified it again?</p>\n\n<p>Stuff like <code>(foo) && (bar || (x = y()))</code> looks like google closure compiler and <strong>has no place in actual source code</strong>. It makes your code hard to read and letting closure compiler do this later is perfectly fine - no need to work with less readable code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T18:17:19.730",
"Id": "51028",
"Score": "0",
"body": "ahm, no, I tend to use logical operators instead of conditional statements often."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T18:23:52.847",
"Id": "51031",
"Score": "0",
"body": "Please don't. Especially when you start putting assignments inside."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T18:25:48.600",
"Id": "51032",
"Score": "0",
"body": "It's a kind of a ( bad? ) habit trying to speed up typeing..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T12:03:33.687",
"Id": "51222",
"Score": "0",
"body": "@ThiefMaster I believe that simple expressions, such as `callback && callback()` are perfectly fine and readable. It's an elegant way of taking advantage of the short-circuit nature of the `&&` operator."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T18:14:17.733",
"Id": "31947",
"ParentId": "31946",
"Score": "1"
}
},
{
"body": "<p>There are always a lots of comments that can be made, but without doing an extremely deep analysis, here's what I could identity:</p>\n\n<h3>Global comments</h3>\n\n<p>1 - I see no reason to use such a complex module definition syntax.</p>\n\n<p>The following is perfectly fine:</p>\n\n<pre><code>!function (obj, field) {\n //privates\n\n obj[field] = { ... };\n}(Object, 'test');\n</code></pre>\n\n<p>2 - Stick to a single naming convention. You are sometimes using the <em>camelCase</em> convention, but your public interface is <em>alllowercase</em> (which is very hard to read in my opinion btw). The most widely spread convention in JavaScript is the <em>camelCase</em> one since that's the one used for native objects.</p>\n\n<p>3 - When checking for <code>null</code> or <code>undefined</code>, you can simply rely on the type coersion of the <code>==</code> operator which will return <code>true</code> for <code>null == undefined</code>. <em>Note that <code>null == rightSideValue</code> will only be <code>true</code> if <code>rightSideValue</code> is <code>null</code> or <code>undefined</code>, which makes this method safe to use.</em></p>\n\n<p>4 - Whenever possible, I wouldn't rely on the string representation of the object to determine it's type. Using <code>typeof</code> is perfectly fine.</p>\n\n<pre><code>function isNumber(o) {\n return typeof o === 'number' && isFinite(o);\n}\n\nfunction isBool(o) {\n return typeof o === 'boolean';\n}\n\n//etc.\n</code></pre>\n\n<p>5 - You do not need to <code>return void 0</code> to return <code>undefined</code>, simply use <code>return;</code>.</p>\n\n<p>6 - It's slow to use an array as a lookup structure. Use a plain <code>Object</code> as a map instead.</p>\n\n<pre><code>var lookupMap = {\n a: true,\n b: true,\n c: true\n};\n\n'a' in lookupMap;\n</code></pre>\n\n<p>Instead of:</p>\n\n<pre><code>var lookup = ['a', 'b', 'c'];\n\nlookup.indexOf('a') !== -1;\n</code></pre>\n\n<p>7 - There is no point to access an hard-coded property using the <code>[]</code> notation. <code>o[\"valueOf\"]()</code> can just be <code>o.valueOf()</code>.</p>\n\n<p>8 - It isin't a good practice to add an extra argument just to declare a private variable without having to use the <code>var x;</code> syntax like you are doing in <code>ishtm</code>. It might not be harmful for the bahaviour but it is for code comprehension. Also it could lead to issues when using a documentation generator.</p>\n\n<h3>Looking at functions</h3>\n\n<p><strong>isnumeric</strong> - I am not sure that it's actually better and you would have to test performances, however here's an alternative without relying on <code>eval</code> and <code>parseFloat</code> with <code>try-catch</code>.</p>\n\n<pre><code>return isFinite(o) && !(\n //the following are needed because isFinite uses Number(o) internally\n this.isArray(o)\n || this.isDate(o) \n || this.isBoolean(o) \n || (this.isString(o) && /^\\s*$/.test(o))\n || o === null\n);\n</code></pre>\n\n<p>However, if we take your path, cant you simplify as:</p>\n\n<pre><code>try {\n return isFinite(parseFloat(o));\n} catch (e) {\n return false;\n}\n</code></pre>\n\n<p><strong>isemptyobj</strong> - I am not sure what implementation you want here, however keep in mind that the <code>for in</code> loop will iterate over inherited properties as well. You might want to consider checking if the object <a href=\"https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty\" rel=\"nofollow\">hasOwnProperty</a>.</p>\n\n<p><strong>isplainobj</strong> - Again I am not sure what implementation you want here, but note that the following returns true.</p>\n\n<pre><code>Object.prototype.toString.call(new function A(){}) === '[object Object]'; //true\n</code></pre>\n\n<p>Perhaps you want this instead?</p>\n\n<pre><code>Object.getPrototypeOf({}) === Object.prototype); //true\nObject.getPrototypeOf(new function A(){}) === Object.prototype; //false\n</code></pre>\n\n<h3>Other ideas</h3>\n\n<p>A generic <code>is</code> function, something like (lets suppose it's part of the public API).</p>\n\n<pre><code>function is(o) {\n return [].slice.call(arguments, 1).some(function (type) {\n var fn = this['is' + type], rx;\n return fn? \n fn.call(this, o) : \n (rx = this.reg[type.toUpperCase()]) && rx.test(o);\n }, this);\n}\n</code></pre>\n\n<p>You could call it like:</p>\n\n<pre><code>Object.test.is('test@test.com', 'email');\n\nObject.test.is([], 'array', 'boolean', 'string');\n</code></pre>\n\n<p><strong>Anyway, I could continue like this for a while, however without having your implementation's documentation or test cases, it's hard to criticize. What's important is that your implementations are doing what your documentation says. Also, it's very important to create a test suite for such modules and perhaps a performance test suite as well.</strong></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T23:28:28.793",
"Id": "51199",
"Score": "0",
"body": "Very elegant. \n\nI see that I should be more specific about code's intensions. For 'isplainobj ' I ment to have the behaviour you pointed out ( wheather or not in inheritance tree ) to detect custom made types. In my experience they behave exactly like plain ( Object ) types. \n\nIf 'for in' starts iterating something ( inherited or no ) then there is some info to deal with, thats isemptyobj's implementation goal;"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T23:53:28.740",
"Id": "51200",
"Score": "0",
"body": "'isnumeric's' implementation is built over a period of time ( that explains weird syntax ), and I know there is one test case ( which I sadly can not remember now of why I've used it like that ) for which I've used '[\"valueOf\"]()' thing, where response should be positive... Btw your 'isnumeric' validates as positive for blank strings of any length and booleans, because .isFinite() is doing type conversion when doing it's thing. Smart use of object lookups and typeof operator. 'void 0' is redundat, I've used it to just to circumvent code warning underlines code editor was giving me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T02:00:25.853",
"Id": "51202",
"Score": "1",
"body": "@NikolaVukovic You are right, I forgot about these cases. I updated my answer accordingly and added another idea. A generic `is` function that checks if a value's type matches one of the provided types."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T02:10:41.213",
"Id": "51204",
"Score": "0",
"body": "sounds resonable, I'll post the possible solution once implemented/tested, etc."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T16:32:16.263",
"Id": "32033",
"ParentId": "31946",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "32033",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T17:30:10.960",
"Id": "31946",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Criticize my JavaScript value tester suite"
}
|
31946
|
<p>Ok, code reviewers, I want you to pick my code apart and give me some feedback on how I could make it better or more simple.</p>
<pre><code>public class PrintAllPath {
private TreeNode root;
private class TreeNode {
TreeNode left;
int item;
TreeNode right;
TreeNode (TreeNode left, int item, TreeNode right) {
this.left = left;
this.item = item;
this.right = right;
}
}
public void create (Integer[] arr) {
if (arr == null) {
throw new NullPointerException("The input array is null.");
}
root = new TreeNode(null, null, arr[0]);
final Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
final int half = arr.length / 2;
for (int i = 0; i < half; i++) {
if (arr[i] != null) {
final TreeNode current = queue.poll();
final int left = 2 * i + 1;
final int right = 2 * i + 2;
if (arr[left] != null) {
current.left = new TreeNode(null, null, arr[left]);
queue.add(current.left);
}
if (right < arr.length && arr[right] != null) {
current.right = new TreeNode(null, null, arr[right]);
queue.add(current.right);
}
}
}
}
public void printPath () {
doPrint(root, new ArrayList<TreeNode>());
}
private void doPrint(TreeNode node, List<TreeNode> path) {
if (node == null) return;
path.add(node);
if (node.left == null && node.right == null) {
System.out.println("Path from root: " + root.item + " to leaf: " + node.item + " - ");
for (TreeNode treeNode : path) {
System.out.print(treeNode.item + " ");
}
System.out.println();
}
doPrint(node.left , path);
doPrint(node.right, path);
path.remove(path.size() - 1);
}
</code></pre>
|
[] |
[
{
"body": "<p>It looks good overall.</p>\n\n<p>I see you have taken my <a href=\"https://codereview.stackexchange.com/a/31931/9357\">previous suggestion</a> to rearrange the <code>TreeNode</code> constructor arguments. Now you have to readjust your calling convention accordingly.</p>\n\n<p>Your <code>create()</code> method acts like a constructor, so you should just make it a constructor. It desperately needs a JavaDoc comment explaining how the input array is to be interpreted.</p>\n\n<p>In <code>create()</code>, I would not bother to check for <code>arr == null</code>. You'll get a <code>NullPointerException</code> anyway when you fetch <code>arr[0]</code>. It's only worth the explicit check if such a check would make debugging substantially easier, i.e. when an improper <code>null</code> would get stored or propagated but not dereferenced until much later. Even then, I'd throw an <code>IllegalArgumentException</code> rather than <code>NullPointerException</code> to emphasize that the caller is at fault.</p>\n\n<p>In <code>doPrint()</code>, <code>path.remove(path.size() - 1)</code> should be just <code>path.removeLast()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T16:41:19.990",
"Id": "51080",
"Score": "0",
"body": "Accepted the rest except - Effective Java mentions to validate each method input, throw exception sooner than later, and use NPE rather than IllegalArgE. I would be receptive if you still have some points to add. Thanks again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T20:34:23.177",
"Id": "51096",
"Score": "0",
"body": "Cross tallied with SO, you were correct. Thanks for all pointers"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-29T07:01:03.047",
"Id": "31973",
"ParentId": "31949",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "31973",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T18:22:38.837",
"Id": "31949",
"Score": "2",
"Tags": [
"java",
"algorithm",
"tree"
],
"Title": "Print all path from root to leaves - code review request"
}
|
31949
|
<p>I'm starting out and need feedback in order to discover the things I'm doing wrong.</p>
<p>This is supposed to behave like <code>strcmp()</code>:</p>
<pre><code>int compare(char *str1, char *str2)
{
while(*str1 || *str2)
{
if(*str1 != *str2)
{
break;
}
++str1;
++str2;
}
return *str1 - *str2;
}
</code></pre>
<p>How can it be improved? Are there any flaws?</p>
<p>Also, would any of the following styles be considered better?</p>
<pre><code>int compare(char *str1, char *str2)
{
while((*str1 || *str2) && *str1 == *str2)
{
++str1;
++str2;
}
return *str1 - *str2;
}
</code></pre>
<p></p>
<pre><code>int compare(char *str1, char *str2)
{
while((*str1 || *str2) && *str1 == *str2) ++str1, ++str2;
return *str1 - *str2;
}
</code></pre>
|
[] |
[
{
"body": "<p>You can skip the check for the end of one of the strings. If the other string ends before the one that you check the length for, the comparison of the characters will catch the difference:</p>\n\n<pre><code>int compare(char *str1, char *str2) {\n while (*str1 && *str1 == *str2) {\n str1++;\n str2++;\n }\n return *str1 - *str2;\n}\n</code></pre>\n\n<p>You can write the same using a <code>for</code> statement if you want it shorter (and less readable):</p>\n\n<pre><code>int compare(char *str1, char *str2) {\n for (;*str1 && *str1 == *str2; str2++) str1++;\n return *str1 - *str2;\n}\n</code></pre>\n\n<p>Just for the sake of it, you can make is shorter (mis)using recursion, but that is a rather terrible solution:</p>\n\n<pre><code>int compare(char *str1, char *str2) {\n return (*str1 && *str1 == *str2) ? compare(++str1, ++str2) : *str1 - *str2;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T22:04:15.593",
"Id": "51045",
"Score": "1",
"body": "Your first version is excellent; it would have been better to end your response there. =)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T21:52:22.860",
"Id": "31954",
"ParentId": "31953",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "31954",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T21:12:03.397",
"Id": "31953",
"Score": "3",
"Tags": [
"c",
"strings",
"reinventing-the-wheel",
"comparative-review"
],
"Title": "Function equivalent to strcmp()"
}
|
31953
|
<p>I'm working my way through <em>The Java Programming Language, Fourth Edition - The Java Series</em>. This is Exercise 6.4:</p>
<blockquote>
<p>Expand your traffic light color enum from Exercise 6.1 on page 152 so that each enum constant has a suitable Color object that can be retrieved with getColor.</p>
</blockquote>
<p>The enum from Exercise 6.1 is as follows:</p>
<pre><code>enum TrafficLightColor {
GREEN,
RED,
YELLOW,
}
</code></pre>
<p>Is the following an adequate solution?</p>
<pre><code>enum TrafficLightColor {
GREEN(0, 255, 0),
YELLOW(255, 255, 0),
RED(255, 0, 0);
Color color;
TrafficLightColor (int r, int g, int b) {
color = new Color(r, g, b);
}
Color getColor() {
return color;
}
}
public class Color {
private int r;
private int g;
private int b;
Color(int r, int g, int b) {
this.r = r;
this.g = g;
this.b = b;
}
public int getR() {
return r;
}
public int getG() {
return g;
}
public int getB() {
return b;
}
}
public class TrafficLight {
private TrafficLightColor currentColor;
TrafficLight(TrafficLightColor currentColor) {
this.currentColor = currentColor;
}
TrafficLightColor getCurrentColor() {
return currentColor;
}
}
import org.junit.Test;
import static org.junit.Assert.*;
public class TrafficLightTest {
@Test
public void testGetCurrentColor() throws Exception {
TrafficLight light = new TrafficLight(TrafficLightColor.GREEN);
assertEquals(0, light.getCurrentColor().getColor().getR());
assertEquals(255, light.getCurrentColor().getColor().getG());
assertEquals(0, light.getCurrentColor().getColor().getB());
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Certainly, that seems adequate. You may want to make the <code>color</code> field <code>private</code>, though. Otherwise having a getter is pretty irrelevant. Also, I would make the field <code>final</code> so that the associated color can never be modified.</p>\n\n<p>Were you told to code your own <code>Color</code> class? There's <a href=\"http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/Color.html\" rel=\"nofollow\">already one provided for you</a> in <code>java.awt</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T23:09:03.180",
"Id": "51047",
"Score": "0",
"body": "Good catch Jeff. I've updated the color field to be:\nprivate final Color color; Is it good form to update the original post with the correction, or leave as is? The exercise was vague on which Color class to use, but I will have a look at java.awt. Thanks for the feedback."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T23:15:14.347",
"Id": "51048",
"Score": "0",
"body": "@weare138 I think you're supposed to leave it as is? But who knows. And no problem!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T23:01:12.097",
"Id": "31959",
"ParentId": "31958",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "31959",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-28T22:52:03.750",
"Id": "31958",
"Score": "3",
"Tags": [
"java",
"enum"
],
"Title": "Critique of enum"
}
|
31958
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.