body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I'm trying to see if there is a better way to design this. I have a class Animal that is inherited by Male and Female classes (Female class has an additional attribute). I also have a class called Habitat, an instance of each would contain any number of Animals including 0.</p>
<pre><code>class Animal:
def __init__(self, life_span=20, age=0):
self.__life_span = life_span
self.__age = age
def get_life_span(self):
return self.__life_span
def get_age(self):
return self.__age
def age(self):
self.__age += 1
class Female(Animal):
__gender = 'female'
def __init__(self, pregnant=False):
self.__pregnant = pregnant
def impregnate(self):
self.__pregnant = True
class Male(Animal):
__gender = 'male'
class Habitat:
def __init__(self, list_of_animals=[Male(), Female()]):
self.__list_of_animals = list_of_animals
def __add_male(self):
self.__list_of_animals.append(Male())
def __add_female(self):
self.__list_of_animals.append(Female())
def add_animal(self):
if random.choice('mf') == 'm':
self.__add_male()
else:
self.__add_female()
def get_population(self):
return self.__list_of_animals.__len__()
</code></pre>
<p>Before I add any more functionality, I would like to find out if that's a proper way to design these classes. Maybe there is a design pattern I can use? I'm new to OOP, any other comments/suggestions are appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-10T00:40:10.843",
"Id": "34636",
"Score": "2",
"body": "FWIW, don't call `obj.__len__()`, use `len(obj)` instead. Also, no need to use name mangling (double leading underscores): Just use `self.age` or `self._age`, especially use the former in favor of trivial getters (you can later replace them with a `property`, *if* you need that extra power, without changing the way client code works with your objects)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-10T00:41:06.173",
"Id": "34637",
"Score": "0",
"body": "@tallseth: already flagged as such. OP: if the moderators agree, your question will be automatically migrated for you. Please do not double-post."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-10T00:41:05.957",
"Id": "34638",
"Score": "0",
"body": "It would appear you're new to OOP in general - what's your experience?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-10T00:46:59.060",
"Id": "34639",
"Score": "0",
"body": "@JonClements somehow I managed to avoid the whole thing and it's been bugging me for years, so now I'm trying to get a grip of it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-10T00:48:45.100",
"Id": "34640",
"Score": "0",
"body": "@MartijnPieters thanks, can I do it myself without waiting for moderators?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-10T00:49:17.600",
"Id": "34641",
"Score": "0",
"body": "Good first attempt - but IMHO - not correct - an Animal is either Male or Female (possibly both given some species), no need to subclass a Gender"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-10T00:53:20.873",
"Id": "34642",
"Score": "0",
"body": "@dfo: No, you can't. It is a moderator-level descision I'm afraid."
}
] |
[
{
"body": "<p>In <code>Habitat.__init__</code>, you've committed a classic beginner's fallacy: using a list as a default argument.</p>\n\n<p>In Python, every call to a function with a default argument will use the same default object. If that object is mutable (e.g. a list) any mutations to that object (e.g. <code>.append</code>) will affect that one object. In effect, all your <code>Habitat</code>s will end up using the exact same list unless you specify a non-default argument.</p>\n\n<p>Instead, use <code>None</code> as the default argument, and test for it:</p>\n\n<pre><code>def __init__(self, animals=None):\n if animals is None:\n animals = [Male(), Female()]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-10T00:40:46.243",
"Id": "21560",
"ParentId": "21559",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-10T00:37:16.780",
"Id": "21559",
"Score": "0",
"Tags": [
"python",
"object-oriented",
"design-patterns"
],
"Title": "Instance of one class to contain arbitrary number of instances of another class in Python"
}
|
21559
|
<p>There are plenty of <code>if</code>s and <code>else</code>s, and someone else told me that using <code>switch</code>/<code>case</code> statements could really clean up the code. However, he didn't implement it for me, so I don't know what I should switch/case.</p>
<p>Also take note that the <code>if (!stricmp(argv[arg], "-vmf"))</code> and <code>if (!stricmp(argv[arg], "-bsp"))</code> blocks are exactly the same, minus the usage of <code>vmf</code> and <code>bsp</code>, and that the <code>wad</code> block is somewhat similar.</p>
<pre><code>#include <cstdio>
#include <cstring>
#include <fstream>
#include <sys\stat.h>
#include "arg.h"
#include "files.h"
#include "stricmp.h"
using namespace std;
//"ifError" takes all the argument flags, as well as a string to output. If silent flag is
//enabled, then "ifError" will not output that text. I put this into the function to reduce
//lines and characters of code.
void ifError(argFlags& argFlags, char* errorMessage)
{
if (!argFlags.sil)
{
if (!argFlags.err)
{
printf("Converts DOOM WAD into VMF and/or BSP file(s).\n\n");
printf("DOOM2BSP [-silent] [-WAD [path][name]] [-VMF [path]] [-BSP [path]]\n\n");
printf(" -WAD Location of WAD.\n");
printf(" -VMF Create VMF file(s) in path.\n");
printf(" -BSP Create BSP file(s) in path.\n");
printf(" -silent Disable text output.\n\n");
}
printf(errorMessage);
}
argFlags.err = true;
}
//Checks if directory exists.
bool checkDir(char* path)
{
struct stat st;
if (!stat(path, &st))
if (st.st_mode & S_IFDIR != 0)
return true;
return false;
}
//This function analyzes our arguments, deals with them accordingly, and decides if there
//are any errors or not. Also opens wad if it exists.
void handleArgs(argFlags& argFlags, files& files, int& argc, char**& argv)
{
//Analyzes all arguments to find "-silent" arg. If silent arg is found, the silent flag
//is turned on, signifying that this program should not output any text.
for (int arg = 1; arg < argc; ++arg)
if (!stricmp(argv[arg], "-silent"))
argFlags.sil = true;
//Analyzes the rest of the arguments, with the silent flag in mind.
for (int arg = 1; arg < argc; ++arg)
{
//If the "-wad" arg is found, turn on wad flag. Look for wad name. If wad name is
//found, check if for its validity and existance. If check fails or if wad name arg
//is not found, output error.
if (!stricmp(argv[arg], "-wad"))
{
argFlags.wad = true;
if ((arg + 1) < argc)
{
files.wad.open(argv[arg + 1], fstream::out | fstream::binary);
if (!files.wad.good())
ifError(argFlags, "Error: WAD name is invalid or does not exist.\n");
}
else
ifError(argFlags, "Error: WAD name is not specified.\n");
}
//If the "-vmf" arg is found, turn on vmf flag. Look for vmf path name. If vmf path
//name is found, check for its validity and existance. If check fails or if vmf
//path arg is not found, output error.
else if (!stricmp(argv[arg], "-vmf"))
{
argFlags.vmf = true;
if ((arg + 1) < argc)
{
files.vmfPath = argv[arg + 1];
if (!checkDir(files.vmfPath))
ifError(argFlags, "Error: VMF path is invalid or does not exist.\n");
}
else
ifError(argFlags, "Error: VMF path is not specified.\n");
}
//If the "-bsp" arg is found, turn on bsp flag. Look for bsp path name. If bsp path
//name is found, check for its validity and existance. If check fails or if bsp
//path arg is not found, output error.
else if (!stricmp(argv[arg], "-bsp"))
{
argFlags.bsp = true;
if ((arg + 1) < argc)
{
files.bspPath = argv[arg + 1];
if (!checkDir(files.bspPath))
ifError(argFlags, "Error: BSP path is invalid or does not exist.\n");
}
else
ifError(argFlags, "Error: BSP path is not specified.\n");
}
}
//Decently self-explanatory.
if (argc == 1)
ifError(argFlags, "Error: No parameters.\n");
else if (!argFlags.wad)
ifError(argFlags, "Error: WAD parameters missing.\n");
else if ((!argFlags.vmf) && (!argFlags.bsp))
ifError(argFlags, "Error: VMF/BSP parameters missing.\n");
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T03:53:27.700",
"Id": "34724",
"Score": "2",
"body": "I think you should read a book about refactoring code, as it will help you to understand the changes you will make, and how to set up testing, etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T05:18:34.740",
"Id": "34725",
"Score": "1",
"body": "Use [Boost.ProgramOptions](http://www.boost.org/doc/libs/1_53_0/doc/html/program_options.html)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T18:03:37.413",
"Id": "34967",
"Score": "0",
"body": "I'll take this opportunity to *strongly* recommend reading [Clean Code by Robert C. Martin](http://www.amazon.com/gp/product/0132350882/). The examples may be in Java, but it really applies to any language."
}
] |
[
{
"body": "<p>I think you should separate the logic parsing the arguments provided from the logic using the argument parsed. At the moment, you are trying to do everything in one place and I'm not quite sure this is correct (for instance, if a filename is also an option name, this leads to an unexpected behavior).</p>\n\n<p>I'd suggest something like (I'm not even sure it would compile but that just to give you an idea) :</p>\n\n<pre><code>void handleArgs(argFlags& argFlags, files& files, int& argc, char**& argv)\n{\n int waitingForArg = 0; // To know if we are expecting an other argument to be provided : 0:no, 1:wad, 2:vmf, 3:bsp\n for (int i = 1; i < argc; i++)\n {\n char* arg = argv[i];\n switch (waitingForArg)\n {\n case 0:\n if (!stricmp(arg, \"-silent\"))\n argFlags.sil = true;\n else if (!stricmp(arg, \"-wad\")\n waitingForArg = 1;\n else if (!stricmp(arg, \"-vmf\")\n waitingForArg = 2;\n else if (!stricmp(arg, \"-bsp\")\n waitingForArg = 3;\n break;\n case 1:\n argFlags.wadFile = arg; waitingForArg = 0;\n break;\n case 2:\n argFlags.vmfFile = arg; waitingForArg = 0;\n break;\n case 3:\n argFlags.bspFile = arg; waitingForArg = 0;\n break;\n }\n }\n\n if (waitingForArg)\n {\n ifError(argFlags, \"Error: file name must be provided with option -wad, -vmf or -bsp\");\n return;\n }\n\n // Logic involving wadFile, wmfFile, bspFile. Checking if they are set and/or if they correspond to existing files.\n}\n</code></pre>\n\n<p>This is just a first step to make things easier to follow (on top of being more correct and more efficient).</p>\n\n<p>Then to remove code duplication, you might want to do something like using an array to store the different possible options ([\"-wad\",\"-vmf\",\"-bsp\"]). In order to do so, you'd replace the \"else if (!stricmp(arg, \"OPTIONS\"))\" with a loops on the different options. Then you might also be happy to store the flags as an array. I think this would make more sense if you had more flags to handle.</p>\n\n<p>I also notice that you have tagged your question as C++ but your code seems to be using some C-style (printf and stuff). This might be something you should fix as well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T05:52:59.813",
"Id": "21566",
"ParentId": "21562",
"Score": "8"
}
},
{
"body": "<p>Josay is correct and you should accept his answer. I'd like to mention a few more things.</p>\n\n<ol>\n<li><p>Please use braces everywhere, the code you're using is known to lead to difficult reading and subtle bugs. Consider:</p>\n\n<pre><code>if (condition)\n a();\n b();\n</code></pre>\n\n<p><code>b()</code> will be executed unconditionally.</p></li>\n<li><p><code>switch</code> wouldn't have helped with your code since you can only switch on integers. It doesn't make the code much shorter unless you have a lot of cases to handle, and the main benefit isn't shorter code anyway: it's better readability.</p></li>\n<li><code>stricmp</code> is Windows-only, the POSIX equivalent is <code>strcasecmp</code>, but I don't think Windows supports it. If you want to be cross-platform, go for Boost and <a href=\"http://www.boost.org/doc/libs/1_53_0/doc/html/boost/algorithm/iequals.html\" rel=\"nofollow\">iequals</a>.</li>\n<li>You're using C++, so you may want to take advantage of it. With your current code it mostly means using <code>string</code> instead of <code>char*</code> and <code>std::cout</code> instead of <code>printf</code>.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T07:43:55.423",
"Id": "21569",
"ParentId": "21562",
"Score": "6"
}
},
{
"body": "<p>Here's a version of ifError() with reduced nesting level by bailing out with an early return:</p>\n\n<pre><code>void ifError(argFlags& argFlags, char* errorMessage)\n{\n argFlags.err = true;\n if (argFlags.sil)\n return;\n if (!argFlags.err)\n {\n printf(\"Converts DOOM WAD into VMF and/or BSP file(s).\\n\\n\");\n printf(\"DOOM2BSP [-silent] [-WAD [path][name]] [-VMF [path]] [-BSP [path]]\\n\\n\");\n printf(\" -WAD Location of WAD.\\n\");\n printf(\" -VMF Create VMF file(s) in path.\\n\");\n printf(\" -BSP Create BSP file(s) in path.\\n\");\n printf(\" -silent Disable text output.\\n\\n\");\n }\n printf(errorMessage);\n}\n</code></pre>\n\n<p>In checkDir() you can merge the two <code>if</code> statements. Make sure to keep the same order, because the second condition needs to operate on <code>st</code> which is initialized in the first condition:</p>\n\n<pre><code>bool checkDir(char* path)\n{\n struct stat st;\n if (!stat(path, &st) && st.st_mode & S_IFDIR != 0)\n return true;\n return false;\n}\n</code></pre>\n\n<p>There's not much to simplify in handleArgs(). Note that using <code>switch</code> is not possible because in C++ strings cannot be used with <code>switch</code> (neither C-strings, nor <code>std::string</code>.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T13:27:28.257",
"Id": "21624",
"ParentId": "21562",
"Score": "1"
}
},
{
"body": "<p>I suggest using a table of : </p>\n\n<pre><code>for each entry in table do:\n if entry.text == parameter\n execute entry.function_pointer\n end-if\nend-for\n</code></pre>\n\n<p>Example table:</p>\n\n<pre><code>\"WAD\", Process_WAD_argument\n\"VMF\", Process_VMF_argument\n</code></pre>\n\n<p>The nice feature about tables in this scenario is that you can add parameters without changing the parsing code: add another line to the table.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T16:34:10.983",
"Id": "22760",
"ParentId": "21562",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T03:42:49.027",
"Id": "21562",
"Score": "6",
"Tags": [
"c++",
"error-handling"
],
"Title": "Handling argument flags"
}
|
21562
|
<p>I wrote this, and it has helped to avoid the 'Some exception weren't handled' problem. Is there something glaringly wrong with this that I might have missed?</p>
<pre><code> /// <summary>
/// Handles any exceptions on this task, and executes action on specified scheduler.
/// </summary>
/// <param name="task">The task.</param>
/// <param name="exceptionHandler">The exception handler.</param>
/// <param name="finalAction">The final action.</param>
/// <param name="scheduler">The scheduler.</param>
public static void Finally(this Task task, Action<Exception> exceptionHandler,
Action finalAction, TaskScheduler scheduler)
{
task.ContinueWith(t =>
{
if(finalAction != null) finalAction();
if(t.IsCanceled || !t.IsFaulted || exceptionHandler == null) return;
var innerException = t.Exception.Flatten().InnerExceptions.FirstOrDefault();
exceptionHandler(innerException ?? t.Exception);
}, scheduler);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T10:20:13.060",
"Id": "34662",
"Score": "0",
"body": "PS: I *think* I wrote this. It was a while back, so it may be that I filched it from somewhere else."
}
] |
[
{
"body": "<p>A couple of personal preferences here:</p>\n\n<ul>\n<li>Allow for no <code>scheduler</code> to be passed in and use the default scheduler in that case.</li>\n<li>Allow for no <code>exceptionHandler</code> if the caller is certain no exceptions will occur.</li>\n<li>Check that <code>task</code> isn't null and throw appropriate exception if it is.</li>\n<li>Check that <code>t.Exception</code> isn't <code>null</code> before using to get the <code>innerException</code>.</li>\n<li>Have the method return the passed in <code>Task</code> so it can be fluently chained.</li>\n</ul>\n\n<p>Refinagled code:</p>\n\n<pre><code>/// <summary>\n/// Handles any exceptions on this task, and executes action on specified scheduler.\n/// </summary>\n/// <param name=\"task\">The task.</param>\n/// <param name=\"exceptionHandler\">The exception handler.</param>\n/// <param name=\"finalAction\">The final action.</param>\n/// <param name=\"scheduler\">The scheduler.</param>\n/// <returns>The passed-in task</returns>\npublic static Task Finally(this Task task, Action finalAction, \n Action<Exception> exceptionHandler = null, TaskScheduler scheduler = null)\n{\n if (task == null) throw new ArgumentNullException(\"task\");\n if (scheduler == null) scheduler = TaskScheduler.Default;\n task.ContinueWith(t =>\n {\n if(finalAction != null) finalAction();\n\n if(t.IsCanceled || !t.IsFaulted) return;\n var innerException = t.Exception == null ? null : t.Exception.Flatten().InnerExceptions.FirstOrDefault();\n if (exceptionHandler != null) exceptionHandler(innerException ?? t.Exception);\n }, scheduler);\n return task;\n}\n</code></pre>\n\n<p>That way, you can write simplified calls such as:</p>\n\n<pre><code>var t = Task.Factory\n .StartNew(() => Console.WriteLine(\"Started\"))\n .Finally(() => Console.WriteLine(\"Finished\"));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T05:56:55.060",
"Id": "34705",
"Score": "0",
"body": "Thanks. I omitted two overloads, which cover the no scheduler, no finalAction cases, but not (yet) the no exceptionHandler. Point taken about the exception being null, though unless I'm mistaken, in your rewriting, it will still choke on the following line if it *is* null."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T13:13:12.100",
"Id": "34739",
"Score": "0",
"body": "Well, depends on the code the caller has written in `exceptionHandler` - your null-coalescing operator (`??`) may give `null` but the line itself won't choke."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T14:40:57.620",
"Id": "34744",
"Score": "0",
"body": "OK, fair point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T18:56:02.987",
"Id": "58432",
"Score": "0",
"body": "Should the default `scheduler` be `TaskScheduler.Default` or `TaskScheduler.Current`? `Task.Factory.StartNew()` uses `Current`, `Task.Run()` `Default`. I'm not sure which one is better in this case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T19:02:26.360",
"Id": "58435",
"Score": "0",
"body": "How do we summon Stephen Toub here?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T16:18:18.423",
"Id": "21586",
"ParentId": "21568",
"Score": "3"
}
},
{
"body": "<p>I think what you've really got here is two extension methods hiding inside one. Your method is doing the work of both a \"finally\" and a \"catch\", and I recommend refactoring it into two methods. The catch method may look something like this:</p>\n\n<p>Edit: clearly I missed checking the exception type before executing the action, but I'm away from a computer and trying to edit code with my iPhone isn't working too well. </p>\n\n<pre><code>public static void Catch<TException>(this Task task, Action<TException> exceptionHandler, \n TaskScheduler scheduler = null) where TException : Exception\n{\n if (exceptionHandler == null)\n throw new ArgumentNullException(\"exceptionHandler cannot be null\");\n\n task.ContinueWith(t =>\n {\n if(t.IsCanceled || !t.IsFaulted || t.Exception == null) return;\n var innerException = t.Exception.Flatten().InnerExceptions.FirstOrDefault();\n exceptionHandler(innerException ?? t.Exception);\n }, scheduler ?? TaskScheduler.Default);\n}\n</code></pre>\n\n<p>Edit: Finally got time to get back to this. Here's an example of a complete solution:</p>\n\n<pre><code>using System;\nusing System.Threading.Tasks;\n\nnamespace ConsoleApplication1\n{\nclass Program\n{\n static void Main(string[] args)\n {\n Task.Run(() => {\n Console.WriteLine(\"In the Task\");\n throw new ArgumentException(\"Thrown from task\");\n //throw new Exception(\"Thrown from task\");\n })\n .Catch<Exception>((e) => Console.WriteLine(\"Caught Exception {0}\", e))\n .Catch<ArgumentException>((ae) => Console.WriteLine(\"Caught Argument Excetion {0}\", ae))\n .Finally(() => Console.WriteLine(\"in the Finally\"));\n\n Console.ReadKey();\n Console.ReadKey();\n }\n}\n\nstatic class TaskExtensions\n{\n\n public static void Finally(this Task task, Action finalAction, \n TaskScheduler scheduler = null)\n {\n if (finalAction == null)\n throw new ArgumentNullException(\"finalAction cannot be null\");\n\n task.ContinueWith(t => finalAction(), scheduler ?? TaskScheduler.Default);\n }\n\n public static Task Catch<TException>(this Task task, Action<TException> exceptionHandler,\n TaskScheduler scheduler = null) where TException : Exception\n {\n if (exceptionHandler == null)\n throw new ArgumentNullException(\"exceptionHandler cannot be null\");\n\n task.ContinueWith(t =>\n {\n if (t.IsCanceled || !t.IsFaulted || t.Exception == null) \n return;\n\n var exception =\n t.Exception.Flatten().InnerExceptions.FirstOrDefault() ?? t.Exception;\n\n if (exception is TException)\n {\n exceptionHandler((TException) exception);\n }\n }, scheduler ?? TaskScheduler.Default);\n\n return task;\n }\n}\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T20:35:41.267",
"Id": "35092",
"Score": "0",
"body": "You're right. I actually realised this since posting this question. I suddenly noticed that I didn't 'need' a catch, and then saw why."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T21:53:52.283",
"Id": "22795",
"ParentId": "21568",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "22795",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T07:06:08.760",
"Id": "21568",
"Score": "6",
"Tags": [
"c#",
"extension-methods",
"task-parallel-library"
],
"Title": "Task.Finally extension, good, bad, or ugly?"
}
|
21568
|
<p>I have a requirement in my current project that will need a Prioritised Queue that supports the IObservable interface. Please notify me of any problems with the implementation that I currently have:</p>
<p><strong>ObservablePriorityQueue<T></strong></p>
<pre><code>public sealed class ObservablePriorityQueue<T> : IQueue<T>, IObservable<T> where T : IPrioritised
{
#region "IObservable<T> Implementation"
// A list of the subscribers for the IObservable implementation
List<IObserver<T>> _subscribers = new List<IObserver<T>>(10);
Object _observableSyncLock = new Object();
#region "Interface specific"
public IDisposable Subscribe(IObserver<T> observer)
{
if (observer == null)
{
throw new ArgumentNullException("The observer cannot be null.");
}
if (!_subscribers.Contains(observer))
{
lock (_observableSyncLock)
{
_subscribers.Add(observer);
}
}
return new Disposable(() =>
{
this.Unsubscribe(observer);
});
}
#endregion
public void Unsubscribe(IObserver<T> observer)
{
if (observer == null)
{
throw new ArgumentNullException("The observer cannot be null.");
}
observer.OnCompleted();
if (_subscribers.Contains(observer))
{
// remove the entry, but don't dispose it just
// in case they want to re-subscribe with the same observer later
lock (_observableSyncLock)
{
_subscribers.Remove(observer);
}
}
}
#endregion
#region "IQueue<T> Implementation"
readonly List<T> _data = new List<T>(100);
Object _queueSyncLock = new Object();
public void Enqueue(T value)
{
if (value == null)
{
throw new ArgumentException("The item to be enqueued cannot be null");
}
lock (_queueSyncLock)
{
_data.Add(value);
}
// now that the entry has been added, notify everyone
Task.Run(() =>
{
lock (_observableSyncLock)
{
foreach (IObserver<T> subscriber in _subscribers)
{
subscriber.OnNext(value);
}
}
});
}
public T Dequeue()
{
if (_data.Count > 0)
{
lock (_queueSyncLock)
{
var result = _data.OrderByDescending(element => element.Priority).ThenBy(element => element.TimeStamp).First();
_data.Remove(result);
return result;
}
}
return default(T);
}
public T Peek()
{
if (_data.Count > 0)
{
return _data.OrderByDescending(element => element.Priority).ThenBy(element => element.TimeStamp).First();
}
return default(T);
}
public Int32 Count { get { return _data.Count; } }
#endregion
}
</code></pre>
<p><strong>IQueue<T></strong></p>
<pre><code>public interface IQueue<T>
{
void Enqueue(T value);
T Dequeue();
T Peek();
Int32 Count { get; }
}
</code></pre>
<p><strong>IPrioritised<T></strong></p>
<pre><code>public interface IPrioritised
{
QueuePriority Priority { get; }
DateTime TimeStamp { get; }
}
</code></pre>
<p><strong>QueuePriority</strong></p>
<pre><code>public enum QueuePriority
{
None = 0,
Lowest = 1,
Low = 2,
Normal = 3,
High = 4,
Highest = 5
}
</code></pre>
<p><strong>Disposable</strong></p>
<pre><code>public sealed class Disposable : IDisposable
{
readonly Action _action;
public Disposable(Action action)
{
_action = action;
}
public void Dispose()
{
if (_action != null)
{
_action();
}
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li>At first, I was confused what exactly did the implementation of <code>IObservable<T></code> mean. You should properly document that.</li>\n<li>You don't need to have a separate lock objects. If you're locking on a specific object, I think you should use that object in the <code>lock</code>.</li>\n<li>If you're just calling a single method in your lambda, you can use more succinct syntax: <code>new Disposable(() => this.Unsubscribe(observer))</code>.</li>\n<li>If you want to make your code thread-safe, you need to lock all your reads too. In <code>Unsubscribe()</code> you don't do that, which means someone could write to the list while you're reading it. The same problem is in <code>Peek()</code>.</li>\n<li><code>Dequeue()</code> shouldn't return <code>default(T)</code> if the queue is empty. This can be problematic especially with value types. Instead, you should have a method like <a href=\"http://msdn.microsoft.com/en-us/library/dd287208.aspx\" rel=\"nofollow\"><code>bool TryDequeue(out T result)</code></a>.</li>\n<li>You're accessing <code>Count</code> outside of a lock. I wouldn't rely on the fact that doing this is safe, I think you should <code>lock</code> before accessing it too.</li>\n<li>Since you're using Rx, you might as well use their <a href=\"http://msdn.microsoft.com/en-us/library/system.reactive.disposables.disposable.create%28v=vs.103%29.aspx\" rel=\"nofollow\"><code>Disposable.Create()</code></a> instead of creating your own.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T13:59:18.640",
"Id": "34668",
"Score": "0",
"body": "Thanks for the comments. I will review these and fix accordingly. As a note, I am not using Rx everything is out of the BCL."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T14:20:03.367",
"Id": "34669",
"Score": "0",
"body": "I have confirmed the need for seperate locks here: http://stackoverflow.com/questions/14813780/multiple-lock-objects-necessary"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T14:40:50.887",
"Id": "34671",
"Score": "0",
"body": "@StuartBlackler Well, I think `IObservable<T>` is much less useful without Rx, so you might consider using it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T14:44:22.693",
"Id": "34673",
"Score": "1",
"body": "@StuartBlackler And you really don't need the separate lock objects, I have added my own answer to that SO question."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T13:46:38.030",
"Id": "21578",
"ParentId": "21574",
"Score": "2"
}
},
{
"body": "<p>In addition to svick's points, I noticed that in your <code>Enqueue</code> method you're checking queued values for <code>null</code>:</p>\n\n<pre><code>public void Enqueue(T value)\n{\n if (value == null)\n {\n throw new ArgumentException(\"The item to be enqueued cannot be null\");\n }\n</code></pre>\n\n<p>However, there is no constraint on the generic type, <code>T</code>. If the user intends to queue value types (such as structs), this will fail.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-02T21:09:05.680",
"Id": "102631",
"ParentId": "21574",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T12:33:53.117",
"Id": "21574",
"Score": "4",
"Tags": [
"c#",
"performance",
"priority-queue"
],
"Title": "ObservablePriorityQueue<T> Implementation"
}
|
21574
|
<p>I've implemented merge sort in Scala: </p>
<pre><code> object Lunch {
def doMergeSortExample() = {
val values:Array[Int] = List(5,11,8,4,2).toArray
sort(values)
printArray(values)
}
def sort(array:Array[Int]) {
if (array.length > 1 ){
var firstArrayLength = (array.length/2)
var first:Array[Int] = array.slice(0, firstArrayLength)
var second:Array[Int] = array.slice(firstArrayLength, array.length)
sort(first)
sort(second)
merge(array, first, second)
}
}
def merge(result:Array[Int], first:Array[Int], second:Array[Int]) {
var i:Int = 0
var j:Int = 0
for (k <- 0 until result.length) {
if(i<first.length && j<second.length){
if (first(i) < second(j)){
result(k) = first(i)
i=i+1
} else {
result(k) = second(j)
j=j+1
}
}else if(i>=first.length && j<second.length){
result(k) = second(j)
j=j+1
} else {
result(k) = first(i)
i=i+1
}
}
}
def printArray(array: Array[Int]) = {
println(array.deep.mkString(", "))
}
def main(args: Array[String]) {
doMergeSortExample();
}
}
</code></pre>
<p>Could you look at this? Are there some Scala tricks to do it better, quicker, smaller or cleaner?</p>
|
[] |
[
{
"body": "<p>Just a few unsorted ideas:</p>\n\n<ul>\n<li><p>Mergesort can be very nicely expressed using Scala's streams. In particular:</p>\n\n<pre><code>def merge(first: Stream[Int], second: Stream[Int]): Stream[Int] =\n (first, second) match {\n case (x #:: xs, ys@(y #:: _)) if x <= y => x #:: merge(xs, ys)\n case (xs, y #:: ys) => y #:: merge(xs, ys)\n case (xs, Empty) => xs\n case (Empty, ys) => ys\n }\n</code></pre>\n\n<p>It'll be slower than working with arrays, but the method is much more\nconcise, and it's completely stateless. And, it will be fully lazy - it will\ncompute only those elements that you ask for. With such a lazy merge sort,\nyou can sort a sequence, then ask only for the first element,\nand you'll get it in <em>O(n)</em> time instead of <em>O(n log n)</em>.</p></li>\n<li><p>Instead of splitting the input into smaller and smaller pieces and then merging them, you can split it into singletons in a single pass and then just merge those singletons. For example, create a <code>Stream</code> of <code>Stream</code>s like</p>\n\n<pre><code>def col2strstr(c: Iterable[Int]): Stream[Stream[Int]] =\n for(x <- c.toStream) yield Stream(x);\n</code></pre>\n\n<p>and then merge pairs of them repeatedly. (Be sure to merge streams with the same or similar length, otherwise the process will be inefficient.)</p></li>\n<li><p>This can be further improved: Instead of just splitting the input into singletons, you can split the input into non-decreasing subsequences. For example (using an informal list notation), you'd split <code>[7,8,9,4,5,6,1,2,3]</code> into <code>[[7,8,9],[4,5,6],[1,2,3]]</code>. This can dramatically reduce the number of merges. In particular, if you pass an already sorted input, it will just check that it's sorted in <em>O(n)</em> without doing any merge.</p></li>\n<li><p>A further improvement is to look for both non-decreasing and non-increasing sequences (and reverse the non-increasing ones before merging them).</p></li>\n</ul>\n\n<p>All these ideas can be seen in Haskell's <a href=\"http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-List.html#v%3asort\">sort</a> implementation: (Haskell's lists are lazy, just like Scala's <code>Stream</code>s.)\n</p>\n\n<pre><code>sort = sortBy compare\nsortBy cmp = mergeAll . sequences\n where\n sequences (a:b:xs)\n | a `cmp` b == GT = descending b [a] xs\n | otherwise = ascending b (a:) xs\n sequences xs = [xs]\n\n descending a as (b:bs)\n | a `cmp` b == GT = descending b (a:as) bs\n descending a as bs = (a:as): sequences bs\n\n ascending a as (b:bs)\n | a `cmp` b /= GT = ascending b (\\ys -> as (a:ys)) bs\n ascending a as bs = as [a]: sequences bs\n\n mergeAll [x] = x\n mergeAll xs = mergeAll (mergePairs xs)\n\n mergePairs (a:b:xs) = merge a b: mergePairs xs\n mergePairs xs = xs\n\n merge as@(a:as') bs@(b:bs')\n | a `cmp` b == GT = b:merge as bs'\n | otherwise = a:merge as' bs\n merge [] bs = bs\n merge as [] = as\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-24T15:21:32.643",
"Id": "129212",
"Score": "0",
"body": "What is the role of @ operator in case (x #:: xs, ys@(y #:: _)) if x <= y => x #:: merge(xs, ys)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-24T15:53:07.780",
"Id": "129217",
"Score": "0",
"body": "@ChetanBhasin It's a [pattern binder](http://www.scala-lang.org/files/archive/spec/2.11/08-pattern-matching.html). If `(y #:: -)` matches, the expression is bound to `ys`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T17:10:16.813",
"Id": "21590",
"ParentId": "21575",
"Score": "15"
}
}
] |
{
"AcceptedAnswerId": "21590",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T13:08:00.910",
"Id": "21575",
"Score": "9",
"Tags": [
"algorithm",
"sorting",
"scala",
"mergesort"
],
"Title": "Merge sort in Scala"
}
|
21575
|
<p>I think this is the simplest way to slugify urls. You have any contra-indication?</p>
<pre class="lang-php prettyprint-override"><code>function url_clean($str){
$str = iconv('utf-8', 'us-ascii//TRANSLIT', $str);
$clean_str = preg_replace(array('/\'|\"/','/ /'),array('','-'),$str);
return $clean_str;
}
</code></pre>
|
[] |
[
{
"body": "<p>There are two issues with your otherwise elegant approach:</p>\n\n<ol>\n<li><p><code>iconv</code> silently cuts the string if a disallowed UTF-8 character is present. The solution would be to add <code>//IGNORE</code> to the <code>iconv()</code> call but 1/ a bug in glibc seems to prevent this 2/ PHP developers don't seem to want to implement a work-around. An <a href=\"http://www.php.net/manual/en/function.iconv.php#108643\" rel=\"nofollow noreferrer\">option</a> is to remove invalid characters yourself:</p>\n\n<pre><code>ini_set('mbstring.substitute_character', \"none\"); \n$text= mb_convert_encoding($text, 'UTF-8', 'UTF-8'); \n</code></pre></li>\n<li><p>You're not removing all characters that are present in ASCII but disallowed in a URL: <a href=\"https://stackoverflow.com/a/13500078/481584\">see this StackOverflow answer</a>.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T14:05:23.397",
"Id": "21580",
"ParentId": "21576",
"Score": "1"
}
},
{
"body": "<p>An alternative, simpler way to code your solution is to use the <code>strtr</code> function which \"translates characters\". Also I made sure to escape the special characters in the regex.</p>\n\n<pre><code>function url_clean($str) {\n $accent = array(' űáéúőóüöíŰÁÉÚŐÓÜÖÍ');\n $clean = array('-uaeuoouoiUAEUOOUOI');\n $str = strtr($str, $accent, $clean);\n return preg_replace('/[^A-Za-z0-9\\-\\.]/', '', $str);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T10:15:20.323",
"Id": "22853",
"ParentId": "21576",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "22853",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T13:23:11.167",
"Id": "21576",
"Score": "2",
"Tags": [
"php",
"url"
],
"Title": "PHP creating slugify (clean URL) links in simple way?"
}
|
21576
|
<p>I've created a WPF program which can draw lines and circles on a canvas. It works well, but I don't think it's the best solution. How can I make it work better? How would you create this program?</p>
<p><strong><code>MainWindow</code> class:</strong></p>
<pre class="lang-cs prettyprint-override"><code>public partial class MainWindow : Window
{
DrawCircle dc;
DrawLine dl;
public MainWindow()
{
InitializeComponent();
}
private void cVas_MouseMove(object sender, MouseEventArgs e)
{
switch (rbLine.IsChecked)
{
case true:
if (dl != null)
dl.MouseMove(Mouse.GetPosition(cVas));
break;
default:
if (dc != null)
dc.MouseMove(Mouse.GetPosition(cVas));
break;
}
}
private void cVas_MouseDown(object sender, MouseButtonEventArgs e)
{
switch (rbLine.IsChecked)
{
case true:
dl = new DrawLine(this);
dl.MouseDown(Mouse.GetPosition(cVas));
break;
default:
dc = new DrawCircle(this);
dc.MouseDown(Mouse.GetPosition(cVas));
break;
}
}
private void cVas_MouseUp(object sender, MouseButtonEventArgs e)
{
dc = null;
dl = null;
}
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
cVas.Children.Clear();
}
}
</code></pre>
<p><strong><code>DrawLine</code> class (the <code>DrawCircle</code> is similar to this):</strong></p>
<pre class="lang-cs prettyprint-override"><code>class DrawLine
{
private Line myLine;
MainWindow mw;
public DrawLine(MainWindow mw)
{
this.mw = mw;
}
public void MouseDown(Point mousePoint)
{
myLine = new Line();
myLine.Stroke = Brushes.Black;
myLine.StrokeThickness = 2;
myLine.X1 = myLine.X2 = mousePoint.X;
myLine.Y1 = myLine.Y2 = mousePoint.Y;
mw.cVas.Children.Add(myLine);
}
public void MouseUp()
{
myLine = null;
}
public void MouseMove(Point mousePoint)
{
if (myLine != null)
{
(mw.cVas.Children[mw.cVas.Children.IndexOf(myLine)] as Line).X2 = mousePoint.X;
(mw.cVas.Children[mw.cVas.Children.IndexOf(myLine)] as Line).Y2 = mousePoint.Y;
}
}
}
</code></pre>
<p><strong>XAML:</strong></p>
<pre class="lang-xaml prettyprint-override"><code><Window x:Class="WPFdraw.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" KeyDown="Window_KeyDown">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="20"></RowDefinition>
</Grid.RowDefinitions>
<Canvas Grid.Row="0" Background="Transparent" Name="cVas" Width="Auto" Height="Auto" MouseMove="cVas_MouseMove" MouseDown="cVas_MouseDown" MouseUp="cVas_MouseUp"></Canvas>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<RadioButton Grid.Column="0" GroupName="tool" IsChecked="True" Name="rbLine" VerticalAlignment="Center">Line</RadioButton>
<RadioButton Grid.Column="1" GroupName="tool" Name="rbCircle" VerticalAlignment="Center">Circle</RadioButton>
<Button Name="btn" Grid.Column="2" Content="klikk" ></Button>
</Grid>
</Grid>
</Window>
</code></pre>
|
[] |
[
{
"body": "<p>A little explanation first. I have written your code in a different way. This does not mean that my code is perfect in any way. I just wanted you to see other options and possibilities to achieve the same result. I'm open for comments if supported by valid arguments. </p>\n\n<p>First of all I suggest you use another naming convention. This way, the name of your controls and variables have a better meaning. For example 'cVas', I'd rename that to 'DrawingCanvas' or 'DrawingSurface'.</p>\n\n<p>Then there's the structure of your code. You have different shapes that have a similar structure and share a certain functionality. In situations like that, you can start thinking about inheritance and/or the use of interfaces.</p>\n\n<p>Below you'll see the code that I have written. Again, this code is not perfect but it shows how it can be done. And to be honest: I think my code is easier to read, shorter and also easier to expand.</p>\n\n<p>I have used an interface, from which both class derive. This way it was easy to create a Pen-object that will draw an IDrawable object. Using the Pen-object also de-couples your UI from the shape-objects. In the constructor you pass the UIElement (in this code only Canvas can be passed through) on which the pen will draw: they are coupled but in this case this is needed.</p>\n\n<p>Due to the fact of the interface and pen-object, the code in your MainWindow.xaml.cs will also be a lot cleaner. You only need to instantiate one IDrawable-object and depending on the mouse-actions you provide what is needed.</p>\n\n<p>I hope you find this useful and helpful! ;)</p>\n\n<p><strong>XAML:</strong></p>\n\n<p>I have not changed much about the XAML except for the names of the controls and I used a StackPanel instead of a Grid with columns.</p>\n\n<p><strong>IDrawable</strong></p>\n\n<pre><code>public interface IDrawable\n{\n void Draw(Point location);\n}\n</code></pre>\n\n<p><strong>MyCircle</strong></p>\n\n<pre><code>//Since you didn't provide the code of your circle-class\n//I quickly wrote a dummy-circle class, it works but not\n//flawless (X and Y coordinates)\npublic class MyCircle : IDrawable\n{\n public Ellipse Circle { get; private set; }\n\n public MyCircle(Point location)\n {\n Circle = new Ellipse\n {\n Stroke = Brushes.Black,\n StrokeThickness = 2,\n Margin = new Thickness(location.X, location.Y, 0, 0)\n };\n }\n\n public void Draw(Point location)\n {\n if(Circle != null)\n {\n Circle.Width = location.X - Circle.Margin.Left;\n Circle.Height = location.Y - Circle.Margin.Top;\n }\n }\n}\n</code></pre>\n\n<p><strong>MyLine</strong></p>\n\n<pre><code>public class MyLine : IDrawable\n{\n public Line Line { get; private set; }\n\n public MyLine(Point location)\n {\n Line = new Line\n {\n Stroke = Brushes.Black,\n StrokeThickness = 2,\n X1 = location.X,\n X2 = location.X,\n Y1 = location.Y,\n Y2 = location.Y \n };\n }\n\n public void Draw(Point location)\n {\n Line.X2 = location.X;\n Line.Y2 = location.Y;\n }\n}\n</code></pre>\n\n<p><strong>Pen</strong></p>\n\n<pre><code>public class Pen\n{\n public Pen(Canvas holder)\n {\n _holder = holder;\n }\n\n private readonly Canvas _holder;\n\n public void Down(IDrawable obj)\n {\n //if more shapes are added:\n //better use a switch-statement\n if(obj is MyCircle)\n _holder.Children.Add((obj as MyCircle).Circle);\n if(obj is MyLine)\n _holder.Children.Add((obj as MyLine).Line);\n }\n\n public void Draw(IDrawable obj, Point location)\n {\n obj.Draw(location);\n }\n}\n</code></pre>\n\n<p><strong>MainWindow</strong></p>\n\n<pre><code>public MainWindow()\n{\n InitializeComponent();\n KeyDown += MainWindowKeyDown;\n DrawingSurface.MouseMove += DrawingSurfaceMouseMove;\n DrawingSurface.MouseDown += DrawingSurfaceMouseDown;\n DrawingSurface.MouseUp += DrawingSurfaceMouseUp;\n _pen = new Pen(DrawingSurface);\n}\n\nprivate IDrawable _dr;\nprivate readonly Pen _pen;\n\nprivate void DrawingSurfaceMouseUp(object sender, MouseButtonEventArgs e)\n{\n _dr = null;\n}\n\nprivate void DrawingSurfaceMouseDown(object sender, MouseButtonEventArgs e)\n{\n if(LineRadioButton.IsChecked == true)\n _dr = new MyLine(Mouse.GetPosition(DrawingSurface));\n else if(CircleRadioButton.IsChecked == true)\n _dr = new MyCircle(Mouse.GetPosition(DrawingSurface));\n\n _pen.Down(_dr);\n}\n\nprivate void DrawingSurfaceMouseMove(object sender, MouseEventArgs e)\n{\n if(_dr != null)\n _pen.Draw(_dr, Mouse.GetPosition(DrawingSurface));\n}\n\nprivate void MainWindowKeyDown(object sender, KeyEventArgs e)\n{\n if(e.Key == Key.Enter)\n DrawingSurface.Children.Clear();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T17:22:58.517",
"Id": "34684",
"Score": "0",
"body": "thanks :) i'm learning interfaces now and it helped me a lot. :D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T09:24:13.130",
"Id": "34716",
"Score": "0",
"body": "Glad I could help. If there's something you don't understand, just ask! ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T15:17:32.343",
"Id": "21583",
"ParentId": "21579",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "21583",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T14:03:37.103",
"Id": "21579",
"Score": "5",
"Tags": [
"c#",
"wpf",
"xaml"
],
"Title": "WPF circle and line drawer solution"
}
|
21579
|
<p>This is an HTML / JavaScript app for calculating someones body mass index.
The app does conversion of metric to standard measurements and standard to metric.</p>
<p>It outputs:</p>
<ul>
<li>BMI </li>
<li>weight category</li>
<li>ideal weight range for given height </li>
<li>percentage over/under ideal weight</li>
</ul>
<p><strong><code>index.html</code></strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>BMI Calculator</title>
<style type="text/css">
#mainDisplay
{
padding:25px;
}
#form
{
width:250px;
}
#results
{
background-color:#E6E6E6;
width:450px;
}
</style>
</head>
<body>
<!-- ... action="PrintBMI.jsp" method="post" onsubmit="calculateBMI()" ... left out for now from <form> below -->
<div id = "mainDisplay">
<form name ="bmiForm" id = "form" action = "index.html">
<fieldset>
<legend>BMI Calculator</legend>
<h3>Enter your weight</h3>
Stone <input type = "text" name = "stone" size = "1" maxlength = "2" />
Pounds <input type = "text" name = "pounds" size = "2" maxlength = "6" />
<br />
<strong>OR</strong>
<br />
KGs <input type = "text" name = "kgs" size = "2" maxlength = "6" />
<h3>Enter your height</h3>
Feet <input type = "text" name = "feet" size = "1" maxlength = "1" />
Inches <input type = "text" name = "inches" size = "1" maxlength = "4" />
<br />
<strong>OR</strong>
<br />
CMs <input type = "text" name = "cms" size = "2" maxlength = "6" />
<p></p><input id = "button" type="button" value = "Find out your BMI" />
</fieldset>
</form>
</div>
<script type="text/javascript" src = "js/formScript.js"></script>
</body>
</html>
</code></pre>
<p><strong><code>formScript.js</code></strong></p>
<pre><code>//***********Constants***********
var POUNDS_IN_STONE = 14;
var KGS_PER_POUND = 0.453592;
var INCHES_IN_FOOT = 12;
var CMS_PER_INCH = 2.54;
var CMS_PER_METRE = 100;
var INPUT_ERROR_MSG = "That was not a valid measurement unit. Please try again";
var IDEAL_BMI_LOWER = 18.5;
var IDEAL_BMI_UPPER = 25;
//***********Global Variables***********
var stoneField = document.forms["bmiForm"]["stone"];
var poundsField = document.forms["bmiForm"]["pounds"]
var kgsField = document.forms["bmiForm"]["kgs"];
var feetField = document.forms["bmiForm"]["feet"];
var inchesField = document.forms["bmiForm"]["inches"];
var cmsField = document.forms["bmiForm"]["cms"];
//***********Register Event handlers***********
document.getElementById("button").onclick = function() { outputBmi() };
stoneField.onchange = function() { updateForm( "stonefld" ) };
stoneField.onchange = function() { updateForm( "poundsfld" ) };
kgsField.onchange = function() { updateForm( "kgsfld" ) };
feetField.onchange = function() { updateForm ( "feetfld" ) };
inchesField.onchange = function() { updateForm ( "inchesfld" ) };
cmsField.onchange = function() { updateForm ( "cmsfld" ) };
//***********Helper rounding number Functions***********
function roundTwoDecimals ( number )
{
return Math.round ( number * 100 ) / 100 ;
}
function roundOneDecimal ( number )
{
return Math.round ( number * 10 ) / 10 ;
}
function toInteger(number)
{
return Math.round ( Number ( number ) );
}
function toIntegerFloor ( number )
{
return Math.floor ( Number ( number) );
}
//***********Helper function for updateForm***********
// deal with a Not a Number input in the specified field
function processNaNInput ( field )
{
field.value = "";
field.focus();
alert(INPUT_ERROR_MSG);
}
//**********************
// updates the fields for the corresponding units of measure after a field is updated
function updateForm ( updatedField )
{
if ( updatedField === "stonefld" || updatedField === "poundsfld" )
{
if ( isNaN ( stoneField.value ) )
{
processNaNInput (stoneField);
}
else if ( isNaN ( poundsField.value ) )
{
processNaNInput(poundsField);
}
else if ( poundsField.value === "" && stoneField.value === "" )
{
kgsField.value = "";
}
else
{
var stoneFldInKgs = ( stoneField.value * POUNDS_IN_STONE ) * KGS_PER_POUND ;
var poundsFldInKgs = poundsField.value * KGS_PER_POUND;
var totalKgs = stoneFldInKgs + poundsFldInKgs;
kgsField.value = roundTwoDecimals ( totalKgs );
}
}
else if ( updatedField === "kgsfld" )
{
if ( isNaN ( kgsField.value ) )
{
processNaNInput( kgsField );
}
else if ( kgsField.value === "")
{
stoneField.value = "";
poundsField.value = "";
}
else
{
var totalKgsInPounds = kgsField.value / KGS_PER_POUND;
var numStone = toIntegerFloor ( totalKgsInPounds / POUNDS_IN_STONE );
var numPounds = roundTwoDecimals ( totalKgsInPounds % POUNDS_IN_STONE );
stoneField.value = numStone;
poundsField.value = numPounds;
}
}
else if ( updatedField === "feetfld" || updatedField === "inchesfld" )
{
if ( isNaN ( feetField.value ) )
{
processNaNInput(feetField);
}
else if ( isNaN ( inchesField.value ) )
{
processNaNInput(inchesField);
}
else if ( feetField.value === "" && inchesField.value === "" )
{
cmsField.value = "";
}
else
{
var feetFldInCms = ( feetField.value * INCHES_IN_FOOT ) * CMS_PER_INCH;
var inchesFldInCms = inchesField.value * CMS_PER_INCH;
var totalCms = feetFldInCms + inchesFldInCms;
cmsField.value = roundTwoDecimals ( totalCms );
}
}
else if ( updatedField === "cmsfld" )
{
if ( isNaN ( cmsField.value ) )
{
processNaNInput(cmsField);
}
else if ( cmsField.value === "" )
{
feetField.value = "";
inchesField.value = "";
}
else
{
var cmsFldInInches = cmsField.value / CMS_PER_INCH;
var numFeet = cmsFldInInches / INCHES_IN_FOOT;
var numInches = cmsFldInInches % INCHES_IN_FOOT;
feetField.value = toIntegerFloor ( numFeet );
inchesField.value = roundOneDecimal ( numInches );
}
}
else
{
alert ( "Invalid parmater passed to completeForm function" )
}
}
//***********Helper Functions Called by calculateBMI***********
// check if any of the fields in the form are empty and if empty outputs
// an error message. Returns false is the form is fully filled out
function hasEmptyFlds ( )
{
// If all fields are empty output a message
if ( ( stoneField.value === null || stoneField.value === "" ) && ( poundsField.value === null || poundsField.value === "" ) && ( kgsField.value === null || kgsField.value === "" ) &&
( feetField.value === null || feetField.value === "" ) && ( inchesField.value === null || inchesField.value === "" ) && ( cmsField.value === null || cmsField.value === "" ) )
{
alert( "Please enter a weight and height" );
return true;
}
// If weight fields of the form are not filled out output an message
else if ( kgsField.value === null || kgsField.value === "" )
{
alert ( "Please enter a weight" );
return true;
}
// If the height fields of the form are not filled out output a message
else if ( cmsField.value === null || cmsField.value === "" )
{
alert ( "Please enter a height" );
return true;
}
else
{
return false;
}
}
// returns the name of the bmi category for a given bmi
function getBmiCategory ( bmi )
{
if ( bmi < 15 )
{
return "Very severely underweight";
}
else if ( bmi < 16 )
{
return "Severely underweight";
}
else if ( bmi < 18.5 )
{
return "Underweight";
}
else if ( bmi < 25 )
{
return "Normal (healthy weight)";
}
else if ( bmi < 30 )
{
return "Overweight";
}
else if ( bmi < 35 )
{
return "Moderately obese";
}
else if ( bmi < 40 )
{
return "Severely obese";
}
else
{
return "Very severely obese";
}
}
//**********************
// calculates and outputs bmi, bmi category, ideal bmi range, ideal weight range and percent over or under ideal weight
function outputBmi ( )
{
if ( ! hasEmptyFlds ( ) )
{
var heightInMetres = cmsField.value / 100;
var bmi = roundOneDecimal ( kgsField.value / ( heightInMetres * heightInMetres ) );
var category = getBmiCategory ( bmi );
//lower weight cut off for a healthy bmi
var lowerKgs = toInteger ( IDEAL_BMI_LOWER * ( heightInMetres * heightInMetres ) );
//upper weight cut off for a healthy bmi
var upperKgs = toInteger ( IDEAL_BMI_UPPER * ( heightInMetres * heightInMetres ) );
//convert lower cut off from kgs to stone and pounds
var totalLowerPounds = lowerKgs / KGS_PER_POUND;
var lowerStone = toIntegerFloor ( totalLowerPounds / POUNDS_IN_STONE );
var lowerPounds = toInteger ( totalLowerPounds % POUNDS_IN_STONE );
//convert upper cut off from kgs to stone and pounds
var totalUpperPounds = upperKgs / KGS_PER_POUND;
var upperStone = toIntegerFloor ( totalUpperPounds / POUNDS_IN_STONE );
var upperPounds = toInteger ( totalUpperPounds % POUNDS_IN_STONE );
var html = "<p id = 'results'>";
html += "Your BMI is : " + bmi + " <br /> Your BMI is in the " + category + " category<br />";
html += "<br />The BMI for Normal ( healthy weight ) is between 18.5 and 25";
html += "<br /><br />Normal (healthy weight) for your height is between:<br />";
html += lowerKgs + " kgs (" + lowerStone + " stone, " + lowerPounds + " pounds ) and ";
html += upperKgs + " kgs (" + upperStone + " stone, " + upperPounds + " pounds ) <br />";
if ( kgsField.value < lowerKgs )
{
var kgsUnderIdeal = lowerKgs - kgsField.value;
var percentUnder = toInteger ( ( kgsUnderIdeal * 100 ) / lowerKgs );
html += "<br />You are " + percentUnder + "% below your ideal weight bracket";
}
else if ( kgsField.value > upperKgs )
{
var kgsOverIdeal = kgsField.value - upperKgs;
var percentOver = toInteger ( ( kgsOverIdeal * 100 ) / upperKgs );
html += "<br />You are " + percentOver + "% over your ideal weight bracket";
}
html += "<br /><br /><a href='/'>< Go back to bmi form</a></p>"
document.getElementById( 'mainDisplay' ).innerHTML = html;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T16:30:51.093",
"Id": "34680",
"Score": "0",
"body": "I know sometimes things are purely up to a dev in the way they style their code, but please, try not to do this: `type = \"text\"` and instead remove the spaces on either side of the equal sign `type=\"text\"`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T17:25:13.560",
"Id": "34685",
"Score": "4",
"body": "Spaces are fine - I use the same style myself - and no-spaces is fine too; use what you prefer. **But** best to avoid the brace-on-new-line style when writing JavaScript. JS [will sometimes try to insert semi-colons](http://stackoverflow.com/a/3218860/167996) in your code if it finds an end-of-line, meaning that linebreaks can break your code. Spaces, however, can't. So never mind jsanc623's comment about that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T20:45:28.970",
"Id": "85350",
"Score": "2",
"body": "I think @jsanc623's comment was about the HTML attributes--the one place where I omit spaces around an equals sign \"operator\". Either way, be consistent: `name =\"bmiForm\"` is not cool."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T02:37:34.840",
"Id": "85380",
"Score": "0",
"body": "That is correct @DavidHarkness - I meant the HTML attributes (http://i.imgur.com/roguC4C.png)"
}
] |
[
{
"body": "<ol>\n<li><p>Constants; instead of creating a bunch of standalone keys I'd group them in a single object, like:</p>\n\n<pre><code>var bmiConstants = {\n POUNDS_IN_STONE: 14,\n KGS_PER_POUND: 0.453592,\n INCHES_IN_FOOT: 12,\n CMS_PER_INCH: 2.54,\n CMS_PER_METRE: 100,\n INPUT_ERROR_MSG: \"That was not a valid measurement unit. Please try again\",\n IDEAL_BMI_LOWER: 18.5,\n IDEAL_BMI_UPPER: 25\n};\n</code></pre></li>\n<li><p>Globals; I would prefer using ids on the input fields (or even better, a jQuery selector) to retrieve them rather than going through <code>document.forms</code>. Like:</p>\n\n<pre><code>var stoneField = document.getElementById(\"stones\");\nvar poundsField = document.getElementById(\"pounds\");\n//...\n</code></pre></li>\n<li><p>Globals; Even more than above, I'd prefer not having these globals at all. Instead you could retrieve them as needed in your functions (and/or pass them in as parameters).</p></li>\n<li><p>Event Handlers; If you're just going to use the <code>onclick</code> and <code>onchange</code> attributes, there's no need to bind them programmatically. You can set them up in your markup instead, like:</p>\n\n<pre><code><input type = \"text\" name = \"stone\" size = \"1\" maxlength = \"2\" onchange=\"updateForm(this);\" />\n<input type = \"text\" name = \"pounds\" size = \"2\" maxlength = \"6\" onchange=\"updateForm(this);\" />\n<!-- ... -->\n\n<input id = \"button\" type=\"button\" value = \"Find out your BMI\" onclick=\"outputBmi();\" />\n</code></pre>\n\n<p>Note that this allows you to easily pass the <code>input</code> field itself to <code>updateForm()</code>, instead of just an arbitrary key.</p></li>\n<li><p>Functions; I'd recommend the following style when writing functions:</p>\n\n<pre><code>function roundTwoDecimals(number) {\n return Math.round(number * 100) / 100; \n}\n</code></pre></li>\n<li><p>Separation of logic and presentation; Instead of composing a big long HTML string in <code>outputBmi()</code> I'd recommend having the basic structure of the output as part of your markup. For instance, contained within a <code>div</code> that is set to <code>display: none</code> initially. Then the only thing <code>outputBmi()</code> needs to do is update the parts that actually change and toggle the visibility of the <code>div</code>. That will result in less code and be more maintainable than trying to construct the entire HTML snippet programmatically.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T20:46:16.957",
"Id": "34770",
"Score": "2",
"body": "Not sure why you got -1, I disagree wit (4) though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T08:22:20.513",
"Id": "34787",
"Score": "0",
"body": "+1 This is a useful answer. As @tomdemuyt, I disagree with 4 also. I would also add to (6) that pure computations can be refactored out to functions. The calculations using local vars are noise you gloss over, when you read it the 3rd time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T11:41:18.747",
"Id": "34947",
"Score": "0",
"body": "\"Constants; instead of creating a bunch of standalone keys I'd group them in a single object\" Could you explain the reason for this and benefits derived over using standalone constants?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T11:44:33.397",
"Id": "34948",
"Score": "0",
"body": "\"2. Globals; I would prefer using ids on the input fields (or even better, a jQuery selector) to retrieve them rather than going through document.forms.\" Again I would appreciate the reasons/advantages for preferring of going through getElementByIds verses using documents.forms. Many thanks for your time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T12:04:14.650",
"Id": "34951",
"Score": "0",
"body": "\"3. Globals; Even more than above, I'd prefer not having these globals at all. Instead you could retrieve them as needed in your functions (and/or pass them in as parameters)\" The reason I created them as global variables was to shorten my code to make it more readable as these global variables are frequently used in many functions. I was wondering what would be the reasons against using global variables in this case?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T07:45:29.170",
"Id": "34995",
"Score": "2",
"body": "@agilesumo - #1) In JavaScript, variables declared without an enclosing context wind up in the global scope by default. Generally speaking, it is considered good practice to minimize the number of things that are declared globally when writing JavaScript. The modified version has one global variable instead of the original 8. There are also slightly more complex techniques that can be used to avoid have *any* globals at all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T07:58:03.870",
"Id": "34996",
"Score": "2",
"body": "@agilesumo - #2) This is partly personal preference, but my feeling is that using `document.forms` is a more brittle approach. You're relying on two things there, the name of the form, and the name of the input field/parameter. If another developer comes along and changes one of those, your code will break in a non-obvious way. With `getElementById` you're relying on only a single piece of information to find your element(s), which makes it less brittle in general, and easier to track down issues if the id ever does get changed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T08:07:39.573",
"Id": "34997",
"Score": "1",
"body": "@agilesumo - #3) Is partly related to #1. Usually in JavaScript you want to avoid using global variables if you can help it. And if you're using a framework like jQuery, looking up an element on demand doesn't take must more code than `$(\"#kgsField\").val()`...which is only a few characters longer than `kgsField.value`. Even without a framework there are ways to avoid having the globals, such as having a `getFields()` function that looks up and returns all the fields in a single object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T08:13:12.470",
"Id": "34998",
"Score": "1",
"body": "@agilesumo - And the other part of #3 is that by looking up the element once and caching the result forever in the global variable, you're pretty much excluding the possibility of doing anything dynamic with the section of the page that contains those fields (i.e. anything that would change the `innerHTML` of the element that contains them). Even if you don't plan on doing anything like that in this case, I think it's generally better to code in a way that at least allows for the possibility in the future."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T09:50:08.193",
"Id": "35000",
"Score": "0",
"body": "Many thanks for answering my questions. Much Appreciated. Very informative answers."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T01:46:04.827",
"Id": "21601",
"ParentId": "21581",
"Score": "7"
}
},
{
"body": "<h1>The Markup</h1>\n\n<pre><code><?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<!DOCTYPE html PUBLIC\n \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\">\n</code></pre>\n\n<p>Any particular reason for using XHTML? The typical way to go these days is HTML5 – also makes the doctype easier. And it will have all the Web 2.0 features.</p>\n\n<pre><code><style type=\"text/css\">\n #mainDisplay\n {\n padding:25px;\n }\n #form\n {\n width:250px;\n }\n #results\n {\n background-color:#E6E6E6;\n width:450px; \n } \n</style>\n</code></pre>\n\n<p>Uh-oh! Don't do CSS (or Javascript for that matter) inline. You are violating the <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\">Separation of Concerns</a> pattern. As a general rule: Any file should only ever contain two languages at most – the language the program is written in and English for documentation, if necessary.</p>\n\n<h1>The Javascript</h1>\n\n<p>First off: Don't clutter the global space. Never – just <em>never</em>. It's so easy to at least use a closure to hide your stuff!</p>\n\n<p>Next up, don't use <code>document.forms</code>, just get the element by id. You can also avoid unnecessary DOM lookups by caching the the DOM element.</p>\n\n<pre><code>document.getElementById(\"button\").onclick = function() { outputBmi() };\n</code></pre>\n\n<p>There is no reason to wrap anything. Just do</p>\n\n<pre><code>document.getElementById(\"button\").onclick = outputBmi;\n</code></pre>\n\n<p>Now to this:</p>\n\n<pre><code>function roundTwoDecimals ( number )\n{\n return Math.round ( number * 100 ) / 100 ; \n}\n\nfunction roundOneDecimal ( number )\n{\n return Math.round ( number * 10 ) / 10 ; \n}\n</code></pre>\n\n<p>Instead of duplicating methods that only differ slightly, abstract it and create a single method that simply takes a parameter to specify how many digits the number should be rounded to.</p>\n\n<pre><code>alert(INPUT_ERROR_MSG);\n</code></pre>\n\n<p>Don't use <code>alert</code>. Ever. It has terrible user experience and most browsers tempt the user to deactivate Javascript for the entire page. Use DOM methods to display appropriate messages instead.</p>\n\n<pre><code>function updateForm ( updatedField )\n // … and the entire thing that follows\n</code></pre>\n\n<p>Warning: Monster method detected. You are using a single parameter with a known set of values to decide what the entire function does – this is a strong sign that you should instead declare <em>individual</em> functions without parameters.</p>\n\n<p>Your function is also <em>way too long</em>. A good function does one thing and it does it well. A good function is no longer than a few lines of code. Your function does too much and it is too hard to keep track of what it is doing.</p>\n\n<pre><code>function hasEmptyFlds ( )\n</code></pre>\n\n<p>Do you like shrtng wrds? Don't do that – don't be lazy.</p>\n\n<pre><code>function getBmiCategory ( bmi )\n // and the entire rest\n</code></pre>\n\n<p>This method clearly shows the too tight coupling of data and logic. A better way to write such methods is to declare an object that simply holds thresholds and the messages and a method that uses this object and programmatically chooses the correct message from it. Also makes it easier to understand and maintain.</p>\n\n<p>A few more things:</p>\n\n<ul>\n<li>If you're going to document functions, use proper JSDoc, not single comments.</li>\n<li>Don't construct a big string of HTML, use DOM methods instead. The browser does all of this for you, so let it do its work!</li>\n<li>You need to work on a lot of the names. <code>updateForm</code> is generic. What does it <em>really</em> tell the caller? Update which form? Update what?</li>\n</ul>\n\n<p>Frankly, there is a lot more to say, but I feel that this is enough to deal with first.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T19:38:30.843",
"Id": "48613",
"ParentId": "21581",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T15:13:19.903",
"Id": "21581",
"Score": "7",
"Tags": [
"javascript",
"html"
],
"Title": "Calculating Body Mass Index (BMI)"
}
|
21581
|
<p>I GET a HTML response from AJAX over cors and the response is a table. Each category has its title and sub elements. The title names vary quite a bit and are likely to change in the future. The sub elements in each title change almost on a daily basis, but the DOM structure doesn't.</p>
<p>Is there a way I could get rid of this if statement and replace it with code that isn't element specific? Some way of selecting DOM elements I'm not aware of?</p>
<p><strong>Relevat JS</strong></p>
<pre><code>classifiedFilter: function (response) {
var Classified = {
ClaAdministrative: [],
Paraeducator: [],
Clerical: [],
Custodial: [],
NonRep: [],
Maintenance: [],
ClaSubstitute: [],
Coaching: []
},
response = $(response).find("table tbody tr td").html();
$(response).find("#isHeadType").remove();
$(response).find("font:contains(Open to all)").parent().parent().remove();
//Filter each span title and classify sub items
$(response).find("span").parents("tr").each(function () {
//Find categories and separate by class
var rowtext = $(this).find("span").text(),
position = "";
position = rowtext.replace(/-/gi, "").replace(/\s/g, "");
$(this).nextAll("tr").addClass(position);
//Push content into Classified
((position === "Administrative") ? $(this).nextUntil(".Paraeducator").each(function () {
Classified.ClaAdministrative.push($.trim("<tr>" + $(this).html() + "</tr>"));
}) : ((position === "Paraeducator") ? $(this).nextUntil(".Clerical").each(function () {
Classified.Paraeducator.push($.trim("<tr>" + $(this).html() + "</tr>"));
}) : ((position === "Clerical") ? $(this).nextUntil(".Custodial").each(function () {
Classified.Clerical.push($.trim("<tr>" + $(this).html() + "</tr>"));
}) : ((position === "Custodial") ? $(this).nextUntil(".NonRep").each(function () {
Classified.Custodial.push($.trim("<tr>" + $(this).html() + "</tr>"));
}) : ((position === "NonRep") ? $(this).nextUntil(".Maintenance").each(function () {
Classified.NonRep.push($.trim("<tr>" + $(this).html() + "</tr>"));
}) : ((position === "Maintenance") ? $(this).nextUntil(".Substitute").each(function () {
Classified.Maintenance.push($.trim("<tr>" + $(this).html() + "</tr>"));
}) : ((position === "Substitute") ? $(this).nextUntil(".Coaching").each(function () {
Classified.ClaSubstitute.push($.trim("<tr>" + $(this).html() + "</tr>"));
}) : ((position === "Coaching") ? $(this).nextAll().each(function () {
Classified.Coaching.push($.trim("<tr>" + $(this).html() + "</tr>"));
}) : []))))))));
});
}
</code></pre>
<p><strong>Summarized HTML GET response</strong> (added spaces for visual aid)</p>
<pre><code><table border="0" cellspacing="0" cellpadding="0" style="MARGIN-TOP: 10px;">
<tr>
<td> <font class="HeadTitle">External Positions: Open to all applicants.</font>
<br>
</td>
</tr>
<tr>
<td height="20" nowrap="nowrap"> <i><span id="ExternalJobs__ctl1_BargainGroup" class="BodyText">Administrative</span></i>
<br/>
<br/>
</td>
</tr>
<tr>
<td nowrap="nowrap" style="padding-left:20px;" class="BodyText"> <b><a href='jobs.aspx?id=3660&type=2&int=External'>Administrative Assistant I, Health Tech-Leave Replacement-2 hours - ME1214</a></b>
</td>
</tr>
<tr>
<td height="20" nowrap="nowrap"> <i><span id="ExternalJobs__ctl2_BargainGroup" class="BodyText">Paraeducator</span></i>
<br/>
<br/>
</td>
</tr>
<tr>
<td nowrap="nowrap" style="padding-left:20px;" class="BodyText"> <b><a href='jobs.aspx?id=3544&type=2&int=External'>Paraeducator, SpEd IP/ELL-6.5hours - MC1223</a></b>
</td>
</tr>
<tr>
<td nowrap="nowrap" style="padding-left:20px;" class="BodyText"> <b><a href='jobs.aspx?id=3603&type=2&int=External'>Special Ed Paraeducator, School Adjustment Program (SA-)-6.5 hours - MK1215</a></b>
</td>
</tr>
<tr>
<td height="20" nowrap="nowrap"> <i><span id="ExternalJobs__ctl3_BargainGroup" class="BodyText">Clerical</span></i>
<br/>
<br/>
</td>
</tr>
<tr>
<td nowrap="nowrap" style="padding-left:20px;" class="BodyText"> <b><a href='jobs.aspx?id=3481&type=2&int=External'>Admin Assistant IV-8 hours - IT1209</a></b>
</td>
</tr>
<tr>
<td height="20" nowrap="nowrap"> <i><span id="ExternalJobs__ctl5_BargainGroup" class="BodyText">Non-Rep</span></i>
<br/>
<br/>
</td>
</tr>
<tr>
<td nowrap="nowrap" style="padding-left:20px;" class="BodyText"> <b><a href='jobs.aspx?id=2732&type=2&int=External'>Licensed Practical Nurse (Pool position) - 2012LPNPool</a></b>
</td>
</tr>
<tr>
<td nowrap="nowrap" style="padding-left:20px;" class="BodyText"> <b><a href='jobs.aspx?id=3472&type=2&int=External'>Certified Occupational/Physical Therapist Assistant- POOL - COTA2012Pool</a></b>
</td>
</tr>
<tr>
<td height="20" nowrap="nowrap"> <i><span id="ExternalJobs__ctl7_BargainGroup" class="BodyText">Substitute</span></i>
<br/>
<br/>
</td>
</tr>
<tr>
<td nowrap="nowrap" style="padding-left:20px;" class="BodyText"> <b><a href='jobs.aspx?id=26&type=2&int=External'>Substitute Food Service Helpers - FSSub</a></b>
</td>
</tr>
<tr>
<td nowrap="nowrap" style="padding-left:20px;" class="BodyText"> <b><a href='jobs.aspx?id=28&type=2&int=External'>Substitute Custodians - MTSub</a></b>
</td>
</tr>
</table>
</code></pre>
|
[] |
[
{
"body": "<p>I have a hard time believing this code is working the way you want it to. </p>\n\n<p>But to answer your question, here is how I would get rid of that if statement. Use a two dimensional array as a lookup table and push items into the arrays there.</p>\n\n<pre><code>var classifiedFilter = function (response) {\n\n var jobTable = [\n [\"Administrative\", []],\n [\"Paraeducator\", []],\n [\"Clerical\", []],\n [\"Custodial\", []],\n [\"NonRep\", []],\n [\"Maintenance\", []],\n [\"Substitute\", []],\n [\"Coaching\", []]\n ],response = $(response).find(\"table tbody tr td\").html();\n\n $(response).find(\"#isHeadType\").remove();\n $(response).find(\"font:contains(Open to all)\").parent().parent().remove();\n //Filter each span title and classify sub items\n $(response).find(\"span\").parents(\"tr\").each(function () {\n //Find categories and separate by class\n var rowtext = $(this).find(\"span\").text(),\n position = \"\";\n\n position = rowtext.replace(/-/gi, \"\").replace(/\\s/g, \"\");\n $(this).nextAll(\"tr\").addClass(position);\n\n //Push content into Classified\n for (i = 0; i < jobTable.length; i++) {\n if (position === jobTable[i][0]) { // section/button is enabled\n if (i === (jobTable.length - 1)) {\n $(this).nextAll().each(function () {\n jobTable[i][1].push($.trim(\"<tr>\" + $(this).html() + \"</tr>\"))\n });\n } else {\n $(this).nextUntil(\".\" + jobTable[i + 1][0]).each(function () {\n jobTable[i][1].push($.trim(\"<tr>\" + $(this).html() + \"</tr>\"))\n });\n }\n }\n }\n });\n\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T16:48:37.160",
"Id": "34813",
"Score": "0",
"body": "I like your code and it works! The only thing is that you're assuming that the titles in the table don't change. If they do, the items won't be classified properly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T17:26:32.607",
"Id": "34814",
"Score": "1",
"body": "This site is for working code. Therefore I did not change any functionality. This code does exactly what yours did while removing the hardcoded if statement."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T00:39:53.170",
"Id": "21647",
"ParentId": "21588",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T16:30:49.580",
"Id": "21588",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"ajax"
],
"Title": "AJAX response DOM element selection"
}
|
21588
|
<p>I was refactoring some code and found this:</p>
<pre><code>DateTime CurrentDateTime = System.now();
Datetime ESTDate = Datetime.newInstance(CurrentDateTime.year(),CurrentDateTime.month(),CurrentDateTime.day(),CurrentDateTime.hour(),CurrentDateTime.minute(),CurrentDateTime.second());
String myDateFormat = ESTDate.format('yyyy-MM-dd hh:mm:ss');
String myDate = myDateFormat.replace(' ', 'T');
object1.birthDate = myDate;
</code></pre>
<p>And I changed it to</p>
<pre><code>object1.birthDate = datetime.now().format('yyyy-MM-dd\'T\'hh:mm:ss');
</code></pre>
<p>CurrentDateTime isn't used anywhere just in those four lines.
How a programmer can even do that? Or WHY?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T22:30:15.823",
"Id": "34691",
"Score": "3",
"body": "What's language is that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T23:32:58.757",
"Id": "34694",
"Score": "0",
"body": "@CyrilleKarmann - Probably C# (or other .NET); `DateTime` is the standard 'timestamp' type, and `System.Now` is the 'current timestamp' property. Personally, though, I'm a little suspicious of anything named `object1`, and storing the _time_ for a birthdate (while technically people _are_ born at a particular 'instant', nobody ever thinks of them that ways - it tends to be the 'local calendar day'). That, and outputting it as a formatted string. It looks like there may have been an attempt to deal with timezones, but I don't see anything that actually references them, so..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T09:38:55.857",
"Id": "34792",
"Score": "0",
"body": "@Clockwork-Muse no, this is *not* C#. [apex-code](http://stackoverflow.com/tags/apex-code/info) is a programming language for Salesforce."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T11:22:31.250",
"Id": "35123",
"Score": "0",
"body": "@Clockwork-Muse imagine that instead birthDate there is a field named f1 -> object1.f1 = ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T16:25:42.477",
"Id": "35137",
"Score": "0",
"body": "@Chiz - Ouch. Is there nothing you can do to get better names for things? I'd be \"Spindle, Fold, and Mutilate\"-ing someone who tried that on regular production code..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T08:07:17.793",
"Id": "35327",
"Score": "0",
"body": "@Clockwork-Muse it's not real names of variables and fields. It's prohibited for me to show real code. I thought it's obvious. The question is not about NAMES but about excessive number of lines and variables."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T18:56:30.370",
"Id": "46164",
"Score": "0",
"body": "@codesparkle Why not put in a line in the tag wiki to avoid confusion in future?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T19:10:22.710",
"Id": "46229",
"Score": "0",
"body": "I've added descriptions to the apex-code, force.com, and salesforce tags."
}
] |
[
{
"body": "<p>The programmer probably didn't understand how quoting works in <code>DateTime.format()</code> - just couldn't get the 'T' to appear in the string, so bailed, put the space there and replaced it. Creating <code>ESTDate</code> from <code>CurrentDateTime</code> is particularly weird, though!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T17:59:44.733",
"Id": "29239",
"ParentId": "21595",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "29239",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T22:11:43.307",
"Id": "21595",
"Score": "4",
"Tags": [
"optimization",
"salesforce-apex"
],
"Title": "Format current date"
}
|
21595
|
<p>I've written a script using the Django ORM to store 'configuration settings' and interacting with the Google Drive API and another API. The script creates a base project folder and subfolders in Google Drive for a list of records, and posts links back to the source database. I'm a beginner in Python, so I'm not sure if I'm doing things the right way, or if it's completely terrible.</p>
<p>I think there are some areas that could be cleaned up -- for example, how I am creating the 'client' and 'service' objects repeatedly inside specific methods. I wasn't sure if it would work to create the objects and pass them between the methods though. I think I could also use the Google 'batch' and 'partial response' methods to optimize HTTP requests.</p>
<p>Also, I need to get this thing on a periodic task or crontab. I was interested in trying celery, so I initially set up the below jobs, and they were creating the clients, but I don't think it's working anymore in Celery.</p>
<p>I removed some of the script and commented areas to make it more understandable.</p>
<pre><code># Celery tasks
@periodic_task(run_every=crontab(hour="*", minute="*", day_of_week="*"))
def sync_folders():
configs = Configuration.objects.all()
for config in configs:
user = config.user
client = create_client(user, config)
try:
create_document_folders(config, client)
except Exception as inst:
pass
@periodic_task(run_every=crontab(hour="*", minute="5", day_of_week="*"))
def sync_files():
configs = Configuration.objects.all()
for config in configs:
user = config.user
client = create_client(user, config)
try:
get_updated_files(config, client)
except Exception as inst:
pass
# Rest of post is the script initiated by celery tasks above.
def create_client(user, config):
# Create the QuickBase Client object
s = config
if s is not None:
if s.qb_realm is not None:
if s.qb_realm != 'www':
baseurl = 'https://' + s.qb_realm + '.quickbase.com'
else:
baseurl = 'https://www.quickbase.com'
else:
baseurl = 'https://www.quickbase.com'
client = quickbase.Client(QUICKBASE_USER, QUICKBASE_PASSWORD, base_url=baseurl)
return client
def get_jobs_wo_folders(config, client):
if client is not None:
query = "{'" + config.root_folder_id + "'.EX.''}"
clist = [config.root_folder_id, config.root_folder_name_fid, config.root_folder_user, '3']
records = client.do_query(query, columns=clist, database=config.qb_root_dbid)
return records
def retrieve_specific_files(service, param):
# Search and retrieve a list of file resources passing a params object
result = []
page_token = None
while True:
try:
if page_token:
param['pageToken'] = page_token
files = service.files().list(**param).execute()
result.extend(files['items'])
page_token = files.get('nextPageToken')
if not page_token:
break
except errors.HttpError, error:
print 'An error occurred: %s' % error
break
return result
def get_csv(list):
si = cStringIO.StringIO()
cw = csv.writer(si)
cw.writerows(list)
return si.getvalue().strip('\r\n')
# Google helper functions
def refresh_access_token(user, config):
instance = UserSocialAuth.objects.get(user=user, provider='google-oauth2')
instance.refresh_token()
# Configuration model has a field 'last_refresh_time' that is auto-now date/time
config.save()
return instance.extra_data['access_token']
def get_access_token(config):
try:
access_token = UserSocialAuth.objects.get(user=config.user, provider='google-oauth2').extra_data['access_token']
return access_token
except Exception as inst:
pprint(inst)
def create_drive_service(config):
"""
Creates a drive service using the 'Configuration' object's
related user. Users initial signup is done with django-socialauth;
the access token and refresh token is saved with django-socialauth &
refresh token handling is done with django-socialauth.
"""
c = config
user = config.user
instance = UserSocialAuth.objects.get(user=user, provider='google-oauth2')
refreshed_at = c.token_last_refresh
now = datetime.now()
expires_in = instance.extra_data['expires']
token_age = (now - refreshed_at).seconds
if token_age > (expires_in - 120):
access_token = refresh_access_token(user, config)
else:
access_token = instance.extra_data['access_token']
try:
credentials = AccessTokenCredentials(access_token, 'Python-urllib2/2.7')
http = httplib2.Http()
http = credentials.authorize(http)
return build('drive', 'v2', http=http)
except Exception as e:
pprint(e)
# Are these next lines pointless? What should I do if the tokens consistently fail?
access_token = refresh_access_token(user)
http = httplib2.Http()
http = credentials.authorize(http)
return build('drive', 'v2', http=http)
def insert_permission(service, file_id, value, perm_type, role):
new_permission = {
'value': value,
'type': perm_type,
'role': role,
}
try:
return service.permissions().insert(
fileId=file_id, body=new_permission, sendNotificationEmails=False).execute()
except errors.HttpError, error:
print 'An error occured: %s' % error
return None
def insert_folder(config, title, parent_idNone, writer=None, mime_type='application/vnd.google-apps.folder'):
service = create_drive_service(config)
owner_permission = {
'role': 'owner',
'type': 'user',
'value': 'me',
}
body = {
'title': title,
'mimeType': mime_type,
'userPermission': owner_permission,
'fields': 'items, items/parents',
}
if parent_id:
body['parents'] = [{'id': parent_id}]
try:
folder = service.files().insert(
body=body,
).execute()
insert_permission(service, folder['id'], writer, 'user', 'writer')
return folder
except errors.HttpError, error:
print 'An error occured: %s' % error
return None
def create_document_folders(config, client):
"""
Gets records that do not have Google drive folders,
and loops through the jobs creating the necessary
base project folder and subfolders.
"""
s = config
records = get_jobs_wo_folders(config, client)
"""
A bunch of logic goes below this to loop through the list of records,
create the new folders, and append the new folder metadata to a the 'rows' list
which is later converted to records_csv
"""
if rows:
records_csv = get_csv(rows)
# Create the records in QuickBase
response = client.import_from_csv(records_csv, clist=folders_clist, database=s.folders_dbid)
</code></pre>
|
[] |
[
{
"body": "<pre><code># Celery tasks\n@periodic_task(run_every=crontab(hour=\"*\", minute=\"*\", day_of_week=\"*\"))\ndef sync_folders():\n configs = Configuration.objects.all()\n for config in configs:\n user = config.user\n client = create_client(user, config)\n</code></pre>\n\n<p>I'd do: <code>create_client(config.user, config)</code></p>\n\n<pre><code> try:\n create_document_folders(config, client)\n except Exception as inst:\n pass\n</code></pre>\n\n<p>Don't do this. You catch an exception and ignore it. You have no clue what went wrong. You should at the very least print out the exception, or put it in a log, or something so you can figure out what what goes wrong.</p>\n\n<pre><code>@periodic_task(run_every=crontab(hour=\"*\", minute=\"5\", day_of_week=\"*\"))\ndef sync_files():\n configs = Configuration.objects.all()\n for config in configs:\n user = config.user\n client = create_client(user, config)\n try:\n get_updated_files(config, client)\n except Exception as inst:\n pass\n</code></pre>\n\n<p>Pretty the same function again. Refactor them and pass <code>get_updated_files</code> or <code>create_document_folder</code> as a parameter to the new function.</p>\n\n<pre><code># Rest of post is the script initiated by celery tasks above. \ndef create_client(user, config):\n # Create the QuickBase Client object\n s = config\n</code></pre>\n\n<p>Why? Just use config. The only advantage to s is that it's harder to read.</p>\n\n<pre><code> if s is not None:\n</code></pre>\n\n<p>Do you really want to support config being None?</p>\n\n<pre><code> if s.qb_realm is not None:\n if s.qb_realm != 'www':\n baseurl = 'https://' + s.qb_realm + '.quickbase.com'\n</code></pre>\n\n<p>Generally its better to use string formatting than concatenation.</p>\n\n<pre><code> else:\n baseurl = 'https://www.quickbase.com'\n</code></pre>\n\n<p>Why is this a special case? it just does the same thing that the above case would do.</p>\n\n<pre><code> else:\n baseurl = 'https://www.quickbase.com'\n\n\n client = quickbase.Client(QUICKBASE_USER, QUICKBASE_PASSWORD, base_url=baseurl)\n return client\n</code></pre>\n\n<p>Combine those two lines</p>\n\n<pre><code>def get_jobs_wo_folders(config, client):\n if client is not None:\n</code></pre>\n\n<p>Having a function silently fail to do its job given bad input is a bad idea. You should throw an exception. I wouldn't even bother to check if client were None, and just let it fail when it tries to use it.</p>\n\n<pre><code> query = \"{'\" + config.root_folder_id + \"'.EX.''}\"\n clist = [config.root_folder_id, config.root_folder_name_fid, config.root_folder_user, '3']\n records = client.do_query(query, columns=clist, database=config.qb_root_dbid)\n return records\n\ndef retrieve_specific_files(service, param):\n # Search and retrieve a list of file resources passing a params object\n result = []\n page_token = None\n while True:\n try:\n if page_token:\n</code></pre>\n\n<p>Use <code>is not None</code> to check for None, just because a few other random things end up being false and its more explicit this way</p>\n\n<pre><code> param['pageToken'] = page_token\n files = service.files().list(**param).execute()\n result.extend(files['items'])\n page_token = files.get('nextPageToken')\n if not page_token:\n break\n except errors.HttpError, error:\n print 'An error occurred: %s' % error\n break\n</code></pre>\n\n<p>Do you really want to try and continue on if there is an error? Shouldn't you just give up this attempt?</p>\n\n<pre><code> return result\n\ndef get_csv(list):\n</code></pre>\n\n<p>avoid list as a variable name since its a builtin python type</p>\n\n<pre><code> si = cStringIO.StringIO()\n cw = csv.writer(si)\n cw.writerows(list)\n return si.getvalue().strip('\\r\\n')\n\n# Google helper functions\ndef refresh_access_token(user, config):\n instance = UserSocialAuth.objects.get(user=user, provider='google-oauth2')\n instance.refresh_token()\n # Configuration model has a field 'last_refresh_time' that is auto-now date/time\n config.save()\n return instance.extra_data['access_token']\n\ndef get_access_token(config):\n try:\n access_token = UserSocialAuth.objects.get(user=config.user, provider='google-oauth2').extra_data['access_token']\n</code></pre>\n\n<p>You just did something very similiar, this suggests that you should extract a common function</p>\n\n<pre><code> return access_token\n except Exception as inst:\n pprint(inst)\n</code></pre>\n\n<p>At least here you print the exception. </p>\n\n<pre><code>def create_drive_service(config):\n\"\"\"\nCreates a drive service using the 'Configuration' object's\nrelated user. Users initial signup is done with django-socialauth;\nthe access token and refresh token is saved with django-socialauth &\nrefresh token handling is done with django-socialauth.\n\"\"\"\n c = config\n user = config.user\n</code></pre>\n\n<p>Why do you sometimes use <code>config.user</code> and other times pass the user as a parameter?</p>\n\n<pre><code> instance = UserSocialAuth.objects.get(user=user, provider='google-oauth2')\n</code></pre>\n\n<p>avoid generic names like instance</p>\n\n<pre><code> refreshed_at = c.token_last_refresh\n now = datetime.now()\n expires_in = instance.extra_data['expires']\n token_age = (now - refreshed_at).seconds\n if token_age > (expires_in - 120):\n access_token = refresh_access_token(user, config)\n</code></pre>\n\n<p>But you've already got the instand, so this does extra work</p>\n\n<pre><code> else:\n access_token = instance.extra_data['access_token']\n\n try:\n credentials = AccessTokenCredentials(access_token, 'Python-urllib2/2.7')\n http = httplib2.Http()\n http = credentials.authorize(http)\n return build('drive', 'v2', http=http)\n except Exception as e:\n pprint(e)\n # Are these next lines pointless? What should I do if the tokens consistently fail?\n access_token = refresh_access_token(user)\n</code></pre>\n\n<p>You shouldn't need to do this as you've just refreshed the token up there.</p>\n\n<pre><code> http = httplib2.Http()\n http = credentials.authorize(http)\n return build('drive', 'v2', http=http)\n\ndef insert_permission(service, file_id, value, perm_type, role):\n new_permission = {\n 'value': value,\n 'type': perm_type,\n 'role': role,\n }\n try:\n return service.permissions().insert(\n fileId=file_id, body=new_permission, sendNotificationEmails=False).execute()\n except errors.HttpError, error:\n print 'An error occured: %s' % error\n return None\n\n\ndef insert_folder(config, title, parent_idNone, writer=None, mime_type='application/vnd.google-apps.folder'):\n service = create_drive_service(config)\n owner_permission = {\n 'role': 'owner',\n 'type': 'user',\n 'value': 'me',\n }\n body = {\n 'title': title,\n 'mimeType': mime_type,\n 'userPermission': owner_permission,\n 'fields': 'items, items/parents',\n }\n if parent_id:\n body['parents'] = [{'id': parent_id}]\n try:\n folder = service.files().insert(\n body=body,\n ).execute()\n insert_permission(service, folder['id'], writer, 'user', 'writer')\n return folder\n except errors.HttpError, error:\n print 'An error occured: %s' % error\n return None\n\ndef create_document_folders(config, client):\n \"\"\"\n Gets records that do not have Google drive folders, \n and loops through the jobs creating the necessary\n base project folder and subfolders.\n \"\"\"\n s = config\n records = get_jobs_wo_folders(config, client)\n \"\"\"\nA bunch of logic goes below this to loop through the list of records,\ncreate the new folders, and append the new folder metadata to a the 'rows' list\nwhich is later converted to records_csv\n\"\"\"\nif rows:\n records_csv = get_csv(rows)\n # Create the records in QuickBase\n response = client.import_from_csv(records_csv, clist=folders_clist, database=s.folders_dbid)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T09:56:15.993",
"Id": "34719",
"Score": "0",
"body": "@Wintson Ewert - You are the man. I had to move on to other work earlier, but that really helped me think about the script differently. I was passing user sometimes because I wasn't sure if config.user was working when I was debugging parts of the script. I only had one config in my database, and it had a User, so I guess I should assume config.user will always work.\n\nIt looks like at the very least, I should do some reading on how to throw exceptions properly, and strip some of the redundancy from the script. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T01:48:33.887",
"Id": "21602",
"ParentId": "21597",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-11T22:26:37.427",
"Id": "21597",
"Score": "3",
"Tags": [
"python",
"performance",
"http",
"django",
"google-drive"
],
"Title": "Storing folders of list of records in Google Drive"
}
|
21597
|
<p>For the <code>m_listeners</code> BlockingCollection<>, I know it's a bit hacky right now, but I'm not sure what to use instead (List<>, Dictionary<>, something else?). I want to be able to add/remove listeners at the same time as I may be broadcasting to those listeners without throwing null reference exceptions. For example add a listener for a <code>TextBox</code> when I open a sub-form and remove the listener when I close the sub-form without throwing an error because the <code>TextBox</code> doesn't exist or the delegate has become null, etc.</p>
<p>WindowsFormsApplication1 containing:</p>
<ul>
<li>Form1, register OnLoad event</li>
<li>button1, register OnClick event</li>
<li>button2, register OnClick event</li>
<li>textbox1, enable multiline property and expand to show several lines at a time</li>
</ul>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
//Fields
private volatile bool cancel1 = false;
private volatile bool cancel2 = false;
private volatile bool cancel3 = false;
private volatile bool cancel4 = false;
public Form1()
{
InitializeComponent();
}
//Event Handlers
private void button1_Click(object sender, EventArgs e)
{
//Automated Producers
if (!cancel1)
{
Task.Factory.StartNew(() =>
{
int count = 0;
while (!cancel1)
{
Log.Append("File", "log to file " + count++);
Thread.Sleep(100);
}
cancel1 = false;
});
}
if (!cancel2)
{
Task.Factory.StartNew(() =>
{
int count = 0;
while (!cancel2)
{
Log.Append("GUI", "log to GUI " + count++);
Thread.Sleep(200);
}
cancel2 = false;
});
}
if (!cancel3)
{
Task.Factory.StartNew(() =>
{
int count = 0;
while (!cancel3)
{
Log.Append("Error", "log to Error " + count++);
Thread.Sleep(300);
}
cancel3 = false;
});
}
if (!cancel4)
{
Task.Factory.StartNew(() =>
{
int count = 0;
while (!cancel4)
{
Log.Append("", "log to console " + count++);
Thread.Sleep(400);
}
cancel4 = false;
});
}
}
private void button2_Click(object sender, EventArgs e)
{
//Cancel Producers
cancel1 = true;
cancel2 = true;
cancel3 = true;
cancel4 = true;
}
private void Form1_Load(object sender, EventArgs e)
{
//Delete Old Files
string LogFile = Directory.GetCurrentDirectory() + "\\Log.txt";
if (File.Exists(LogFile))
File.Delete(LogFile);
string VerboseLog = Directory.GetCurrentDirectory() + "\\VerboseLog.txt";
if (File.Exists(VerboseLog))
File.Delete(VerboseLog);
//Add Consumer Callback methods to Logger class
//Append to File
Log.RegisterWriter(
new Action<string, string>((tag, entry) =>
{
if (tag == "File")
{
using (TextWriter Stream = new StreamWriter(LogFile, true))
{
Stream.WriteLine(entry);
}
}
}));
//Append to different file
Log.RegisterWriter(
new Action<string, string>((tag, entry) =>
{
using (TextWriter Stream = new StreamWriter(VerboseLog, true))
{
Stream.WriteLine(DateTime.Now + ":\t" + entry);
}
}));
//Append to Console
Log.RegisterWriter(
new Action<string, string>((tag, entry) =>
{
Console.WriteLine(entry);
}));
//Append to multiline textBox1
Log.RegisterWriter(
new Action<string, string>((tag, entry) =>
{
if (tag == "GUI")
{
entry += "\r\n";
if (this.InvokeRequired)
{
this.BeginInvoke(new Action<string>(textBox1.AppendText), new object[] { entry });
return;
}
else
{
//Under the circumstances, this never occurs. An invoke is always required.
textBox1.AppendText(entry);
return;
}
}
}));
}
}
public static class Log
{
//Fields
private static BlockingCollection<Tuple<string, string>> m_logItems;
private static BlockingCollection<Action<string, string>> m_listeners;
//Methods
public static void Append(string p_tag, string p_text)
{
//Add Log Entry
m_logItems.Add(new Tuple<string, string>(p_tag, p_text));
}
public static void RegisterWriter(Action<string, string> p_callback)
{
//Add callback method to list
m_listeners.Add(p_callback);
}
//Constructor
static Log()
{
//Init Blocking Lists
m_listeners = new BlockingCollection<Action<string, string>>();
m_logItems = new BlockingCollection<Tuple<string, string>>();
//Begin Log Entry Consumer Task
Task.Factory.StartNew(() =>
{
//Consume as Log Entries are added to the collection
foreach (var logentry in m_logItems.GetConsumingEnumerable())
{
//Broadcast to each listener
foreach (var callback in m_listeners)
{
callback(logentry.Item1, logentry.Item2);
}
}
});
}
}
}
</code></pre>
<p>I didn't want to use a third-party logging library (partially to understand these mechanisms better) and just wanted to create a very simple way to post items from pretty much anywhere in my code (any thread) to various outputs (files, textboxes, the console, etc.).</p>
<p>The frequency of logging in the real application is much much slower than demonstrated here (i.e. it should never produce more than can be consumed under real-world conditions).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T00:45:48.903",
"Id": "34698",
"Score": "0",
"body": "You don't ever need to unregister a callback?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T01:10:40.213",
"Id": "34699",
"Score": "0",
"body": "Yes, I will want to be able to unregister a callback. It's just that BlockingCollection is a bad choice for the `m_listeners` as it has no remove method that lets me unregister a specific item. I don't know what can be used instead that is still thread-safe."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T02:20:10.453",
"Id": "34701",
"Score": "3",
"body": "@JoshW You don't need to necessarily use a thread-safe collection. You can simply introduce your own `lock` with a private locking object wrapping access to the underlying collection."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T04:48:37.953",
"Id": "34704",
"Score": "0",
"body": "This whole setting makes little sense to me. Why don't expose a single `event` from `Log`, and just fire it whenever someone logs something? You don't need any 'thread safety' to do that - just `invoke` in the handler."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T15:25:35.960",
"Id": "34748",
"Score": "0",
"body": "@avip I looked into your suggestion and tried to implement it, however I can't invoke because I am not necessarily using any `Controls` in the Log class. I've never implemented the `ISynchronizeInvoke` interface, so I'm not sure that's any easier at this point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T19:09:30.713",
"Id": "34759",
"Score": "0",
"body": "@ChrisSinclair I implemented your suggestion and posted it as the answer below. Thanks for the simple suggestion, seems to work well."
}
] |
[
{
"body": "<p>Answering my own question here based off suggestions in the question comments.</p>\n\n<p>This seems to work decently well. Good to have debugger Output Console open and see the behaviour of registering/unregistering logs to the GUI textbox (especially multiple clicks).</p>\n\n<p>I changed from using a BlockingCollection for the <code>m_listeners</code> object to instead use a normal <code>Dictionary<></code>. Locks were added around each section of code that could (or does) change the <code>m_listeners</code> dictionary.</p>\n\n<p>As a side note I changed from using a few booleans to end the Producer tasks to instead use CancellationTokens as that's the built mechanism for that sort of thing.</p>\n\n<p>Form requires 4 buttons and a textbox</p>\n\n<ul>\n<li>Form1, register OnLoad</li>\n<li>button1, register OnClick</li>\n<li>button2, register OnClick</li>\n<li>button3, register OnClick</li>\n<li>button4, register OnClick</li>\n<li>textbox1, enable multiline property and expand to show several lines at a time</li>\n</ul>\n\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing System.Collections.Concurrent;\nusing System.IO;\n\nnamespace WindowsFormsApplication1\n{\n public partial class Form1 : Form\n {\n //Fields\n CancellationTokenSource m_tokenSource = new CancellationTokenSource();\n List<int> m_logtoGUIHandle = new List<int>();\n\n //Methods\n public Form1()\n {\n InitializeComponent();\n }\n private void Form1_Load(object sender, EventArgs e)\n {\n //Button Descriptions\n button1.Text = \"Generate\";\n button2.Text = \"Cancel\";\n button3.Text = \"Register\";\n button4.Text = \"Unregister\";\n\n //Delete Old Files\n string LogFile = Directory.GetCurrentDirectory() + \"\\\\Log.txt\";\n if (File.Exists(LogFile))\n File.Delete(LogFile);\n\n string VerboseLog = Directory.GetCurrentDirectory() + \"\\\\VerboseLog.txt\";\n if (File.Exists(VerboseLog))\n File.Delete(VerboseLog);\n\n //Add Consumer Callback methods to Logger class\n //Append to File\n Log.RegisterWriter(new Action<string, string>((tag, entry) =>\n {\n if (tag == \"File\")\n {\n using (TextWriter Stream = new StreamWriter(LogFile, true))\n {\n Stream.WriteLine(entry);\n }\n }\n }));\n\n //Append to different file\n Log.RegisterWriter(new Action<string, string>((tag, entry) =>\n {\n using (TextWriter Stream = new StreamWriter(VerboseLog, true))\n {\n Stream.WriteLine(DateTime.Now + \":\\t\" + entry);\n }\n }));\n\n //Append to Console\n Log.RegisterWriter(new Action<string, string>((tag, entry) =>\n {\n Console.WriteLine(entry);\n }));\n }\n\n //Event Handlers\n private void button1_Click(object sender, EventArgs e)\n {\n CancellationToken ct = m_tokenSource.Token;\n\n //Automated Producers\n Task.Factory.StartNew(() =>\n {\n int count = 0;\n while (!ct.IsCancellationRequested)\n {\n //Log Event\n Log.Append(\"File\", \"log to file \" + count++);\n Thread.Sleep(100);\n }\n }, ct);\n\n Task.Factory.StartNew(() =>\n {\n int count = 0;\n while (!ct.IsCancellationRequested)\n {\n Log.Append(\"GUI\", \"log to GUI \" + count++);\n Thread.Sleep(200);\n }\n }, ct);\n\n Task.Factory.StartNew(() =>\n {\n int count = 0;\n while (!ct.IsCancellationRequested)\n {\n Log.Append(\"Error\", \"log to Error \" + count++);\n Thread.Sleep(300);\n }\n }, ct);\n\n Task.Factory.StartNew(() =>\n {\n int count = 0;\n while (!ct.IsCancellationRequested)\n {\n Log.Append(\"\", \"log to console \" + count++);\n Thread.Sleep(400);\n }\n }, ct);\n }\n private void button2_Click(object sender, EventArgs e)\n {\n //Cancel Producers\n m_tokenSource.Cancel();\n //Required or Producers will immediately exit in cancelled state\n m_tokenSource = new CancellationTokenSource();\n }\n private void button3_Click(object sender, EventArgs e)\n {\n //Append to multiline textBox1\n m_logtoGUIHandle.Add(Log.RegisterWriter(\n new Action<string, string>((tag, entry) =>\n {\n if (tag == \"GUI\")\n {\n entry += \"\\r\\n\";\n if (this.InvokeRequired)\n {\n this.BeginInvoke(new Action<string>(textBox1.AppendText), new object[] { entry });\n return;\n }\n else\n {\n //Under the circumstances, this never occurs. An invoke is always required.\n textBox1.AppendText(entry);\n return;\n }\n }\n })));\n }\n private void button4_Click(object sender, EventArgs e)\n {\n foreach (var h in m_logtoGUIHandle)\n {\n Log.UnregisterWriter(h);\n }\n }\n }\n\n public static class Log\n {\n //Fields\n private static Dictionary<int, Action<string, string>> m_listeners;\n private static BlockingCollection<Tuple<string, string>> m_logItems;\n private static int handle = 0;\n private static object syncObject = new object();\n\n //Methods\n public static void Append(string p_tag, string p_text)\n {\n //Add Log Entry\n m_logItems.Add(new Tuple<string, string>(p_tag, p_text));\n }\n public static int RegisterWriter(Action<string, string> p_callback)\n {\n //Add callback method to list\n lock (syncObject)\n {\n handle++;\n m_listeners[handle] = p_callback;\n return handle;\n }\n }\n public static void UnregisterWriter(int p_handle)\n {\n //Remove callback method from list\n lock (syncObject)\n {\n if (m_listeners.ContainsKey(p_handle))\n {\n m_listeners.Remove(p_handle);\n }\n }\n }\n\n //Constructor\n static Log()\n {\n //Init\n m_listeners = new Dictionary<int, Action<string, string>>();\n m_logItems = new BlockingCollection<Tuple<string, string>>();\n\n //Begin Log Entry Consumer Task\n Task.Factory.StartNew(() =>\n {\n //Continuously consumes Log Entries added to the collection, blocking-wait if empty\n foreach (var logentry in m_logItems.GetConsumingEnumerable())\n {\n //Lock to prevent enumerator changes to callback dictionary\n lock (syncObject)\n {\n //Broadcast to each listener\n foreach (var callback in m_listeners)\n {\n callback.Value(logentry.Item1, logentry.Item2);\n }\n }\n }\n });\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T19:12:01.283",
"Id": "34760",
"Score": "1",
"body": "Welcome, Josh! Could you add a paragraph explaining what you changed (the lock) so that this makes sense out of context?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T19:47:25.487",
"Id": "34764",
"Score": "0",
"body": "@codesparkle Thanks, I added some detail about the changes I made to get this working nicely."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T19:07:45.880",
"Id": "21638",
"ParentId": "21600",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "21638",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T00:11:36.860",
"Id": "21600",
"Score": "2",
"Tags": [
"c#",
"multithreading"
],
"Title": "Simple ThreadSafe Log Class"
}
|
21600
|
<p>I am new to javascript and want to make sure I am on the right track when playing a sound. Is there anything I should not be doing better or not be doing at all. Below is a simple function. </p>
<pre><code><script language="javascript" type="text/javascript">
function playSound(soundfile) {
if (navigator.userAgent.indexOf('Firefox') != -1) {
document.getElementById("dummy").innerHTML = "<embed src=\"" + soundfile + "\" hidden=\"true\" autostart=\"true\" loop=\"false\" type=\"application/x-mplayer2\" />";
} else {
document.getElementById("dummy").innerHTML = "<embed src=\"" + soundfile + "\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
}
}
</script>
</head>
<body>
<span id="dummy"></span>
<a href="#" onclick="playSound('doorbell.wav');">Click here to hear a sound</a>
</body>
</code></pre>
<p>I am not sure whether I should be using the audio tag or not. I appreciate any feedback</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T09:03:04.430",
"Id": "34713",
"Score": "0",
"body": "Why do you use [`embed`](http://www.w3.org/TR/html5/embedded-content-0.html#the-embed-element) instead of [`audio`](http://www.w3.org/TR/html5/embedded-content-0.html#the-audio-element)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T09:17:13.123",
"Id": "34714",
"Score": "0",
"body": "Consider building the element using something like jQuery instead of doing a concatenation of strings which is hard to read and difficult to maintain."
}
] |
[
{
"body": "<p>Regarding the HTML:</p>\n\n<h3><code>script</code> element</h3>\n\n<p>For JavaScript, <a href=\"http://www.w3.org/TR/html5/scripting-1.html#the-script-element\" rel=\"nofollow\">you can</a> simply use <code><script></code> without the <code>type</code> attribute:</p>\n\n<blockquote>\n <p>If the language is not that described by \"text/javascript\", then the <code>type</code> attribute must be present</p>\n</blockquote>\n\n<p>The <code>language</code> attribute is obsolete:</p>\n\n<blockquote>\n <p>Authors should not specify a <code>language</code> attribute on a <code>script</code> element.</p>\n</blockquote>\n\n<h3><code>a</code> element</h3>\n\n<p>I'd say a real button should be used here, not a link:</p>\n\n<ul>\n<li><code>button</code> element with <a href=\"http://www.w3.org/TR/html5/forms.html#the-button-element\" rel=\"nofollow\"><code>button</code> type</a>: <code><button type=\"button\" onclick=\"…\">Click here to hear a sound</button></code></li>\n<li><code>input</code> element with <a href=\"http://www.w3.org/TR/html5/forms.html#button-state-%28type=button%29\" rel=\"nofollow\"><code>button</code> type</a>: <code><input type=\"button\" onclick=\"…\" value=\"Click here to hear a sound\" /></code></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T09:00:23.293",
"Id": "21609",
"ParentId": "21604",
"Score": "2"
}
},
{
"body": "<p>Don't duplicate sections of code! In particular, avoid putting 'execution' code in these simple conditionals, instead use them to build a shared executor:</p>\n\n<pre><code>function playSound(soundfile) {\n var type_attr = '';\n if (navigator.userAgent.indexOf('Firefox') != -1) {\n type_attr = \"type=\\\"application/x-mplayer2\\\"\";\n }\n document.getElementById(\"dummy\").innerHTML = \"<embed src=\\\"\" + soundfile + \"\\\" hidden=\\\"true\\\" autostart=\\\"true\\\" loop=\\\"false\\\" \" + type_attr + \" />\";\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T22:22:54.420",
"Id": "21643",
"ParentId": "21604",
"Score": "2"
}
},
{
"body": "<p>Use jQuery and then do it like this:</p>\n\n<pre><code><pre>\n <script> \n $(document).ready(function() { \n var obj = document.createElement(\"audio\"); \n obj.setAttribute(\"src\", \"http://kahimyang.info/resources/click.m... \n $.get(); \n\n $(\".playSound\").click(function() { \n obj.play(); \n }); \n }); \n </script> \n</pre>\n</code></pre>\n\n<p>Put this snippet at the bottom of the page after that all anchors with class \"playSound\" will play a sound. Somewhere in your page your link should look loke below: </p>\n\n<pre><code><pre>\n <a href=\"#\" class=\"playSound\">Play</a> \n</pre>\n</code></pre>\n\n<p>For more details visit this blog:</p>\n\n<p><a href=\"http://kahimyang.info/kauswagan/code-blogs/1652/how-to-play-a-sound-when-an-element-is-clicked-in-html-page\" rel=\"nofollow\">http://kahimyang.info/kauswagan/code-blogs/1652/how-to-play-a-sound-when-an-element-is-clicked-in-html-page</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T12:34:22.303",
"Id": "42755",
"ParentId": "21604",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "21643",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T03:57:49.153",
"Id": "21604",
"Score": "2",
"Tags": [
"javascript",
"html5"
],
"Title": "Playing sound on a button click"
}
|
21604
|
<p>I am pulling multiple feeds from youtube that have a callback function which makes markup from each feed. They add that markup to a documentFragment stored in var data. When all the feeds have contributed what they should, a final callback runs. Each feed can deal with its own thumbnails and page menu, so it makes sense to get that started without waiting for all of the feeds to be done. Some markup requires all of them to be done, so I do that in the final callback. To complicate matters, the markup needs to be appended in an order dictated by the user and some sets of markup may need to be cloned if requested. This allows the user to easily build the plugin as they see fit. Here is the option for that.</p>
<pre><code>build:['listsMenu', 'listTitle', 'listDesc', 'player', 'pageMenu', 'thumbnails']
</code></pre>
<p>or another possibility...something like this:</p>
<pre><code>build:['player', 'listsMenu', 'pageMenu', 'thumbnails', 'pageMenu']
</code></pre>
<p>This is the best solution I have been able to come up with so far. Any suggestions are appreciated!</p>
<pre><code>//in the function that makes the ajax calls -
data = {};
namespace.thumbs.prototype.feedCallback = function(context, options, data, optList, listNum, feed) {
if (options.build.indexOf('pageMenu') !== -1 || options.build.indexOf('thumbnails') !== -1) {
var feedVideosInPages = this.return_feedVideosInPages(options.thumbCount, options.thumbsPerPage, feed.videos);
var pagesMenu = this.return_PagesMenu(options, listNum, feedVideosInPages);
var thumbnails = this.return_thumbsMarkup(options, optList, listNum, feedVideosInPages);
data.pagesMenus = data.pagesMenus || document.createDocumentFragment();
data.thumbnails = data.thumbnails || document.createDocumentFragment();
if (pagesMenu) { data.pagesMenus.appendChild(pagesMenu); }
data.thumbnails.appendChild(thumbnails);
}
data.each = data.each || [];
data.each.push({'feed':feed, 'optList':optList, 'listNum':listNum});
if (data.each.length === options.lists.length) { this.allFeedsReady(context, options, data); }
};
namespace.thumbs.prototype.allFeedsReady = function(context, options, data) {
this.sort_dataEach(data);
elems = document.createDocumentFragment();
addedElemNames = [];
clonedElems = {};
toAdd = options.build.slice();
var buildLength = options.build.length;
for (var i=0; i<buildLength; ++i) {
var name = options.build[i];
if (addedElemNames.indexOf(name) === -1) { //this is the first time the element has been added.
switch (name) {
case 'pageMenu': elem = data.pagesMenus; break;
case 'thumbnails': elem = data.thumbnails; break;
case 'player': elem = this.return_playerDiv(context); break;
case 'listMenu': elem = this.return_listsMenuMarkup(data.each); break;
//case 'listTitle': elem = allData.markup.listsTitles[0]; break;
case 'listDesc': elem = this.return_listsDescsMarkup(data.each); break;
case 'videoTitle': elem = this.return_videoTitleMarkup(data.each); break;
default: elem = false;
}
addedElemNames.push(name);
}
else {
elem = clonedElems[name];
}
toAdd.splice(toAdd.indexOf(name), 1); //remove this item from array of things to be added
if (elem) {
if (toAdd.indexOf(name) !== -1) { clonedElems[name] = elem.cloneNode(true); }//the build will contain another copy, so clone it
elems.appendChild(elem);
}
}
context.appendChild(elems);
}
</code></pre>
|
[] |
[
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li><code>data</code> should be declared with <code>var</code>, so should a number of other variables. Please paste your code into the JSHint.com site and have a look</li>\n<li><p>It is considered better form to have 1 comma separated <code>var</code> statement:</p>\n\n<pre><code>var feedVideosInPages = this.return_feedVideosInPages(options.thumbCount, options.thumbsPerPage, feed.videos),\n pagesMenu = this.return_PagesMenu(options, listNum, feedVideosInPages),\n thumbnails = this.return_thumbsMarkup(options, optList, listNum, feedVideosInPages);\n</code></pre></li>\n<li><p><code>return_feedVideosInPages</code> is a terrible name, I assume you chose it because <code>feedVideosInPages</code> was already taken ;) I would for something shorter:</p>\n\n<pre><code>var feedVideos = this.getFeedVideosInPages(options.thumbCount, options.thumbsPerPage, feed.videos),\n</code></pre>\n\n<p>which is still horizontally challenged, since you call that function only once, and since <code>thumbCount</code> and <code>thumbsPerPage</code> are in the same convenient <code>options</code> object you could improve even further to:</p>\n\n<pre><code>var feedVideos = this.getFeedVideos(options, feed.videos),\n</code></pre>\n\n<p>Finally, if you think about it, since you get the videos from the feed, let <code>getFeedVidoes</code> decide/worry about which property of <code>feed</code> contains the videos:</p>\n\n<pre><code>var feedVideos = this.getFeedVideos(options, feed),\n</code></pre></li>\n<li><p>Bad (TMI):</p>\n\n<pre><code>if (toAdd.indexOf(name) !== -1) { clonedElems[name] = elem.cloneNode(true); }//the build will contain another copy, so clone it\n</code></pre>\n\n<p>Better ( Comment on top ):</p>\n\n<pre><code>//The build will contain another copy, so clone it\nif (toAdd.indexOf(name) !== -1) { clonedElems[name] = elem.cloneNode(true); }\n</code></pre>\n\n<p>Even better ( never drop the newline, but you can drop the curlies! )</p>\n\n<pre><code>//The build will contain another copy, so clone it\nif (toAdd.indexOf(name) !== -1)\n clonedElems[name] = elem.cloneNode(true);\n</code></pre>\n\n<p>The <code>~</code> operator ( Bitwise NOT ) is great for comparing to <code>-1</code>:</p>\n\n<pre><code>if (!~toAdd.indexOf(name))\n clonedElems[name] = elem.cloneNode(true);\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T15:45:21.360",
"Id": "75626",
"Score": "0",
"body": "I wrote this code so long ago :) I've come a long way since then, but thanks for the notes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T15:46:40.703",
"Id": "75627",
"Score": "1",
"body": "Yeah, I am hunting down zombie questions ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T15:05:39.790",
"Id": "43711",
"ParentId": "21605",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T04:35:44.043",
"Id": "21605",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"performance",
"plugin"
],
"Title": "Creating and referencing markup....cloning, etc. efficient system for this plugin"
}
|
21605
|
<p>Sometimes "a" service does not respond and so we need to restart it. Usually it's a glitch in the network. We can have like 100 calls at the same time so the service cannot be restarted for 100 hundred times. The service is a Singleton. The command is called through a dispatcher, it's sync so different calls are executed in sequence.</p>
<p>Do you think that this approach is right to limit the restarting of the service?</p>
<pre><code>public class RecoverServiceCommand extends AbstractCommand {
/**
* Logger for this class
*/
private static final Logger log = LoggerFactory
.getLogger(RecoverServiceCommand.class);
@Override
public boolean isAsynch() {
return false;
}
@Override
public boolean postCondition(Object... arg0) {
return true;
}
@Override
public boolean preCondition(Object... arg0) {
return true;
}
@Override
public void undo() {
}
@Override
protected void doExecute(Object... arg0) throws CommandException {
long now = System.nanoTime();
synchronized (RecoverServiceCommand.class) {
if (now - Service.getInstance().getLastUpdate() > Utils.TimeSpan)
Service.getInstance().restartService(now);
else
log.warn("Messaging queues not restarted because it was already restarted not so long ago");
}
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>First of all, it looks like as a workaround for another bug. You might want to fix that bug instead of this workaround.</p></li>\n<li><p>Comments like the following are unnecessary:</p>\n\n<pre><code> /**\n * Logger for this class\n */\n</code></pre>\n\n<p>It just repeats the code and forces readers to read more than necessary.</p></li>\n<li><p><code>Service.getInstance()</code> is repeated. Create a local variable for it.</p></li>\n<li><p>Synchronizing on public objects (like <code>RecoverServiceCommand.class</code>) is error-prone. I'd use a private lock object instead. See: <a href=\"https://stackoverflow.com/q/442564/843804\">Avoid synchronized(this) in Java?</a></p></li>\n<li><p>A minor change could be extracting out a <code>boolean needsRestart</code> local variable which would make the intention of the expression a little bit more clear.</p>\n\n<p>Reference: <em>Chapter 6. Composing Methods</em>, <em>Introduce Explaining Variable</em> in <em>Refactoring: Improving the Design of Existing Code</em> by Martin Fowler</p>\n\n<blockquote>\n <p>Put the result of the expression, or parts of the expression, \n in a temporary variable with a name that explains the purpose.</p>\n</blockquote></li>\n<li><p>Currently the code is tightly coupled with the <code>Service</code> and the <code>Utils</code> classes. If you want to write unit tests it's not too easy because it needs a working <code>Service</code> instance and it depends on the system time too. To make it easier to test you could pass the dependencies to the constructor:</p>\n\n<pre><code>private static final ReentrantLock lock = new ReentrantLock();\n\nprivate final Service service;\n\nprivate final Ticker ticker;\n\nprivate final long updateInterval;\n\npublic RecoverServiceCommand(final Service service, final Ticker ticker, \n final long updateInterval) {\n this.service = checkNotNull(service);\n this.ticker = checkNotNull(ticker);\n checkArgument(updateInterval > 0, \"updateIntarval must be bigger than zero\");\n this.updateInterval = updateInterval;\n}\n\n@Override\nprotected void doExecute(final Object... arg0) throws CommandException {\n final long now = ticker.read();\n lock.lock();\n try {\n final boolean needsRestart = \n (now - service.getLastUpdate()) > updateInterval;\n if (needsRestart) {\n service.restartService(now);\n } else {\n log.warn(\"Messaging queues not restarted because \"\n + \"it was already restarted not so long ago\");\n }\n } finally {\n lock.unlock();\n }\n}\n</code></pre>\n\n<p>Here is a few tests with EasyMock:</p>\n\n<pre><code>import static org.easymock.EasyMock.expect;\n\nimport org.easymock.EasyMockSupport;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.google.common.base.Ticker;\n\npublic class RecoverServiceCommandTest {\n\n private EasyMockSupport mockery;\n private Service service;\n private Ticker ticker;\n\n @Before\n public void setUp() {\n mockery = new EasyMockSupport();\n service = mockery.createMock(Service.class);\n ticker = mockery.createMock(Ticker.class);\n }\n\n @After\n public void tearDown() {\n mockery.verifyAll();\n\n }\n\n @Test(expected = IllegalArgumentException.class)\n public void testInvalidUpdateInterval() throws Exception {\n final long invalidUpdateInterval = 0;\n\n mockery.replayAll();\n\n new RecoverServiceCommand(service, ticker, invalidUpdateInterval);\n }\n\n @Test\n public void testUpdateIsRequired() throws Exception {\n final long updateInterval = 100;\n\n final long currentTime = 300L;\n expect(ticker.read()).andReturn(currentTime);\n expect(service.getLastUpdate()).andReturn(199L);\n service.restartService(currentTime);\n\n mockery.replayAll();\n\n final RecoverServiceCommand command = \n new RecoverServiceCommand(service, ticker, updateInterval);\n command.doExecute();\n }\n\n @Test\n public void testUpdateIsNotRequired() throws Exception {\n final long updateInterval = 100;\n\n final long currentTime = 300L;\n expect(ticker.read()).andReturn(currentTime);\n expect(service.getLastUpdate()).andReturn(200L);\n\n mockery.replayAll();\n\n final RecoverServiceCommand command = \n new RecoverServiceCommand(service, ticker, updateInterval);\n command.doExecute();\n }\n\n}\n</code></pre>\n\n<p>I've used the <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Ticker.html\" rel=\"nofollow noreferrer\"><code>Ticker class</code></a> from Guava. It's easy to mock it and it has a <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Ticker.html#systemTicker%28%29\" rel=\"nofollow noreferrer\"><code>systemTicker</code></a> which you can use in production code. The <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Preconditions.html\" rel=\"nofollow noreferrer\">check methods are also in Guava</a>.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T08:28:50.133",
"Id": "34937",
"Score": "1",
"body": "1. Yes, working on that :)\n2. It's the log4E plugin\n4. Didn't know that, thanks!\n6. It's not the way the dispatcher works but I'll keep that in mind. Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T23:47:47.060",
"Id": "21684",
"ParentId": "21613",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "21684",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T10:19:39.120",
"Id": "21613",
"Score": "5",
"Tags": [
"java",
"multithreading"
],
"Title": "Timing single operation to not be repeated for a fixed time"
}
|
21613
|
<p>I am working on project in which I need to display different colors
on RGB led. I am using pwm to drive different colors on LED. My Pic
is PIC24FJ64GA004 with which I am working on now. Basic concept of
this project is to use switch to controls colors. </p>
<p>Colors on RGB led will be according to days and month in year. For
that I am using 7-segment led with switch to count days and month.</p>
<p>Problem is that I have only one switch on my board. I have designed
hardware and bits for it has been tested as well. So hardware works
fine.</p>
<p>At the moment my problem is pic code.</p>
<p>I am stuck in switch use now. I have one switch on board. I need to
display how many times switch pressed on 7 segment. Problem is that
I am new to Pic code and confuse as well. First switch status will be checked. If switch pressed for two seconds it will go days mode. otherwise it will stick to months mode.It will display month or days according to that.I have pasted my code here please give
me some positive advice.</p>
<p>I would like to know is this coding is going in right way or not.</p>
<pre><code>void switch_function(void)
{
if (PORTAbits.RA4==1) // is SW1 pressed?
{
IEC0bits.T1IE = 1; // Enable Output Compare interrupts
T1CONbits.TON = 1; // Start Timer1 with assumed settings
if (modecounter==0) // Checking status of month
{
if (PORTAbits.RA4==1)
{
counter++;
if (counter== 12)
{
counter = 0;
}
}
}
else if(modecounter ==1) // Checking status of days
{
if (PORTAbits.RA4==1)
{
counter++;
if (counter== 32)
{
counter = 0 ;
}
}
}
else
{
}
}
else
{
counter =0;
}
return ;
}
//***** Timer1 interrupt *****//
void __attribute__((interrupt, auto_psv)) _T1Interrupt(void)
{
timer_counter++;
if (timer_counter== 2)
{
if (PORTAbits.RA4==1)
{ // is SW1 still has pressed status after 2sec delay?
modecounter = 1; // switch to days
}
else
{
modecounter = 0; // switch to months
}
}
else
{
}
IFS0bits.T1IF=0; /* clear timer1 interrupt flag */
return;
}
//***** Timer2 interrupt *****//
void __attribute__ ((__interrupt__, no_auto_psv)) _T2Interrupt(void)
{
IFS0bits.T2IF = 0; /* clear timer2 interrupt flag */
return;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T12:46:28.537",
"Id": "34723",
"Score": "1",
"body": "Hello, and welcome to Code Review! Unfortunately, we only focus on already working code (see the [faq](http://codereview.stackexchange.com/faq)), so your question is off-topic. Sorry for the inconvenience."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T15:02:29.877",
"Id": "34808",
"Score": "0",
"body": "Post it on http://stackoverflow.com/ with tags c embedded pic."
}
] |
[
{
"body": "<p>A few comments:</p>\n\n<ol>\n<li>Why check this twice <code>PORTAbits.RA4==1</code> in the same if-block?</li>\n<li><p>Following can be rewritten:</p>\n\n<pre><code>counter++;\nif (counter== 12)\n{ \n counter = 0;\n} \n</code></pre>\n\n<p>to:</p>\n\n<pre><code>if(++counter == 12)\n{\n counter = 0;\n}\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>counter = (++counter == 12) ? 0 : counter;\n</code></pre></li>\n<li><p>Same here</p>\n\n<pre><code>if (PORTAbits.RA4==1) \n{ // is SW1 still has pressed status after 2sec delay?\n modecounter = 1; // switch to days \n}\nelse\n{\n modecounter = 0; // switch to months\n}\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>modecounter = (PORTAbits.RA4==1) ? 1 : 0;\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T16:00:06.163",
"Id": "34751",
"Score": "0",
"body": "I am using switch twice because I want to switch counter from month to days."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T16:01:14.663",
"Id": "34752",
"Score": "0",
"body": "First It will add month and then will add days. In order to switch to days. Need to press switch for 2 seconds."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T13:52:41.133",
"Id": "21625",
"ParentId": "21615",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "21625",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T11:52:45.160",
"Id": "21615",
"Score": "-3",
"Tags": [
"c",
"algorithm",
"performance"
],
"Title": "Project RGB with Switches"
}
|
21615
|
<p>I am trying to insert into a database using JDBC and each thread will be inserting into the database. I need to insert into around 30-35 columns. I wrote a stored procedure that will UPSERT into those columns. </p>
<p>The problem I am facing is, if you look at my run method, I have around 30 columns written over there for insertion. Is there any way I can simplify my run method so that it doesn't looks so messy which is looking right now for me? And I have few more columns as well. So if I keep on adding new columns there, it will be looking so messy at one point in my run method.</p>
<p>Are there any way to make this look cleaner, keeping in mind thread safety issues?</p>
<pre><code>class Task implements Runnable {
private Connection dbConnection = null;
private CallableStatement callableStatement = null;
public Task() {
}
@Override
public void run() {
dbConnection = getDbConnection();
callableStatement = dbConnection.prepareCall(Constants.UPSERT_SQL);
callableStatement.setString(1, String.valueOf(userId));
callableStatement.setString(2, Constants.getaAccount(userId));
callableStatement.setString(3, Constants.getaAdvertising(userId));
callableStatement.setString(4, Constants.getaAvgSellingPriceMainCats(userId));
callableStatement.setString(5, Constants.getaCatAndKeywordRules(userId));
callableStatement.setString(6, Constants.getaClvBehavior(userId));
callableStatement.setString(7, Constants.getaClvChurn(userId));
callableStatement.setString(8, Constants.getaClvInfo(userId));
callableStatement.setString(9, Constants.getaClvSegmentation(userId));
callableStatement.setString(10, Constants.getaCsaCategoriesPurchased(userId));
callableStatement.setString(11, Constants.getaCustomerService(userId));
callableStatement.setString(12, Constants.getaDemographic(userId));
callableStatement.setString(13, Constants.getaFinancial(userId));
callableStatement.setString(14, Constants.getaGeolocation(userId));
callableStatement.setString(15, Constants.getaInterests(userId));
callableStatement.setString(16, Constants.getaLastContributorsPurchased(userId));
callableStatement.setString(17, Constants.getaLastItemsLost(userId));
callableStatement.setString(18, Constants.getaLastItemsPurchased(userId));
callableStatement.setString(19, Constants.getaLastProductsPurchased(userId));
callableStatement.setString(20, Constants.getaLastSellersPurchasedFrom(userId));
callableStatement.setString(21, Constants.getaMainCategories(userId));
callableStatement.setString(22, Constants.getaMessaging(userId));
callableStatement.setString(23, Constants.getaPositiveSellers(userId));
callableStatement.setString(24, Constants.getaPromo(userId));
callableStatement.setString(25, Constants.getaScores(userId));
callableStatement.setString(26, Constants.getaSegmentation(userId));
callableStatement.setString(27, Constants.getaSellers(userId));
callableStatement.setString(28, Constants.getaSrpBuyerUpiCount(userId));
}
}
private Connection getDBConnection() {
Connection dbConnection = null;
Class.forName(Constants.DRIVER_NAME);
dbConnection = DriverManager.getConnection(url,user,password);
return dbConnection;
}
</code></pre>
<p>This is my main thread code from which I am creating threads:</p>
<pre><code>//create thread pool with given size
ExecutorService service = Executors.newFixedThreadPool(noOfThreads);
try {
// queue some tasks
for (int i = 0; i < noOfTasks * noOfThreads; i++) {
service.submit(new Task());
}
service.shutdown();
service.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
while (!service.isTerminated()) {
}
} catch (Exception e) {
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-09T07:20:35.303",
"Id": "34726",
"Score": "0",
"body": "You can try my suggestion from [this answer](http://stackoverflow.com/a/12887046/1065197)"
}
] |
[
{
"body": "<p>Following things are observed in your code:</p>\n\n<ol>\n<li><code>Constants</code> is the name of class itself.</li>\n<li><code>getXXX</code> method is static method in class <code>Constants</code></li>\n</ol>\n\n<p>Going by all above analysis I consider the use of Reflection API to call the <code>getXXX</code> methods of class <code>Constants</code> and storing those methods in an <code>ArrayList</code>. And finally calling these methods in a loop. The code look something like this:</p>\n\n<pre><code>class Task implements Runnable {\n\n private Connection dbConnection = null;\n private CallableStatement callableStatement = null;\n\n public Task() {\n\n }\n public ArrayList<Method> getRequiredMethods()\n {\n Class<Constants> consClass = Constants.class;\n Method[] methods = consClass.getDeclaredMethods();\n ArrayList<Method> requiredMethods = new ArrayList();\n for (int i = 0 ; i < methods.length ; i++)\n {\n String sName = methods[i].getName();\n if (sName.startsWith(\"seta\"))\n {\n requiredMethods.add(methods[i]);\n }\n }\n return requiredMethods;\n }\n\n @Override\n public void run() {\n try\n {\n dbConnection = getDbConnection();\n callableStatement = dbConnection.prepareCall(Constants.UPSERT_SQL);\n ArrayList<Method> methods = getRequiredMethods();\n callableStatement.setString(1 , String.valueOf(userId));\n for (int i = 0 ; i < methods.length ; i++)\n {\n //callableStatement.setString(i+2,(String)((methods.get(i)).invoke(null,userId)));\n methods.get(i).invoke(null,callableStatement,userId);\n } \n }\n catch (Exception ex)\n {\n ex.printStackTrace();\n }\n }\n</code></pre>\n\n<p>And change your <code>getxxx</code> to <code>setxxx</code> method as follows:</p>\n\n<pre><code> public static void setaAccount(final CallableStatement stat, int userId) {\n final String A_ACCOUNT = \"{\\\"lv\\\":[{\\\"v\\\":{\\\"regSiteId\\\":null,\\\"userState\\\":null,\\\"userId\\\":\" + userId\n + \"},\\\"cn\\\":1}],\\\"lmd\\\":1360185069691}\";\n stat.setString(2,A_ACCOUNT);//2 is the column Number.\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-09T08:34:29.853",
"Id": "34727",
"Score": "0",
"body": "Thanks Vishal. Looks more cleaner now. I tried your suggestion but it is complaining at few lines like `The method setString(int, String) in the type PreparedStatement is not applicable for the arguments (int, Object)` and also at `NameComprator` as well it cannot be resolved something and also `The method compare(Method, Method) of type XMPTask must override or implement a supertype method`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-09T08:38:28.607",
"Id": "34728",
"Score": "0",
"body": "It was happening because `(methods.get(i)).invoke(null,userid)` returns Object. I have typecast it to `String` now . See the updated Code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-09T08:41:07.843",
"Id": "34729",
"Score": "0",
"body": "Yeah that thing I figured it out. But what about other errors I mentioned? I think you forgot to put class name right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-09T08:44:55.700",
"Id": "34730",
"Score": "0",
"body": "I fixed that as well. Sorry for bothering."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-09T08:45:37.887",
"Id": "34731",
"Score": "0",
"body": "It was Typo mistake . forget to write class before MyComparator declaration. It is fixed now"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-09T08:45:59.440",
"Id": "34732",
"Score": "0",
"body": "One thing I wanted to confirm here is- There won't be a thread safety issues here with the way you are doing? As I will be running this program with lot of multiple threads."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-09T08:47:31.273",
"Id": "34733",
"Score": "0",
"body": "If you are executing it using multiple threads then you should synchronize every `getXXX` methods of `Constants` class"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-09T08:49:43.893",
"Id": "34734",
"Score": "0",
"body": "can you post here those codes also where you creating multiple threads and calling the methods..?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-09T08:51:15.063",
"Id": "34735",
"Score": "0",
"body": "sure. let me do that as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-09T08:56:17.500",
"Id": "34736",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/24225/discussion-between-farhan-jamal-and-vishal-k)"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-09T08:22:55.777",
"Id": "21622",
"ParentId": "21620",
"Score": "1"
}
},
{
"body": "<p>You can use the following utility method:</p>\n\n<pre><code>public static void setStrings (CallableStatement stmt, Object ... values)\n{\n for (int count = values.length, i = 0; i < count; i++)\n stmt.setString (i + 1, String.valueOf (values [i]));\n}\n</code></pre>\n\n<p>in your <code>run()</code> like this:</p>\n\n<pre><code>setStrings (\n callableStatement,\n userId,\n Constants.getaAccount (userId),\n Constants.getaAdvertising (userId),\n ...\n Constants.getaSrpBuyerUpiCount (userId));\n</code></pre>\n\n<p>This is shorter and much more readable for me.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-09T09:44:53.783",
"Id": "34737",
"Score": "0",
"body": "Thanks Mikhail for the suggestion. So that means I should pass out all the columns names from setString method right? And also I am not supposed to synchronize setStrings method here?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-09T09:03:00.157",
"Id": "21623",
"ParentId": "21620",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "21622",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-09T07:12:06.103",
"Id": "21620",
"Score": "4",
"Tags": [
"java",
"database",
"jdbc"
],
"Title": "Inserting into database columns"
}
|
21620
|
<pre><code>import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
class RemoveDuplicates {
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<Integer>();
list.add(1);
list.add(1);
list.add(1);
list.add(4);
System.out.println(RemoveDuplicates.rmDuplicates(list));
}
public static List<Integer> rmDuplicates(List<Integer> list) {
Collections.sort(list);
Iterator<Integer> it = list.iterator();
int index = 0;
while (it.hasNext() && index < list.size() - 1) {
int current = it.next();
index++;
if (current == list.get(index)) {
it.remove();
index--;
}
}
return list;
}
}
</code></pre>
<p>Update: I did not want a sorted list. Just removing duplicates is enough and I wanted it in place. I thought without sorting it would be tricky to remove duplicates.</p>
|
[] |
[
{
"body": "<p>I would not save keystrokes by calling your method <code>rmDuplicates</code>, I would simply call it <code>removeDuplicates</code>.</p>\n\n<p>Using both an Iterator and an index means you're probably doing it wrong.</p>\n\n<p>If you did not have to modify the provided list, I would do the following:</p>\n\n<pre><code>LinkedList<Integer> helperList = new LinkedList<Integer>();\nIterator<Integer> it = list.iterator();\nwhile (it.hasNext()) {\n Integer current = it.next();\n if( !helperList.contains( current ) ){\n helperList.add( current )\n }\n}\nreturn helperList;\n</code></pre>\n\n<p>As the other reviewer pointed out, your method also sorts the list, do not assume that sorting a provided list is harmless.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T15:40:19.503",
"Id": "21629",
"ParentId": "21626",
"Score": "3"
}
},
{
"body": "<p>LinkedList is designed to preserve the order in which elements were inserted into it above all other considerations. It should only be used when you need to retrieve the items in the list in order, because there is a faster collection available for any other type of access.</p>\n\n<p>It looks from your code like you want a <em>sorted</em> list of elements, in addition to <em>duplicates removed</em> as stated in your question. Sets are designed to have no duplicates and TreeSet is designed to sort your items as they are inserted. If you use a TreeSet instead of a LinkedList you don't need a rmDuplicates method at all! If you are concerned about returning a Set instead of a List, you can always return a Collection because it has about the same signature. Time the difference between your method and using a TreeSet with a hundred thousand elements. I think you will be surprised how fast TreeSet is!</p>\n\n<pre><code>public static void main(String[] args) {\n TreeSet<Integer> list = new TreeSet<Integer>();\n list.add(1);\n list.add(1);\n list.add(1);\n list.add(4);\n System.out.println(list);\n}\n</code></pre>\n\n<p>If you needed to preserve the insertion order, I'd use a LinkedHashSet:</p>\n\n<pre><code>public static Collection<Integer> rmDuplicates(Collection<Integer> list) {\n return new LinkedHashSet(list);\n}\n</code></pre>\n\n<p>If you have tried this with a custom type of Object instead of an integer and it didn't work, then you need to <a href=\"http://glenpeterson.blogspot.com/2010/09/using-java-collections-effectively-by.html\" rel=\"nofollow\">implement equals(), hashcode(), and maybe compareTo() properly</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T16:09:04.037",
"Id": "21631",
"ParentId": "21626",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "21631",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T14:45:50.860",
"Id": "21626",
"Score": "1",
"Tags": [
"java"
],
"Title": "Code review for style, clarity and efficiency. Removing duplicates from linkedlist"
}
|
21626
|
<p>After being inspired by some MVC style design patterns, I have been trying to separate data from views in my code and move toward a more sensibly organized object based approach. (please, don't bother telling me that my code doesn't follow strict MVC pattern correctly, that is not my concern at this point!) All the data for a single tutorial is now handled by a data model object (currentTutorial) while currentvideo holds the state and relevant data (such as auto-pause times) for the videos but I have hit a bit of a wall with trying to couple the currentvideo and currentTutorial objects. </p>
<p>I want the currentvideo object to be a property of the currentTutorial object, it makes no sense for it to exist separately as there is exactly one corresponding video for each tutorial and I think it makes my code looser, more confusing and fragile as a result. </p>
<p>Unfortunately every time I try to move the video object into the tutorial object I run into countless scoping problems that just kinda make my brain hurt and I end up reverting back to this point. I know it's a pretty big ask but I would be very grateful to any OOP guru who could untangle this mess for me! :)</p>
<p>P.S. I will of course consider suggestions relating to other issues but this is my main concern right now..</p>
<pre><code>var conjugationsets = [
["작다", "놀다", "닦다"],
["웃다", "울다", "멀다"]
];
var section_number = 0;
var tutorial_number = 0;
//firstpause, tryagain, tryagainpause, firstcongrats, firstcongratspause, secondcongrats, secondcongratspause, thirdcongrats
var videos = [{
url: "conjugation tut.mp4",
times: [159, 160.5, 163.8, 164.15, 166.8, 167.1, 170, 171.7]
}, {
url: "play.mp4",
times: [159, 160.5, 163.8, 164.15, 166.8, 167.1, 170, 171.7]
}];
var questionnum = 0;
var currentvideo;
var currentset = {};
var currentTutorial;
function handler() {
tutorial_number++;
currentTutorial = new Buildtutorial;
currentvideo = new Buildvideo(videos[tutorial_number]);
currentvideo.videoobject.play(0);
}
function Buildtutorial(num) {
if (num){tutorial_number = num};
this.sets = [
{name: "Conjugation",tutorials: ["ㅗ and ㅏ regular", "ㅜ, ㅓ and ㅣ regular", "ㅏ and ㅓ reductive", "ㅗ and ㅜ reductive", "ㅣ reductive"]},
{name: "Sentence Building",tutorials: ["Particles", "Word Order"]}
];
this.tutorial_name = this.sets[section_number].tutorials[tutorial_number];
this.section_name = this.sets[section_number].name;
this.tutorial_number = tutorial_number;
this.section_number = section_number;
update_menu(this);
}
function Buildvideo(x) {
if (x === undefined) {
alert("no new videos");
return;
}
this.firstpause = x.times[0];
this.url = x.url;
this.tryagain = x.times[1];
this.tryagainpause = x.times[2];
this.firstcongrats = x.times[3];
this.firstcongratspause = x.times[4];
this.secondcongrats = x.times[5];
this.time = $("#video").get(0).currentTime;
this.secondcongratspause = x.times[6];
this.thirdcongrats = x.times[7];
this.videoobject = $("#video").get(0);
$(this.videoobject).bind('ended', handler);
this.load = function() {
$("#video").html("<source src='" + currentvideo.url + "' type='video/ogg'>");
this.videoobject.load();
};
this.start = function(time) {
this.videoobject.currentTime = time;
time = time || 0;
this.videoobject.play();
this.pause(this.firstpause);
};
this.pause = function(time) {
this.videoobject.addEventListener('timeupdate', function() {
if (this.currentTime >= time && this.currentTime < (time + 0.3)) {
console.log("pause at " + this.currentTime);
this.pause();
}
}, true);
};
}
function getnewset() {
currentset = {
conjugations: {},
baseverb: conjugationsets[tutorial_number][questionnum]
};
}
var random = function(r) {
r.children().sort(function() {
return (Math.round(Math.random()) - 0.5);
}).appendTo(r);
};
var vowels = "0ㅏㅐㅑㅒㅓㅔㅕㅖㅗㅘㅙㅚㅛㅜㅝㅞㅟㅠㅡㅢㅣ".split(""),
leads = "0ㄱㄲㄴㄷㄸㄹㅁㅂㅃㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎ".split(""),
tails = "0ㄱㄲㄳㄴㄵㄶㄷㄹㄺㄻㄼㄽㄾㄿㅀㅁㅂㅄㅅㅆㅇㅈ".split("");
function render(x) {
$("#wrong0").text(x.conjugations.incorrect[0]);
$("#wrong1").text(x.conjugations.incorrect[1]);
$("#wrong2").text(x.conjugations.incorrect[2]);
$("#correct").text(x.conjugations.correct);
random($(".answers"));
$(".answer").css("border-radius", "0px");
$('.answer').first().css('border-radius', '10px 0px 0px 10px');
$('.answer').last().css('border-radius', '0px 10px 10px 0px');
$(".answer").css("background-color", "#B7BECC");
$("#base").text(x.baseverb);
}
function update_menu(y){
$("#nav,#nav *").css("background-color", "white");
var query = "#" + y.section_name + ",#" + y.section_name + "" + y.tutorial_number;
$(query).css("background-color", "rgb(215,215,215)");
}
function render_menu(x) {
var nav = $("#nav");
$.each(x.sets, function(ind, val) {
var text = "";
$.each(val.tutorials, function(i, v) {
text += "<li id='" + val.name + i + "'class='tutorial_title'>" + v + "</li>"
});
nav.append($("<li id='" + x.sets[ind].name + "' class='section_title'>" + val.name + "</li><ul id='tutorial_titles'>" + text + "</ul>"));
});
update_menu(x);
$(".tutorial_title").click(function(){
var id = $(this).attr('id');
var num = id.substring(id.length - 1);
currentTutorial = new Buildtutorial(num);
});
}
$(function() {
//set mouseover colors
$(".answer").each(function() {
$(this).mouseover(function() {
var bg = $(this).css("background-color");
if (bg === "rgb(183, 190, 204)" || bg === "#b7becc") {
$(this).css("background-color", "#E5E8EE");
}
}).mouseout(function() {
var bg = $(this).css("background-color");
if (bg === "rgb(229, 232, 238)" || bg === "#e5e8ee") {
$(this).css("background-color", "#B7BECC");
}
});
});
function seperate(x) {
x = x.charCodeAt();
var y = {},
z = {};
y.tail = (x - 44032) % 28;
y.vowel = 1 + ((x - 44032 - y.tail) % 588 / 28);
y.lead = 1 + (parseInt((x - 44032) / 588, 10));
z.vowel = vowels[y.vowel];
z.tail = tails[y.tail];
z.lead = leads[y.lead];
return z;
}
function buildhangeul(x) {
var tail = tails.indexOf(x.tail),
vowel = vowels.indexOf(x.vowel),
lead = leads.indexOf(x.lead),
codepoint = tail + (vowel - 1) * 28 + (lead - 1) * 588 + 44032;
return String.fromCharCode(codepoint);
}
function conjugate(base) {
var output = {},
each = base.split("");
output.incorrect = [];
if (each[each.length - 1] === "다") {
var stemlast = each[each.length - 2],
lastjamo = seperate(stemlast);
//ㅂ irregular
if (lastjamo.tail === "ㅂ") {
lastjamo.tail = "0";
stemlast = buildhangeul(lastjamo);
output.correct = each.slice(0, -2).join("") + stemlast + "워";
output.incorrect[0] = each.slice(0, -1).join("") + buildhangeul({
lead: "ㅇ",
vowel: lastjamo.vowel,
tail: "0"
});
output.incorrect[1] = each.slice(0, -1).join("") + "워";
output.incorrect[2] = each.slice(0, -2).join("") + stemlast + "와";
} else if (lastjamo.vowel === "ㅏ" && lastjamo.tail !== "0" || lastjamo.vowel === "ㅗ" && lastjamo.tail !== "0") {
//ㅏ and ㅗ regular
output.correct = stemlast + "아";
output.incorrect[0] = buildhangeul({
lead: lastjamo.lead,
vowel: lastjamo.vowel,
tail: "0"
}) + buildhangeul({
lead: lastjamo.tail,
vowel: "ㅏ",
tail: "0"
});
output.incorrect[1] = stemlast + "ㅏ";
output.incorrect[2] = stemlast;
} else if (lastjamo.vowel === "ㅓ" && lastjamo.tail !== "0" || lastjamo.vowel === "ㅜ" && lastjamo.tail !== "0" || lastjamo.vowel === "ㅣ" && lastjamo.tail !== "0") {
//ㅓ, ㅜ, and ㅣ regular
output.correct = stemlast + "어";
output.incorrect[0] = buildhangeul({
lead: lastjamo.lead,
vowel: lastjamo.vowel,
tail: "0"
}) + buildhangeul({
lead: lastjamo.tail,
vowel: "ㅓ",
tail: "0"
});
output.incorrect[1] = stemlast + "ㅓ";
output.incorrect[2] = stemlast;
}
//ㅏ and ㅓ reductive
else if (lastjamo.vowel === "ㅏ" && lastjamo.tail === "0" || lastjamo.vowel === "ㅓ" && lastjamo.tail === "0") {
output.correct = stemlast;
output.incorrect[0] = stemlast + buildhangeul({
lead: "ㅇ",
vowel: lastjamo.vowel,
tail: "0"
});
output.incorrect[1] = buildhangeul({
lead: lastjamo.lead,
vowel: "ㅐ",
tail: "0"
});
output.incorrect[2] = base;
}
//ㅗ and ㅜ reductive
else if (lastjamo.vowel === "ㅗ" && lastjamo.tail === "0") {
lastjamo.vowel = "ㅘ";
output.correct = buildhangeul(lastjamo);
output.incorrect[0] = stemlast + "와";
output.incorrect[1] = stemlast + "아";
output.incorrect[2] = buildhangeul({
lead: lastjamo.lead,
vowel: "ㅝ",
tail: "0"
});
} else if (lastjamo.vowel === "ㅜ" && lastjamo.tail === "0") {
lastjamo.vowel = "ㅝ";
output.correct = buildhangeul(lastjamo);
output.incorrect[0] = stemlast + buildhangeul({
lead: "ㅇ",
vowel: "ㅝ",
tail: "0"
});
output.incorrect[1] = buildhangeul({
lead: lastjamo.lead,
vowel: "ㅜ",
tail: "0"
}) + buildhangeul({
lead: "ㅇ",
vowel: "ㅓ",
tail: "0"
});
output.incorrect[2] = buildhangeul({
lead: lastjamo.lead,
vowel: "ㅘ",
tail: "0"
});
}
//ㅣreductive
else if (lastjamo.vowel === "ㅣ" && lastjamo.tail === "0") {
lastjamo.vowel = "ㅕ";
output.correct = each.slice(0, -2).join("") + buildhangeul(lastjamo);
}
//르 irregular
else if (stemlast === "르") {
var secondlastjamo = seperate(each[each.length - 3]);
secondlastjamo.tail = "ㄹ";
if (secondlastjamo.vowel === "ㅗ") {
stemlast = "라";
} else if (secondlastjamo.vowel === "ㅜ") {
stemlast = "러";
}
var secondlast = buildhangeul(secondlastjamo);
output.correct = each.slice(0, -3).join("") + secondlast + stemlast;
}
} else {
alert("Only Korean verbs in dictionary form please ;)");
}
return output;
}
$('.answer').click(function() { //click answer
//wait for tutorial to end
if (currentvideo.videoobject.currentTime <= currentvideo.firstpause) {
$("#warning").text("Not yet!").fadeIn(300).delay(1400).fadeOut(300);
return
}
if ($(this).text() === currentset.conjugations.correct) {
//if correct
//skip to congratulations
$(this).css("background-color", "#62F05F");
questionnum++;
if (questionnum === 1) {
currentvideo.start(currentvideo.firstcongrats);
currentvideo.pause(currentvideo.firstcongratspause);
} else if (questionnum === 2) {
currentvideo.start(currentvideo.secondcongrats);
currentvideo.pause(currentvideo.secondcongratspause);
} else if (questionnum === 3) {
currentvideo.start(currentvideo.thirdcongrats);
questionnum = 0;
}
getnewset();
currentset.conjugations = conjugate(currentset.baseverb);
setTimeout(function() {
render(currentset);
}, 2000);
//if incorrect
} else {
//skip to try again msg
$(this).css("background-color", "red");
currentvideo.start(currentvideo.tryagain);
currentvideo.pause(currentvideo.tryagainpause);
}
});
$("#reset").click(function() {
currentvideo.videoobject.currentTime = 0;
currentvideo.start();
});
currentTutorial = new Buildtutorial(tutorial_number);
render_menu(currentTutorial);
currentvideo = new Buildvideo(videos[tutorial_number]);
getnewset();
currentvideo.load();
currentvideo.videoobject.play();
currentvideo.pause(currentvideo.firstpause);
currentset.conjugations = conjugate(currentset.baseverb);
render(currentset);
});
</code></pre>
|
[] |
[
{
"body": "<p>I cannot answer your scoping question, though I would not bother putting video under tutorial if it gives you hassles. I can give a review of your code.</p>\n\n<ul>\n<li>lowerCamelCasing is good : <code>currentvideo</code> -> <code>currentVideo</code>, <code>currentset</code> -> <code>currentSet</code>, <code>section_number</code> -> <code>sectionNumber</code> etc.</li>\n<li>Do not skip newlines after <code>if</code> conditions: ( <code>if (num){tutorial_number = num};</code> )</li>\n<li>Production code should not have <code>console.log</code></li>\n<li>I am not sure how <code>currentTutorial = new Buildtutorial;</code> works, I think you are missing <code>()</code></li>\n<li>I like your <code>videos</code> and <code>conjugationSets</code> objects</li>\n<li>The parameter <code>x</code> for <code>Buildvideo</code> could use a better name</li>\n<li><code>Buildtutorial</code> and <code>Buildvideo</code> are constructors, they ought to have the name of what you build. <code>Tutorial</code> and <code>Video</code> would be better constructor names.</li>\n<li><code>questionnum</code> should probably be part of your model</li>\n<li><code>handler</code> as a function name is too vague</li>\n<li>The object that you assign to <code>this.sets</code> in <code>BuildTutorial</code> should probably have been defined on top next to <code>videos</code> and <code>conjugationSets</code></li>\n<li>I know it's not your concern, but calling <code>update_menu</code> from a constructor is far away from MVC</li>\n<li>The <code>times</code> member of <code>videos</code> should probably not be an array but an object instead, it would be easier to maintain <code>videos</code> then</li>\n<li>the function name <code>random</code> does not give away that it randomizes an array, also the parameter name <code>r</code> is unfortunate</li>\n<li>You can consider to turn these statements <code>$(\"#wrong0\").text(x.conjugations.incorrect[0]);</code> etc into a loop, this will make your code more flexible</li>\n<li>In <code>//set mouseover colors</code> I would suggest not to hard code colors in JavaScript but to toggle CSS classes</li>\n<li>In <code>function seperate(x)</code> and <code>buildhangeul</code> you should document better the magic numbers, I have no idea what they do</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T19:24:55.370",
"Id": "43642",
"ParentId": "21630",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T16:03:12.410",
"Id": "21630",
"Score": "2",
"Tags": [
"javascript",
"object-oriented",
"mvc"
],
"Title": "Making one object the property of another whilst avoiding scope issues"
}
|
21630
|
<p>I was recently asked to implement an interface for a job interview. the class has methods to add customers and movies, the customers can watch or like movies and add friends. there are methods to get recommendations for users. All public methods in SocialMoviesImpl were defined by the interface, so I could not change them</p>
<p>the company decided not to continue with the hiring process, I would like some feedback in what I implemented. I used hashmaps to store the information since it is fast to access</p>
<pre><code>import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class SocialMoviesImpl implements SocialMovies {
Map<Integer,String> movies;
Map<Integer,Customer> customers;
public SocialMoviesImpl(){
this.movies= new HashMap<Integer,String>();
this.customers= new HashMap<Integer,Customer>();
}
/**
* add a movie, runtime complexitiy is O(1) //hashmap
* @param movieId the id of the movie
*
*/
public void addMovie(int movieId, String title) {
this.movies.put(movieId,title);
}
/**
* gets a movie, O(1)
*/
public String lookupMovie(int movieId) {
return this.movies.get(movieId);
}
/**
* adds a new customer, O(1)
*/
public void addCustomer(int customerId, String name) {
this.customers.put(customerId, new Customer(customerId, name));
}
/**
* obtains the customer, O(1)
*/
public String lookupCustomer(int customerId) {
Customer cust= this.customers.get(customerId);
return cust!=null?cust.getName():null;
}
/**
* O(4), 3 searches and 1 add
*/
public void addLikedMovie(int customerId, int movieId) {
if(this.customers.containsKey(customerId) && this.movies.containsKey(movieId)){
this.customers.get(customerId).addLike(movieId);
}else{
throw new IllegalArgumentException("movie or client does not exists");
}
}
/**
* O(4)
*/
public void addWatchedMovie(int customerId, int movieId) {
if(this.customers.containsKey(customerId) && this.movies.containsKey(movieId)){
this.customers.get(customerId).addWatch(movieId);
}else{
throw new IllegalArgumentException("movie or client does not exists");
}
}
/**
* O(6)
*/
public void addFriend(int customerId1, int customerId2) {
if(this.customers.containsKey(customerId1) && this.customers.containsKey(customerId2)){
//we add a key to the customers friend entry
this.customers.get(customerId1).addFriend(customerId2);
this.customers.get(customerId2).addFriend(customerId1);
}else{
throw new IllegalArgumentException("the customerId or movieId provided does not exists");
}
}
/**
* returns any movie that has been liked by a friend.
*
*
*/
public Collection<Integer> getRecommendationsFromFriends(int customerId) {
return getFriendRecommendations(customerId, 1);
}
/**
* returns every movie that has been liked by a defined number of friends.
* O(n^2)
*
*/
public Collection<Integer> getFriendRecommendations(int customerId,
int minimumCommonFriends) {
if(minimumCommonFriends<1){
//negative doesnt make sense and zero will mean every movie
throw new IllegalArgumentException("please provide a positive non-zero number of minimum common friends");
}
//iterate through all friends and their movies
Map<Integer,Integer> recommends= new HashMap<Integer,Integer>();
Collection<Integer> friends=this.customers.get(customerId).getFriends();
for(Integer friendId:friends){
Customer friend= this.customers.get(friendId);
for(Integer movie: friend.getLikes()){
Integer ammount=recommends.get(movie);
ammount=ammount!=null?ammount+1:1; //increment or set to 1 if first time
recommends.put(movie,ammount); //we dont care about who is recommending it
}
}
//now, filter only those recommended by at least the treshold
Set<Integer> keys=recommends.keySet();
Set<Integer> toRemove= new HashSet<Integer>(); //we cannot remove during iteration
for(Integer movie: keys){
Integer commonFriends= recommends.get(movie); //ammount of friends who liked it
if(commonFriends<minimumCommonFriends){
toRemove.add(movie);
}
}
keys.removeAll(toRemove);
return recommends.keySet();
}
/**
* class that holds information about the customer (liked, watched, etc).
* @author santiago
*
*/
class Customer{
private int customerId;
private String name;
private Set<Integer> likes;
private Set<Integer> watched;
private Set<Integer> friends;
public Customer(int id, String name){
this.customerId=id;
this.name=name;
this.likes= new HashSet<Integer>();
this.watched= new HashSet<Integer>();
this.friends= new HashSet<Integer>();
}
public String getName(){
return this.name;
}
public Set<Integer> getLikes() {
return likes;
}
public Set<Integer> getWatched() {
return watched;
}
public Set<Integer> getFriends() {
return friends;
}
public void addFriend(int friend){
this.friends.add(friend);
}
public void addWatch(int movie){
this.watched.add(movie);
}
public void addLike(int movie){
this.likes.add(movie);
}
}
</code></pre>
<p>}</p>
<p>this is the provided interface</p>
<pre><code>import java.util.Collection;
// Maintains a network of movies and customers
// All methods should return an empty collection, -1, or null on failure, as appropriate <---*** I just noted this and feel very very bad.
public interface SocialMovies {
// Defines a movie ID to title mapping in the system
void addMovie(int movieId, String title);
// Returns the title of the given movie
String lookupMovie(int movieId);
// Defines a customer ID to name mapping in the system
void addCustomer(int customerId, String name);
// Returns the name of the given customer
String lookupCustomer(int customerId);
// Record that a movie was "liked" by the given customer
void addLikedMovie(int customerId, int movieId);
// Record that a movies has been watched by the given customer
void addWatchedMovie(int customerId, int movieId);
// Associate two customers as being friends
void addFriend(int customerId1, int customerId2);
// Returns the IDs of movies that:
// - Have not been watched by the given customer
// - Have been "liked" by at least one of the given customer's friends
Collection<Integer> getRecommendationsFromFriends(int customerId);
// Returns the IDs of customers that have at least <minimumCommonFriends> in common
// with the given customer
Collection<Integer> getFriendRecommendations(int customerId, int minimumCommonFriends);
</code></pre>
<p>}</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T19:17:03.320",
"Id": "34761",
"Score": "0",
"body": "I like this question, but unfortunately, I can't help answer it. I think I'd do it very differently, but I can't tell how much of that is Java idiom (vs the C# I use) and how much would actually be improvements. Do you really need to indicate the complexity of each function, though? That seems overkill to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T20:33:45.303",
"Id": "34768",
"Score": "0",
"body": "yes, they ask to provide complexity for every method"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T21:12:29.687",
"Id": "34773",
"Score": "0",
"body": "Just to be sure, you know that both getRecommendationsFromFriends and getFriendRecommendations are wrongly implemented?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T21:32:07.953",
"Id": "34774",
"Score": "0",
"body": "@santiagozky - My understanding of complexity was that there is no such thing as `O(2)`, `O(4)`, etc. See [wikipedia](http://en.wikipedia.org/wiki/Big_O_notation#Orders_of_common_functions) - `O(1)` is just an indication of constant time. At best, it would be `4*O(1)` - four constant-time operations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T08:45:34.923",
"Id": "34789",
"Score": "0",
"body": "@Bobson, you are right. I havent used the notation in several years and I was in a hurry and didn't have time to recheck that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T08:43:19.417",
"Id": "34791",
"Score": "0",
"body": "Just as an hint regarding the complexity of HashMap operations: [What is the time complexity of HashMap.containsKey() in java?](http://stackoverflow.com/a/8923291/638893)"
}
] |
[
{
"body": "<p>My thoughts in no particular order:</p>\n\n<ul>\n<li><p>You can remove most of the \"this.\" in your code. That looks terrible to me, sorry.</p></li>\n<li><p>addMovie and lookupMovie should probably be part of a separate class like MovieDatabase</p></li>\n<li><p>Customer.addWatch() has a misleading name, not consistent with SocialMovies.addWatchedMovie</p></li>\n<li><p>addCustomer does not verify that the id is already used</p></li>\n<li><p>lookupMovie has no exception handling</p></li>\n<li><p>lookupCustomer has no exception handling</p></li>\n<li><p>lookupCustomer returns the name, would it not be better to return the customer object?</p></li>\n<li><p>addLikedMovie & addWatchedMovie: I would separate the 2 exceptions, so that it is clear which id does not exist.</p></li>\n<li><p>Should a method that throws IllegalArgumentException have that in the method declaration?</p></li>\n<li><p>addLikedMovie & addWatchedMovie: Do not follow the DRY principle</p></li>\n<li><p>should addLikeMovie also call addWatchedMovie ?</p></li>\n<li><p>The error message in addFriend is wrong, copy pasting is not your friend</p></li>\n<li><p>Ammount is not spelled correctly</p></li>\n<li><p>Why is one method called getRecommendationsFromFriends and the other one getFriendRecommendations? Confusing.</p></li>\n<li><p>Are you sure that getFriendRecommendations is O(n^2)?</p></li>\n<li><p>//we cannot remove during iteration <- Are you sure, how about calling remove() on an iterator?</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T20:32:19.767",
"Id": "34766",
"Score": "0",
"body": "thanks for the feedback. maybe I should have make clear that all the methods were defined in an interface provided by them, so I had no control over them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T20:33:42.357",
"Id": "34767",
"Score": "0",
"body": "I was wondering about that, do you still have the interface, it might make this easier to review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T20:38:14.860",
"Id": "34769",
"Score": "0",
"body": "yes, I just added, along with a note in the comments about some very clear instructions I shamefully ignored :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T21:35:57.077",
"Id": "34776",
"Score": "0",
"body": "@santiagozky - Well, that explains `getRecommendationsFromFriends` vs `getFriendRecommendations`... I disapprove of their interface. It should be `getMovieRecommendationsFromFriends`, since otherwise it could be returning friends which your friends recommended to you."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T18:49:48.917",
"Id": "21636",
"ParentId": "21633",
"Score": "3"
}
},
{
"body": "<p>Your <code>getRecommendationsFromFriends</code> and <code>getFriendRecommendations</code> implementations are incorrect as the documentation shows:</p>\n\n<ul>\n<li><code>getRecommendationsFromFriends</code>: return <strong>movie</strong> id's</li>\n<li><code>getFriendRecommendations</code>: return <strong>customer</strong> id's</li>\n</ul>\n\n<p>This is the biggest issue with your implementation. </p>\n\n<p><code>getRecommendationsFromFriends</code> is fairly straight-forward:</p>\n\n<pre><code>public Collection<Integer> getRecommendationsFromFriends(int customerId) {\n /* 1. Validate Customer\n * 2. Collect the id's for movies his friends like\n * 3. Remove the customer's watched movies from the friend likes\n * 4. Return the collection (a set is good here, maybe even a TreeSet for sorting\n */\n}\n</code></pre>\n\n<p>2 and 3 could be combined (a helper method in <code>Customer</code> could be handy)</p>\n\n<p><code>GetFriendRecommendations</code> is slightly more complicated, but not unreasonable for an interview. (keep in mind there could be many many customers!). Remember to always read (and re-read!) the documentation to make sure you have a firm grasp on what the interface is supposed to provide.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T08:47:37.353",
"Id": "34790",
"Score": "0",
"body": "thanks for the feedback. I was a bit on a hurry and I didnt take time enough to understand what I was ask to do. I hope I learnt a lesson, it could have been a great job opportunity"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T13:06:41.323",
"Id": "34801",
"Score": "1",
"body": "The good thing is you are looking for feedback and trying to improve. Keep on coding!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T00:03:27.583",
"Id": "21646",
"ParentId": "21633",
"Score": "4"
}
},
{
"body": "<p>Don't feel bad about your code, I've seen worse, you'll be fine, asking this here is a huge step forward.</p>\n\n<p>Here are the things that were most critical in my view</p>\n\n<h2>1. Division of Responsibility</h2>\n\n<p>I would have a class for each model, and each model can do CRUD (create read update delete) on it, e.g. a <code>Movie</code> class and a <code>Person</code> class ( and <code>Customer</code> extends person)</p>\n\n<p>I think not having a <code>Movie</code> class was one of the major issues.</p>\n\n<h2>2. Better references</h2>\n\n<p>Instead of this</p>\n\n<pre><code> private Set<Integer> likes;\n private Set<Integer> watched;\n private Set<Integer> friends;\n</code></pre>\n\n<p>I would do this </p>\n\n<pre><code> private Set<Movie> likes;\n private Set<Movie> watched;\n private Set<Customer> friends;\n</code></pre>\n\n<h2>3. Other small things</h2>\n\n<p>you say: </p>\n\n<blockquote>\n <p>we cannot remove during iteration</p>\n</blockquote>\n\n<p>Well it's true in this form of iteration, but in this case you can simply use an <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Iterator.html\" rel=\"nofollow\"><code>Iterator</code></a>, which has a <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Iterator.html#remove%28%29\" rel=\"nofollow\"><code>remove method</code></a> that allows to remove items while iterating. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T13:14:06.403",
"Id": "34803",
"Score": "0",
"body": "Indeed. I think the main point of improvement is the fact that there is almost no domain model here."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T05:36:38.997",
"Id": "21651",
"ParentId": "21633",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "21646",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T17:28:24.947",
"Id": "21633",
"Score": "6",
"Tags": [
"java",
"interview-questions"
],
"Title": "interview question, friends, movies and likes"
}
|
21633
|
<p>Is there a cleaner/more efficient way to loop through the columns in EF implicitly than the way written below?</p>
<pre><code>static void Main(string[] args) {
using (var db = new someDbContext()) {
var query = from p in db.someTable
select new {
column1 = p.column1
column2 = p.column2
};
var columnAccessors = CreateAccessors(query.FirstOrDefault());
foreach (var row in query) {
foreach (var col in columnAccessors) {
var val = col(row);
//Do something with val here.
}
}
}
}
static Func<T, object>[] CreateAccessors<T>(T source = default(T)) {
var propertyAccessors = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(p => p.CanRead)
.Select((p, i) => new {
Index = i,
Property = p,
Accessor = CreatePropertyAccessor<T>(p)
})
.ToArray();
return propertyAccessors.Select(p => p.Accessor).ToArray();
}
static Func<T, object> CreatePropertyAccessor<T>(PropertyInfo prop) {
var param = Expression.Parameter(typeof(T), "input");
var propertyAccess = Expression.Property(param, prop.GetGetMethod());
var castAsObject = Expression.TypeAs(propertyAccess, typeof(object));
var lambda = Expression.Lambda<Func<T, object>>(castAsObject, param);
return lambda.Compile();
}
</code></pre>
<p>I've tried simply doing a <code>foreach (var col in row)</code> before but I know that it won't work because row doesn't contain a definition for GetEnumerator and I'm not sure how one would go about implementing a solution that would do so generically for something like this.</p>
<p>I was working on implementing a DataReader and came across this page: <a href="http://www.developerfusion.com/article/122498/using-sqlbulkcopy-for-high-performance-inserts/" rel="nofollow noreferrer">http://www.developerfusion.com/article/122498/using-sqlbulkcopy-for-high-performance-inserts/</a>. The thought occurred to me that I could modify the CreatePropertyAccessors segments to loop through columns and so I came up with the above. Problem being I'm just not sure that it's a "good" solution.</p>
<p><strong>Edit:</strong></p>
<p>With one small change the following is possible as well:</p>
<pre><code>var query = from p in db.someTable
select new SomeModel {
item1 = p.column1,
item2 = p.column2
};
var columnAccessors = CreateAccessors<SomeModel>();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T18:55:49.713",
"Id": "34757",
"Score": "2",
"body": "Why do you need to loop through each column?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T19:27:02.040",
"Id": "34762",
"Score": "0",
"body": "@Bobson Depends on the situation but for example: I could print out the value of each column to the console without having to do something like `Console.WriteLine(row.column1 + \", \" row.Column2);` Which honestly isn't that bad with only two columns but it starts to get ridiculous once you pass 5 or so."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T19:28:26.390",
"Id": "34763",
"Score": "0",
"body": "That makes sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-09T09:36:51.480",
"Id": "36459",
"Score": "1",
"body": "Entity Framework is doing all its best for developer not to think about \"columns\" but rather entities. That's why you have properties rather than an array of columns. Each column has its own meaning, so if they are semantically equivalent then most likely you designed your DB incorrectly. Even if you do need to output all record values comma-separated, you would most likely want to apply certain formatting to each column"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-10T00:36:16.077",
"Id": "36514",
"Score": "0",
"body": "@almaz If I was displaying the results to my users then absolutely. I'd probably start building the appropriate models in MVC and decorating them with whatever tags I needed and all that fancy stuff. However, when I'm developing stuff on the fly and just trying to randomly test things I often find myself wishing I had a quick way to display the raw information returned from queries."
}
] |
[
{
"body": "<p>So I had a look and made a few modifications, see below with comments.</p>\n\n<pre><code>// Made the method generic, the constaint is required by DbSet\nstatic void LoopThroughColumns<T>(Func<someDbContext, DbSet<T>> getTable)\n where T : class\n{\n using (var db = new someDbContext())\n {\n // Selecting columns exlicitly was unnecessary\n var query = getTable(db);\n var columnAccessors = CreateAccessors<T>();\n\n foreach (var row in query)\n {\n foreach (var col in columnAccessors)\n {\n var val = col(row);\n }\n }\n }\n}\n\n// Parameter is unnecessary as you never used it\nstatic Func<T, object>[] CreateAccessors<T>()\n{\n // Index and Property values weren't being used\n // ToArray() was an unnecessary conversion\n var propertyAccessors = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)\n .Where(p => p.CanRead)\n .Select((p, i) => CreatePropertyAccessor<T>(p));\n\n return propertyAccessors.Select(e => e).ToArray();\n}\n\nstatic Func<T, object> CreatePropertyAccessor<T>(PropertyInfo prop)\n{\n var param = Expression.Parameter(typeof(T), \"input\");\n var propertyAccess = Expression.Property(param, prop.GetGetMethod());\n var castAsObject = Expression.TypeAs(propertyAccess, typeof(object));\n var lambda = Expression.Lambda<Func<T, object>>(castAsObject, param);\n return lambda.Compile();\n}\n</code></pre>\n\n<p>Usage is a little different now, you would call it like this:</p>\n\n<pre><code>LoopThroughColumns(e => e.someTable);\n</code></pre>\n\n<p>To be extra-super cool (ie. generic) you could even pass in an <code>Action<object></code> and have that define what is done with <code>val</code>, then derive different methods on that one. Below I'm creating a <code>PrintColumnValues</code> method which calls <code>LoopThroughColumns</code> with an specific <code>Action<object></code> to perform.</p>\n\n<pre><code>static void LoopThroughColumns<T>(Func<someDbContext, DbSet<T>> getTable, Action<object> actionOnObject)\n where T : class\n{\n using (var db = new someDbContext())\n {\n var query = getTable(db);\n var columnAccessors = CreateAccessors<T>();\n\n foreach (var row in query)\n {\n foreach (var col in columnAccessors)\n {\n actionOnObject(col(row));\n }\n }\n }\n}\n\nstatic void PrintColumnValues<T>(Func<someDbContext, DbSet<T>> getTable)\n where T : class\n{\n LoopThroughColumns(getTable, \n new Action<object>(e => \n {\n Console.WriteLine(e);\n }));\n}\n</code></pre>\n\n<p>Usage</p>\n\n<pre><code>PrintColumnValues(e => e.someTable);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-10T00:39:27.477",
"Id": "36515",
"Score": "0",
"body": "The parameter was there to support anonymous types through the following syntax: `CreateAccessors(query.FirstOrDefault())`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-09T05:33:55.667",
"Id": "23644",
"ParentId": "21634",
"Score": "3"
}
},
{
"body": "<p>Unless I'm really missing that point of your exercise, have you considered something akin to the following?</p>\n\n<pre><code>List<string> retVal = new List<string>();\nforeach (object prop_loopVariable in new EFModelObj().GetType().GetProperties()) {\n prop = prop_loopVariable;\n retVal.Add(prop.Name);\n}\nincludePath = retVal.ToArray();\n</code></pre>\n\n<p>Where <code>EFMOdelObj</code> is a model from your EF models. This will return a list of all the column/property names and can easily be modified to get the value as well (say in a <code>dictionary<string, dynamic></code> where string is the column name and dynamic is the value.</p>\n\n<p>There are, of course, probably more efficient ways to do that. Such as not using <code>object</code> in the iterator, etc.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-02T15:10:55.917",
"Id": "118645",
"ParentId": "21634",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T17:57:11.323",
"Id": "21634",
"Score": "8",
"Tags": [
"c#",
"entity-framework"
],
"Title": "Looping through columns in Entity Framework"
}
|
21634
|
<p>I'm making an image-downloading app that sets the image as the device wallpaper. For this I used the class:</p>
<p><code>ImageDownloader.java</code></p>
<p>This class has a function which accepts a URL and an <code>ImageView</code>. It downloads and assigns the image found at the URL to the ImageView using an <code>AsyncTask</code> class defined within.</p>
<p>I managed to implement it as intended and wanted to extend its use to helping me set the devices wallpaper. This turned out to be pretty complicated but I managed with the following code in my <code>MainActivity.java</code>:</p>
<pre><code>public class MainActivity extends Activity {
private final ImageDownloader mDownload = new ImageDownloader();
public static Bitmap bima=null;
public static WallpaperManager wm;
</code></pre>
<p>in onCreate:</p>
<pre><code> wm = WallpaperManager.getInstance(getApplicationContext());
mDownload.download(url,imageView);
</code></pre>
<p>method defined in the MainActivity.Java:</p>
<pre><code>public static void setbima(Bitmap bimu) {
try {wm.setBitmap(bimu);} catch (Exception e) {}
}
</code></pre>
<p>Then I used my function in the <code>ImageDownloader</code> class' <code>AsyncTask</code>'s <code>onPostExecute</code> like this:</p>
<pre><code>MainActivity.setbima(bitmap);
</code></pre>
<p>Making use of the bitmap that was being passed to there by the <code>AsyncTask</code> class.</p>
<p>With the <code>WallpaperManager</code> object I wanted to make use of that bitmap, because its function <code>.setBitmap()</code> accepts bitmaps and puts the system wallpaper to that bitmap.</p>
<p>I am just wondering if my way of achieving this is optimal or is there a simpler way to have achieved this? It seems a very far-fetched way of doing this and I wouldn't be surprised if it is as I am a beginner programmer.</p>
|
[] |
[
{
"body": "<p>The system you have in place is efficient in the sense that it offloads the network-based work on to an AsyncTask, and the callback updates the wallpaper.</p>\n\n<p>You don't give the details of your <code>ImageLoader</code> <code>AsyncTask</code>, but you could neaten a few things up by putting them in to there... and it would look something like:</p>\n\n<pre><code>public ImageLoader extends AsyncTask<String, Void, BitMap> {\n\n private final Context context;\n\n ImageLoader(Context context) {\n this.context = context;\n }\n\n public BitMap doInBackground(String urlpath) {\n // set the bitmap... do the work.\n return bitmap;\n }\n\n public void PostExecute(BitMap result) {\n try {\n WallpaperManager.getInstance(context).setBitmap(result);\n } catch (....) {\n ....\n }\n }\n\n}\n</code></pre>\n\n<p>With the above task, it becomes a simple thing to do in the onCreate of the MainActivity:</p>\n\n<pre><code>new ImageDownloader(getApplicationContext()).execute(url);\n</code></pre>\n\n<p>That's the way to make it neat....</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T18:18:27.700",
"Id": "42886",
"ParentId": "21635",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T18:07:01.760",
"Id": "21635",
"Score": "6",
"Tags": [
"java",
"beginner",
"android",
"image",
"url"
],
"Title": "Image-downloader/wallpaper setter"
}
|
21635
|
<p>I'm new to scala and I'm noticing I have some repeating code in my controllers.</p>
<p>I'm wondering if anyone can give some hints for traits and parameterization for eliminating duplicate code for basic crud operations on the web services - I'm still a little confused about how to use scala 'generics'/parameters.</p>
<p>Don't mind the json - I've fixed this horrible scrappy code now using the objects to render themselves as json.</p>
<p>Code piece</p>
<pre><code>package controllers
import play.api.mvc._
import securesocial.core._
import play.Logger
import models.{ResponseMessage, GraphedUser}
import com.tinkerpop.blueprints.Vertex
import service.{BaseFramedEntity, SecureSocialUserService, FramedGraphService, GraphDbService}
import play.api.libs.json._
import scala.util.parsing.json
import json.JSONArray
import play.api.libs.concurrent.{Akka, Promise}
import play.api.Play.current
import securesocial.core.UserId
import Predef._
import play.mvc.With
/**
* Controller for user api
*/
object UsersController extends BaseController with securesocial.core.SecureSocial {
val collectionName = "users"
def index = Action {
implicit request =>
//get all users
val pageOption = request.queryString.get("page")
pageOption match {
case Some(page) => {
val resultsPerPageOption = request.queryString.get("numResults")
resultsPerPageOption match {
case Some(size) => Ok(renderUserJson(getUserList(page.head.toInt, size.head.toInt))) //Both page and size exists
case None => Ok(renderUserJson(getUserList(page.head.toInt, defaultPageSize))) //only page exists
}
}
case None => Ok(renderUserJson(getUserList(defaultPage, defaultPageSize))) //page doesn't exist. Ignore size.
}
}
def view(id: String) = Action {
implicit request =>
val userOption = FramedGraphService.getFramedVertexByProperty("userId", id, classOf[GraphedUser])
userOption match {
case Some(user) => {
Ok(user.toString)
}
case None => InternalServerError("Could not find user")
}
}
def follow(id: String) = SecuredAction(true) {
implicit request =>
//Must validate user...
val currentUserIdentityOption = SecureSocial.currentUser
currentUserIdentityOption match {
case Some(currentUser) => {
val userToFollowOption = FramedGraphService.getFramedVertexByProperty("userId", id, classOf[GraphedUser])
userToFollowOption match {
case Some(userToFollow) => {
GraphDbService.addEdge(null, currentUser.id.id, id, "follows")
val message = ResponseMessage("ok", "following user: " + id.toString).toJsonString
Ok(message)
}
case None => Ok(ResponseMessage("error", "cannot find user: " + id.toString).toJsonString)
}
}
case None => InternalServerError(ResponseMessage("error", "unknown error").toJsonString)
}
}
private def getUserList(page: Int, size: Int): Iterable[GraphedUser] = {
val fullUsersList = FramedGraphService.getFramedVerticesByProperty(BaseFramedEntity.TYPE_KEY, GraphedUser.USER_TYPE, classOf[GraphedUser])
fullUsersList.slice((page - 1) * size, (page - 1) * size + size)
}
private def renderUserJson(users: Iterable[GraphedUser]): String = {
val listToConvert = for (user <- users) yield
Json.toJson(Map(
"userId" -> Json.toJson(user.getUserId),
"graphId" -> Json.toJson(user.asVertex().getId.toString),
"firstName" -> Json.toJson(user.getFirstName),
"lastName" -> Json.toJson(user.getLastName),
"fullName" -> Json.toJson(user.getFullName),
"providerId" -> Json.toJson(user.getProviderId),
"firstName" -> Json.toJson(user.getAvatarUrl)))
val concatenated = listToConvert.foldLeft("")(_ + _)
surroundJsonWithObject(concatenated, collectionName)
}
}
</code></pre>
|
[] |
[
{
"body": "<p>for all the option matchers you could use getOrElse\nAnd remember: Option is also a list with all given features</p>\n\n<p>here an example</p>\n\n<pre><code>val resultsPerPageOption = request.queryString.get(\"numResults\")\nval size= resultsPerPageOption.map(_.head.toInt).getOrElse(defaultPageSize)\nOk(renderUserJson(getUserList(page.head.toInt, size)))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T19:57:28.833",
"Id": "29530",
"ParentId": "21637",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T18:55:33.127",
"Id": "21637",
"Score": "6",
"Tags": [
"scala"
],
"Title": "Scala Play Controller - Refactoring out Duplication for Restful Web Services"
}
|
21637
|
<p>I've written a simple Python module that depends on watchdog to monitor for modified files, then runs various integration and build processes.</p>
<p>I'm fairly new to Python, so I'd appreciate all criticism. For example of how I'm using the module <a href="http://github.com/hbmartin/kirb" rel="nofollow">see this</a>.</p>
<pre><code>import sys, os, time, copy, logging
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class ChangeHandler(FileSystemEventHandler):
def __init__(self, callback):
if callable(callback):
self.callback = callback
else:
raise TypeError('callback is required')
def on_modified(self, event):
if event.is_directory or event.event_type is not "modified":
return
self.callback(event.src_path)
class Watcher(object):
file_set = {}
def _trim_root(self, path, root = None):
if root is None:
root = self.root
if path.startswith(root):
path = path[len(root):]
if path.startswith('/'):
path = path[1:]
return path
def _on_file_changed(self, src_path):
src_path = self._trim_root(src_path)
for out, props in self.file_set.iteritems():
files = props['files']
callbacks = props['callbacks']
if src_path in files:
if callable(callbacks['onchange']):
if not callbacks['onchange'](os.path.abspath(src_path)):
raise Exception('onchange callback errored for file ' + src_path)
print os.path.abspath(out)
self._compile(files, callbacks, os.path.abspath(out))
def _compile(self, files, callbacks, out):
if hasattr(callbacks, 'mode') and callbacks['mode'] is 'slurp':
slurpy = [out, []]
for fname in files:
with open(fname) as infile:
slurpy[1].append([fname, infile.read()])
if hasattr(callbacks, 'each') and callable(callbacks['each']):
callbacks['each'](slurpy)
else:
raise Exception('slurp mode requires an each handler')
else:
# default mode is concat, also contains break for files_only mode
if hasattr(callbacks, 'each') and callable(callbacks['each']):
rv = callbacks['each']([out, files])
if type(rv) is list:
files = rv
elif rv is False:
logging.info('each callback asked us to exit quietly')
return
elif rv is True:
logging.info('finished each callback, proceeding with original file list')
else:
raise TypeError('the each callback must return an array of file names or True')
if hasattr(callbacks, 'mode') and callbacks['mode'] is 'files_only':
logging.info("files_only mode, no concat or post")
return
with open(out, 'w') as outfile:
for fname in files:
with open(fname) as infile:
for line in infile:
outfile.write(line if not hasattr(callbacks, 'line') else callbacks['line'](line))
logging.info("Wrote file: " + out)
if hasattr(callbacks, 'post') and callable(callbacks['post']):
callbacks['post'](out)
def compile(self):
for out, props in self.file_set.iteritems():
files = props['files']
callbacks = props['callbacks']
self._compile(files, callbacks, os.path.abspath(out))
def FileSet(self, out = None, files = None, callbacks = {}):
if type(files) is not list:
raise TypeError('files list is a required argument')
if type(out) is not str:
raise TypeError('out is a required argument')
if hasattr(self.file_set, out):
raise Exception('out file is already in use by another FileSet')
if out in files:
raise Exception('cannot watch out file')
self.file_set[out] = {'files' : files, 'callbacks' : callbacks}
return out
def MirrorSet(self, orig = None, new = None, addl = None):
if type(orig) is not str:
raise TypeError('orig list is a required argument')
if type(new) is not str:
raise TypeError('new is a required argument')
try:
files = copy.deepcopy(self.file_set[orig]['files'])
skin_path = os.path.join(self.root, new)
out = os.path.join(skin_path, orig)
for i, filename in enumerate(files):
filePath = os.path.join(skin_path, filename)
if (os.path.exists(filePath)):
files[i] = os.path.join(new, files[i])
if addl is not None and type(addl) is list:
files.extend(addl)
self.file_set[out] = {'files' : files, 'callbacks' : self.file_set[orig]['callbacks']}
except:
raise
def stop(self):
self.observer.stop()
def start(self):
event_handler = ChangeHandler(self._on_file_changed)
self.observer = Observer()
self.observer.schedule(event_handler, self.root, recursive=True)
self.observer.start()
def __init__(self, root = None):
if type(root) is not str:
raise TypeError('root is required as argument in object instantation')
self.root = os.path.abspath(root)
</code></pre>
|
[] |
[
{
"body": "<pre><code>import sys, os, time, copy, logging\nfrom watchdog.observers import Observer\nfrom watchdog.events import FileSystemEventHandler\n\n\nclass ChangeHandler(FileSystemEventHandler):\n def __init__(self, callback):\n if callable(callback):\n self.callback = callback\n else:\n raise TypeError('callback is required')\n\n def on_modified(self, event):\n if event.is_directory or event.event_type is not \"modified\":\n</code></pre>\n\n<p>Don't use <code>is</code> to compare strings, you've got no guarantees it'll do anything useful. \nUse <code>==</code>\n return\n self.callback(event.src_path)</p>\n\n<p>I think this would be clearer as:</p>\n\n<pre><code> if not event.is_directory and event.event_type == modified:\n self.callback(event.src_path)\n</code></pre>\n\n<p>As it stands, the logic is obscured.</p>\n\n<pre><code>class Watcher(object):\n file_set = {}\n</code></pre>\n\n<p>No! This is a class attribute, you almost certainly wanted an object attribute. You should store this <code>__init__</code> as <code>self.file_set</code>.</p>\n\n<pre><code> def _trim_root(self, path, root = None):\n if root is None:\n root = self.root\n</code></pre>\n\n<p>You only ever pass None, so don't have it as a parameter.</p>\n\n<pre><code> if path.startswith(root):\n path = path[len(root):]\n if path.startswith('/'):\n path = path[1:]\n return path\n</code></pre>\n\n<p>Look at os.path.relpath, python already does the logic you've got here.</p>\n\n<pre><code> def _on_file_changed(self, src_path):\n src_path = self._trim_root(src_path)\n for out, props in self.file_set.iteritems():\n files = props['files']\n callbacks = props['callbacks']\n</code></pre>\n\n<p>Don't use dictionaries as general purpose storage devices. Instead, use objects.</p>\n\n<pre><code> if src_path in files:\n if callable(callbacks['onchange']):\n</code></pre>\n\n<p>You just the ignore the callable if its not callable. That's asking for hard to diagnose bugs.</p>\n\n<pre><code> if not callbacks['onchange'](os.path.abspath(src_path)):\n raise Exception('onchange callback errored for file ' + src_path)\n</code></pre>\n\n<p>Have your callback reports problems with exceptions, not return values.</p>\n\n<pre><code> print os.path.abspath(out)\n self._compile(files, callbacks, os.path.abspath(out))\n\n def _compile(self, files, callbacks, out):\n if hasattr(callbacks, 'mode') and callbacks['mode'] is 'slurp':\n</code></pre>\n\n<p>hasattr checks for attributes, 'mode' is a key. You've got a significant deficiency in your understanding of python there. <code>hasattr</code> will always return false. This suggests to me that you can't possible have done any serious testing of this code.</p>\n\n<pre><code> slurpy = [out, []]\n</code></pre>\n\n<p>Lists are for lists of things. That isn't a list of things, that's two things. It should probably be two variables.</p>\n\n<pre><code> for fname in files:\n</code></pre>\n\n<p>I recommend spelling out filename, rather then abbreviating it</p>\n\n<pre><code> with open(fname) as infile:\n slurpy[1].append([fname, infile.read()])\n if hasattr(callbacks, 'each') and callable(callbacks['each']):\n</code></pre>\n\n<p>Again, this doesn't work. AT ALL.</p>\n\n<pre><code> callbacks['each'](slurpy)\n else:\n raise Exception('slurp mode requires an each handler')\n else:\n # default mode is concat, also contains break for files_only mode\n if hasattr(callbacks, 'each') and callable(callbacks['each']):\n rv = callbacks['each']([out, files])\n</code></pre>\n\n<p>Firstly, its wrong. But secondly, you should have gotten tired of typing this by now and made a function out of it.</p>\n\n<pre><code> if type(rv) is list:\n</code></pre>\n\n<p>Generally a better idea to check for types using <code>isinstance</code>, but even better to avoid checking types at all.</p>\n\n<pre><code> files = rv\n elif rv is False:\n</code></pre>\n\n<p>Check for false using <code>not rv</code></p>\n\n<pre><code> logging.info('each callback asked us to exit quietly')\n return\n</code></pre>\n\n<p>Throw exceptions, Python loves exceptions</p>\n\n<pre><code> elif rv is True:\n</code></pre>\n\n<p>Use <code>elif rv:</code></p>\n\n<pre><code> logging.info('finished each callback, proceeding with original file list')\n</code></pre>\n\n<p>I suggest returning None and checking for that here</p>\n\n<pre><code> else:\n raise TypeError('the each callback must return an array of file names or True')\n</code></pre>\n\n<p>In python, they are lists not arrays</p>\n\n<pre><code> if hasattr(callbacks, 'mode') and callbacks['mode'] is 'files_only':\n logging.info(\"files_only mode, no concat or post\")\n return\n with open(out, 'w') as outfile:\n for fname in files:\n with open(fname) as infile:\n for line in infile:\n outfile.write(line if not hasattr(callbacks, 'line') else callbacks['line'](line))\n logging.info(\"Wrote file: \" + out)\n if hasattr(callbacks, 'post') and callable(callbacks['post']):\n callbacks['post'](out)\n\n def compile(self):\n for out, props in self.file_set.iteritems():\n files = props['files']\n callbacks = props['callbacks']\n self._compile(files, callbacks, os.path.abspath(out))\n\n def FileSet(self, out = None, files = None, callbacks = {}):\n</code></pre>\n\n<p>Python cnvention resevers CamelCase for class names. Also, this should be <code>add_fileset</code></p>\n\n<pre><code> if type(files) is not list:\n raise TypeError('files list is a required argument')\n</code></pre>\n\n<p>If the parameter is required, why did you provide a default value! </p>\n\n<pre><code> if type(out) is not str:\n raise TypeError('out is a required argument')\n if hasattr(self.file_set, out):\n raise Exception('out file is already in use by another FileSet')\n</code></pre>\n\n<p>Again hasattr is incorrect here, you want <code>out in self.file_set</code></p>\n\n<pre><code> if out in files:\n raise Exception('cannot watch out file')\n self.file_set[out] = {'files' : files, 'callbacks' : callbacks}\n return out\n\n def MirrorSet(self, orig = None, new = None, addl = None):\n if type(orig) is not str:\n raise TypeError('orig list is a required argument')\n if type(new) is not str:\n raise TypeError('new is a required argument')\n</code></pre>\n\n<p>Again, don't provide defaults and then reject them. Python can do a perfectly good job of rejecting missing parameters. Also, don't check types. Document what the types are supposed to be, but let trust the user of your code.</p>\n\n<pre><code> try:\n files = copy.deepcopy(self.file_set[orig]['files'])\n</code></pre>\n\n<p>Why are you making a deepcopy?</p>\n\n<pre><code> skin_path = os.path.join(self.root, new)\n out = os.path.join(skin_path, orig)\n for i, filename in enumerate(files):\n filePath = os.path.join(skin_path, filename)\n if (os.path.exists(filePath)):\n files[i] = os.path.join(new, files[i])\n</code></pre>\n\n<p>Don't modify the list you are iterating over, create a new list.</p>\n\n<pre><code> if addl is not None and type(addl) is list:\n files.extend(addl)\n</code></pre>\n\n<p>Don't check types, and especially don't ignore incorrect types</p>\n\n<pre><code> self.file_set[out] = {'files' : files, 'callbacks' : self.file_set[orig]['callbacks']}\n except:\n raise\n</code></pre>\n\n<p>Don't catch an exception just to re-raise it.</p>\n\n<pre><code> def stop(self):\n self.observer.stop()\n\n def start(self):\n event_handler = ChangeHandler(self._on_file_changed)\n self.observer = Observer()\n self.observer.schedule(event_handler, self.root, recursive=True)\n self.observer.start()\n\n def __init__(self, root = None):\n if type(root) is not str:\n raise TypeError('root is required as argument in object instantation')\n</code></pre>\n\n<p>DON'T!</p>\n\n<pre><code> self.root = os.path.abspath(root)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T00:10:44.577",
"Id": "34780",
"Score": "0",
"body": "Thanks a million, Winston! I'm working on implementing these changes now :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T22:01:56.530",
"Id": "21641",
"ParentId": "21639",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "21641",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T19:41:10.277",
"Id": "21639",
"Score": "5",
"Tags": [
"python",
"beginner",
"file-system",
"modules",
"makefile"
],
"Title": "Monitor filesystem for continuous integration and build"
}
|
21639
|
<p>I wrote it more for educational reasons and less as something that can compete with existing alternatives. </p>
<p>But I enjoyed writing it and wish to get some feedback, JavaScript is my second language :)</p>
<p>(I hope the main issue is lack of comments, but I wonder if there is anything else hairy about the code)</p>
<p>Here is the main plugin code:</p>
<pre><code>(function ($) {
'use strict';
/*
* Base function for all transformations
*/
function base(property, transformer, params) {
var value = $.map(params, function (item, index) {
return transformer.call(this, item);
}).join(", ");
return this.each(function () {
var $this = $(this);
var existingTransformation = $this.css("transform");
if (existingTransformation === 'none') {
existingTransformation = '';
}
if (existingTransformation !== '') {
existingTransformation += ' ';
}
$this.css({
transform: existingTransformation + property + "(" + value + ")"
});
});
};
/*
* Numeric to string conversion internal helper functions
*/
function suffixNumber(param, suffix){
if (typeof param === "number") {
param += suffix;
}
return param;
};
function toDeg(param){
return suffixNumber(param, "deg");
}
function toPx(param){
return suffixNumber(param, "px");
}
function toPc(param){
return suffixNumber(param, "%");
}
function toStr(param){
return suffixNumber(param, "");
}
/*
* The plugin's outer world functions
*/
var functionParamTypes = {
number:toStr,
length:toPx,
angle:toDeg
}
var functionNames = [
{
"name":"matrix",
"type":functionParamTypes.length
},
{
"name":"translate",
"type": functionParamTypes.length
},
{
"name":"translateX",
"type": functionParamTypes.length
},
{
"name":"translateY",
"type": functionParamTypes.length
},
{
"name":"scale",
"type": functionParamTypes.number
},
{
"name":"scaleX",
"type": functionParamTypes.number
},
{
"name":"scaleY",
"type": functionParamTypes.number
},
{
"name":"rotate",
"type": functionParamTypes.angle
},
{
"name":"skew",
"type": functionParamTypes.angle
},
{
"name":"skewX",
"type": functionParamTypes.angle
},
{
"name":"skewY",
"type": functionParamTypes.angle
},
{
"name":"matrix3d",
"type": functionParamTypes.length
},
{
"name":"translate3d",
"type": functionParamTypes.length
},
{
"name":"translateZ",
"type": functionParamTypes.length
},
{
"name":"scale3d",
"type": functionParamTypes.length
},
{
"name":"scaleZ",
"type": functionParamTypes.length
},
{
"name":"rotate3d",
"type": functionParamTypes.angle
},
{
"name":"rotateX",
"type": functionParamTypes.angle
},
{
"name":"rotateY",
"type": functionParamTypes.angle
},
{
"name":"rotateZ",
"type": functionParamTypes.angle
},
{
"name":"perspective",
"type": functionParamTypes.angle
}
];
$.each(functionNames,function(index, item){
var name = item.name, type = item.type;
$.fn[name] = function () {
return base.call(this, name, type, arguments);
}
});
})(jQuery);
</code></pre>
<ul>
<li><p>Latest version can be found <a href="https://github.com/eranation/jquery-transform/blob/master/jquery.transform.js" rel="nofollow">here</a> </p></li>
<li><p>Live demo can be found <a href="http://htmlpreview.github.com/?https://raw.github.com/eranation/jquery-transform/master/demo/demo.html" rel="nofollow">here</a></p></li>
<li><p>Usage example can be found <a href="https://github.com/eranation/jquery-transform/blob/master/demo/js/demo.js" rel="nofollow">here</a></p></li>
</ul>
|
[] |
[
{
"body": "<p>I like the demo, from a once over:</p>\n\n<ul>\n<li><p>the functionNames make my eyes glaze over, data tables variables should be sorted and tabbed in my mind:</p>\n\n<pre><code> var functionNames = [ \n { name: \"matrix\", type: functionParamTypes.length}, \n { name: \"matrix3d\", type: functionParamTypes.length}, \n { name: \"perspective\", type: functionParamTypes.angle },\n { name: \"rotate\", type: functionParamTypes.angle }, \n { name: \"rotate3d\", type: functionParamTypes.angle }, \n { name: \"rotateX\", type: functionParamTypes.angle }, \n { name: \"rotateY\", type: functionParamTypes.angle }, \n { name: \"rotateZ\", type: functionParamTypes.angle },\n { name: \"scale\", type: functionParamTypes.number}, \n { name: \"scale3d\", type: functionParamTypes.length}, \n { name: \"scaleX\", type: functionParamTypes.number}, \n { name: \"scaleY\", type: functionParamTypes.number},\n { name: \"scaleZ\", type: functionParamTypes.length}, \n { name: \"skew\", type: functionParamTypes.angle }, \n { name: \"skewX\", type: functionParamTypes.angle }, \n { name: \"skewY\", type: functionParamTypes.angle }, \n { name: \"translate\", type: functionParamTypes.length}, \n { name: \"translate3d\", type: functionParamTypes.length}, \n { name: \"translateX\", type: functionParamTypes.length}, \n { name: \"translateY\", type: functionParamTypes.length}, \n { name: \"translateZ\", type: functionParamTypes.length} \n ]; \n</code></pre></li>\n<li><p>It is preferred to have 1 single comma-separated <code>var</code> statement:</p>\n\n<pre><code>var $this = $(this),\n existingTransformation = $this.css(\"transform\");\n</code></pre></li>\n<li>It is preferred to have either all single or all double quoted strings, I would suggest single quoted strings</li>\n<li>You have some missing and some unnecessary semicolons, please check out <a href=\"http://jshint.com/\" rel=\"nofollow\">http://jshint.com/</a></li>\n<li>Other than that, a fun piece of code</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T21:06:07.910",
"Id": "43742",
"ParentId": "21640",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "43742",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T19:59:57.717",
"Id": "21640",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"plugin"
],
"Title": "jQuery plugin for easy CSS3 transformation"
}
|
21640
|
<p>I've been writing a collection of signal processing function optimized with SSE intrinsics (mostly for audio processing). Here is a linear interpolation function I wrote. It works well and is quite fast (much better than straight lerp), but I'm using the full 8 registers available, and I'm wondering if there's something I'm not seeing that would improve its efficiency.</p>
<pre><code>void SSE_vInterpLinear (const float *sourceX, const float *sourceY, float *resultY, const int lengthX)
{
assert(lengthX % 4 == 0);
__m128 *mXphases = (__m128*)sourceX;
__m128 *mYresult = (__m128*)resultY;
__m128 mX0, mY0, mY1, mYtemp, mXtemp, mtemp;
__declspec(align(16)) float pos[4];
for (int i = 0; i < lengthX; i+=4) {
// floor the values in X to get indexing positions at X0, and add 1 for X1 index positions
mX0 = _mm_floor_ps(*mXphases);
_mm_store_ps(pos, mX0);
mY0 = _mm_set_ps(sourceY[(int)pos[3]], sourceY[(int)pos[2]], sourceY[(int)pos[1]], sourceY[(int)pos[0]]);
mY1 = _mm_set_ps(sourceY[(int)pos[3]+1], sourceY[(int)pos[2]+1], sourceY[(int)pos[1]+1], sourceY[(int)pos[0]+1]);
mYtemp = _mm_sub_ps(mY1, mY0);
mXtemp = _mm_sub_ps(*mXphases, mX0);
mtemp = _mm_mul_ps(mYtemp, mXtemp);
*mYresult = _mm_add_ps(mY0, mtemp);
mXphases++;
mYresult++;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T23:09:47.127",
"Id": "34778",
"Score": "0",
"body": "Chris, welcome to Code Review! Please format your code using spaces, not tabs, as the latter don't display properly (I've edited your question to fix that)."
}
] |
[
{
"body": "<p>One improvement would be to restrict the number of (random) memory accesses. First notice is that for each sourceY[fixed] there's also a memory read from sourceY[fixed+1];</p>\n\n<p>I believe these should be at least combined to single 64-bit memory accesses.</p>\n\n<p>A more crucial improvement would be at higher level: is the interpolation really random, or could the xvalues be say <em>localized</em> to say 8-15 successive indices? Then I'd pursuit for a technique that reads them to 2 or 4 xmm registers and tries to shuffle the values in place an in parallel.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T14:18:12.803",
"Id": "23268",
"ParentId": "21644",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-12T22:29:19.190",
"Id": "21644",
"Score": "3",
"Tags": [
"c++",
"assembly",
"sse"
],
"Title": "Trying to improve and better understand Intel SSE intrinsics"
}
|
21644
|
<p>This may be a poor title name. So I'm basing what I did <a href="http://forums.codeguru.com/showthread.php?231156-MFC-String-How-to-convert-between-a-CString-and-a-BSTR" rel="nofollow">from this website</a>.</p>
<p>The idea is though that I have made a lot of work to a Service Object for a OPOS MSR device. (useless detail) One of the DirectIO calls gets some data off of a card and was supposed to return a byte array. That ended up being a big mistake because Unicode and translating was just a big big <strong>BIG</strong> headache. So my suggestion was to just convert the byte array to a string in C++ then send fire a DirectIO event with said string and call it good. So I did that, and it appears to work. One thing that has me concerned though is one of the lines from that website</p>
<blockquote>
<p>The general rule to COM resource is, if you allocate it then you release it. The only exception is when a value is passed over a COM interface as an OUT param. In that case, the receiver of the value is responsible for releasing the resource</p>
</blockquote>
<p>but I'm rather proud of my code none the less. I'll post my SO code and my mock up OPOS code (a test for me to show it works)</p>
<pre><code>LONG ReaderHelper::ULCRead(LPVOID param)
{
BYTE* bTmp = new BYTE[4];
//a call to fill said bTmp with error checking and so forth
CString str;
for (int i = 0; i < 4; i++)
{
str.AppendFormat( _T("%02X"), bTmp[i]);
}
delete[] bTmp;
BSTR bstring = str.AllocSysString();
LONG data = str.GetLength();
USNMSRRFID* pso = (USNMSRRFID*)param;
COPOSMSR msr(pso->mlpDispatch);
msr.SODirectIO(0, &data, &bstring);
SysFreeString(bstring);
msr.ReleaseDispatch();
}
</code></pre>
<p><strong>MOCK UP OPOS</strong>
yes it is ugly, sorry</p>
<pre><code> void msr_DirectIOEvent(int EventNumber, ref int pData, ref string pString)
{
Console.WriteLine();
Console.WriteLine("\t\t<{0}><{1}><{2}>:Len:{4}<{3}>", EventNumber, pData,pString, GetHexBytes(pString), pString.Length);
Console.WriteLine();
}
string GetHexBytes(string str)
{
var bytes = System.Text.UnicodeEncoding.Unicode.GetBytes(str);
string strbytes = "";
foreach (byte b in bytes)
strbytes += string.Format("{0}:", b.ToString("X2"));
return strbytes;
}
</code></pre>
<p>yields me this</p>
<pre><code>2013-02-12.21:59:30 #Page:3#
2013-02-12.21:59:30 ULCRead(4)-00:00:00:00:
<0><8><00000000>:Len:8<30:00:30:00:30:00:30:00:30:00:30:00:30:00:30:00:>
2013-02-12.21:59:30 #Page:4#
2013-02-12.21:59:30 ULCRead(4)-9D:5A:AD:47:
<0><8><9D5AAD47>:Len:8<39:00:44:00:35:00:41:00:41:00:44:00:34:00:37:00:>
2013-02-12.21:59:30 #Page:5#
2013-02-12.21:59:30 ULCRead(4)-5D:E3:EC:93:
<0><8><5DE3EC93>:Len:8<35:00:44:00:45:00:33:00:45:00:43:00:39:00:33:00:>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T11:51:57.493",
"Id": "34795",
"Score": "0",
"body": "What exactly do you want reviewed? What should we look for?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T13:58:30.960",
"Id": "34804",
"Score": "0",
"body": "basically is ULCRead done properly? I'm getting the desired results... but how is it? Did I do it right? Did i miss any memory leaks? Did I release my COM object correctly?"
}
] |
[
{
"body": "<ol>\n<li>This <code>BYTE* bTmp = new BYTE[4];</code> could just be put on the stack with <code>BYTE bTmp[4];</code> (the proper term is actually automatic storage duration which in most cases means it ends up on the stack). This normally avoids a call to <code>malloc</code> and you don't have to delete it explicitly.</li>\n<li>I'm not too versed in COM programming but if <code>msr.SODirectIO(0, &data, &bstring);</code> could throw an exception you might want to wrap it into a <code>try {} finally {}</code> in order to ensure the cleanup of the <code>BSTR</code> and COM resource is done regardless.</li>\n<li><p>I know it's just a quick mockup but <code>GetHexBytes</code> could be reduced by using Linq:</p>\n\n<pre><code>string GetHexBytes(string str)\n{\n var bytes = System.Text.UnicodeEncoding.Unicode.GetBytes(str);\n var hexBytes = bytes.Select(b => b.ToString(\"X2\")).ToArray();\n return string.Join(\":\", hexBytes);\n}\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T09:01:49.567",
"Id": "35967",
"ParentId": "21649",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "35967",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T04:30:11.630",
"Id": "21649",
"Score": "5",
"Tags": [
"c#",
"c++"
],
"Title": "OPOS DirectIO event review"
}
|
21649
|
<p>I'm currently converting a CSS 960 fluid grid to SASS. How can I improve my current implementation? My column classes <code>.two.columns</code> are getting a bit unruly. Is there a better way to write them?</p>
<pre><code>// Variables
$width: 960px;
.container {
position: relative;
width: $width;
margin: 0 auto;
padding: 0;
.column, .columns {
float: left;
display: inline;
margin-left: 10px;
margin-right: 10px;
}
}
.row {
margin-bottom: 20px;
}
// Nested Column Classes
.column.alpha, .columns.alpha {
margin-left: 0;
}
.column.omega, .columns.omega {
margin-right: 0;
}
// 960 GRID
// (1 * (960 / 16)) - (2 * 10)
.container {
.one {
&.column, &.columns {
width: 40px;
}
}
.two.columns {
width: 100px;
}
.three.columns {
width: 160px;
}
.four.columns {
width: 220px;
}
.five.columns {
width: 280px;
}
.six.columns {
width: 340px;
}
.seven.columns {
width: 400px;
}
.eight.columns {
width: 460px;
}
.nine.columns {
width: 520px;
}
.ten.columns {
width: 580px;
}
.eleven.columns {
width: 640px;
}
.twelve.columns {
width: 700px;
}
.thirteen.columns {
width: 760px;
}
.fourteen.columns {
width: 820px;
}
.fifteen.columns {
width: 880px;
}
.sixteen.columns {
width: 940px;
}
.one-third.column {
width: 300px;
}
.two-thirds.column {
width: 620px;
}
.offset-by-one {
padding-left: 60px;
}
.offset-by-two {
padding-left: 120px;
}
.offset-by-three {
padding-left: 180px;
}
.offset-by-four {
padding-left: 240px;
}
.offset-by-five {
padding-left: 300px;
}
.offset-by-six {
padding-left: 360px;
}
.offset-by-seven {
padding-left: 420px;
}
.offset-by-eight {
padding-left: 480px;
}
.offset-by-nine {
padding-left: 540px;
}
.offset-by-ten {
padding-left: 600px;
}
.offset-by-eleven {
padding-left: 660px;
}
.offset-by-twelve {
padding-left: 720px;
}
.offset-by-thirteen {
padding-left: 780px;
}
.offset-by-fourteen {
padding-left: 840px;
}
.offset-by-fifteen {
padding-left: 900px;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T08:33:47.443",
"Id": "34788",
"Score": "0",
"body": "It's possible to write a loop that will generate those, using names such as \"column.8\" and \"offset-by-3\" (that is, 3 instead of three). I don't know SASS enough to write it myself though. This will make your code much shorter and your $width variable will become useful. :)"
}
] |
[
{
"body": "<p>You could use a for loop to have it generate the columns for you, like...</p>\n\n<pre><code>$grid-column: 16;\n$grid-gutter: 10px;\n$column-width: 50px;\n\n.column {\n position: relative;\n display: inline;\n float: left;\n margin-right: ($grid-gutter / 2);\n margin-left: ($grid-gutter / 2);\n}\n\n@for $n from 1 through $grid-column {\n .grid-#{$n} {\n @extend .column;\n width: ($column-width * $n) + ($grid-gutter * ($n - 1));\n }\n}\n\n@for $n from 1 through $grid-column - 1 {\n .offset-#{$n} {\n padding-left: ($column-width * $n) + ($grid-gutter * $n);\n }\n}\n</code></pre>\n\n<p>That would output</p>\n\n<pre><code>.column, .grid-1, .grid-2, .grid-3, .grid-4, .grid-5, .grid-6, .grid-7, .grid-8, .grid-9, .grid-10, .grid-11, .grid-12, .grid-13, .grid-14, .grid-15, .grid-16 {\n position: relative;\n display: inline;\n float: left;\n margin-right: 5px;\n margin-left: 5px;\n}\n\n.grid-1 {\n width: 50px;\n}\n\n.grid-2 {\n width: 110px;\n}\n\n.grid-3 {\n width: 170px;\n}\n\n.grid-4 {\n width: 230px;\n}\n\n.grid-5 {\n width: 290px;\n}\n\n.grid-6 {\n width: 350px;\n}\n\n.grid-7 {\n width: 410px;\n}\n\n.grid-8 {\n width: 470px;\n}\n\n.grid-9 {\n width: 530px;\n}\n\n.grid-10 {\n width: 590px;\n}\n\n.grid-11 {\n width: 650px;\n}\n\n.grid-12 {\n width: 710px;\n}\n\n.grid-13 {\n width: 770px;\n}\n\n.grid-14 {\n width: 830px;\n}\n\n.grid-15 {\n width: 890px;\n}\n\n.grid-16 {\n width: 950px;\n}\n\n.offset-1 {\n padding-left: 60px;\n}\n\n.offset-2 {\n padding-left: 120px;\n}\n\n.offset-3 {\n padding-left: 180px;\n}\n\n.offset-4 {\n padding-left: 240px;\n}\n\n.offset-5 {\n padding-left: 300px;\n}\n\n.offset-6 {\n padding-left: 360px;\n}\n\n.offset-7 {\n padding-left: 420px;\n}\n\n.offset-8 {\n padding-left: 480px;\n}\n\n.offset-9 {\n padding-left: 540px;\n}\n\n.offset-10 {\n padding-left: 600px;\n}\n\n.offset-11 {\n padding-left: 660px;\n}\n\n.offset-12 {\n padding-left: 720px;\n}\n\n.offset-13 {\n padding-left: 780px;\n}\n\n.offset-14 {\n padding-left: 840px;\n}\n\n.offset-15 {\n padding-left: 900px;\n}\n</code></pre>\n\n<p>etc..</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T23:34:47.360",
"Id": "34830",
"Score": "0",
"body": "Great answer - exactly what I was looking for thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T10:50:38.220",
"Id": "21656",
"ParentId": "21650",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "21656",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T04:54:56.220",
"Id": "21650",
"Score": "3",
"Tags": [
"sass"
],
"Title": "SASS 960 fluid grid"
}
|
21650
|
<p>I have an Apps Script that is supposed to run through the spreadsheet, and if a company belongs to a certain country (there's a country column), set the value of the region row to something (e.g. Africa).</p>
<p>The spreadsheet has more than 8500 rows and this is the dirty code I have. It's working, but if there's a better way to write it, I'd appreciate any pointers:</p>
<pre><code>function setRegions() {
var mySheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var myCompany = mySheet.getDataRange().getValues();
var start = 2;
for(i = 1; i < myCompany.length; i++){
var univ = myCompany[i];
var country_code = univ[4];
if (country_code == "ke" ||
country_code == "ng" ||
country_code == "ug" ||
country_code == "za" ||
country_code == "sn" ||
country_code == "gh") {
rgMyRange = mySheet.getRange("M" + start);
rgMyRange.setValue("AFRICA");
}else if (country_code == "eg" ||
country_code == "sa" ||
country_code == "ma"){
rgMyRange = mySheet.getRange("M" + start);
rgMyRange.setValue("MENA");
}else if (country_code == "br" ||
country_code == "ar" ||
country_code == "mx" ||
country_code == "pe" ||
country_code == "co"){
rgMyRange = mySheet.getRange("M" + start);
rgMyRange.setValue("LATAM");
}else if (country_code == "my" ||
country_code == "th" ||
country_code == "id" ||
country_code == "ph"){
rgMyRange = mySheet.getRange("M" + start);
rgMyRange.setValue("APAC");
}else if (country_code == "in") {
rgMyRange = mySheet.getRange("M" + start);
rgMyRange.setValue("IN");
}
start++;
}
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>TL;DR</strong> : My comments won't improve the performances much. Also, I've never used Apps Script.</p>\n\n<p>This being said, here what I did : I decided to change details to make your code more concise (removing variables used only once for instance).</p>\n\n<pre><code>function setRegions() {\n var mySheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();\n var myCompany = mySheet.getDataRange().getValues();\n for(i = 1, start = 2; i < myCompany.length; i++, start++){\n var country_code = myCompany[i][4];\n if (country_code == \"ke\" || \n country_code == \"ng\" || \n country_code == \"ug\" || \n country_code == \"za\" ||\n country_code == \"sn\" ||\n country_code == \"gh\") {\n mySheet.getRange(\"M\" + start).setValue(\"AFRICA\");\n }else if (country_code == \"eg\" ||\n country_code == \"sa\" ||\n country_code == \"ma\"){\n mySheet.getRange(\"M\" + start).setValue(\"MENA\");\n }else if (country_code == \"br\" ||\n country_code == \"ar\" ||\n country_code == \"mx\" ||\n country_code == \"pe\" ||\n country_code == \"co\"){\n mySheet.getRange(\"M\" + start).setValue(\"LATAM\");\n }else if (country_code == \"my\" ||\n country_code == \"th\" ||\n country_code == \"id\" ||\n country_code == \"ph\"){\n mySheet.getRange(\"M\" + start).setValue(\"APAC\");\n }else if (country_code == \"in\") {\n mySheet.getRange(\"M\" + start).setValue(\"IN\");\n }\n }\n }\n</code></pre>\n\n<p>Then, you can get rid of the different tests on the country_code by storing what you want in a dictionary :</p>\n\n<pre><code>function setRegions() {\n var dict = {\n \"ke\" : \"AFRICA\",\n \"ng\" : \"AFRICA\",\n \"ug\" : \"AFRICA\",\n \"za\" : \"AFRICA\",\n \"sn\" : \"AFRICA\",\n \"gh\" : \"AFRICA\",\n \"eg\" : \"MENA\",\n \"sa\" : \"MENA\",\n \"ma\" : \"MENA\",\n \"br\" : \"LATAM\",\n \"ar\" : \"LATAM\",\n \"mx\" : \"LATAM\",\n \"pe\" : \"LATAM\",\n \"co\" : \"LATAM\",\n \"my\" : \"APAC\",\n \"th\" : \"APAC\",\n \"id\" : \"APAC\",\n \"ph\" : \"APAC\",\n \"in\" : \"IN\",\n };\n var mySheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();\n var myCompany = mySheet.getDataRange().getValues();\n for(i = 1, start = 2; i < myCompany.length; i++, start++){\n var country_code = myCompany[i][4];\n if (dict[country_code])\n {\n mySheet.getRange(\"M\" + start).setValue(dict[country_code]);\n }\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T12:19:43.953",
"Id": "34799",
"Score": "0",
"body": "Apps Script implements Dicts like this:\n\n var dict = {\n \"ke\" : \"AFRICA\",\n \"ng\" : \"AFRICA\",\n \"ug\" : \"AFRICA\",\n \"za\" : \"AFRICA\",\n \"sn\" : \"AFRICA\",\n \"gh\" : \"AFRICA\",\n \"eg\" : \"MENA\",\n \"sa\" : \"MENA\",\n \"ma\" : \"MENA\",\n \"br\" : \"LATAM\",\n \"ar\" : \"LATAM\",\n \"mx\" : \"LATAM\",\n \"pe\" : \"LATAM\",\n \"co\" : \"LATAM\",\n \"my\" : \"APAC\",\n \"th\" : \"APAC\",\n \"id\" : \"APAC\",\n \"ph\" : \"APAC\",\n \"in\" : \"IN\",\n };"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T12:27:52.690",
"Id": "34800",
"Score": "0",
"body": "+Josay your code works like a charm, I'm going to run it on the 8000 records spreadsheet and see how it performs"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T22:29:42.330",
"Id": "34827",
"Score": "0",
"body": "Glad you like it. I've updated my code to take your comment into account. Not sure if perf will be better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T06:46:22.200",
"Id": "34933",
"Score": "0",
"body": "Keeping the code at array level should speed things up, rather than run the setValue within the loop. I'm modifying it to see if it's going to perform better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T07:44:05.430",
"Id": "34934",
"Score": "0",
"body": "Not quite sure what the bottleneck is here."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T10:40:32.980",
"Id": "21655",
"ParentId": "21654",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "21655",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T09:38:22.983",
"Id": "21654",
"Score": "2",
"Tags": [
"google-apps-script"
],
"Title": "Script for recording a country in which a company belongs"
}
|
21654
|
<p>I have a web scraping application that contains long string literals for the URLs. What would be the best way to present them (keeping in mind that I would like to adhere to <a href="http://www.python.org/dev/peps/pep-0008/#maximum-line-length" rel="nofollow">PEP-8</a>.</p>
<pre><code>URL = "https://www.targetwebsite.co.foo/bar-app/abc/hello/world/AndThen?whatever=123&this=456&theother=789&youget=the_idea"
br = mechanize.Browser()
br.open(URL)
</code></pre>
<p>I had thought to do this:</p>
<pre><code>URL_BASE = "https://www.targetwebsite.co.foo/"
URL_SUFFIX = "bar-app/abc/hello/world/AndThen"
URL_ARGUMENTS = "?whatever=123&this=456&theother=789&youget=the_idea"
br = mechanize.Browser()
br.open(URL_BASE + URL_SUFFIX + URL_ARGUMENTS)
</code></pre>
<p>But there are many lines and it's not a standard way of representing a URL.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T14:25:55.910",
"Id": "96329",
"Score": "1",
"body": "I would put the URLS in a config file, or take them as a parameter."
}
] |
[
{
"body": "<p>You could use continuation lines with <code>\\</code>, but it messes the indentation:</p>\n\n<pre><code>URL = 'https://www.targetwebsite.co.foo/\\\nbar-app/abc/hello/world/AndThen\\\n?whatever=123&this=456&theother=789&youget=the_idea'\n</code></pre>\n\n<p>Or you could use the fact that string literals next to each other are automatically concatenated, in either of these two forms:</p>\n\n<pre><code>URL = ('https://www.targetwebsite.co.foo/'\n 'bar-app/abc/hello/world/AndThen'\n '?whatever=123&this=456&theother=789&youget=the_idea')\n\nURL = 'https://www.targetwebsite.co.foo/' \\\n 'bar-app/abc/hello/world/AndThen' \\\n '?whatever=123&this=456&theother=789&youget=the_idea'\n</code></pre>\n\n<p>I often use the parenthesized version, but the backslashed one probably looks cleaner.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T14:23:01.137",
"Id": "21660",
"ParentId": "21658",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T12:57:03.020",
"Id": "21658",
"Score": "5",
"Tags": [
"python",
"url"
],
"Title": "Presenting long string literals (URLs) in Python"
}
|
21658
|
<p>This is a Python module I have just finished writing which I plan to use at Project Euler. Please let me know how I have done and what I could do to improve it.</p>
<pre><code># This constant is more or less an overestimate for the range in which
# n primes exist. Generally 100 primes exist well within 100 * CONST numbers.
CONST = 20
def primeEval(limit):
''' This function yields primes using the
Sieve of Eratosthenes.
'''
if limit:
opRange = [True] * limit
opRange[0] = opRange[1] = False
for (ind, primeCheck) in enumerate(opRange):
if primeCheck:
yield ind
for i in range(ind*ind, limit, ind):
opRange[i] = False
def listToNthPrime(termin):
''' Returns a list of primes up to the nth
prime.
'''
primeList = []
for i in primeEval(termin * CONST):
primeList.append(i)
if len(primeList) >= termin:
break
return primeList
def nthPrime(termin):
''' Returns the value of the nth prime.
'''
primeList = []
for i in primeEval(termin * CONST):
primeList.append(i)
if len(primeList) >= termin:
break
return primeList[-1]
def listToN(termin):
''' Returns a list of primes up to the
number termin.
'''
return list(primeEval(termin))
def lastToN(termin):
''' Returns the prime which is both less than n
and nearest to n.
'''
return list(primeEval(termin))[-1]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T08:24:01.633",
"Id": "34936",
"Score": "0",
"body": "It is a good idea to always follow PEP-0008 style guidolines: http://www.python.org/dev/peps/pep-0008/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-03T13:04:28.620",
"Id": "161558",
"Score": "0",
"body": "See [this answer](http://codereview.stackexchange.com/a/42439/11728)."
}
] |
[
{
"body": "<p>General programming issues (non-Python specific):</p>\n\n<ul>\n<li><p><strong>Avoiding duplicated code:</strong> <code>listToNthPrime()</code> and <code>nthPrime()</code> are identical beside the indexing. The later could be changed to <code>def nthprime(termin): return listToNthPrime(termin)[-1]</code>. But it can be argued if such a function is needed anyway, because indexing the first or last element of lists is such a basic usage that usually no further abstraction is necessary. So you could just replace you calls to <code>nthPrime()</code> by <code>listToNthPrime()[-1]</code>. The same is obviously also valid for <code>listToN()</code> and <code>lastToN()</code> in both senses. In fact you can just omit these functions.</p></li>\n<li><p><strong>Naming:</strong> all identifier names should catch its purpose according to the abstraction level as precise they can (resulting clunky names are usually showing a need to refactor / change the abstraction). In that sense the name <code>primeEval</code> could be improved. \"Eval\" often is just too general to be really meaningful. <code>iterPrimes()</code> will work. Further it makes it clear that it is no list.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T20:57:45.093",
"Id": "21677",
"ParentId": "21659",
"Score": "1"
}
},
{
"body": "<pre><code># This constant is more or less an overestimate for the range in which\n# n primes exist. Generally 100 primes exist well within 100 * CONST numbers.\nCONST = 20\n\ndef primeEval(limit):\n</code></pre>\n\n<p>Python convention says that functions should named lowercase_with_underscores</p>\n\n<pre><code> ''' This function yields primes using the\n Sieve of Eratosthenes.\n\n '''\n if limit:\n</code></pre>\n\n<p>What is this for? You could be trying to avoid erroring out when limit=0, but it seems to me that you still error at for limit=1.</p>\n\n<pre><code> opRange = [True] * limit\n</code></pre>\n\n<p>As with functions, lowercase_with_underscore</p>\n\n<pre><code> opRange[0] = opRange[1] = False\n\n for (ind, primeCheck) in enumerate(opRange):\n</code></pre>\n\n<p>You don't need the parens around <code>ind, primeCheck</code></p>\n\n<pre><code> if primeCheck:\n yield ind\n for i in range(ind*ind, limit, ind):\n opRange[i] = False\n\n\ndef listToNthPrime(termin):\n ''' Returns a list of primes up to the nth\n prime.\n '''\n primeList = []\n for i in primeEval(termin * CONST):\n primeList.append(i)\n if len(primeList) >= termin:\n break\n return primeList\n</code></pre>\n\n<p>You are actually probably losing out by attempting to stop the generator once you pass the number you wanted. You could write this as:</p>\n\n<pre><code> return list(primeEval(termin * CONST))[:termin]\n</code></pre>\n\n<p>Chances are that you gain more by having the loop be in the loop function than you gain by stopping early. </p>\n\n<pre><code>def nthPrime(termin):\n ''' Returns the value of the nth prime.\n\n '''\n primeList = []\n for i in primeEval(termin * CONST):\n primeList.append(i)\n if len(primeList) >= termin:\n break\n return primeList[-1]\n\ndef listToN(termin):\n ''' Returns a list of primes up to the\n number termin.\n '''\n return list(primeEval(termin))\n\ndef lastToN(termin):\n ''' Returns the prime which is both less than n\n and nearest to n.\n\n '''\n return list(primeEval(termin))[-1]\n</code></pre>\n\n<p>All of your functions will recalculate all the primes. For any sort of practical use you'll want to avoid that and keep the primes you've calculated.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T23:39:43.093",
"Id": "34831",
"Score": "0",
"body": "Are you suggesting that I just omit the loop within the functions nthPrime and listToNthPrime, or that I change the function primeEval to include a parameter which will allow it to terminate early? I just tested the calling functions without the loop. I was surprised the loop provides only 3% increase in speed. Also, what do you mean by \"keep primes you've calculated\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T23:43:04.793",
"Id": "34832",
"Score": "0",
"body": "@JackJ, I'm suggesting you omit the loop. By keeping the primes, I mean that you should run sieve of erasthones once to find all the primes you need and use that data over and over again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T00:57:53.387",
"Id": "34837",
"Score": "0",
"body": "@JackJ, store it in a variable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T00:58:23.293",
"Id": "34838",
"Score": "0",
"body": "Sorry, but how would I reuse that data? By saving the output of the sieve to a file? Also, is the reason for omitting the loop to increase readability?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T22:51:07.823",
"Id": "21682",
"ParentId": "21659",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T13:38:43.503",
"Id": "21659",
"Score": "3",
"Tags": [
"python",
"programming-challenge",
"primes"
],
"Title": "Project Euler: primes in Python"
}
|
21659
|
<p>The code does seem a bit repetitive in places such as the <code>parenturlscraper</code> module and the <code>childurlscraper</code> module.</p>
<p>Does anyone have any recommendations for improving my code and condensing it a little?</p>
<p>In essence, the code scrapes <a href="http://planecrashinfo.com/database.htm" rel="nofollow">this site</a> and populates a table with details about each crash, geocoding the location data extracted from the site using Google.</p>
<pre><code>__version__ = '0.1'
__author__ = 'antmancoder'
# Importing of modules required for the script to run successfully
import scraperwiki
import lxml.html
import urlparse
import urllib2
import dateutil.parser
from geopy import geocoders
# Introduction of various global variables required throughout the running of the code
urlstem = "http://planecrashinfo.com"
urlyeardb = "database.htm"
yearsource = urlparse.urljoin(urlstem, urlyeardb)
yearlist = []
sourcepageurl = []
def parenturlscraper():
"""Function scrapes all of the parent URLs from 'planecrashinfo.com/database'"""
html = scraperwiki.scrape(yearsource)
root = lxml.html.fromstring(html)
hrefs = root.cssselect('td a')
for href in hrefs:
link = href.attrib['href']
url = urlparse.urljoin(urlstem, link)
yearlist.append(url)
def childurlscraper():
"""Function scrapes all of the child URLs from those scraped in the parenturlscraper module"""
for url in yearlist:
html = scraperwiki.scrape(url)
root = lxml.html.fromstring(html)
hrefs = root.cssselect('td a')
url = url[0:34]
for href in hrefs:
linkurl = href.attrib['href']
url = urlparse.urljoin(url, linkurl)
sourcepageurl.append(url)
def sourcepagescraper():
"""Function scrapes respective data for each accident and placed it into DB"""
for url in sourcepageurl:
try:
html = scraperwiki.scrape(url)
root = lxml.html.fromstring(html)
for tr in root.cssselect("body"):
tds = tr.cssselect("td")
location = coorlookup(tds[7].text_content())
for td in tds:
crashinfo = {}
crashinfo['url'] = url
crashinfo['date'] = dateutil.parser.parse(tds[3].text_content()).date()
crashinfo['time'] = tds[5].text_content()
crashinfo['location'] = tds[7].text_content()
crashinfo['latitude'] = location[1][0]
crashinfo['longitude'] = location[1][1]
crashinfo['operator'] = tds[9].text_content()
crashinfo['flight no'] = tds[11].text_content()
crashinfo['route'] = tds[13].text_content()
crashinfo['aircraft type'] = tds[15].text_content()
crashinfo['registration'] = tds[17].text_content()
crashinfo['cn ln'] = tds[19].text_content()
crashinfo['aboard'] = tds[21].text_content()
crashinfo['fatalities'] = tds[23].text_content()
crashinfo['ground'] = tds[25].text_content()
crashinfo['summary'] = tds[27].text_content()
scraperwiki.sqlite.save(unique_keys=['url'], data=crashinfo)
except urllib2.HTTPError, err:
if err.code == 404:
continue
def coorlookup(location):
"""Function is called from the 'sourcepagescraper' function to geolocate locations listed on website for each accident"""
g = geocoders.Google()
try:
loc = g.geocode(location, exactly_one=True)
return loc
except:
return ("",("",""))
parenturlscraper()
childurlscraper()
sourcepagescraper()
</code></pre>
|
[] |
[
{
"body": "<pre><code>__version__ = '0.1'\n__author__ = 'antmancoder'\n\n# Importing of modules required for the script to run successfully\n</code></pre>\n\n<p>Comments should be used for the non-obvious parts of your code. Explaining that we have imports is obvious. It doesn't need a comment.</p>\n\n<pre><code>import scraperwiki\nimport lxml.html\nimport urlparse\nimport urllib2\nimport dateutil.parser\nfrom geopy import geocoders\n\n# Introduction of various global variables required throughout the running of the code\nurlstem = \"http://planecrashinfo.com\"\nurlyeardb = \"database.htm\"\n</code></pre>\n\n<p>Global constants should be in ALL_CAPS, by convention</p>\n\n<pre><code>yearsource = urlparse.urljoin(urlstem, urlyeardb)\nyearlist = []\nsourcepageurl = []\n</code></pre>\n\n<p>You shouldn't have global variables. It is better to return and pass parameters.</p>\n\n<pre><code>def parenturlscraper():\n \"\"\"Function scrapes all of the parent URLs from 'planecrashinfo.com/database'\"\"\"\n html = scraperwiki.scrape(yearsource)\n root = lxml.html.fromstring(html)\n\n hrefs = root.cssselect('td a')\n\n for href in hrefs:\n link = href.attrib['href']\n url = urlparse.urljoin(urlstem, link)\n yearlist.append(url)\n</code></pre>\n\n<p>Instead of appending to a global variable, you should append them into a local list and <code>return</code> it. </p>\n\n<pre><code>def childurlscraper():\n \"\"\"Function scrapes all of the child URLs from those scraped in the parenturlscraper module\"\"\"\n for url in yearlist:\n html = scraperwiki.scrape(url)\n root = lxml.html.fromstring(html)\n</code></pre>\n\n<p>Just did this, you should write a function that that combines the above two lines</p>\n\n<pre><code> hrefs = root.cssselect('td a')\n url = url[0:34]\n</code></pre>\n\n<p>Why? This is a good place to have a comment explaining why you just did that.</p>\n\n<pre><code> for href in hrefs:\n linkurl = href.attrib['href']\n url = urlparse.urljoin(url, linkurl)\n</code></pre>\n\n<p>You should store in child_url. As it is you are reusing the variable from before. Your code will actually reeatedly join the elements onto each other. So I'm pretty sure that's not what you wanted.</p>\n\n<pre><code> sourcepageurl.append(url)\n</code></pre>\n\n<p>Again, append onto a local list, and then return that.</p>\n\n<pre><code>def sourcepagescraper(): \n \"\"\"Function scrapes respective data for each accident and placed it into DB\"\"\"\n for url in sourcepageurl:\n try: \n html = scraperwiki.scrape(url)\n root = lxml.html.fromstring(html)\n for tr in root.cssselect(\"body\"):\n</code></pre>\n\n<p>Okay, you call it <code>tr</code> but its actually the body. Also, isn't there only ever one body? Do you really need a lloop?</p>\n\n<pre><code> tds = tr.cssselect(\"td\")\n location = coorlookup(tds[7].text_content())\n for td in tds:\n</code></pre>\n\n<p>This doesn't seem right. You wnat to iterate over each cell? But then you look at all the cells to fetch the data.</p>\n\n<pre><code> crashinfo = {}\n crashinfo['url'] = url\n crashinfo['date'] = dateutil.parser.parse(tds[3].text_content()).date()\n crashinfo['time'] = tds[5].text_content()\n crashinfo['location'] = tds[7].text_content()\n crashinfo['latitude'] = location[1][0]\n crashinfo['longitude'] = location[1][1]\n crashinfo['operator'] = tds[9].text_content()\n crashinfo['flight no'] = tds[11].text_content()\n crashinfo['route'] = tds[13].text_content()\n crashinfo['aircraft type'] = tds[15].text_content()\n crashinfo['registration'] = tds[17].text_content()\n crashinfo['cn ln'] = tds[19].text_content()\n crashinfo['aboard'] = tds[21].text_content()\n crashinfo['fatalities'] = tds[23].text_content()\n crashinfo['ground'] = tds[25].text_content()\n crashinfo['summary'] = tds[27].text_content()\n</code></pre>\n\n<p>You can use something like:</p>\n\n<pre><code>crashinfo = {\n 'url' : url,\n 'date' : dateutil.parser.parse(tds[3].text_content())).date()\n ...\n}\n</code></pre>\n\n<p>which will probably be a bit better. Also, I'd avoid reference the cells by the index. That'll break if new cells are added. Are there classes on the cells you can use? I'd also probably make a big list like:</p>\n\n<pre><code>DATA = [\n ('time', 5),\n ('operator', 9)\n]\n</code></pre>\n\n<p>And then loop over the list to fill in the dict. </p>\n\n<pre><code> scraperwiki.sqlite.save(unique_keys=['url'], data=crashinfo)\n except urllib2.HTTPError, err:\n if err.code == 404:\n continue\n</code></pre>\n\n<p>Firstly, you want to put as little as possible in the try block. This is helped by the fact that python has an else block. Everything after <code>.scrape</code> should be in the else block. But the error handling also is a bit off. I think you want to ignore scrapings when the page cannot be found. But you should really reraise the exception when its not that. As it stands, you ignore it. Also, continue is exactly the same as pass here.</p>\n\n<pre><code>def coorlookup(location):\n \"\"\"Function is called from the 'sourcepagescraper' function to geolocate locations listed on website for each accident\"\"\"\n g = geocoders.Google()\n</code></pre>\n\n<p>Avoid single letter variables names, they are harder to follow</p>\n\n<pre><code> try:\n loc = g.geocode(location, exactly_one=True)\n return loc\n</code></pre>\n\n<p>Combine those two lines</p>\n\n<pre><code> except:\n</code></pre>\n\n<p>Don't ever (well almost ever) use bare excepts. Catch the specif error you want to handle.\n return (\"\",(\"\",\"\"))</p>\n\n<pre><code>parenturlscraper()\nchildurlscraper()\nsourcepagescraper()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T16:35:49.423",
"Id": "21670",
"ParentId": "21663",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T14:36:39.040",
"Id": "21663",
"Score": "1",
"Tags": [
"python",
"url",
"web-scraping"
],
"Title": "URL and source page scraper"
}
|
21663
|
<p>I have to define a lot of values for a Python library, each of which will represent a statistical distribution (like the Normal distribution or Uniform distribution). They will contain describing features of the distribution (like the mean, variance, etc). After a distribution is created it doesn't really make sense to change it.</p>
<p>I also expect other users to make their own distributions, simplicity is an extra virtue here.</p>
<p>Scala has really nice syntax for classes in cases like this. Python seems less elegant, and I'd like to do better. </p>
<p>Scala:</p>
<pre><code>class Uniform(min : Double, max : Double) {
def logp(x : Double) : Double =
1/(max - min) * between(x, min, max)
def mean = (max + min)/2
}
</code></pre>
<p>Python:</p>
<pre><code>class Uniform(object):
def __init__(self, min, max):
self.min = min
self.max = max
self.expectation = (max + min)/2
def logp(self, x):
return 1/(self.max - self.min) * between(x, self.min, self.max)
</code></pre>
<p>It's not <em>terrible</em>, but it's not great. There are a lot of extra <code>self</code>s in there and the constructor part seems pretty boilerplate.</p>
<p>One possibility is the following nonstandard idiom, a function which returns a dictionary of locals:</p>
<pre><code>def Uniform(min, max):
def logp(x):
return 1/(max - min) * between(x, min, max)
mean = (max + min)/2
return locals()
</code></pre>
<p>I like this quite a bit, but does it have serious drawbacks that aren't obvious?</p>
<p>It returns a dict instead of an object, but that's good enough for my purposes and <a href="https://stackoverflow.com/questions/1305532/convert-python-dict-to-object">would be easy to fix with a that made it return an object</a>.</p>
<p>Is there anything better than this? Are there serious problems with this?</p>
|
[] |
[
{
"body": "<p>I'm not sure how Pythonic this is, but how about something like this:</p>\n\n<pre><code>class DynaObject(object):\n def __init__(self, *args, **kwargs):\n for (name, value) in kwargs.iteritems():\n self.__setattr__(name, value)\n\nclass Uniform(DynaObject):\n __slots__ = [\"min\", \"max\"]\n\n def logp(self, x): \n return 1/(self.max - self.min) * between(x, self.min, self.max)\n\n def mean(self): return (self.max + self.min)/2\n</code></pre>\n\n<p>You would then construct a <code>Uniform</code> object like:</p>\n\n<pre><code>u = Uniform(min=1, max=2)\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Since answering I saw a <a href=\"http://www.reddit.com/r/programming/comments/18pg2w/a_python_function_decorator_that_automatically/\" rel=\"nofollow\">post on Reddit</a> for a <a href=\"https://github.com/nu11ptr/PyInstanceVars\" rel=\"nofollow\">GitHub project</a> that offers a similar solution using a function decorator instead of sub-classing. It would allow you to have a class like:</p>\n\n<pre><code>class Uniform(object):\n @instancevars\n def __init__(self, min, max): \n pass\n\n def logp(self, x): \n return 1/(self.max - self.min) * between(x, self.min, self.max)\n\n @property\n def mean(self): return (self.max + self.min)/2\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T06:18:14.087",
"Id": "34812",
"Score": "0",
"body": "Recommendation: Use `@property` before `mean` so that `mean` acts like a (read-only) property."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T06:11:40.623",
"Id": "21667",
"ParentId": "21666",
"Score": "6"
}
},
{
"body": "<p>You might prefer to use <a href=\"http://docs.python.org/2/library/collections.html#collections.namedtuple\" rel=\"nofollow noreferrer\"><code>namedtuple</code></a> for the attributes, and the <a href=\"http://docs.python.org/2/library/functions.html#property\" rel=\"nofollow noreferrer\"><code>property</code></a> decorator for <code>mean</code>. Note that <code>mean</code> is now computed every time it's accessed - maybe you don't want this, or maybe it makes sense since <code>max</code> and <code>min</code> are mutable.</p>\n\n<pre><code>from collections import namedtuple\n\nclass Uniform(namedtuple('Uniform', ('min', 'max'))):\n\n def logp(self, x):\n return 1/(self.max - self.min) * between(x, self.min, self.max)\n\n @property\n def mean(self):\n return 0.5*(self.min + self.max)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T17:17:47.343",
"Id": "82630",
"Score": "1",
"body": "+1 but it's nicer to pass in the field names as a list of names though, not as a space separated string :) in fact I don't even know why the latter \"syntax\" is allowed in Python in the first place."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-02-13T06:18:37.220",
"Id": "21668",
"ParentId": "21666",
"Score": "9"
}
},
{
"body": "<p>This mostly comes down to a difference of style. Python really prefers explicit rather than implicit, hence explicit <code>self</code>, assignment in <code>__init__</code>, etc. It will never support a syntax like you see in Scala. This is the same reason <code>locals()</code> isn't much liked in Python--it is implicit state rather than explicit parseable syntax.</p>\n\n<p>Getting your <code>def mean</code> behavior is easy with the <code>@property</code> decorator, however. That's a non-issue. I'll focus on the initialization and implicit <code>self</code>.</p>\n\n<p>The drawbacks of your approach are that it is non-standard, it is less explicit about <code>self</code>, and the object it creates lacks a normal class. We can make it look more standard, though. The namedtuple approach from @detly is perfect if you want to make an immutable object. If you need mutable objects or a more complex initialization signature, you can use a class decorator that wraps the <code>__init__</code> call with a function that updates the instance dictionary. This is made really easy by <a href=\"http://docs.python.org/2/library/inspect.html#inspect.getcallargs\"><code>inspect.getcallargs</code></a>.</p>\n\n<pre><code>import inspect\n\ndef implicit_init(cls):\n def pass_(self):\n pass\n original_init = getattr(cls, '__init__', pass_)\n def assigning_init(self, *args, **kwds):\n # None stands in place of \"self\"\n callargs = inspect.getcallargs(original_init, None, *args, **kwds)\n self.__dict__.update(callargs)\n original_init(self, *args, **kwds)\n\n cls.__init__ = assigning_init\n\n return cls\n\n\n@implicit_init\nclass Uniform(object):\n # an init is still necessary for the creation signature\n # you can \n def __init__(self, min, max):\n # you can put stuff here, too.\n # self.min etc will already be set\n pass\n\n @property #makes readonly\n def mean(self):\n return (self.max + self.min) / 2\n\n def logp(self, x):\n return 1/(self.max - self.min) * between(x, self.min, self.max)\n</code></pre>\n\n<p>Notice there is still a bunch of <code>self</code>s in there. Python style <em>really</em> likes those, so I recommend you go no further. If you really want to get rid of them, you have to be a little ugly. The problem is that your approach conflates class creation with instance creation, approaching a prototype-style. It is not possible (without reading internal details of function objects and bytecode) to know which vars are class vars and which are instance vars. Python has support for <em>class</em> metaprogramming because there are various metaclass hooks where one can customize class creation and where the class namespace is separated neatly into its name, bases and dict (see the three-argument form of <a href=\"http://docs.python.org/2/library/functions.html#type\"><code>type()</code></a>). But it's not easy to do the same for <em>functions</em>.</p>\n\n<p>We can get around this by <em>delaying initialization of the class</em> (i.e., dynamically modifying the class) until right before the first instance is created. (I'm not going to write this because it's quite an involved bit of code, but it requires a decorator.) You might also be able to come up with a semantic you like by inspecting the <code>Uniform</code> function's code object and building a class dynamically from there.</p>\n\n<pre><code>>>> def Uniform(min, max):\n... def logp(x):\n... return 1/(max-min) * between(x,min,max)\n... mean = (max+min)/2\n... return locals()\n... \n>>> uco = Uniform.func_code\n>>> uco.co_varnames\n('min', 'max', 'logp', 'mean')\n>>> uco.co_consts\n(None, <code object logp at 0x108f8a1b0, file \"<stdin>\", line 2>, 2)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T10:34:56.420",
"Id": "21669",
"ParentId": "21666",
"Score": "6"
}
},
{
"body": "<p>It is possible with Python 3.5+ to pass the variable types for type hints, too. This makes it even more similar to a Scala CaseClass:</p>\n\n<pre><code>import typing\nclass Uniform(typing.NamedTuple(\"GenUniform\",[('min',float),('max',float)])):\n def logp(self, x: float) -> float:\n return 1/(max - min) * between(x, min, max)\np1 = Uniform(**{'min': 0.5, 'max': 1.0})\np2 = Uniform(min=0.2, max=0.3)\np3 = Uniform(0.1, 0.2)\n</code></pre>\n\n<p>See following answer for reference:\n<a href=\"https://stackoverflow.com/a/34269877/776847\">https://stackoverflow.com/a/34269877/776847</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-31T15:15:02.803",
"Id": "262357",
"Score": "0",
"body": "I'm not very good with python and I don't know scala at all, but how does this help the original code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-31T15:39:57.000",
"Id": "262371",
"Score": "0",
"body": "I added a function. Does it make more sense? The additional value lies in code hinting and typisation respectively."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-31T12:19:27.383",
"Id": "140114",
"ParentId": "21666",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T05:55:06.033",
"Id": "21666",
"Score": "10",
"Tags": [
"python",
"scala"
],
"Title": "Scala inspired classes in Python"
}
|
21666
|
<p>Basically, I did an object (using hibernate) with a field called sorting_order. This field needs to be unique and I wish to swap two object by one. So one element has to be after or before the current element to be able to move. My object can only move by one up or down. I came up with this code, but I was wondering if there was a better way to do this. </p>
<p>Thank you!</p>
<pre><code>/**
* Move two personal task macro
*
* @param userProfileModel - The {@link UserProfileModel}.
* @param move - true = up or false = down.
*/
private void movePersonnalTaskMacro(UserProfileModel userProfileModel, boolean move) {
Assert.notNull(userProfileModel, "userProfileModel required.");
logger.info("Preparing to move a personnal task macro.");
PersonnalTaskMacro selectedPersonnalTaskMacro = userProfileModel.getSelectedPersonnalTaskMacro();
/* Initialize sorting order (increment/decrement) */
int selectedPersonnalTaskMacroSortOrder = selectedPersonnalTaskMacro.getSortingOrder();
int nextPersonnalTaskMacroSortOrder = selectedPersonnalTaskMacroSortOrder + 1;
int previousPersonnalTaskMacroSortOrder = selectedPersonnalTaskMacroSortOrder - 1;
/* Condition validation */
int personnalTaskMacroListSize = userProfileModel.getPersonnalTaskMacroList().size();
int selectedPersonnalTaskMacroIndex = userProfileModel.getPersonnalTaskMacroList().indexOf(
selectedPersonnalTaskMacro);
if (personnalTaskMacroListSize > 1) {
if (move == false && selectedPersonnalTaskMacroIndex >= 1) {
int previousPersonnalTaskMacroIndex = selectedPersonnalTaskMacroIndex - 1;
PersonnalTaskMacro previousPersonnalTaskMacro = userProfileModel.getPersonnalTaskMacroList().get(
previousPersonnalTaskMacroIndex);
previousPersonnalTaskMacro.setSortingOrder(selectedPersonnalTaskMacroSortOrder);
selectedPersonnalTaskMacro.setSortingOrder(previousPersonnalTaskMacroSortOrder);
logger.info("Moved the selected personnal task macro down by one");
}
if (move == true && nextPersonnalTaskMacroSortOrder <= personnalTaskMacroListSize) {
int nextPersonnalTaskMacroIndex = selectedPersonnalTaskMacroIndex + 1;
PersonnalTaskMacro nextPersonnalTaskMacro = userProfileModel.getPersonnalTaskMacroList().get(
nextPersonnalTaskMacroIndex);
nextPersonnalTaskMacro.setSortingOrder(selectedPersonnalTaskMacroSortOrder);
selectedPersonnalTaskMacro.setSortingOrder(nextPersonnalTaskMacroSortOrder);
logger.info("Moved the selected personnal task macro up by one");
}
Collections.sort(userProfileModel.getPersonnalTaskMacroList());
}
}
</code></pre>
|
[] |
[
{
"body": "<p>My thoughts in somewhat random order</p>\n\n<ul>\n<li><p>A boolean that indicates up/down could be improved with public 2 constants in your class UP = 0, DOWN = 1, and then the caller uses either constant. Or even better, use and ENUM as mentioned by cl-r.</p></li>\n<li><p>To be more DRY I would create 1 method that can swap any 2 people, then I would do something like </p>\n\n<pre><code>if (move == UP ) {\n swapPersonnal( selectedPersonnalTaskMacroIndex , selectedPersonnalTaskMacroIndex - 1 )\n}\nelse {\n swapPersonnal( selectedPersonnalTaskMacroIndex , selectedPersonnalTaskMacroIndex + 1 )\n}\n</code></pre></li>\n<li><p>In general I find this code to be confusing, the data-model is not clear, this requires more comments, I cannot easily distinguish between</p>\n\n<ul>\n<li>.getSortingOrder() giving selectedPersonnalTaskMacroSortOrder, I think I understand. <em>This method give the current order of the objectin the database</em>.</li>\n<li>getPersonnalTaskMacroList().size(); , why do you need it, it is not obvious. <em>I need it to don't get outofbound exception of my collection size. For instance, when I try to move up an object where there's no next object.</em></li>\n<li>selectedPersonnalTaskMacroIndex, what is the difference with sortingOrder() ? Not obvious. <em>The selectedPersonnalTaskMacroIndex represent the index in my java collection and the sortingOrder is a number in my database which is unique and acts as the custom sorting order.</em></li>\n<li>userProfileModel.getPersonnalTaskMacroList().get( previousPersonnalTaskMacroIndex); How is the userProfile task macro list tied to the previous personnel macro index, at this point the code does not make any sense to me? <em>This actually get the object to swap his order (aka setSortingOrder) with the current one. In this case, it's the previous one.</em></li>\n</ul></li>\n<li><p>Personnal is not correctly spelled, not sure if you can still fix this. <em>I should fix this lol.</em></p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T22:32:59.730",
"Id": "34828",
"Score": "1",
"body": "Rather than using the two constants, it would be better to name the parameter `moveUp`, then just check it's value alone (rather than comparing it to true/false). However, as boolean parameters are to be avoided, that suggests something else should be done - perhaps some sort of `moveUp(...)`/`moveDown(...)` combo."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T10:25:40.220",
"Id": "34859",
"Score": "0",
"body": "You can also use `enum direction {UP,DOWN}` - `swapPersonnal( move == direction.UP) ? .., .. -1 : .., .. +1)`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T18:48:50.727",
"Id": "21675",
"ParentId": "21672",
"Score": "1"
}
},
{
"body": "<pre><code>private void movePersonnalTaskMacro (UserProfileModel userProfileModel, boolean move) {\n</code></pre>\n\n<p>This is a private method but it does not access any members of its class. It is a smell. This probably means its home is one of the parameters, (usually first). <code>UserProfileModel</code> seems like a case of smurf typing. <code>boolean move</code> we will probably need a <a href=\"http://www.refactoring.com/catalog/replaceParameterWithExplicitMethods.html\" rel=\"nofollow\">Replace Parameter with Method</a> </p>\n\n<pre><code>PersonnalTaskMacro selectedPersonnalTaskMacro = userProfileModel.getSelectedPersonnalTaskMacro();\n\n/* Initialize sorting order (increment/decrement) */\nint selectedPersonnalTaskMacroSortOrder = selectedPersonnalTaskMacro.getSortingOrder();\n</code></pre>\n\n<p>A case of <em>Inappropriate Intimacy</em>. Call chains such as <code>userProfileModel.getSelectedPersonnalTaskMacro().getSortingOrder()</code> usually are.</p>\n\n<pre><code>int personnalTaskMacroListSize = userProfileModel.getPersonnalTaskMacroList().size();\nint selectedPersonnalTaskMacroIndex = userProfileModel.getPersonnalTaskMacroList().indexOf(\n selectedPersonnalTaskMacro);\n</code></pre>\n\n<p>More cases of the same. Also we see down <code>.getPersonnalTaskMacroList()</code> returns the actual field (Because you can sort it outside of the owner class). The collection should be encapsulated. </p>\n\n<p>Since you plan to do nothing if <code>personnalTaskMacroListSize</code> is not greater than 1. say explicitly so. It makes it more readable, and saves you also from <em>Arrow Code</em>. </p>\n\n<pre><code>if (personnalTaskMacroListSize > 1) {\n</code></pre>\n\n<p>to</p>\n\n<pre><code>if (personnalTaskMacroListSize <= 1) return ;\n</code></pre>\n\n<p>Dispatch on parameter, is a bad idea:</p>\n\n<pre><code> if (move == false \n\n if (move == true\n</code></pre>\n\n<p>Moreover it is not needed in the first place. Many times user clicks Up or Down, and instead of </p>\n\n<pre><code> onUpClicked() {\n movePersonnalTaskMacroUp();\n }\n\n onDownClicked() {\n movePersonnalTaskMacroDown();\n }\n</code></pre>\n\n<p>We get something like:</p>\n\n<pre><code> onUpClicked() {\n movePersonnalTaskMacro(true);\n }\n\n onDownClicked() {\n movePersonnalTaskMacro(false);\n }\n</code></pre>\n\n<p>Less clear while reading the call site. Less clear while reading the implementation. Hides (some times loses) the users intent in the meantime.</p>\n\n<p><code>personnalTaskMacro.getSortingOrder</code>\n<code>PersonnalTaskMacro.setSortingOrder</code> Why does a Personal Task Macro needs to know in what order it participates in some collection of User Profile. If we decide to have a dozen more different lists of such macros, will we add a dozen more fields to Personal Task Macros. I am guessing this was because of some ORM issue. You had a sort order column in personalTaskMacro table so you had a property in that class. If that is the case you should fix your mapping. If not, why was it?</p>\n\n<pre><code>Collections.sort(userProfileModel.getPersonnalTaskMacroList());\n</code></pre>\n\n<p>Why do you need to sort if you only swapped two elements of the list. Also as mentioned above collections should be encapsulated. (If you need to have a property so your ORM can access it, make those getter and setter private.)</p>\n\n<p>Here is my suggestion. Main refactorings are <a href=\"http://www.refactoring.com/catalog/moveMethod.html\" rel=\"nofollow\">Move Method</a> and <a href=\"http://www.refactoring.com/catalog/replaceParameterWithExplicitMethods.html\" rel=\"nofollow\">Replace Parameter with Explicit Methods</a> and <a href=\"http://www.refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html\" rel=\"nofollow\">Replace Nested Conditional with Guard Clauses</a>. Also DRY the element swapping as suggested by @tomdemuyt.</p>\n\n<pre><code>class UserProfile {\n List<PersonalTask> personalTaskList;\n int selected;\n\n public void moveSelectedUp() {\n if (personalTaskList.size() <= 1) return;\n\n if (selected <= 0) return;\n\n swap(personalTaskList, selected, selected - 1);\n selected--;\n }\n\n public void moveSelectedDown() {\n if (personalTaskList.size() <= 1) return;\n\n if (selected >= personalTaskList.size() - 1) return;\n\n swap(personalTaskList, selected, selected + 1);\n selected++;\n }\n\n static <T> void swap(List<T> list, int a, int b) {\n T tmp = list.get(a);\n list.set(a, list.get(b));\n list.set(b, tmp);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T14:26:32.707",
"Id": "34869",
"Score": "0",
"body": "Loved all the explanations and solution is quite elegant . I started out with a swap solution too, but was stuck because of ORM (as you said I have a field which contains my sorting order)..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T08:50:08.043",
"Id": "22703",
"ParentId": "21672",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "22703",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T17:04:18.913",
"Id": "21672",
"Score": "4",
"Tags": [
"java",
"optimization",
"algorithm",
"design-patterns",
"generics"
],
"Title": "Move object by one up or down algorithm in a custom order"
}
|
21672
|
<p>I wanted to be able to consistently label an arbitrary number of objects on my site. It's pretty simple, but I if there's a more clever way...</p>
<pre><code>// Usage:
// ColorTable.getColor('my link name');
ColorTable = {
'_colors' : [
'#F4BB2E',
'#2DE656',
'#66CCFF',
'#6666FF',
'#CC66FF',
'#FF6FCF',
'#FC4048'
],
'tableSize' : function() { return this['_colors'].length; },
'nextIndex' : function() {
if (localStorage["ColorTable:_index"]===undefined) {
localStorage["ColorTable:_index"] = -1;
}
rv = (parseInt(localStorage["ColorTable:_index"]) + 1) % this.tableSize();
localStorage["ColorTable:_index"] = rv;
return rv;
},
'getIndex' : function(key) {
if (!localStorage["ColorTable:" + key]) {
localStorage["ColorTable:" + key] = this.nextIndex();
}
return localStorage["ColorTable:" + key];
},
'setIndex' : function(key, index) {
if (index >= 0 && index < this.tableLength()) {
localStorage["ColorTable:" + key] = index;
return localStorage["ColorTable:" + key];
} else {
return false;
}
},
'getColor' : function(key) {
return this['_colors'][this.getIndex(key)];
}
};
</code></pre>
|
[] |
[
{
"body": "<p>Minor nitpicks:</p>\n\n<p>None of you keywords are reserved words (especially if it starts with an underscore!) so encasing them in single-quotes is superfluous.</p>\n\n<p><code>ColorTable.tableSize</code> is an example of the <a href=\"http://www.codinghorror.com/blog/2012/07/new-programming-jargon.html\" rel=\"nofollow\">smurf-naming convention</a> (see item 21). Drop the second instance of table to become <code>ColorTable.size</code></p>\n\n<p>For <code>setIndex</code> you return two different datatypes: <code>index</code> on success, and <code>false</code> for failure. Since <code>index</code> is an arguements known to external code, what purpose does this serve? For consistency, you should return <code>true/false</code> for pass/fail <strong>if you have to.</strong> If you <strong>have</strong> to, how about a single point-of-return? You'd have to introduce a variable, and two more LOCs, but... <code>single point-of-return</code>!</p>\n\n<p>But why not throw an exception? The existing mixed-type return suggests that calling code doesn't use the return value in any meaningful way.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T21:08:41.733",
"Id": "21679",
"ParentId": "21676",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "21679",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T19:22:53.203",
"Id": "21676",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Rotating color table object (for easy and consistent labeling)"
}
|
21676
|
<p>So I made a socket communication library. And a part of it is <code>IConnection</code> </p>
<pre><code>public enum ConnectionState
{
NotConnected, Connecting, Connected, Authenticated, Disconnecting, Disconnected
}
public interface IConnection
{
ConnectionState State { get; }
event Action Connected;
event Action Disconnected;
event Action Authenticated;
event Action AuthenticationFailed;
// this two methods are the core of my question
void OnAuthenticated();
void OnAuthenticationFailed();
bool Send(byte[] data);
void Connect();
void Close();
}
</code></pre>
<p>Of course <code>IConnection</code> provides information about connection state and is able to fire <code>Connected/Disconnected</code> events as it holds <code>Socket</code>. There is no doubt.</p>
<p>Now, users of <code>IConnection</code> would also like to know when it becomes authenticated. For example, server might listen to that events, and once connection is authenticated - send client's initial configuration data. Or client might listen to that events and decide to start communication or retry authentication process.</p>
<p>But. The problem is, authentication process exists in the protocol layer. <code>IConnection</code> has no idea such layer even exists. Protocol layer actually uses <code>IConnection</code> to send serialized to <code>byte[]</code> message to the other party. And for this one particular message kind, protocol layer is able to send data upon connection in <code>ConnectionState.Connected</code> state.</p>
<p>So, for <code>IConnection</code> to be able to change it's state and inform subscribers on auth process i had to implement this two methods</p>
<pre><code>void OnAuthenticated();
void OnAuthenticationFailed();
</code></pre>
<p>Which are, obviously called from protocol layer authentication process code.</p>
<p>I feel like I'm doing something wrong here. And since i work alone, any thoughts will be much appreciated. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T23:47:12.617",
"Id": "34833",
"Score": "0",
"body": "Maybe the class that works with the connection (the one that represents protocol layer) should expose the `Authenticated` event?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T00:21:30.440",
"Id": "34834",
"Score": "0",
"body": "@svick This is one of the ways, but i like it less then current because other services will have to be aware of this Authentication Service, and it will have to be single instance per connection."
}
] |
[
{
"body": "<p>You're not quite correct saying that IConnection has no ideas about protocol layer - in your defininition IConnection provides events about authentication process. So your code should have some connections between IConnection and protocol layer. I have no clue about entire relationships between layers in your application, but I can suggest some method:</p>\n\n<ul>\n<li><p>provide function for calling events (like you suggested) </p></li>\n<li><p>implement IConnection in protocol layer </p></li>\n<li><p>realization of IConnection listens what happens in protocol layer (i.e. AssignAuthentificationService function)</p></li>\n<li><p>implement IAuthentifiedConnection that knows about protocol layer </p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T10:00:23.823",
"Id": "34853",
"Score": "0",
"body": "So you find normal situation when one class calls `IConnection.OnAuthenticated()` and then `IConnection` itself fires the `Authenticated` event?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T12:47:18.253",
"Id": "34864",
"Score": "0",
"body": "Actually i like the last idea, `IConnection` implementation, or to be precise extension of default implementation might exist in Protocol layer / business logic"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T07:21:46.273",
"Id": "22698",
"ParentId": "21680",
"Score": "5"
}
},
{
"body": "<p>Remember that interfaces are usage contracts. They do not define how a class should be implemented.</p>\n\n<p>Hence it's up to the implementation to handle the authentication process. So if we look at the contract only, the <code>OnXxx</code> methods do not belong in it. </p>\n\n<p>If we are looking at implementations there is nothing that says that all future implementations of the class would required a third party to handle the authentication.</p>\n\n<p>However, your current implementation do. So what you could do to allow third party to interact with the connection is to create a second interface which only targets that: <code>IRequireThirdPartyAuthentication</code> which has those to methods.</p>\n\n<p>Your implementation should have the following layout:</p>\n\n<pre><code>public class MyConnection : IConnection, IRequireThirdPartyAuthentication\n{\n}\n</code></pre>\n\n<p>Are you sure that all connections will require authentication? If not: Create interface inheritance as ivn suggested.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T13:13:03.027",
"Id": "22707",
"ParentId": "21680",
"Score": "3"
}
},
{
"body": "<p>I ended up moving the core part of the protocol like authentication, keep-alive service and basic message types that will be most likely used everywhere to the Communication assembly.</p>\n\n<p>So now IConnection does auth process itself as it is aware of core protocol.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T17:14:57.820",
"Id": "22721",
"ParentId": "21680",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "22698",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T22:34:27.197",
"Id": "21680",
"Score": "2",
"Tags": [
"c#",
"authentication",
"library",
"socket"
],
"Title": "Properties and on change events"
}
|
21680
|
<p>i created a database class from a good tutorial and wanted to put it up here so it would get in some search results. it took me about 2 days to find it. also i added a few custom functions to it.. here it is :P and if there is something that can be done better or more proficiently please feel free to let me know.</p>
<pre><code>config.php:
// Database Constants
defined('DB_HOST') ? NULL : define('DB_HOST', 'edit:host');
defined('DB_USER') ? NULL : define('DB_USER', 'edit:user');
defined('DB_PASS') ? NULL : define('DB_PASS', 'edit:pass');
defined('DB_NAME') ? NULL : define('DB_NAME', 'edit:databasename');
</code></pre>
<p>database.class.php:</p>
<pre><code>class Database {
private $dbhost = DB_HOST;
private $dbuser = DB_USER;
private $dbpass = DB_PASS;
private $dbname = DB_NAME;
private $dbh;
private $error;
private $stmt;
public function __construct() {
// set DSN
$dsn = 'mysql:host=' . $this->dbhost . ';dbname=' . $this->dbname;
// set OPTIONS
$options = array(
PDO::ATTR_PERSISTENT => TRUE,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instance
try {
$this->dbh = new PDO($dsn, $this->dbuser, $this->dbpass, $options);
} catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
public function query($query) {
$this->stmt = $this->dbh->prepare($query);
}
public function selectQuery($table, $fields, $FieldToQuery, $value) {
try {
if ((gettype($fields) != 'array') || (gettype($value) != 'array')) {
$fields = (array) $fields;
$FieldToQuery = (array) $FieldToQuery;
$value = (array) $value;
}
$holders = $FieldToQuery;
for ($i = 0; $i < count($holders); $i++) {
$holders[$i] = ':' . $holders[$i];
}
$array = array_combine($holders, $value);
$query = 'SELECT ' . implode(',', $fields) . ' FROM ' . $table . ' WHERE ' .
implode(',',$FieldToQuery) . ' = ' . implode(',', $holders);
$this->query($query);
$this->bindArray($array);
$rows = $this->resultset();
return $rows;
} catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
public function insertQuery($table, $fields, $values) {
try {
if ((gettype($fields) != 'array') || (gettype($values) != 'array')) {
$fields = (array) $fields;
$values = (array) $values;
}
$holders = $fields;
for ($i = 0; $i < count($holders); $i++) {
$holders[$i] = ':' . $holders[$i];
}
$array = array_combine($holders, $values);
$query = 'INSERT INTO ' . $table . '(' . implode(',', $fields)
. ') VALUES (' . implode(',', $holders) . ')';
$this->query($query);
$this->bindArray($array);
$this->execute();
} catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
public function bindArray($array) {
foreach ($array as $key => $value) {
$this->bind($key, $value);
}
}
public function bind($param, $value, $type = null) {
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}
public function execute() {
$this->stmt->execute();
}
public function resultset() {
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function single() {
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function rowCount() {
return $this->stmt->rowCount();
}
public function lastInsertId() {
return $this->dbh->lastInsertId();
}
public function beginTransaction() {
return $this->dbh->beginTransaction();
}
public function endTransaction() {
return $this->dbh->commit();
}
public function cancelTransaction() {
return $this->dbh->rollBack();
}
public function debugDumpParams() {
return $this->stmt->debugDumpParams();
}
}
</code></pre>
<p>here is the link <a href="http://culttt.com/2012/10/01/roll-your-own-pdo-php-class/" rel="nofollow">http://culttt.com/2012/10/01/roll-your-own-pdo-php-class/</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T02:39:36.633",
"Id": "34839",
"Score": "0",
"body": "Code Review is meant for reviewing code that *you* wrote, not code that you found on the internet."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T02:56:45.917",
"Id": "34840",
"Score": "0",
"body": "@svick: Looks like it's only partly tutorial code. The `bindArray`, `selectQuery`, and `insertQuery` methods look original."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T20:51:32.750",
"Id": "34912",
"Score": "1",
"body": "@TraeMoore: Please don't change your code too much once you've posted the question; it makes the answers look like people are seeing things. :)"
}
] |
[
{
"body": "<p>Those constants, <code>DB_HOST</code> etc, since there's no easy way to redefine them, pretty much ensure that you can only ever have one database per run of your app. Maybe this is an issue for you; maybe it's not. But it can be a showstopper if you have to use two databases. I'd at least accept args for host, db, user, and password, and maybe default to the DB_ constants if the args are not set. (Personally, i'd get rid of the constants altogether, but i can see some logic behind them...)</p>\n\n<p>Your select query almost certainly fails for more than one field. The standard syntax is <code>...WHERE field1 = value1 AND field2 = value2...</code> rather than <code>WHERE field1, field2... = value1, value2...</code>.</p>\n\n<p>While you're at it, you might consider using an associative array to replace the two separate ones. Maybe even for the insert as well. <code>array('field1' => 'value1', 'field2' => value2, ...)</code> is a bit less error-prone than having two separate arrays, and it looks like <code>bindArray</code> already expects such an array anyway.</p>\n\n<p>Maybe it's just me, but i don't see any way to retrieve <code>$error</code>. Either provide a getter for it or just get rid of it altogether and let the exceptions propagate like you do with most of the other methods. If you decide to keep it, you need to make sure to let the caller know to look at the error. (The mostly-standard way of doing that is to return <code>false</code>.) But really, you should probably just let the caller catch the exception, for consistency's sake; they'll have to do so for the rest of your methods anyway, and they shouldn't have to wonder how you're handling errors this time (or scratch their heads when they handle errors just like they do everywhere else, and aren't getting an exception back, but stuff's not working).</p>\n\n<p>As far as your config script, it looks like the conditional operator is being abused. It works, as <code>define</code> is a real function rather than a language construct...but it's still abuse. The conditional operator is made for deciding between two values, which is why the <code>? NULL :</code> is there.</p>\n\n<pre><code>if (!defined('DB_HOST')) define('DB_HOST', 'hostname');\n</code></pre>\n\n<p>is easier to follow, and is even less to type. :P</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T20:23:05.863",
"Id": "34904",
"Score": "0",
"body": "After reading this i see exactly what your saying and am going to figure out how to fix it so that i can still keep what i have. I do see what your saying about error's piling up. i do need to implement some sort of err solution... Forgive me for not catching all corners, ive only been doing php for about 2 weeks. – Trae Moore 5 mins ago.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T01:29:10.030",
"Id": "34930",
"Score": "0",
"body": "You're forgiven... *this time...* :) Really, though, the point of this site is to bring up those details you hadn't thought about. As long as you consider our suggestions, it's all good."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T02:22:10.020",
"Id": "21687",
"ParentId": "21685",
"Score": "2"
}
},
{
"body": "<p>The constructor is basically always creating the same instances, so you are not really using the class as an object. I would rather create a database class that can be used like:</p>\n\n<pre><code>$db = new Database('localhost', 'root', 'root', 'dbname');\n</code></pre>\n\n<p>and then instantiate it as:</p>\n\n<pre><code>$db = new Database(DB_HOST, DB_USER ...);\n</code></pre>\n\n<p>which will prevent you from having to refactor your class if in the future when you'll need to connect to multi databases.</p>\n\n<p>Also you are using <code>$this->stmt</code> as the current statement just to save the:</p>\n\n<pre><code>$stmt = $pdo->prepare('...');\n</code></pre>\n\n<p>which doesn't really make any sense and just reconvert the OOP of PDO back to the functional way of programming.</p>\n\n<p>This:</p>\n\n<pre><code>public function rowCount() {\n return $this->stmt->rowCount();\n}\n\npublic function lastInsertId() {\n return $this->dbh->lastInsertId();\n}\n\npublic function beginTransaction() {\n return $this->dbh->beginTransaction();\n}\n\npublic function endTransaction() {\n return $this->dbh->commit();\n}\n\npublic function cancelTransaction() {\n return $this->dbh->rollBack();\n}\n\npublic function debugDumpParams() {\n return $this->stmt->debugDumpParams();\n}\n</code></pre>\n\n<p>is just useless and unmaintainable. Why don't you extend the PDO class instead?</p>\n\n<p>PDO provides a good error handling via Exceptions and you are taking it away by saving it to a private property that is never even called. Why do you wan't to hide errors? Why don't you just let <code>PDOException</code>s being thrown? Or why don't you create a:</p>\n\n<pre><code>class DatabaseException extends Exception {}\n</code></pre>\n\n<p>exception class?</p>\n\n<p><strong>tl;dr</strong>: <em>think with objects</em>!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T20:23:33.880",
"Id": "34905",
"Score": "0",
"body": "@cHao no i didn't.. your crazy :P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T20:25:33.340",
"Id": "34906",
"Score": "0",
"body": "@TraeMoore: I have no idea what you're talking about. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T20:30:22.673",
"Id": "34907",
"Score": "0",
"body": "@cHao while this is fun, maybe you could give me some pointers? the first time i tried to make this class i used extends and ended up with nothing..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T20:41:17.530",
"Id": "34911",
"Score": "0",
"body": "@jeffrey isn't surrounding things in try and catch error catching?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T20:54:56.943",
"Id": "34913",
"Score": "0",
"body": "@TraeMoore: In this case, it's error *hiding*. :P Callers will be expecting to catch exceptions (cause that's how every other method works), and in a handful of methods you're sticking error messages in some whole other place that (a) you don't let callers know to check, and (b) they wouldn't have access to check even if they knew. If you're not going to fix the problem, and don't have some cleanup to do, don't catch the exception."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T21:14:29.703",
"Id": "34915",
"Score": "0",
"body": "@cHao can you link me on some articles.. i have no idea what you're saying..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T23:52:20.643",
"Id": "34923",
"Score": "0",
"body": "@TraeMoore: I'm saying you should really decide whether you want to throw exceptions, return an error code, or what have you. However you choose to do errors, *do it consistently.* As it is, all those one-line methods that just call PDO functions will throw a PDOException if they fail, cause that's what your constructor is telling them to do (see `PDO::ATTR_ERRMODE`). But other methods are instead catching PDOExceptions and squirreling away the message, surprising anyone who *expects* an exception on failure (cause that's what happens everywhere else)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T23:53:10.503",
"Id": "34925",
"Score": "0",
"body": "As for articles, i don't know of any. Other than perhaps [the wikipedia article on POLA](http://en.wikipedia.org/wiki/Principle_of_least_astonishment)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T12:39:09.253",
"Id": "34954",
"Score": "0",
"body": "@TraeMoore, the hell is going on here?"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T14:55:32.570",
"Id": "22710",
"ParentId": "21685",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T01:41:05.653",
"Id": "21685",
"Score": "1",
"Tags": [
"php",
"mysql",
"classes",
"pdo"
],
"Title": "PHP PDO Custom class ple"
}
|
21685
|
<p>I just started to learn Objective C with <em>Programming in Objective C</em> by Stephen G. Kochanand and I would love to get your feedback to see if I'm getting OOP concept with Objective-C right.</p>
<p><strong>GraphicObject.h</strong></p>
<pre><code>#import <Foundation/Foundation.h>
@interface GraphicObject : NSObject
{
int fillColor;
int lineColor;
BOOL filled;
}
-(void) fillColor: (int) fc;
-(void) lineColor: (int) lc;
-(int) getFilledColor;
-(int) getLineColor;
-(BOOL) filled;
@end
</code></pre>
<p><strong>GraphicObject.m</strong></p>
<pre><code>#import "GraphicObject.h"
@implementation GraphicObject
//--------------------------Get and Set filled/line colors----------------------------------//
-(void) fillColor:(int)fc
{
fillColor = fc;
}
-(void) lineColor:(int)lc
{
lineColor = lc;
}
-(int) getFilledColor
{
return fillColor;
}
-(int) getLineColor
{
return lineColor;
}
//-------------------------------------Is filled?--------------------------------------------//
-(BOOL) filled
{
filled = fillColor;
return filled;
}
@end
</code></pre>
<p><strong>Rectangle.h</strong></p>
<pre><code>#import "GraphicObject.h"
#import "XYPoint.h"
@interface Rectangle : GraphicObject
@property float width, height, tx, ty;
-(XYPoint *) origin;
-(void) setWidth: (float) w andHeight: (float) h;
-(void) setOrigin:(XYPoint *)pt;
-(void) translate:(XYPoint *)point;
-(float) area;
-(float) perimeter;
@end
</code></pre>
<p><strong>Rectangle.m</strong></p>
<pre><code>#import "Rectangle.h"
#import "XYPoint.h"
@implementation Rectangle
{
XYPoint *origin;
}
@synthesize width, height, tx, ty;
-(void) setWidth: (float) w andHeight: (float) h
{
width = w;
height = h;
}
-(void) translate:(XYPoint *)point
{
tx = origin.x + point.x;
ty = origin.y + point.y;
}
-(void)setOrigin:(XYPoint *)pt
{
if (!origin)
origin = [[XYPoint alloc] init];
origin.x = pt.x;
origin.y = pt.y;
}
-(XYPoint *) origin
{
return origin;
}
-(float) area
{
return width * height;
}
-(float) perimeter
{
return (width + height) * 2;
}
@end
</code></pre>
<p><strong>XYPoint.h</strong></p>
<pre><code>#import <Foundation/Foundation.h>
@interface XYPoint : NSObject
@property float x, y;
-(void) setX:(float)xP andY: (float)yP;
@end
</code></pre>
<p><strong>XYPoint.m</strong></p>
<pre><code>#import "XYPoint.h"
@implementation XYPoint
@synthesize x, y;
-(void) setX:(float)xP andY:(float)yP
{
x = xP;
y = yP;
}
@end
</code></pre>
<p><strong>Circle.h</strong></p>
<pre><code>#import "GraphicObject.h"
@interface Circle : GraphicObject
@property float radius, diameter;
-(float) getArea;
-(float) getCircumference;
-(void) setDiameter:(float)d andRadius: (float)r;
@end
</code></pre>
<p><strong>Circle.m</strong></p>
<pre><code>#import "Circle.h"
@implementation Circle
@synthesize radius, diameter;
-(float) getArea
{
return (radius * radius) * 3.14;
}
-(float) getCircumference
{
return (3.14 * diameter);
}
-(void) setDiameter:(float)d andRadius: (float)r;
{
diameter = d;
radius = r;
}
@end
</code></pre>
<p><strong>Triangle.h</strong></p>
<pre><code>#import "GraphicObject.h"
@interface Triangle : GraphicObject
@property float sideA, sideB, sideC, base, height;
-(float) getArea;
-(float) getPerimeter;
-(void) setBase:(float)b andHeight:(float)h;
-(void) setSideA:(float)a andB: (float)b andC: (float)c;
@end
</code></pre>
<p><strong>Triangle.m</strong></p>
<pre><code>#import "Triangle.h"
@implementation Triangle
@synthesize sideA, sideB, sideC, base, height;
-(float) getArea
{
return (base/2) * height;
}
-(float) getPerimeter
{
return sideA + sideB + sideC;
}
-(void) setBase:(float)b andHeight:(float)h;
{
base = b;
height = h;
}
-(void) setSideA:(float)a andB: (float)b andC: (float)c
{
sideA = a;
sideB = b;
sideC = c;
}
@end
</code></pre>
<p><strong>main</strong></p>
<pre><code>#import <Foundation/Foundation.h>
#import "Rectangle.h"
#import "Circle.h"
#import "Triangle.h"
#import "GraphicObject.h"
#import "XYPoint.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
//----------------------------------Creating instance objects of all classes-------------------------------
Rectangle *myRectangle = [[Rectangle alloc] init];
Circle *myCircle = [[Circle alloc] init];
Triangle *myTriangle = [[Triangle alloc] init];
XYPoint *myPoint = [[XYPoint alloc] init];
//----------------------------------Testing XYPoint class and Rectangle class-------------------------------
[myPoint setX:5 andY:10];
[myRectangle setOrigin:myPoint];
[myRectangle setWidth:10 andHeight:7];
NSLog(@"Rectangle Width = %.1f Height = %.1f is at (%.1f,%.1f)", myRectangle.width, myRectangle.height, myRectangle.origin.x, myRectangle.origin.y);
//------------------------------------------Testing Circle class--------------------------------------------
[myCircle setDiameter:6 andRadius:3];
NSLog(@"Circle area = %.1f Circumference = %.1f", [myCircle getArea], [myCircle getCircumference]);
//-----------------------------------------Testing Triangle class-------------------------------------------
[myTriangle setSideA:5 andB:6 andC:7];
[myTriangle setBase:5 andHeight:12];
NSLog(@"Triangle Perimeter = %.1f Area = %.1f", [myTriangle getPerimeter], [myTriangle getArea]);
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T21:01:29.267",
"Id": "41196",
"Score": "0",
"body": "This is primarily an issue for Stack Exchange sites, and a *little* less crucial when you're looking at code in your full-screen IDE. But, please try to avoid putting so much empty whitespace (empty lines) in your code. It makes it harder to read with so much scrolling required. Thanks. Otherwise, a good question :)"
}
] |
[
{
"body": "<p>I have to make the same suggestion as for your last question: use properties and stick to name conventions</p>\n\n<p>Your code as it is</p>\n\n<pre><code>#import <Foundation/Foundation.h>\n\n@interface GraphicObject : NSObject\n\n{\n int fillColor;\n int lineColor;\n BOOL filled;\n}\n\n-(void) fillColor: (int) fc;\n-(void) lineColor: (int) lc;\n-(int) getFilledColor;\n-(int) getLineColor;\n-(BOOL) filled;\n\n@end\n</code></pre>\n\n<p>Your code with name conventions (setters of an ivar prefixed with set…, getters named as the ivar/property)</p>\n\n<pre><code>#import <Foundation/Foundation.h>\n\n@interface GraphicObject : NSObject\n\n{\n int fillColor;\n int lineColor;\n BOOL filled;\n}\n\n-(void) setFillColor: (int) fc;\n-(void) setLineColor: (int) lc;\n-(int) filledColor;\n-(int) lineColor;\n-(BOOL) filled;\n\n@end\n</code></pre>\n\n<p>Your code with properties</p>\n\n<pre><code>#import <Foundation/Foundation.h>\n\n@interface GraphicObject : NSObject\n\n{\n int fillColor;\n int lineColor;\n BOOL filled;\n}\n@property int fillColor;\n@property int lineColor;\n@property BOOL filled;\n\n@end\n</code></pre>\n\n<p>But actually for nowadays compilers you don't need to declare iVars for properties</p>\n\n<pre><code>#import <Foundation/Foundation.h>\n\n@interface GraphicObject : NSObject\n\n@property int fillColor;\n@property int lineColor;\n@property BOOL filled;\n\n@end\n</code></pre>\n\n<p>and you also dont need to declare synthesize, as it is default now</p>\n\n<p>As properties generate setters7getters for you, the implementation could be</p>\n\n<pre><code>#import \"GraphicObject.h\"\n\n@implementation GraphicObject\n\n@end\n</code></pre>\n\n<hr>\n\n<p>Cocoa's name conventions suggest not to use the word <code>and</code> in method names to indicate the setting of an object's state</p>\n\n<pre><code>-(void) setDiameter:(float)d andRadius: (float)r;\n</code></pre>\n\n<p>becomes </p>\n\n<pre><code>-(void) setDiameter:(float)d radius: (float)r;\n</code></pre>\n\n<p><sub>BTW: <code>diamater = radius * 2</code>, so there is no need to pass both</sub></p>\n\n<p><code>and</code> is suggested for action that might be triggered after setting.<br>\nSome made up example </p>\n\n<pre><code>-(void) sendData:(NSData *)data \n toURL:(NSURL *) url \nandPerformSuccessSelector:(SEL)successSelector \n performFailureSelector:(SEL)failureSelector;\n\n-(void) setSideA:(float)a b: (float)b c: (float)c\n</code></pre>\n\n<p>instead of XYPoint class</p>\n\n<pre><code>#import \"XYPoint.h\"\n\n@implementation XYPoint\n\n@synthesize x, y;\n\n-(void) setX:(float)xP andY:(float)yP\n{\n x = xP;\n y = yP;\n}\n\n@end\n</code></pre>\n\n<p>you could use the <a href=\"https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CGGeometry/Reference/reference.html#//apple_ref/doc/uid/TP30000955-CH2g-C016211\" rel=\"nofollow\">CGPoint struct</a> (iOS) or <a href=\"https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/doc/uid/20000018-SW20\" rel=\"nofollow\">NSPoint</a> (Cocoa)</p>\n\n<pre><code>struct CGPoint {\n CGFloat x;\n CGFloat y;\n};\ntypedef struct CGPoint CGPoint;\n</code></pre>\n\n<p>As this is a plain C type, you cant use it, where you need to use objects. Wrap it in a NSValue object than, for example to store it into an array:</p>\n\n<pre><code>NSArray *points = @[[NSValue valueWithCGPoint:p1], [NSValue valueWithCGPoint:p2]]\n</code></pre>\n\n<hr>\n\n<p>I just had a look into Stephen G. Kochan's book in amazon. he is also sticking to the naming conventions, see page 96 program 6.2. </p>\n\n<p><code>-setNumerator:</code> as setter, <code>-numerator</code> as getter.</p>\n\n<p>Although he is not using properties in this example, he most likely will also explain and use them later in the book.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T23:12:30.677",
"Id": "34922",
"Score": "0",
"body": "Thank you so much for the great feedback again! I stick to name conventions next time :) Regarding the struct yes, I read about it a bit but he still didnt go over this in the book, I know he will later on (Just got to page 9). Thanks again, we need more people like you here and this site will be even more awesome ;) @vikingosegundo"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T23:52:29.000",
"Id": "34924",
"Score": "0",
"body": "Just to emphasize again: naming conventions are very important, as different parts of the cocoa framework depend on them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T00:21:11.690",
"Id": "34928",
"Score": "0",
"body": "Thanks! and I meant chapter 9 (not page:/) @vikingosegundo"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T17:26:08.083",
"Id": "22723",
"ParentId": "21688",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "22723",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T02:38:36.977",
"Id": "21688",
"Score": "2",
"Tags": [
"beginner",
"objective-c",
"computational-geometry"
],
"Title": "Creating shapes program with multiple classes (different files)"
}
|
21688
|
<p>I've tried to write a bash script that gives me a general overview of the status of git repos I have cloned/created. It's not meant to replace <code>git status</code> by any means, but give an overview of several repos. </p>
<p>Keep in mind I'm not the most knowledgeable about bash scripting AND git, so I imagine there is a better way to do this:</p>
<pre><code>#!/bin/bash
# Help from: http://www.leancrew.com/all-this/2010/12/batch-comparison-of-git-repositories/
index=0
gitrepos=()
#TODO: There has got to be a better way to add all these folders to the array
#add repos folder
for d in ~/repos/*; do
gitrepos[(index+=1)]="$d"
done
#add other important folders
gitrepos[(index+=1)]=~/.vim
gitrepos[(index+=1)]=~/dot_files
gitrepos[(index+=1)]=~/bin
for d in "${gitrepos[@]}"; do
if [ -e $d ]; then
cd $d
else
echo " Did not find repo: $d"
continue
fi
reponame="`basename $d`"
ok=true
git fetch --quiet origin 2>/dev/null
if [ ! -z "`git diff HEAD origin/HEAD 2> /dev/null`" ]; then
echo " $reponame --> Out of sync with origin/HEAD"
ok=false
fi
if [ ! -z "`git ls-files --other --exclude-standard 2> /dev/null`" ]; then
echo " $reponame --> Untracked files present"
ok=false
fi
if [ ! -z "`git diff --cached --shortstat 2> /dev/null`" ]; then
echo " $reponame --> Changes to be committed"
ok=false
fi
if [ ! -z "`git diff --shortstat 2> /dev/null`" ]; then
echo " $reponame --> Changes to be staged/committed"
ok=false
fi
if $ok; then
echo " OK --> $reponame"
fi
done
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T11:48:07.903",
"Id": "38096",
"Score": "0",
"body": "Have you tried [`fgit`](https://github.com/l0b0/fgit)? It's served me well for years. Disclaimer: I'm the author."
}
] |
[
{
"body": "<p>Yes there is a better way of filling an array. You can use globbing inside of array parens. Also I suggest being explicit about what you do in bash and use <code>declare -a</code> to declare arrays and later on <code>declare</code> for other variables</p>\n\n<pre><code>declare -a repos=(~/repos/* ~/.vim ~/dot_files ~/bin)\n</code></pre>\n\n<p>In case of adding stuff to an array, after it got created:</p>\n\n<pre><code>repos+=(\"more stuff\" here)\n</code></pre>\n\n<p>Maybe you want to name you iterating variable more verbose, instead of <code>d</code> <code>repodir</code> or something.</p>\n\n<p>Your first if contains a <code>continue</code> so you can emphasize on this one and just go on with no <code>else</code>. Also don't miss the double quotes in case of directory names with spaces in them. Also you should check for <code>-d</code> since you <code>cd</code> into it.</p>\n\n<pre><code>if [ -d \"$d\" ]; then\n echo \"No repo at $d\"\n continue\nfi\ncd \"$d\"\n</code></pre>\n\n<p><code>[ ! -z \"`cmd`\" ]</code> is more verbose than it needs to be. You can just do <code>[ \"`cmd`\" ]</code>.</p>\n\n<p>Read the \"Arrays\" chapter in the bash manpage.</p>\n\n<p>I attach my test file for this answer which also shows functions and some refactoring which allows to discard this <code>ok</code> variable.</p>\n\n<pre><code>#!/bin/bash\nmain() {\n local -a repos=(* /foo/bar)\n echo -e \"repos: ${repos[@]}\"\n for path in \"${repos[@]}\"; do\n check_repo \"$path\"\n done\n}\n\ncheck_repo() {\n local path=\"$1\"\n local name=\"`basename \"$path\"`\"\n local report=\"\"\n if [ ! -d \"$path\" ]; then\n echo -e \"$name\\n not a directory: $path\"\n return\n fi\n cd \"$path\"\n if [ \"`echo foo 2> /dev/null`\" ]; then\n report+=\"\\n oh oh\"\n fi\n cd - > /dev/null\n if [ -z \"$report\" ]; then\n report+=\"\\n OK\"\n fi\n echo -e \"$name$report\"\n}\n\nmain\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T05:08:50.510",
"Id": "35173",
"Score": "0",
"body": "Thanks for your comments! They have taught me quite a lot about bash."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T17:46:29.427",
"Id": "35212",
"Score": "0",
"body": "Me too. Never have read \"Arrays\" before."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T00:11:55.187",
"Id": "22878",
"ParentId": "21691",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "22878",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T03:01:52.570",
"Id": "21691",
"Score": "3",
"Tags": [
"bash",
"shell"
],
"Title": "Improve a script to generally check status of several git repos"
}
|
21691
|
<p>I am doing web apps, mostly single page apps. So i have to give absolute and fixed positioning a lot via css. </p>
<p>For Example, consider this page layout:</p>
<pre><code><html>
<div class="app-header">
</div>
<div class="main-app-area"> <!-- app contains four pages -->
<div class="app-page" style="visibility: visible"></div>
<div class="app-page"></div>
<div class="app-page"></div>
<div class="app-page"></div>
<div class="app-page"></div>
</div>
</html>
</code></pre>
<p>CSS</p>
<pre><code>.app-header
{
position: fixed;
top: 0px;
left: 0px;
width: 100%;
}
.main-app-area
{
width: 100%;
height: 100%;
}
.app-page
{
width: 100%;
height: 100%;
position: absolute;
top: 0px;
left: 0px;
visibility: hidden;
}
</code></pre>
<p>I really don't know, Is this right way of doing single page apps? Will it cause any performance problems? </p>
|
[] |
[
{
"body": "<p>Have a look at this, maybe this helps a little. I made only little changes. first of all you have to know a child element is always positioned absolute or relative to his parent. so it is important to make child and parent elements, except you want a div as a placeholder to load the data in another way...</p>\n\n<p>play arround with the code (like why is position:absolute 5px top and left only 5px from the orange...) it may helps to understand. also have a look at the class .app-page.active !</p>\n\n<pre><code><style type=\"text/css\">\n.app-header\n{\n background-color:green;\n position: fixed;\n top: 10px;\n left: 10px;\n width: 100%;\n\n}\n.main-app-area\n{\n background-color:orange;\n width: 100%;\n height: 100%;\n position:relative;\n top:20px;\n left:20px;\n}\n\n.app-page\n{\n background-color:fuchsia;\n opacity:0.5;\n position: absolute;\n width: 100%;\n height: 100%;\n top: 5px;\n left: 5px;\n visibility: hidden;\n\n}\n.app-page.active {\n visibility:visible;\n}\n</style>\n\n<div class=\"app-header\">xxx\n <div class=\"main-app-area\"> <!-- app contains four pages -->\n yyy\n <div class=\"app-page active\">zzz</div>\n <div class=\"app-page\"></div>\n <div class=\"app-page\"></div>\n <div class=\"app-page\"></div>\n <div class=\"app-page\"></div>\n </div>\n</div>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T03:58:28.883",
"Id": "35780",
"Score": "0",
"body": "Hi !!! My question is, excessive use of absolute and fixed positioning cause to any performance and layout delay?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T07:58:17.060",
"Id": "35794",
"Score": "1",
"body": "No, not at all. Most layout delays or kind of jumping boxes happen if positions aren't \"made\", then the content gets loaded, needs more space and pushes the box somewhere else."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T12:24:53.100",
"Id": "23161",
"ParentId": "22695",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T05:54:42.180",
"Id": "22695",
"Score": "2",
"Tags": [
"javascript",
"html",
"css",
"layout"
],
"Title": "HTML - single page layout - absolute positioning"
}
|
22695
|
<p>To provide some background context, I'm implementing a web-based solution (Java, Spring, Hibernate) that allows the creation/authoring of task-centric workflow documents. Basically a workflow provides an ordered collection of tasks (and related content) for a user to step through.</p>
<p>One of the available task types is a "risk assessment" matrix, in which the user selects a "risk" level (i.e. "how likely is it that this thing will break?") and a "consequence" level (i.e. "how bad is it if the thing <em>does</em> break?"). Based upon their input, some text provided by the workflow author will be displayed. </p>
<p>Essentially these tasks are backed by a 5x5 matrix of strings, and by selecting a "risk" and "consequence" level, the user is indicating a position in the matrix. </p>
<p>There's one further complication, in that all text provided by the document author must support internationalization. To deal with this I've implemented an <code>InternationalText</code> entity, which simply refers to a collection of <code>LocalText</code> entities, each one of which specifies a language, and a string of text in that language. That all works fine. </p>
<p>What I'm wondering about is, what's the best way to store the matrix itself in the data model? I can't just serialize an array of Strings, as each position in the matrix is actually occupied by an <code>InternationalText</code> instance and not a <code>String</code>. I suppose maybe I could serialize an array of <code>InternationalText</code> ids, but that seems fairly hacky, doesn't it?</p>
<p>Under my current approach, I've explicitly declared a field dedicated to each position in the matrix. That makes for 25 getters and 25 setters. To avoid having to deal with that nonsense, I added some helper methods that take advantage of reflection in order to get and set fields based upon their matrix position, in standard <code>(x, y)</code> notation (I use a two-dimensional <code>JSONArray</code> to transport the matrix data to/from the rest of the application).</p>
<p>What I'm really after is the cleanest, most convenient way of managing the matrix content. I think what I have is fairly reasonable, but can anyone think of a better approach?</p>
<p>Here's the code:</p>
<pre><code>@Entity
@Table(name = "matrixText")
public class MatrixText extends AccountItem {
private static final Logger LOG = Logger.getLogger(MatrixText.class);
//fields
//relationships
private TemplateQuestion template;
//XXX: addressing is <consequence>_<risk> == <x>_<y>
private InternationalText text0_0;
private InternationalText text0_1;
private InternationalText text0_2;
private InternationalText text0_3;
private InternationalText text0_4;
private InternationalText text1_0;
private InternationalText text1_1;
private InternationalText text1_2;
private InternationalText text1_3;
private InternationalText text1_4;
private InternationalText text2_0;
private InternationalText text2_1;
private InternationalText text2_2;
private InternationalText text2_3;
private InternationalText text2_4;
private InternationalText text3_0;
private InternationalText text3_1;
private InternationalText text3_2;
private InternationalText text3_3;
private InternationalText text3_4;
private InternationalText text4_0;
private InternationalText text4_1;
private InternationalText text4_2;
private InternationalText text4_3;
private InternationalText text4_4;
public MatrixText() {
//all fields default to null
}
@OneToOne(optional = false, fetch=FetchType.LAZY)
public TemplateQuestion getTemplate() {
return template;
}
public void setTemplate(TemplateQuestion template) {
this.template = template;
}
@ManyToOne(optional = true, fetch=FetchType.LAZY)
public InternationalText getText0_0() {
return text0_0;
}
public void setText0_0(InternationalText text0_0) {
this.text0_0 = text0_0;
}
//...
@ManyToOne(optional = true, fetch=FetchType.LAZY)
public InternationalText getText4_4() {
return text4_4;
}
public void setText4_4(InternationalText text4_4) {
this.text4_4 = text4_4;
}
@Transient
public InternationalText getTextAtCoordinate(int x, int y) {
//XXX: x=<consequence>, y=<risk>
if (x < 0 || x > 4 || y < 0 || y > 4) {
//invalid coordinate
return null;
}
String methodName = "getText" + x + "_" + y;
try {
return (InternationalText)this.getClass().getMethod(methodName).invoke(this);
}
catch (Exception e) {
LOG.error("Unable to find/invoke getter with name=" + methodName);
}
//couldn't invoke the getter
return null;
}
@Transient
public void setTextAtCoordinate(int x, int y, InternationalText text) {
if (x < 0 || x > 4 || y < 0 || y > 4) {
//invalid coordinate
return;
}
String methodName = "setText" + x + "_" + y;
try {
this.getClass().getMethod(methodName, InternationalText.class).invoke(this, text);
}
catch (Exception e) {
LOG.error("Unable to find/invoke setter with name=" + methodName);
}
}
@SuppressWarnings("unchecked")
@Override
@Transient
public JSONObject getJson() {
JSONObject result = new JSONObject();
JSONArray matrix = new JSONArray();
for (int x = 0; x < 5; x++) {
JSONArray col = new JSONArray();
matrix.add(col);
for (int y = 0; y < 5; y++) {
InternationalText text = this.getTextAtCoordinate(x, y);
col.add(text == null ? null : text.getId());
}
}
//we need to put the matrix inside of a JSONObject due to constraints imposed by inheritance
result.put("matrix", matrix);
return result;
}
@SuppressWarnings("unchecked")
@Transient
public JSONObject getJson(Language language) {
JSONObject result = new JSONObject();
JSONArray matrix = new JSONArray();
for (int x = 0; x < 5; x++) {
JSONArray col = new JSONArray();
matrix.add(col);
for (int y = 0; y < 5; y++) {
InternationalText text = this.getTextAtCoordinate(x, y);
col.add(text == null ? null : text.getTextForLanguage(language));
}
}
//we need to put the matrix inside of a JSONObject due to constraints imposed by inheritance
result.put("matrix", matrix);
return result;
}
</code></pre>
<p>If you'd like something a bit less abstract, here's a screenshot of what it looks like in the UI:</p>
<p><img src="https://i.stack.imgur.com/jRptm.png" alt="enter image description here"></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T12:47:48.557",
"Id": "34865",
"Score": "2",
"body": "Why can't you have a `List` of `InternationalText`s?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T13:01:04.200",
"Id": "34867",
"Score": "0",
"body": "That may be a possibility, combined with the `@OrderColumn` annotation. However I'm not sure if that will play well with `null` elements in the collection (as you can see from my implementation, the text for any given matrix position is allowed to be null). Do you know if that's supported? Also it would require some custom code to enforce that the list always has the correct number of things in it when persisting the entity."
}
] |
[
{
"body": "<ol>\n<li><p>I'd extract out a validation method:</p>\n\n<pre><code>private boolean isValidCoordinates(final int x, final int y) {\n if (x < 0 || x > 4 || y < 0 || y > 4) {\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>Currently it's duplicated.</p></li>\n<li><p><code>0</code>, <code>4</code>, <code>5</code> should be named constants. It would improve readability.</p></li>\n<li><p>Instead of only logging and swallowing the exceptions throw an <code>IllegalStateException</code>. \nIt seems to me that if it happens you lost some data. Consider crashing early. See: <em>The Pragmatic Programmer: From Journeyman to Master</em> by <em>Andrew Hunt</em> and <em>David Thomas</em>: <em>Dead Programs Tell No Lies</em>. </p></li>\n<li><p>I'd try creating a class for the <code><consequence>_<risk></code> pair and use it as a key in a map. Values could be <code>InternationalText</code> instances:</p>\n\n<pre><code>// it should have a better name\npublic class ConsequenceLevelRiskLevelPair {\n private int consequenceLevelRiskLevelPairId;\n\n private ConsequenceLevel consequenceLevel;\n private RiskLevel riskLevel;\n\n // TODO: hashCode and equals here\n}\n\n\npublic class MatrixText extends AccountItem {\n\n ...\n\n private Map<ConsequenceLevelRiskLevelPair, InternationalText> texts = ...\n\n\n}\n</code></pre>\n\n<p><code>ConsequenceLevel</code> would contain the name of the level and an ID. <code>RiskLevel</code> is similar with risk level name.</p>\n\n<p>I have not used Hibernate/JPA recently (and have not tried the solution above) but I guess Hibernate can handle maps with non-string keys.\nThis Stack Overflow question also could help: <a href=\"https://stackoverflow.com/questions/4099237/how-to-map-a-2-d-matrix-in-java-to-hibernate-jpa\">How to map a 2-d matrix in Java to Hibernate/JPA?</a></p>\n\n<p>It would make the reflection unnecessary.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T12:27:36.000",
"Id": "23053",
"ParentId": "22696",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T07:06:06.390",
"Id": "22696",
"Score": "2",
"Tags": [
"java",
"database",
"reflection",
"hibernate"
],
"Title": "ORM Entity with many similar relationships"
}
|
22696
|
<p>This should tell me whether the product is taxable or imported. Name should indicate if the product is imported or certain keywords should tell that the product is non-taxable (chocolates, book, pills).</p>
<p>Could you please review the following class products?</p>
<pre><code>class Product
NON_TAXABLE = [/chocolates/, /book/, /pills/]
def initialize(product_name)
@product_name = product_name
end
def is_taxable?
taxable = false
NON_TAXABLE.each { |x| taxable = x.match(@product_name) if taxable }
!taxable
end
def is_imported?
/imported/.match(@product_name)
end
end
</code></pre>
|
[] |
[
{
"body": "<p>Your <code>is_taxable?</code> function code does not seem to work. The issue is that <code>taxable</code> is never going to be true, so you'll never assign a new value. You want to write <code>if !taxable</code> instead. Your code becomes:</p>\n\n<pre><code>def is_taxable?\n taxable = false\n NON_TAXABLE.each { |x| taxable = x.match(@product_name) if !taxable }\n !taxable\nend\n</code></pre>\n\n<p>It's still possible to make it simpler using Ruby functions on arrays.</p>\n\n<pre><code>def is_taxable?\n NON_TAXABLE.none? { |x| x.match(@product_name) }\nend\n</code></pre>\n\n<p>This means: if my product is not among the tax-free products, then it is taxable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T08:46:51.220",
"Id": "34850",
"Score": "0",
"body": "I got confused many times by the \"double not logic\" (a taxable product is not is non taxable list) and by Ruby double not, but this should be a correct answer now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T10:06:21.130",
"Id": "34854",
"Score": "0",
"body": "you can drop `!!`, a successful match is a truish value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T10:20:05.153",
"Id": "34857",
"Score": "0",
"body": "Yeah, but I would expect is_taxable? to return `true` or `false`, not a partial match or `false`. I don't know what's idiomatic in Ruby though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T10:21:32.940",
"Id": "34858",
"Score": "0",
"body": "It's definetely idiomatic to return only true/false for a `method?`. But I was talking about the `!!` in the block, `Enumerable#none?` will always return a boolean no matter what."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T10:36:49.340",
"Id": "34860",
"Score": "0",
"body": "Right, updated."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T08:01:26.330",
"Id": "22701",
"ParentId": "22699",
"Score": "5"
}
},
{
"body": "<p>If you change the <code>NON_TAXABLE</code> constant from a bunch of regular expressions to one big regular expression to rule them all, like this:</p>\n\n<pre><code>NON_TAXABLE_RE = Regexp.union(%w(chocolates books pills))\n</code></pre>\n\n<p>Then the <code>is_taxable?</code> method (I prefer <code>taxable?</code>) would look like this:</p>\n\n<pre><code>def is_taxable?\n not NON_TAXABLE_RE.match(@product_name) #I like the explicit 'not'\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T22:57:26.620",
"Id": "22735",
"ParentId": "22699",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T07:41:28.763",
"Id": "22699",
"Score": "3",
"Tags": [
"object-oriented",
"ruby",
"finance"
],
"Title": "Determining if a product is taxable or imported"
}
|
22699
|
<p>I came across polymorphism in the book that I'm reading and decided to do a little experiment. Essentially what I did was to create a base class called <code>Asset</code> and two subclasses that derive from Asset, called <code>Property</code> and <code>Stock</code>. I created instances of these two types and passed them to this function:</p>
<pre><code>public static void PrintAsset(Asset theAsset)
{
Console.WriteLine(theAsset.name);
Console.WriteLine(theAsset.GetType().ToString());
string x;
if (theAsset.GetType() == typeof(Stock))
{
Stock theStock = (Stock)theAsset;
x = (theStock.numShares * theStock.stockPrice).ToString();
}
else
{
Property theStock = (Property)theAsset;
x = (theStock.value).ToString();
}
Console.WriteLine(x + "\n");
}
</code></pre>
<p>Initially, the method only consisted of the first two lines, and the output shocked me since I would've figured the incoming reference (theAsset) would've been cast to <code>Asset</code>, but <code>.GetType().ToString()</code> surprisingly produced "...Stock" and "...Property" in the Console output.</p>
<p>I'm assuming the fact that they allow you to see the true class of the object being passed to the method for a reason, so doing something like this should be considered acceptable, but I was wondering if perhaps you SO/SE folks might disagree. Is there some unforeseen problem that this causes? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T11:08:43.873",
"Id": "34861",
"Score": "1",
"body": "Just because something is allowed doesn't mean it's a good idea to do it."
}
] |
[
{
"body": "<p>You have to learn a lot about OOP... There is no polymorphism in your code, as this principle is designed to tackle exactly the kind of code you've written. </p>\n\n<p>The code that uses <code>Asset</code> <strong>should never</strong> branch its logic based on actual derived type (otherwise it would brake <a href=\"http://en.wikipedia.org/wiki/Open/closed_principle\">Open-Closed Principle</a>), instead classes should use polymorphism to specify differences in logic. Here is simple example based on your code:</p>\n\n<pre><code>public abstract class Asset\n{\n public string Name {get; set;}\n public abstract decimal CalculateValue();\n //... other common properties and methods of Asset\n}\n\npublic class Property : Asset\n{\n public decimal Value {get;set;}\n\n public override decimal CalculateValue()\n {\n return Value;\n }\n}\n\n//usage\npublic static void PrintAsset(Asset theAsset)\n{\n Console.WriteLine(theAsset.Name);\n Console.WriteLine(theAsset.GetType().ToString());\n\n string assetValue = theAsset.CalculateValue().ToString();\n Console.WriteLine(assetValue + \"\\n\");\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T11:25:13.217",
"Id": "34862",
"Score": "0",
"body": "Everything is reasonable. But I wouldn't say that in original code there is no polymorphism. `PrintAsset()` takes the whole family of types which belongs to the class `Asset` directly or indirectly (descendants `Stock` and `Property`). Thus that function is kinda polymorphic (handles more than one type). And have type-dependent behaviour (which isn't an indicator of polymorphism). Usually in OOP-emphased languages only functions that use leaf types (i.e. in C# that enforced for sealed classes and structs) are polymorphic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T12:43:31.933",
"Id": "34863",
"Score": "0",
"body": "You probably ment Liskovs Substitution Principle and not OCP."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T12:50:18.983",
"Id": "34866",
"Score": "1",
"body": "[Liskov's substitution principle](http://en.wikipedia.org/wiki/Liskov_substitution_principle) will also be broken, but I did mean Open-Closed Principle. From Wikipedia: \"The idea was that once completed, the implementation of a class could only be modified to correct errors; new or changed features would require that a different class be created\" (open to extension, closed to modification)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T10:44:20.407",
"Id": "34944",
"Score": "0",
"body": "I understand abstract/virtual/override, but I'm afraid I don't yet understand o/c principle. Hopefully I'll understand it after reading this 1,000-page book! As far as not performing the calculation of the value via member functions (i.e. methods, which would be very OOP), I've been mainly working in VB6, and OOP is a bit sketchy there, so my VB6 code was a 50/50 mix of OOP and procedural. In C#, I would indeed use an OOP approach (as opposed to the static void external to the classes on which it operates shown here), but I'm afraid I don't understand your justification for doing it that way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T11:11:03.897",
"Id": "34946",
"Score": "1",
"body": "There is a set of recommended principles for writing \"proper\" OOP code called [SOLID](http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)), and Open-Closed Principle is one of them. It's probably better for you to read (and understand) those principles first, don't think I can explain it better... As to my justification - your code will not work properly if I pass something other than `Stock` or `Property`. So it means that whenever someone adds a new type of asset he should update this method as well. It breaks Open-Closed Principle, and make code hard to maintain"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T10:29:05.760",
"Id": "22704",
"ParentId": "22702",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T08:45:55.397",
"Id": "22702",
"Score": "0",
"Tags": [
"c#",
"polymorphism"
],
"Title": "Is this the proper way to find the subclass of a polymorphic superclass?"
}
|
22702
|
<p>I am new to node.js and asynchronous programming and this is my first small project to learn it. I have written a small Telnet chat server and the program works but I want to know if this is the correct way to write programs in node.js (asynchronous programming model).</p>
<pre><code>var tcp = require('net');
var Server = tcp.createServer();
var pwd=[]; // keep tracks of connected clients
var ip=[]; // keeps tracks of connected clients IP address
var Cpwd = "Rushabh"; // password that you require to login
Server.on('connection' ,function(conn){
conn.setEncoding('utf-8');
conn.write("Password:");// ask user for password on their terminal
console.log("[" + conn.remoteAddress + "] has joined the chat");
conn.on('data' , function(data){
if(pwd.indexOf(conn)>-1){//check if it is an old client or a new client
console.log("[" + conn.remoteAddress + "]:" + data);
if(pwd.length > 0){ // check if atleast one client is connected
sendMessage(conn , data);// broadcast message to all client connected
}
}
else{//if it is a new client then server should first check for password
data= data.toString('utf-8').trim();
var message = " has joined the chat";
if(Cpwd == data){ // if it is a new client than check for password
pwd.push(conn);
ip.push(conn.remoteAddress);
sendMessage(conn , message);
}
else {
conn.write("Password rejected:" + data);conn.end();}// disconnect client
}
});
conn.on('end' , function() { // remove the client from reference array
var i , client;
for(i in pwd){
client = pwd[i];
if(!client.writable){
pwd.splice(i,1);
console.log(ip[i]+ " has left the chat");
ip.splice(i,1);
}
}
});
});
function sendMessage(conn , message){ //function to send message to all connected client
var i , client;
for(i in pwd){
client = pwd[i];
if(client.writable){
if(conn === client){
client.write("[me]:" + message);
}
else
client.write("[" + conn.remoteAddress +"]:" + message);
}
else{
pwd.splice(i , 1);
console.log(ip[i]+ " has left the chat");
ip.splice(i,1);
}
}
}
Server.listen(8000);
</code></pre>
|
[] |
[
{
"body": "<p>From a once over:</p>\n\n<p><strong>Naming</strong></p>\n\n<ul>\n<li>variable names should start with a lower case letter, unless they are constructors\n<ul>\n<li><code>Server</code> -> <code>server</code></li>\n<li><code>Cpwd</code> -> <code>password</code></li>\n</ul></li>\n<li><code>pwd</code> contains all the connections, any reader would guess it contains passwords</li>\n</ul>\n\n<p><strong>More on variables</strong></p>\n\n<ul>\n<li>There is no good reason to have a separate array <code>ip</code>, since it always contains as many entries as <code>pwd</code> which already contains the the ip addresses in <code>remoteAddress</code>.</li>\n<li>Having the password inside your scrip is ok for a prototype, it is not for production</li>\n</ul>\n\n<p><strong>Functions</strong></p>\n\n<p>You encapsulated <code>sendMessage</code> into a function, you should also have a <code>leave</code> or <code>quit</code> function and a <code>joinChat</code> function.</p>\n\n<p><strong>Flow</strong></p>\n\n<ul>\n<li>You announce that a user joins the chat before checking the password</li>\n<li>In <code>on 'end'</code> you could just use <code>indexOf</code> on <code>conn</code> instead of manually looping over all connections.</li>\n</ul>\n\n<p>Other than that I think you are doing fine with the asynchronous model of Node.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T21:57:56.273",
"Id": "38797",
"ParentId": "22706",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "38797",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T12:03:03.843",
"Id": "22706",
"Score": "2",
"Tags": [
"javascript",
"node.js",
"asynchronous",
"chat"
],
"Title": "Simple Telnet chat server"
}
|
22706
|
<p>As part of a larger web app we are producing, I was asked to help build functionality to tie a page's shopping cart into <code>localStorage</code> for persistence. What follows are the three functions that I wrote that produce a JSON representation of the cart, and stores it in LS.</p>
<p>As far as I can tell, it all works great. I'm curious if I'm missing any best practices, or if I've done something that could prove problematic at scale, etc. Maybe there are just some general improvements I could make or something you would do differently. I just want to make sure I'm always working towards producing the best code I can, and unfortunately I don't have the resources on my team to do internal code review.</p>
<p>Note that all the console logging is mostly there for debugging, and almost all of it will be removed before the code itself goes live. I'm particularly interested if my <code>for</code>-loop approach is the best possible solution for searching and updating existing JSON items.</p>
<pre><code>var cartItems;
var MyApp = {};
// On load, look for an existing cart to preload
MyApp.getCart = function() {
// Check for localStorage
if(localStorage) {
if(localStorage['myapp.cart'] != null) {
// Get the cart
cartItems = JSON.parse(localStorage['myapp.cart']);
checkoutCounter = cartItems.count;
// Update the button counter value
counterSpan.text(checkoutCounter);
// External function to enable the button
MyApp.theCounter();
}
} else {
console.log('localStorage not detected, cannot get cart.');
}
};
// Add an item to the localStorage cart
MyApp.saveToCart = function(role) {
if(localStorage) {
console.log('localStorage detected. Processing cart item: '+role);
// Create a new cart array object if there isn't one
if(cartItems == null) {
console.log('Cart is empty, preparing new cart array');
cartItems = {
'count': '1',
'items':[{'item':role,'quantity':'1'}]
};
console.log('Cart array created');
} else {
console.log('Existing cart detected, searching for existing role.');
var newItem = true;
// Loop our array to see if we need to update an existing item
for(var i = 0; i < cartItems.items.length; i++) {
if(cartItems.items[i].item === role) {
console.log('Existing role detected: '+role);
newItem = false;
var itemQuantity = parseInt(cartItems.items[i].quantity);
console.log('Updating current role quantity: '+itemQuantity);
itemQuantity++;
console.log('New role quantity: '+itemQuantity);
cartItems.items[i].quantity = itemQuantity.toString();
}
}
// We must not have found an existing item, so add one
if(newItem) {
console.log('Role not found. Adding role to cart with quantity 1: '+role);
cartItems.items.push({'item':role,'quantity':'1'});
}
// Update the item count
var cartCount = cartItems.count;
console.log('Current cart count: '+cartCount);
cartCount++;
console.log('New cart count: '+cartCount);
cartItems.count = cartCount.toString();
}
// Push the prepared data into localStorage
console.log('Saving cart data...');
localStorage['myapp.cart'] = JSON.stringify(cartItems);
console.log('Cart data saved.');
} else {
console.log('localStorage not supported, item not saved for later');
}
};
// Remove an item from the localStorage cart
MyApp.deleteFromCart = function(role) {
if(localStorage) {
console.log('localStorage detected. Removing cart item: '+role);
// Blow away the whole cart object from localStorage if it only held this one item, it's assuming the one item must match what triggered the remove action
if(parseInt(cartItems.count) == 1) {
console.log('Only 1 item in cart. Removing cart object entirely.');
localStorage.removeItem('myapp.cart');
} else {
// Update the item count
var cartCount = cartItems.count;
console.log('Current cart count: '+cartCount);
cartCount--;
console.log('New cart count: '+cartCount);
cartItems.count = cartCount.toString();
console.log('Multiple items in cart, searching for role: '+role);
// Find the item to update it
for(var i = 0; i < cartItems.items.length; i++) {
if(cartItems.items[i].item === role) {
console.log('Role '+role+' found with quantity: '+cartItems.items[i].quantity);
var itemQuantity = parseInt(cartItems.items[i].quantity);
// If there was only one, remove it entirely from the cart object
if(itemQuantity == 1) {
console.log('Removing role from cart.');
cartItems.items.splice(i,1);
// Just reduce it by one
} else {
itemQuantity--;
console.log('Updating current role quantity: '+itemQuantity);
cartItems.items[i].quantity = itemQuantity.toString();
}
}
}
// Push the prepared data into localStorage
console.log('Saving cart data...');
localStorage['myapp.cart'] = JSON.stringify(cartItems);
console.log('Cart data saved.');
}
} else {
console.log('Local Storage not supported, item not saved for later');
}
};
</code></pre>
|
[] |
[
{
"body": "<p>You should write a thin wrapper around <code>localStorage</code> so that you don't have to constantly ask <code>if (localStorage)</code> every time you want to use it. You can also do that test once, and if it doesn't exist, stub it out with a simple <code>{}</code>:</p>\n\n<pre><code>if (!localStorage) {\n console.log(\"LocaleStorage is not supported, data will not be persisted\")\n\n // Let the program use a stub object to proceed\n localStorage = {};\n localStorage.prototype.removeItem = function(key) {\n this[key] = null;\n }\n}\n\nstore = {\n read: function(key) {\n if (localStorage[key])\n return JSON.parse(localStorage[key])\n\n return null;\n },\n\n write: function(key, value) {\n localStorage[key] = JSON.stringify(value)\n },\n\n clear: function(key) {\n localStorage.removeItem(key);\n }\n}\n</code></pre>\n\n<p>Now your methods look much simpler:</p>\n\n<pre><code>// On load, look for an existing cart to preload\nMyApp.getCart = function() {\n // Get the cart\n cartItems = store.read(\"myapp.cart\")\n checkoutCounter = cartItems.count;\n // Update the button counter value\n counterSpan.text(checkoutCounter);\n // External function to enable the button\n MyApp.theCounter();\n};\n</code></pre>\n\n<p>There's a <em>ton</em> of cleanup to be done by making this object oriented. You could be creating a ShoppingCart class which has save/load/addItem/removeItem/etc, and then creating a global instance called <code>myCart</code>. It would be much, much cleaner than a bunch of global functions.</p>\n\n<p>By which I mean:</p>\n\n<pre><code>ShoppingCart = function(name) {\n this.name = name;\n this.items = store.read(name)\n}\n\nShoppingCart.prototype = {\n save: function () {\n store.write(this.name, this.items)\n },\n\n\n addItem: function (role) {\n if (this.items[role])\n this.items[role] += 1;\n else\n this.items[role] = 1;\n\n this.save()\n },\n\n removeItem: function(role) {\n if (this.items[role])\n this.items[role] -= 1;\n\n if (this.items[role] == 0)\n delete this.items[role];\n\n this.save()\n }\n\n}\n\nvar myCart = new ShoppingCart(\"myapp.cart\");\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T15:41:55.773",
"Id": "34874",
"Score": "0",
"body": "Thanks for the idea, I like it. I assume in your example above you mean function(key), rather than function(name), right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T15:45:31.043",
"Id": "34875",
"Score": "0",
"body": "Yeah, now fixed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T15:52:23.390",
"Id": "34876",
"Score": "0",
"body": "So, when you say that I could clean it up by making it object oriented, is that not what I did by namespacing the functions within MyApp? Or am I combining principles where I shouldn't be?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T16:12:08.950",
"Id": "34880",
"Score": "0",
"body": "You've got a lose series of functions writing directly to a global variable called `cartItems`. JavaScript does provide a level of encapsulation that you're not taking advantage of."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T16:19:10.220",
"Id": "34881",
"Score": "0",
"body": "@TheQuicksilver See my update for a simplified ShoppingCart class."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T15:30:12.683",
"Id": "22714",
"ParentId": "22711",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "22714",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T14:59:36.513",
"Id": "22711",
"Score": "3",
"Tags": [
"javascript",
"json",
"logging",
"e-commerce",
"browser-storage"
],
"Title": "localStorage functions for website shopping cart"
}
|
22711
|
<p>I am leaning Haskell and decided to do the following <a href="http://www.scs.stanford.edu/11au-cs240h/labs/lab1.html" rel="nofollow">lab assignment</a> from <em>CS240h: Functional Systems in Haskell</em>. I welcome any advice on more idiomatic coding style and performance tips. </p>
<p>Notes:</p>
<ul>
<li>I chose <code>Data.HashTable</code> on the assumption that it would be faster than <code>Data.Map</code> as the number of entries increase. <strong>Edit:</strong> this seems to be an erroneous assumption as timing on about 5M of input has <code>Data.Map</code> at 3.5s and <code>Data.HashTable</code> at 5.3s. </li>
<li>Some of the <code>_ <- mapM</code> does not feel right.</li>
<li>I also wondered if using some sort of <code>ByteString</code> would be better, but I was also confused on how to make it work with UTF-8 and coming up with a suitable hash function, so I dropped that idea.</li>
</ul>
<p>Here is the code I ended with:</p>
<pre><code>module Lab1 where
import Prelude hiding (lookup, readFile, getContents)
import System.Environment (getArgs)
import System.IO.UTF8 (readFile, getContents)
import Data.Char (isAlpha, toLower, isPunctuation)
import Data.HashTable
import Data.Maybe (fromMaybe)
import Data.Function (on)
import Data.List (sortBy, dropWhileEnd)
type Frequencies = HashTable String Int
-- Get relevant words according to the instructions in the assignment.
-- Convert to lowercase, keep the single quotes ("Don't" -> "don't")
getWords :: String -> [String]
getWords str = let
isGoodChar c = isAlpha(c) || c `elem` "`'"
chunk s = let (word, notGood) = span isGoodChar s
(_, rest) = span (not . isGoodChar) notGood
in word : (if rest == "" then [] else chunk rest)
trim = (dropWhile isPunctuation) . (dropWhileEnd isPunctuation)
lower = map toLower str
in [trimmed | word <- chunk lower, let trimmed = trim word, trimmed /= ""]
emptyFrequencies :: IO Frequencies
emptyFrequencies = fromList hashString []
increaseCount :: Frequencies -> String -> IO Frequencies
increaseCount frequencies word = do
maybeCount <- lookup frequencies word
let count = fromMaybe 0 maybeCount
_ <- update frequencies word (count + 1)
return frequencies
countWords :: Frequencies -> String -> IO Frequencies
countWords frequencies str = do
_ <- mapM (increaseCount frequencies) (getWords str)
return frequencies
-- read list files from arguments or use stdin
processInputs :: IO Frequencies
processInputs = do
frequencies <- emptyFrequencies
args <- getArgs
contents <- if args == [] then sequence [getContents]
else mapM readFile args
_ <- mapM (countWords frequencies) contents
return frequencies
printFrequencies :: IO ()
printFrequencies = do
frequencies <- processInputs
list <- toList frequencies
let sorted = sortBy (compare `on` negate . snd) list
maxLengthWord = maximum $ map (length . fst) sorted
maxLengthBar = 80 - maxLengthWord - 1
maxCount = (snd . head) sorted
baseUnit = (fromIntegral maxLengthBar) / (fromIntegral maxCount) :: Double
makeBar count = replicate (round $ (fromIntegral count) * baseUnit) '#'
pad w = take (maxLengthWord + 1) $ (w ++ cycle " ")
bars = [(pad w) ++ bar | (w, count) <- sorted, let bar = makeBar count, bar /= ""]
_ <- mapM putStrLn bars
return ()
</code></pre>
<hr>
<p>I spent a bit more time and find out I could use <code>foldlM</code> and <code>mapM_</code> in a couple places.</p>
<p>Also I ran the code through <em>hlint</em> and it pointed out that <code>break isGoodChar</code> could replace <code>span (not . isGoodChar)</code> and that I had some unnecessary parentheses. So here is the updated version:</p>
<pre><code>module Lab1 where
import Prelude hiding (lookup, readFile, getContents)
import System.Environment (getArgs)
import System.IO.UTF8 (readFile, getContents)
import Data.Char (isAlpha, toLower, isPunctuation)
import Data.HashTable
import Data.Maybe (fromMaybe)
import Data.Function (on)
import Data.List (sortBy, dropWhileEnd)
import Data.Foldable (foldlM)
type Frequencies = HashTable String Int
-- Get relevant words according to the instructions in the assignment.
-- Convert to lowercase, keep the single quotes ("Don't" -> "don't")
getWords :: String -> [String]
getWords str = let
isGoodChar c = isAlpha c || c `elem` "`'"
chunk s = let (word, notGood) = span isGoodChar s
(_, rest) = break isGoodChar notGood
in word : (if null rest then [] else chunk rest)
trim = dropWhile isPunctuation . dropWhileEnd isPunctuation
lower = map toLower str
in [trimmed | word <- chunk lower, let trimmed = trim word, trimmed /= ""]
emptyFrequencies :: IO Frequencies
emptyFrequencies = fromList hashString []
increaseCount :: Frequencies -> String -> IO Frequencies
increaseCount frequencies word = do
maybeCount <- lookup frequencies word
let count = fromMaybe 0 maybeCount
_ <- update frequencies word (count + 1)
return frequencies
countWords :: Frequencies -> String -> IO Frequencies
countWords frequencies str =
foldlM increaseCount frequencies (getWords str)
-- read list files from arguments or use stdin
processInputs :: IO Frequencies
processInputs = do
frequencies <- emptyFrequencies
args <- getArgs
contents <- if null args
then sequence [getContents]
else mapM readFile args
foldlM countWords frequencies contents
printFrequencies :: IO ()
printFrequencies = do
frequencies <- processInputs
list <- toList frequencies
let sorted = sortBy (compare `on` negate . snd) list
maxLengthWord = maximum $ map (length . fst) sorted
maxLengthBar = 80 - maxLengthWord - 1
maxCount = (snd . head) sorted
baseUnit = fromIntegral maxLengthBar / fromIntegral maxCount :: Double
makeBar count = replicate (round $ fromIntegral count * baseUnit) '#'
pad w = take (maxLengthWord + 1) (w ++ cycle " ")
bars = [pad w ++ bar | (w, count) <- sorted, let bar = makeBar count, bar /= ""]
mapM_ putStrLn bars
</code></pre>
|
[] |
[
{
"body": "<p>Inside do notation, you don't need to use <code>_ <-</code> to discard the value of a computation. So\n<code>_ <- update frequencies word (count + 1)</code> can be written as <code>update frequencies word (count + 1)</code></p>\n\n<p>Haskell programmers tend to prefer immutable collections like <code>Data.Map</code> or <code>Data.IntMap</code> over hash tables. <code>Data.HashTable</code> uses mutable references and requires you to work inside the IO monad. Generally, it is good practice to relegate the IO monad to the outer layers of your program and keep the core pure.</p>\n\n<p>To work efficiently with Unicode data, consider using the <a href=\"http://hackage.haskell.org/package/text\" rel=\"nofollow\">text</a> package.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T04:14:42.960",
"Id": "35306",
"Score": "0",
"body": "I added the `_ <- ` because eclipsefp reports a warning if I don't. So I thought that was a best practice. Yes, `Data.Map` turned out to be more efficient and also let me parallelize the code. I will try out the text package to see if it speeds up the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T06:42:35.743",
"Id": "35450",
"Score": "0",
"body": "Using the `text` package worked great! It brought down the time from 3.5s to 2.1s."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T07:34:17.500",
"Id": "35451",
"Score": "1",
"body": "Handling strings as list of characters (like the String type does) is conceptually elegant but can be inefficient for intensive string processing. In those cases it's better to use `text`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T16:42:47.430",
"Id": "38268",
"Score": "0",
"body": "Yes, you will get a warning if you use `mapM` and discard its results without being explicit (i.e. writing `_ <- mapM ...`).\n\nHowever, instead of using `mapM`, you can use `mapM_` which is the same as `mapM` except that it ignores the results from the actions. This is a common pattern, and there is also `forM_`, `sequence_` and so on."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T21:32:27.427",
"Id": "22940",
"ParentId": "22713",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "22940",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T15:21:14.187",
"Id": "22713",
"Score": "6",
"Tags": [
"haskell"
],
"Title": "Counting word frequencies in Haskell"
}
|
22713
|
<p>I have written a Backbone View (javascript) for a component called "twist-panel".</p>
<p>A twist panel is basically a card flip, it has a front and back side, and can flip to the back and to the front.</p>
<p>Here is the code:</p>
<pre><code>var TwistPanel = Backbone.View.extend({
initialize: function() {
this.$front = this.$el.find('.twist-panel-side-front');
this.$back = this.$el.find('.twist-panel-side-back');
this.atFront = true;
this.isFlipping = false;
// Fix the height of the twist panel container.
this.$el.height(this.$front.outerHeight(true));
},
toBack: function() {
var self = this;
if (this.isFlipping || !this.atFront) return;
// Fix height.
this.$el.height(this.$back.outerHeight(true));
this.$front.afterTransition(function() {
self.atFront = false;
self.isFlipping = false;
self.trigger('twist', 'back');
});
this.isFlipping = true;
this.$el.addClass('twist');
},
toFront: function(callback) {
var self = this;
if (this.isFlipping || this.atFront) return;
// Fix height.
this.$el.height(this.$front.outerHeight(true));
this.$back.afterTransition(function() {
self.atFront = true;
self.isFlipping = false;
self.trigger('twist', 'front');
});
this.isFlipping = true;
this.$el.removeClass('twist');
}
});
</code></pre>
<p>As you can see in the code above, there is a lot of code duplication.
I would really appreciate some help on getting the code DRY.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T19:29:26.363",
"Id": "34898",
"Score": "0",
"body": "`var self = this;` seems to be missing in toFront?"
}
] |
[
{
"body": "<p>The usual way I approach the problem is by asking: what <em>does</em> change?</p>\n\n<ul>\n<li><code>self.atFront</code> is flipped: not an issue here, you can simply write <code>self.atFront = !self.atFront</code>.</li>\n<li>conditions using <code>atFront</code> vs. <code>!atFront</code> (not an issue: if we factorize everything, we don't need to know what the state is: we just want to change it)</li>\n<li>the string in <code>self.trigger</code></li>\n<li><code>$front</code> vs. <code>$back</code></li>\n<li><code>removeClass()</code> vs. <code>addClass()</code>.</li>\n</ul>\n\n<p>Quite a lot of things change, actually! At this point, we don't know yet if avoiding duplication is worth it: it often leads to more complicated code and it can be longer, too. But let's try it. I took your code, created a <code>flip</code> function, and tried to see what could fit in it. When writing this, I realized that it was simpler to put everything in the <code>flip</code> function, so I tried it:</p>\n\n<pre><code>var TwistPanel = Backbone.View.extend({\n initialize: function() {\n this.$front = this.$el.find('.twist-panel-side-front');\n this.$back = this.$el.find('.twist-panel-side-back');\n\n this.atFront = true;\n this.isFlipping = false;\n\n // Fix the height of the twist panel container.\n this.$el.height(this.$front.outerHeight(true));\n },\n flip: function() {\n var self = this;\n var otherSide = ... ? this.$back : this.$front;\n\n if (this.isFlipping) return;\n\n this.$el.height(otherSide.outerHeight(true));\n\n this.$front.afterTransition(function() {\n self.isFlipping = false;\n self.trigger('twist', otherSide.name);\n });\n\n this.isFlipping = true;\n if (this.$el.hasClass('twist')) {\n this.$el.removeClass('twist')) {\n } else {\n this.$el.addClass('twist');\n }\n }\n});\n</code></pre>\n\n<p>(I don't know about your application, but I guess <code>toFront</code> can never be called when we're already in front. If it's not true, then we need to keep <code>toFront</code> and <code>toBack</code> which will call <code>flip</code> themselves.)</p>\n\n<p>At this point, I have two big issues left: I don't know how to decide what is the other side, and I don't know how to get its name (<code>otherSide.name</code>, used in the <code>self.trigger()</code> call). Since I don't know about this, I decided to resolve another issue, even if it is minor. This issue is that the <code>removeClass/addClass</code> logic looks wrong. It would probably be simpler to use something that is more than a value, and HTML5 data-* attributes are perfect for this since they are key-value and supported by jQuery. You can then replace the last five lines by this single one:</p>\n\n<pre><code>this.$el.data('twist', otherSide.name);\n</code></pre>\n\n<p><code>$el</code> will either contain <code>data-twist=\"front\"</code> or <code>data-twist=\"back\"</code>: you then need to change your CSS to account for this minor change. What's nice here is that it's now possible to get the string you're interested in (<code>front</code> or <code>back</code>). And it's also easy to assign <code>otherSide</code>. We'll use jQuery <code>data()</code> for this. Here's the final untested code:</p>\n\n<pre><code>var TwistPanel = Backbone.View.extend({\n initialize: function() {\n this.$front = this.$el.find('.twist-panel-side-front');\n this.$back = this.$el.find('.twist-panel-side-back');\n\n this.isFlipping = false;\n\n // Fix the height of the twist panel container.\n this.$el.height(this.$front.outerHeight(true));\n },\n flip: function() {\n var self = this;\n var otherSide = this.$el.data('twist') === 'front' ? this.$back : this.$front;\n var otherSideName = this.$el.data('twist') === 'front' ? 'back' : 'front';\n\n if (this.isFlipping) return;\n\n this.$el.height(otherSide.outerHeight(true));\n\n this.$front.afterTransition(function() {\n self.isFlipping = false;\n self.trigger('twist', this.$el.data('twist'));\n });\n\n this.isFlipping = true;\n this.$el.data('twist', otherSideName);\n }\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T09:05:18.980",
"Id": "22742",
"ParentId": "22718",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "22742",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T16:37:02.657",
"Id": "22718",
"Score": "4",
"Tags": [
"javascript",
"backbone.js"
],
"Title": "Javascript plugin DRY"
}
|
22718
|
<p>We need to select a model reference from a view. To do this we need to add a dropdownlistfor. This is based on a selectlist containing database models.</p>
<h2>passing selectlists by viewbag</h2>
<p>This solves our problem, but we do not like using ViewBag:</p>
<pre><code>public ActionResult Create()
{
ViewBag.SomeModels = new SelectList(context.SomeModel, "id", "modelDescription");
return View();
}
</code></pre>
<h2>Our solution</h2>
<p>We added a context to a viewmodel to do the same, but this is MVC anti-pattern:</p>
<pre><code>public class SomeModelViewModel : SomeModel
{
private SomeContext context = new SomeContext ();
public SelectList getSomeOtherModels()
{
return new SelectList(context.SomeOtherModel, "id", "modelDescription");
}
}
</code></pre>
<p>Does anyone have suggestions for a clean way to solve this problem?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T09:34:15.477",
"Id": "34883",
"Score": "2",
"body": "In such cases i'm adding my selectlist to my model and pass it to my view, but stil wondering if there is a better solution +"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T10:06:53.767",
"Id": "34884",
"Score": "0",
"body": "I personally don't think its an anti-pattern at all, the model is exclusively for the view so inclusion of view constructs is IMO not a bad thing"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T13:20:55.410",
"Id": "34885",
"Score": "0",
"body": "In my opnion this is an anti-pattern, because I have a context in the model layer and contexts are bound to controllers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T16:58:46.047",
"Id": "34887",
"Score": "0",
"body": "Why do you need to pass the `SelectList`? Can't you have the items for the select list in one Property, and the selected value in another?"
}
] |
[
{
"body": "<p>I think there are a few things that can be fixed here, but overall I don't think this is automatically an anti-pattern. It could just be executed a little better.</p>\n\n<p><em>Caveat: I don't practice what I preach nearly as often as I should.</em></p>\n\n<p>What I tend to do in my own projects, and the standard where I work, is for the view model to expose an <code>IEnumerable<SelectListItem></code> (actually, when we're lazy, we put this enumerable in the ViewBag like you have but we're trying to get away from that.) Rather than giving the context to your view model, just give the items to the view model when it's constructed and have it generate the <code>SelectListItem</code>s from them. AFAIK, that's the controller's job.</p>\n\n<pre><code>public class SomeViewModel\n{\n public IEnumerable<SelectListItem> ListItems { get; private set; }\n\n public SomeViewModel(IEnumerable<SomeModel> items)\n {\n ListItems = items\n .Select(i => new SelectListItem()\n {\n Text = i.Name,\n Value = i.Id,\n Selected = i.IsSelected // or whatever\n })\n .ToList();\n }\n}\n\npublic class SomeController\n{\n public ActionResult Index()\n {\n var viewModel = new SomeViewModel(_context.SomeModels);\n\n return View(viewModel);\n }\n}\n</code></pre>\n\n<p>Again, I can't promise this is the more \"correct\" way to do it, but I've done it and seen it done on at least four different projects, and it's worked well for us so far.</p>\n\n<p>P.S. Your ViewModel probably shouldn't inherit from your Model. I've never actually seen that done before, but some cursory Googling shows that it's not really recommended. You should have the exact properties you need in the view copied into your view model (I hear there are tools for his), and use a tool like AutoMapper to copy values back and forth when necessary.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T23:32:18.383",
"Id": "35678",
"Score": "1",
"body": "I love the idea that the ViewModel requires the list so make it to the constructor. Never thought of that and actually I liked it A LOT. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-11T16:40:10.773",
"Id": "94027",
"Score": "1",
"body": "and what you do in `[HttpPost]` actions, how do you get these values again?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T01:38:29.880",
"Id": "22806",
"ParentId": "22719",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "22806",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T09:30:05.553",
"Id": "22719",
"Score": "7",
"Tags": [
"c#",
"mvc",
"asp.net-mvc-4"
],
"Title": "Passing a selectlist to the view based on database models from viewmodel is a MVC anti-pattern"
}
|
22719
|
<p>I am trying to convert myself from using mysql extension to using PDO, with that being said I was curious if I am going about this the right way.</p>
<p>I have a custom logging system that I built I am wondering if the way I implemented this would work or not. I am planning on duplicating the main functions of PDO and doing the same as what I did prepare?</p>
<p>What I wanted to know is if the way I turned on exceptions and internally using try/catch blocks to capture and log errors then rethrowing the exception after I logged the error is the right way to do this or is there another more efficient way of doing this.</p>
<pre><code>class rDB extends PDO {
private $dsn = "mysql:host=10.10.10.43";
private $user = "user";
private $pass = "pass";
/**
* @var Logger Writes messages to custom csv log based on debug level of 1-5
* 1 Being Critical Error, 5 Being a simple Note
*/
private $logger;
public function __construct($logger) {
$this->logger = $logger;
$this->logger->log(5, 'Connecting to MySQL DB');
try {
/* Call to Parent Function */
parent::__construct($this->dsn, $this->user, $this->pass);
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->logger->log(5, 'Connected to MySQL DB');
}
catch(PDOException $e) {
$this->logger->log(2, 'Connection to MySQL DB Failed-> '.$e->getPrevious());
throw $e;
}
}
public function prepare($statement, array $driver_options = 'array()') {
try {
$this->logger->log(5, 'Preparing statement');
/* Call to Parent Function */
$value = parent::prepare($statement, $driver_options);
}
catch(PDOException $e) {
$this->logger->log(2, 'Error preparing statement-> '.$e->getMessage());
throw $e;
}
$this->logger->log(5, 'Statement is prepared.');
return $value;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>This mostly looks good to me. \nI don't think that logging exceptions should be the concern of your rDB class. Also, you could utilize the <a href=\"https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md\" rel=\"nofollow\">PSR logger interface</a></p>\n\n<pre><code>class rDB extends PDO implements \\Psr\\Log\\LoggerAwareInterface\n{\n //do not override the PDO constructor\n\n public function setLogger(\\Psr\\Log\\LoggerInterface $logger)\n {\n $this->logger = $logger;\n }\n\n //override the PDO methods as you have done but, call\n //$this->log() instead of $this->logger->log()\n //i.e.\n public function prepare($statement, $driver_options = array())\n {\n $this->log(\\Psr\\Log\\LogLevel::INFO, $statement, array(\n 'driver_options' => $driver_options\n ));\n return parent::prepare($statement, $driver_options);\n }\n\n private function log($level, $message, $context = array())\n {\n //note: only log if a logger is set\n if ($this->logger) {\n $this->logger($level, $message, $context);\n }\n }\n}\n</code></pre>\n\n<p>A factory method added to your rDb class could be useful to construct an instance for you:</p>\n\n<pre><code>public static function createInstance($params)\n{\n $dsn = array_key_exists('dsn', $params) ? $params['dsn']: null;\n $user = array_key_exists('user', $params) ? $params['user'] : null;\n $pass = array_key_exists('pass', $params) ? $params['pass']: null;\n $logger = array_key_exists('logger', $params) ? $params['logger']: null;\n\n $rdb = new rDB($dsn, $user, $pass);\n $rdb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n if ($logger) {\n $rdb->setLogger($logger);\n }\n\n return $rdb;\n}\n</code></pre>\n\n<p><em><strong>EDIT</em></strong>\nI suggest using a factory method to construct your instance instead of overriding the constructor primarily because 1) Changing the argument list in any overridden method effectively changes the interface. This makes it more difficult to replace one class with another. 2) I feel that constructors should do no more than serve as a way to inject dependencies that are always needed and initialize default values.</p>\n\n<p>In your application, somewhere during initialization/bootstrap:</p>\n\n<pre><code>//Depending on your environment (production, development, etc),\n//you can configure different kinds of loggers. For example,\n//a development logger would probably log EVERYTHING but a\n//production logger might only log error, critical, alert, emergency\n$logger = new YourLoggerClassWhichImplementsLoggerInterface();\n\ntry {\n $dbConfig = //read in a configuration from somewhere\n $rdb = rDB::createInstance(array(\n 'dsn' => $dbConfig->dsn,\n 'user' => $dbConfig->user,\n 'pass' => $dbConfig->pass,\n 'logger' => $logger,\n ));\n\n //Now pass $rdb to whatever needs it (i.e. a controller).\n} catch (Exception $e) {\n $logger->error($e->getMessage(), array('exception' => $e));\n //Display some kind of error page to the user\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T04:23:15.167",
"Id": "35578",
"Score": "0",
"body": "Thank you for your suggestions, I see your point about logging exceptions in rDB, I found I was tempted to log the exceptions again when i was implementing the rDB class. Is there a reason why you wouldnt override the contructor as long as you called the parent?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T13:27:33.500",
"Id": "35591",
"Score": "0",
"body": "I don't see a reason to override the PDO constructor. My preference is to create factory methods to construct objects in some particular way (as I've shown in the createInstance method above). I find factory methods to be more flexible than overridden constructors."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T19:45:25.463",
"Id": "35668",
"Score": "0",
"body": "I am not familar with factory methods or how they work, ( I will look into them ) I am still new to PHP, I am using WebORB for PHP to build a dataservice for AS3 project and its been a big learning curve for me. Thanks for your suggestions"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T16:08:18.540",
"Id": "22782",
"ParentId": "22720",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "22782",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T17:02:22.267",
"Id": "22720",
"Score": "6",
"Tags": [
"php",
"object-oriented",
"classes",
"pdo"
],
"Title": "PHP Extending PDO Class"
}
|
22720
|
<p>I'm using a lightweight jQuery popup plugin called 'bPopup'. I'm using it on my website at the moment to load multiple popup windows when clicked. I was recently told that my code was inefficient as I was loading multiple popups with multiple JavaScript 'listeners':</p>
<pre><code><script type="text/javascript">
;(function($) {
$(function() {
$('#my-button_1').bind('click', function(e) {
e.preventDefault();
$('#element_to_pop_up_32754925023').bPopup();
});
});
})(jQuery);
</script>
<script type="text/javascript">
;(function($) {
$(function() {
$('#my-button_2').bind('click', function(e) {
e.preventDefault();
$('#element_to_pop_up_95031153149').bPopup();
});
});
})(jQuery);
</code></pre>
<p>^^ The multiple JavaScript 'listeners'. And, for the Popups:</p>
<pre><code><!-- Button that triggers the popup -->
<a class="main" id="my-button_1" href="#">Popup 1</a></b><br />
<!-- Element to pop up -->
<div id="element_to_pop_up_1">
// ...
</div>
<!-- Button that triggers the popup -->
<a class="main" id="my-button_1" href="#">Popup 1</a></b><br />
<!-- Element to pop up -->
<div id="element_to_pop_up_1">
// ...
</div>
</code></pre>
<p>He's probably right (sure of it), but not sure how to implement this, or whether this is even possible (small chance he's wrong).</p>
|
[] |
[
{
"body": "<p>He is right. Think about maintenance. </p>\n\n<p>If you wanted to add another link that popped up another element you would need to add yet another listener function. Removing one would be the same thing. Too many things to keep track of.</p>\n\n<p>Change the code to add the event according to a class name and then you can bind to all at once. Then include the popup element ID within the attributes of the opener link.</p>\n\n<pre><code>$('.popup-opener').bind('click', function(e) {\n e.preventDefault();\n $($(this).attr('popup-element')).bPopup();\n});\n\n<!-- Button that triggers the popup -->\n<a class=\"main popup-opener\" popup-element=\"element_to_pop_up_1\" id=\"my-button_1\" href=\"#\">Popup 1</a></b><br />\n<!-- Element to pop up -->\n<div id=\"element_to_pop_up_1\">\n// ...\n</div>\n</code></pre>\n\n<p>Better yet, use the <code>on()</code> function to bind the event. <a href=\"http://api.jquery.com/on/\" rel=\"nofollow\">http://api.jquery.com/on/</a></p>\n\n<p>Adding new openers now requires no changes to the javascript. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T14:01:49.910",
"Id": "34957",
"Score": "0",
"body": "Yeah, figured it out yesterday (I'm a complete amateur with JS), thanks anyway!! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-25T14:50:09.287",
"Id": "96732",
"Score": "0",
"body": "I think its working with @nickles80 code. The popup button just needs to be like this (Note the `#` is added): `popup-element=\"#element_to_pop_up_1\"`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T20:42:16.793",
"Id": "22729",
"ParentId": "22724",
"Score": "1"
}
},
{
"body": "<p>The below function ( myFunction() ) takes the Id of anchor/div tag which is clicked and another id of div content to be display. And applies the same style for all popup models. And also it hides the old popup which already opened when u open new popup. All popup properties you can change.</p>\n\n<p>Here i used only for two popups but you can use it for many as same did here.</p>\n\n<pre><code><script type=\"text/javascript\">\n\nfunction myFunction(whId,whtDivContent,e) {\n //var totWidth = $(document).width();\n //var marTop = position.top;\n var elt = $(whId);\n var position = elt.position();\n var marLeft = position.left - 130;\n\n if(marLeft <= 1) {\n marLeft = 10;\n }\n\n var openModal_profile ='#openModal_profile';\n var openModal_menu ='#openModal_menu';\n\n // Prevents the default action to be triggered. \n e.preventDefault();\n\n $(whtDivContent).bPopup({\n position: [marLeft, 0] //x, y\n ,opacity: 0.9\n ,closeClass : 'b-close'\n ,zIndex: 2\n ,positionStyle: 'fixed' //'fixed' or 'absolute' 'relative'\n ,follow: [false,false] //x, y\n ,onOpen: function() {\n if(openModal_profile == whtDivContent) {\n $(openModal_menu).bPopup().close();\n }\n else if(openModal_menu == whtDivContent) {\n $(openModal_profile).bPopup().close();\n }\n\n $(whId).css({'background-color':\"#DFDFDF\"}); \n }\n ,onClose: function() { $('.close').click(); $(whId).css({'background-color':\"\"}); }\n\n });\n}\n\n\n;(function($) {\n // DOM Ready\n $(function() {\n // From jQuery v.1.7.0 use .on() instead of .bind()\n //$(id_menu).on('click',function(e) {}\n\n var id_menu = '#id_menu';\n var openModal_menu ='#openModal_menu';\n $(id_menu).toggle(function(e) {\n //$(id_menu).css({'background-color':\"#DFDFDF\"});\n myFunction(id_menu,openModal_menu,e);\n },function(e){\n //$(id_menu).css({'background-color':\"\"});\n $('.close').click();\n $(openModal_menu).bPopup().close();\n\n });\n\n var id_profile = '#id_profile';\n var openModal_profile ='#openModal_profile';\n $(id_profile).toggle(function(e) {\n //$(id_profile).css({'background-color':\"#DFDFDF\"});\n myFunction(id_profile,openModal_profile,e);\n },function(e){\n //$(id_profile).css({'background-color':\"\"});\n\n $(openModal_profile).bPopup().close();\n });\n\n //ENDS HERE \n });\n})(jQuery); \n\n\n</script>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-22T11:33:50.153",
"Id": "24245",
"ParentId": "22724",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "22729",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T18:20:11.223",
"Id": "22724",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Using multiple popup windows with bPopup"
}
|
22724
|
<p>What is the best way to <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="nofollow">DRY</a> this code up?</p>
<pre><code>class NotificationsController < ApplicationController
before_filter :load_user
def unsubscribe
if @facebook_admin && @facebook_admin.auth_key == params[:auth_key]
@facebook_admin.update_notification_settings(params[:type] => false)
elsif @user && @user.auth_key == params[:auth_key]
@user.update_notification_settings(params[:type] => false)
end
end
private
def load_user
if params[:type].present?
if params[:facebook_admin_id].present?
@facebook_admin = FacebookAdmin.find_by_id(params[:facebook_admin_id])
elsif params[:user_id].present?
@user = User.find_by_id(params[:user_id])
end
end
end
end
</code></pre>
|
[] |
[
{
"body": "<p>Verbosity of a controller is typically a signal of dubious design. As I see it, you have two sensible options:</p>\n\n<ol>\n<li><p>If <code>User</code> and <code>FacebookAdmin</code> are two very different user entities: they should be treated in two separate controllers.</p></li>\n<li><p>If <code>User</code> and <code>FacebookAdmin</code> are very similar (i.e. <code>FacebookAdmin</code> inherits from <code>User</code>): they can share the same controller but use always <code>@user</code> as variable. This way the code will be simplified dramatically.</p></li>\n</ol>\n\n<p>What you should not have is a controller full of conditional branches, that will be an unmaintainable mess (and awful to test).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T09:09:50.003",
"Id": "22743",
"ParentId": "22727",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T19:17:21.307",
"Id": "22727",
"Score": "2",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Unsubscribing Facebook admins and regular users from notifications"
}
|
22727
|
<p>I've been using JavaScript for some time now, but mostly just jQuery to prettify web pages. I've started doing some serious development with it in the last year.</p>
<p>So, I want to make sure I'm not doing something stupid. I found <a href="http://www.yuiblog.com/blog/2007/06/12/module-pattern/">a post about the module pattern</a>, and it makes sense to me, so I'm going to attempt to use it on this project instead of keeping nearly everything global.</p>
<p>I'm just a little fuzzy on where I should put event listeners. Is there going to be any issues with scope if the listener is instantiated inside a method? If I'm building something like a toolbar with different functions (kind of like a paint program with 'move', 'select', 'paintbrush', and 'eraser' options), do I keep the onClick for all of those in global scope?</p>
<pre><code>PROJ.namespace("easel");
PROJ.easel.canvas = function() {
//private variable to store current state
var current_mode = "select";
return {
enableSelect: function () {
//disable other tools, enable 'select' event listeners
}
enablePaintbrush: function () {
//disable other tools, enable 'paintbrush' event listeners
}
enableMove: function () {
//disable other tools, enable 'move' event listeners
}
enableEraser: function () {
//disable other tools, enable 'eraser' event listeners
}
};
}();
//event listeners for the tool pallete
$('#tools #paintbrush').on('click', function() { PROJ.easel.canvas.enablePaintbrush() };
$('#tools #move').on('click', function() { PROJ.easel.canvas.enableMove() };
$('#tools #select').on('click', function() { PROJ.easel.canvas.enableSelect() };
$('#tools #eraser').on('click', function() { PROJ.easel.canvas.enableEraser() };
</code></pre>
<p>Of course, once the specific tool is selected, it needs its own listeners. For example, a paintbrush needs handlers for 'mousedown' (start painting), 'mousemove' (lay down paint), and 'mouseup' (stop painting). Can those listeners be enabled inside of PROJ.easel.canvas?</p>
<p>EDIT: How are you supposed to pick an "answer" on codereview.stackexchange.com? You're asking peoples' opinions...</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T21:13:08.237",
"Id": "34914",
"Score": "1",
"body": "I strongly suggest reading http://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript it's a great resource on JS design patterns, it's free and it describes how to solve your issue in length"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T21:28:47.353",
"Id": "34918",
"Score": "0",
"body": "This looks like a good resource, I'll start reading it."
}
] |
[
{
"body": "<ul>\n<li><p>Deep Namespacing Pitfalls</p>\n\n<p>JavaScript was not designed to handle very deep namespaces and does not have built-in ways to handle such. And further more, JS is NOT your typical, classical OOP language like Java, C++ and C# so better avoid such conventions.</p>\n\n<p>Also, I forgot if I read this from a JS book or got it from a video from YUI, accessing object properties incurs a performance penalty (although minute, but still an overhead). Since the practice you have shown is basically nested objects, where properties hold objects, then it will cost you.</p>\n\n<p>As a general tip, you <em>can</em> do namespacing but avoid deep namespaces.</p></li>\n<li><p>Selecting IDs</p>\n\n<p>IDs are supposed to be unique elements in the page. Thus, specificity should not be an issue here and so you can directly just select an ID by using the ID without any other selector.</p>\n\n<pre><code>//So\n$('#tools #eraser')\n//can just be \n$('#eraser')\n</code></pre></li>\n<li><p>\"return\" module pattern vs \"append-to-namespace\" module pattern</p>\n\n<p>Well, I just made up those pattern names, but it would be easier to call them that way. </p>\n\n<p>The return module pattern has issues. For one, it completely overrides/erases an existing namespace by assigning another object to it. Secondly, having a <code>return</code> inside the module is pretty messy. Forgetting a comma is one such problem.</p>\n\n<p>Thus, the \"append-to-namespace\" pattern is better in some ways and is <a href=\"http://jsfiddle.net/b6vpP/\" rel=\"nofollow\">better explained in the actual code</a>:</p>\n\n<pre><code>//the this.namespace given below is provided into this block as ns\n(function(ns){\n\n //you can check ns for stuff appended prior to this block's execution\n //this can be seen in some libraries like RequireJS for pre-config parameters\n if(ns.somethingAttachedBefore){...}\n\n //also, instead of returning stuff to the namespace, you can append to it\n //effectively avoids object literal lists and forgotten commas\n ns.something = function(){...}\n\n\n//this line assigns an existing namespace or a new object to the given namespace\n}(this.namespace = this.namespace || {}));\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T17:53:21.070",
"Id": "34966",
"Score": "0",
"body": "I'll admit that I don't fully understand the syntax here. How is this whole thing enclosed in ()'s? Are they interchangeable with {} in JS?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T18:07:56.353",
"Id": "34969",
"Score": "0",
"body": "By the way, good info, thanks. I've often brought up the \"ID's are singular\" issue with many designers, so I know it well. I'm just more careful than warranted in this case. Probably because I've often had to code JS for a designer who used the same ID multiple times. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T19:02:12.083",
"Id": "34972",
"Score": "0",
"body": "Aha, nevermind. Self-invoking anonymous function. I'm sure I knew about those at one point in time..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T15:11:30.600",
"Id": "22754",
"ParentId": "22730",
"Score": "2"
}
},
{
"body": "<p>The way I like to use the module partern is in combination with the Oberserver pattern. I've included detailed comments in the code to help explain the two a bit. I would <strong>highly recomend you watch <a href=\"https://tutsplus.com/lesson/custom-events-and-the-observer-pattern/\" rel=\"nofollow\">this video</a></strong> by Jeffery Way. He does a really nice job of explaining the two and also some custom events, which I think you might be interested in. Also read the links he puts under the video, they'll provide you with a complete understanding of it all.</p>\n\n<p>I explain most of it in the code with comments. Anyways the following code will help you get the picture:</p>\n\n<pre><code>(function ( $, window, document, undefined ) {\n \"use strict\";\n\n var PROJ = {\n init: function() {\n //Set up my Observer Pattern\n var o = $( {} );\n $.subscribe = o.on.bind(o);\n $.unsubscribe = o.off.bind(o);\n $.publish = o.trigger.bind(o);\n\n //By using the object PROJ you can reference it with \"this\" (i.e. this.whatever();), easy peazy \"namespacing\"\n //Example:\n this.setUpListeners();\n },\n\n setUpListeners: function() {\n $('#tools #paintbrush').on('click', function() { PROJ.enablePaintbrush() };\n $('#tools #move').on('click', function() { PROJ.enableMove() };\n $('#tools #select').on('click', function() { PROJ.enableSelect() };\n $('#tools #eraser').on('click', function() { PROJ.enableEraser() };\n\n //Here is where the Observer Pattern kicks in nicely\n //I'm done with the listeners, and I'm letting everyone that is subscribed know that.\n //You can also namespace easily with \"/\" like so: (\"enable/Select\") or (\"enable/Move\") etc.\n $.publish( \"listeners/are/set/up\" );\n },\n\n enableSelect: function() {\n //do some stuff\n\n //I'm done with \"enable\", and I'm letting everyone that is subscribed know that.\n $.publish( \"enable\" );\n },\n\n enablePaint: function() {\n //do more stuff\n\n //When enable is published, run enableMove\n $.subscribe( \"enable\", this.enableMove( //You can pass arguments here to other functions, limiting the scope );\n },\n\n enableMove: function() {\n //In a callback \"this\" refers to the element in question, and not to the PROJ object\n\n //You can cache it out here:\n var self = this\n\n $(\"#something\").on( \"click\", function() {\n //To resolve that you can also cache the reference in here\n var self = PROJ\n\n //this will work\n self.enableMove();\n\n //this will not work because we are in a callback\n this.enableMove();\n\n //You can use your Pub/Sub model anywhere, even in callbacks\n $.publish( \"done/with/this/baby\" );\n });\n },\n\n enableEraser: function() {\n $.subscribe( \"done/with/this/baby\", this.enableSelect() );\n //Just like that I've created a loop, by calling enableSelect it goes back and runs it again.\n } //The last closing braquet doesn't have a comma\n }; //Close the PROJ object\n\n //Initialize the whole thing. Can be referenced anywhere in your code after it has been declared.\n PROJ.init();\n})( jQuery, window, document );\n</code></pre>\n\n<p>Hopefully that provided some insight. If there's any part which needs clarification I'll be happy to explain. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T19:32:04.097",
"Id": "34973",
"Score": "0",
"body": "Your example and the video were very helpful. I can more clearly see how this can work now. I knew about custom listeners, but hadn't made the leap to the pub/sub model yet. This was very helpful. I'll go through the links as well now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T21:07:35.377",
"Id": "34974",
"Score": "0",
"body": "What would member variables look like?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T20:49:25.367",
"Id": "35019",
"Score": "0",
"body": "``$.subscribe( 'name', function() );`` should not be ``$.subscribe( \"name\", function );`` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T04:46:00.917",
"Id": "35044",
"Score": "0",
"body": "Doesn't matter if you use \"\" or '' they both have the same effect. Usually '' is used inside \"\" for example: `$(\"div:contains('John')\")`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T04:52:28.510",
"Id": "35045",
"Score": "0",
"body": "@coding_hero does this answer your question?\nhttp://googleappsdeveloper.blogspot.com/2010/06/private-member-variables-in-javascript.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-10T22:48:23.137",
"Id": "190805",
"Score": "0",
"body": "Video link moved to `https://www.youtube.com/watch?v=eIovclygbwM`"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T16:20:42.173",
"Id": "22758",
"ParentId": "22730",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "22758",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T21:02:38.613",
"Id": "22730",
"Score": "8",
"Tags": [
"javascript",
"design-patterns"
],
"Title": "JavaScript event handlers, scope, and the module design pattern"
}
|
22730
|
<p>I'm making a comment box using a contenteditable div, but I want to remove formatting from text a user might copy/paste into it (also no <kbd>CTRL+B</kbd> or <kbd>CTRL+I</kbd> shortcuts allowed either). Only "approved" formatting ("tagged" names, URLs, etc).</p>
<p>Originally I went the regex route but was informed regex + html is not a good approach, so I then tried using jQuery/DOM manipulation and found a solution there as well. </p>
<p>I am worried though, that my jQuery selector used in <code>$nodesToReplace</code> is too long and possibly inefficient although it basically describes what I want returned. I'm just wondering if there was another more elegant/shorter/more efficient way to do this that I may have overlooked. Here's the code:</p>
<p>Two utility functions (for reference)</p>
<pre><code>// Change an Element's type (change it's html tags) to "newType"
jQuery.fn.changeElemTypeTo = function(newType){
// just make sure it's a plain element name
newType.replace(/[<\/>]/ig,'');
var newElemStr = '<' + newType + '>' + this.html() + '</' + newType + '>';
console.log('*Nodes with tags replaced: ',newElemStr);
return this.replaceWith(newElemStr);
};
// Remove/strip the html tags from an element
jQuery.fn.removeElemTags = function(){
var tmp = this.replaceWith(this.html());
console.log('*Node with tags Removed: ',this.html());
return tmp;
};
</code></pre>
<p>main handler with super long selector in <code>$nodesToReplace</code>...</p>
<pre><code>$('#input').on('paste', function() {
var $inputDiv = $(this);
setTimeout(function() {
var oldHTML = '', newHTML = '';
// look through the commentbox for headings and other (mostly) block
// elements
var $nodesToReplace = $inputDiv.find('h1,h2,h3,h4,h5,h6,address,article,aside,blockquote,div,p,pre,dd,dt');
var $nodesToRemove = $inputDiv.find('*').not($nodesToReplace);
$nodesToRemove.each(function(){
console.log('Nodes with tags to remove: ',$(this).outerHtml());
$(this).removeElemTags();
});
$nodesToReplace.each(function(){
console.log('Nodes with tags to replace: ',$(this).outerHtml());
$(this).changeElemTypeTo('p');
});
}, 10);
});
</code></pre>
<p>I also have a demo on JSBin: <a href="http://jsbin.com/adazel/10/edit" rel="nofollow">http://jsbin.com/adazel/10/edit</a></p>
|
[] |
[
{
"body": "<p>I struggled with the same issue in the past, and decided to simply use a disposable DOM element to convert the HTML to plaintext:</p>\n\n<pre><code>var message = \"...\"; // Contains HTML markup\nvar tmp = document.createElement(\"DIV\");\ntmp.innerHTML = message;\nvar message = tmp.textContent||tmp.innerText;\n// message now contains plaintext, and tmp can be disposed of\n</code></pre>\n\n<p>With this approach, we still needed to allow the user to enter a single tag. For this, we simply implemented a microformat where the user enters \"placeholders\" with bracket symbols:</p>\n\n<blockquote>\n <p>Hello [[person]], having a good day?</p>\n</blockquote>\n\n<p>Since this is just plain text, it will not be removed by the above conversion process, and can simply be replaced with the appropriate HTML tags:</p>\n\n<pre><code>message.replace('/\\[\\[person\\]\\]/g', '<strong>some name</strong>');\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-01T19:47:48.167",
"Id": "41639",
"Score": "0",
"body": "wow thanks, can't believe I didn't know about the `textContent` property before"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T17:30:34.337",
"Id": "26162",
"ParentId": "22731",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "26162",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T21:04:34.530",
"Id": "22731",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"dom",
"formatting"
],
"Title": "Stripping formatting from text - Am I using an efficient jQuery selector?"
}
|
22731
|
<p>I'm writing the markup for <a href="https://i.stack.imgur.com/H9CKZ.jpg" rel="nofollow noreferrer"><em>Corpora - A Business Theme</em></a>:</p>
<p>And started from the header section:</p>
<p><img src="https://i.stack.imgur.com/M9Y7W.jpg" alt="Screenshot of header"></p>
<p>Here is my markup for it:</p>
<pre><code><header>
<div class="topHeaderPart">
<a href="#" class="logo">
<img src="images/logo.png" alt="Corpora - A Business Theme">
</a>
<ul class="primaryContacts">
<li><address>Phone: <em class="headerPhone">1.800.corp</em></address></li>
<li><address>Email: <em class="headerEmail">office@corpora.com</em></address></li>
<li><address>Follow Us: <a href="#" class="headerRSS"></a><a href="#" class="headerTwitter"></a><a href="#" class="headerFacebook"></a></address></li>
</ul>
</div> <!-- topHeaderPart -->
<nav>
<a href="#">Home<br><span>go to start</span></a>
<a href="#">Services<br><span>what we do</span></a>
<a href="#">Gallery<br><span>our best products</span></a>
<a href="#">Our Clients<br><span>what we've done for others</span></a>
<a href="#">About Us<br><span>who we are</span></a>
<a href="#">Contact Us<br><span>let's keep in touch</span></a>
</nav>
<div class="slider">
<div class="slides">
<a href="#" class="slideButton prev"></a>
<a href="#" class="slideButton next"></a>
<section id="slide1">
<h1>Awesome business card design</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Curabitur eget metus ac diam laoreet luctus rhoncus non nisi. Aenean at lobortis augue.</p>
<a href="#" class="buyNow">Buy it now</a> <span>or <a href="#">Find Out More</a></span>
<img src="images/slide1.png" alt="slide1-image">
</section>
<section id="slide2">
<h1>Awesome business card design</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Curabitur eget metus ac diam laoreet luctus rhoncus non nisi. Aenean at lobortis augue.</p>
<a href="#" class="buyNow">Buy it now</a> <span>or <a href="#">Find Out More</a></span>
<img src="images/slide1.png" alt="slide1-image">
</section>
<!-- ... -->
<section id="slideN">
<h1>Awesome business card design</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Curabitur eget metus ac diam laoreet luctus rhoncus non nisi. Aenean at lobortis augue.</p>
<a href="#" class="buyNow">Buy it now</a> <span>or <a href="#">Find Out More</a></span>
<img src="images/slide1.png" alt="slide1-image">
</section>
</div> <!-- slides -->
</div> <!-- slider -->
</header>
</code></pre>
<p>Does it semantically correct? Special attention for tags <code>address</code>, <code>em</code>, <code>span</code>, <code>section</code>. <br> Many thanks to you all.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T21:21:14.560",
"Id": "34917",
"Score": "3",
"body": "Welcome, SakerONE! Thanks for your question; I embedded the header screenshot for you."
}
] |
[
{
"body": "<h3><code>address</code></h3>\n<p>I'd enclose the <code>ul.primaryContacts</code> in <em>one</em> <code>address</code> element (not every item separately):</p>\n<pre><code><address>\n <ul class="primaryContacts">\n <li>Phone: <em class="headerPhone">1.800.corp</em></li>\n <li>Email: <em class="headerEmail">office@corpora.com</em></li>\n <li>Follow Us: <a href="#" class="headerRSS"></a><a href="#" class="headerTwitter"></a><a href="#" class="headerFacebook"></a></li>\n </ul>\n</address>\n</code></pre>\n<h3>links without content</h3>\n<p>Your follow links don't contain any content: <code><a href="#" class="headerRSS"></a><a href="#" class="headerTwitter"></a><a href="#" class="headerFacebook"></a></code></p>\n<p>Screenreader users wouldn't be able to make sense of these links.</p>\n<p>Either add the text to it (and visually hide it, and display the icons via CSS), or use <code>img</code> here (together with the <code>alt</code> attribute, of course).</p>\n<p>Same problem with the two slideButtons (<code><a href="#" class="slideButton prev"></a></code>).</p>\n<h3><code>em</code></h3>\n<p>I don't think the <code>em</code> element is correct in these cases:</p>\n<ul>\n<li><code><em class="headerPhone">1.800.corp</em></code></li>\n<li><code><em class="headerEmail">office@corpora.com</em></code></li>\n</ul>\n<p><a href=\"http://www.w3.org/TR/html5/text-level-semantics.html#the-em-element\" rel=\"nofollow noreferrer\">http://www.w3.org/TR/html5/text-level-semantics.html#the-em-element</a>:</p>\n<blockquote>\n<p>The <code>em</code> element represents <strong>stress emphasis</strong> of its contents.</p>\n</blockquote>\n<p>And, important:</p>\n<blockquote>\n<p>The placement of stress emphasis changes the meaning of the sentence.</p>\n</blockquote>\n<p>In your cases the <code>em</code> doesn't change any meaning. You wouldn't stress the phone number or the email address while reading.</p>\n<h3>contact URIs</h3>\n<p>You could link your contact details:</p>\n<ul>\n<li><code><a class="headerPhone" href="tel:…">1.800.corp</a></code> (with the <a href=\"https://www.rfc-editor.org/rfc/rfc3966\" rel=\"nofollow noreferrer\"><code>tel</code> URI scheme</a>)</li>\n<li><code><a class="headerEmail" href="mailto:office@corpora.com">office@corpora.com</a></code> (with the <a href=\"http://en.wikipedia.org/wiki/Mailto\" rel=\"nofollow noreferrer\"><code>mailto</code> URI scheme</a>)</li>\n</ul>\n<h3><code>br</code></h3>\n<p>You use <code>br</code> in the navigation (<code><a href="#">Home<br><span>go to start</span></a></code>), but this is <a href=\"http://www.w3.org/TR/html5/text-level-semantics.html#the-br-element\" rel=\"nofollow noreferrer\">not a correct use</a>:</p>\n<blockquote>\n<p><code>br</code> elements must be used only for line breaks <strong>that are actually part of the content</strong>, as in poems or addresses.</p>\n</blockquote>\n<h3>site heading</h3>\n<p>Your page should probably have a site heading. Currently your <a href=\"http://gsnedders.html5.org/outliner/\" rel=\"nofollow noreferrer\">outline</a> would be:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Untitled Section\n Untitled Section\n Awesome business card design\n Awesome business card design\n Awesome business card design\n</code></pre>\n<p>In your case, the logo (resp. the <code>alt</code> value) is the site/page heading, so you'd have:</p>\n<pre><code><h1>\n <a href="#" class="logo">\n <img src="images/logo.png" alt="Corpora - A Business Theme">\n </a>\n</h1>\n</code></pre>\n<h3>slider</h3>\n<p>It depends on content and context of your page if the slider should be part of <code>header</code> or not. Is the slider present on all pages? Then it's probably correct to place it in the <code>header</code>. But if it would be part of the main content of a page, it shouldn't be in the <code>header</code>.</p>\n<p>I think you should enclose the whole slider in a <code>section</code> (resp. <code>aside</code>); if possible, find a heading for it. As soon as you use such a sectioning element for the slide, you can enclose the two slide buttons in a <code>nav</code> element (as they are the main navigation <em>for that sectioning element</em>). Also, each slide could be an <code>article</code> (instead of a <code>section</code>).</p>\n<p>Then you'd get the following outline (together with the site heading mentionend before):</p>\n<pre class=\"lang-none prettyprint-override\"><code>Corpora - A Business Theme\n Untitled Section (this is your site nav)\n Untitled Section (this is the slider heading)\n Untitled Section (this is your slider nav)\n Awesome business card design\n Awesome business card design\n Awesome business card design\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T12:00:12.883",
"Id": "22748",
"ParentId": "22732",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "22748",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T21:13:48.820",
"Id": "22732",
"Score": "8",
"Tags": [
"html",
"html5"
],
"Title": "Semantically correct html5 markup"
}
|
22732
|
<p>So the task is that a string being passed to one of my methods looks like this</p>
<p><code><DIV><GKY><UID><END></code></p>
<p>it is generated this way from another program, so it will always have that format. Now to sum up how it works is like this.. This is to represent 3 byte arrays a DIV key (short for diversification) a Guest Key (GKY), and a Unique ID (UID). This particular class that i made stores those byte arrays as a 2 character hex string. IE {0x03, 0xFE, 0xE0} would be stored as "03FEE0"</p>
<p>so those are the requirements of the class.. I have to be able to parse that string to store those byte arrays for access later. DIV (if present) will always be 16 bytes long. GKY is variable and can be at most 192 bytes. UID is required and will always be present and is always 7 bytes. so I came up with this... as far as I can tell it works.</p>
<pre><code>#pragma once
class KeyInputParser
{
public:
KeyInputParser(void)
{
//DIV will always be 16bytes... but it is either not required
DIV = new char[32];
//uid will ALWAYS be 7 bytes and is required
UID = new char[14];
}
~KeyInputParser(void)
{
delete[] DIV;
delete[] GKY;
delete[] UID;
}
char* DIV;
char* GKY;
char* UID;
void SetKeyString(const char* str)
{
wcout << "KeyInputParser::SetString()+" << endl;
wcout << "\t" << str << endl;
char* div;
char* gky;
char* uid;
div = (char*)memchr(str, '>', strlen(str));
div++;
gky = (char*)memchr(div, '>', strlen(div));
gky++;
uid = (char*)memchr(gky, '>', strlen(gky));
uid++;
for(int i=0; i<strlen(div); i++)
{
if(div[i] == '<')
{//DIV will always be 16bytes... but it is either not required
memcpy(DIV, div, i);
DIV[i] = '\0';
break;
}
}
for(int i=0; i<strlen(gky); i++)
{//gky will vary, but max out at 192 bytes
if(gky[i] == '<')
{
GKY = new char[i+1];
memcpy(GKY, gky, i);
GKY[i] = '\0';
break;
}
}
for(int i=0; i<strlen(uid); i++)
{//uid will ALWAYS be 7 bytes and is required
if(uid[i] == '<')
{
memcpy(UID, uid, i);
UID[i] = '\0';
break;
}
}
wcout << "KeyInputParser::SetString()-" << endl;
}
};
</code></pre>
<p>I don't care for the way it came out, but I am very new to C++.</p>
|
[] |
[
{
"body": "<p>First of all separate code into header (<code>.hpp</code>) and implementation file (<code>.cpp</code>)</p>\n\n<p><strong>Header : (<code>my_header.hpp</code>)</strong></p>\n\n<pre><code>#ifndef MY_HEADER\n#define MY_HEADER\nclass KeyInputParser\n{\npublic:\n KeyInputParser () // there is no need for funcName (void) in C++\n ~KeyInputParser () // that is neccessary only for C\n char* DIV;\n char* GKY;\n char* UID;\n void SetKeyString (const char* str);\n // Progress bewteen div, gky and uid\n char* Progress (char* previous);\n // Get data between <>\n void ExtractField (char* small, char* big);\n};\n#endif\n</code></pre>\n\n<p><strong>Implementation : (<code>my_code.cpp</code>)</strong></p>\n\n<pre><code>#include <cstring> \n#include \"my_header.hpp\"\n\nKeyInputParser::KeyInputParser () \n{\n //DIV will always be 16bytes... but it is either not required\n DIV = new char[32];\n //uid will ALWAYS be 7 bytes and is required\n UID = new char[14];\n}\n\nKeyInputParser::~KeyInputParser () \n{\n delete[] DIV;\n delete[] GKY;\n delete[] UID;\n}\n\nchar* KeyInputParser::Progress (char* previous) \n{\n char* arr = (char*) memchr (previous, '>', strlen (previous));\n arr++;\n return arr;\n}\n\nvoid KeyInputParser::ExtractField (char* small, char* big) \n{\n for(int i = 0; i < strlen (small); i++)\n {\n if(small [i] == '<')\n {\n memcpy (big, small, i);\n big[i] = '\\0';\n break;\n }\n }\n}\nvoid KeyInputParser::SetKeyString (const char* str) \n{\n char* div = Progress (str);\n char* gky = Progress (div);\n char* uid = Progress (gky);\n\n ExtractField (div, DIV);\n // Code for GKY will be copied due to allocation\n // It might be possible to fix it to be used with ExtractField function\n for(int i = 0; i < strlen (gky); i++)\n {\n if(gky[i] == '<')\n {\n GKY = new char[i+1];\n memcpy(GKY, gky, i);\n GKY[i] = '\\0';\n break;\n }\n }\n ExtractField (uid, UID);\n}\n</code></pre>\n\n<p>This is just a rough refactoring of your code.\nThe thing number one that will need to be fixed is to drop all those C string functions and use <code>std::string</code> instead.</p>\n\n<p>I did not test the code so I cannot guarantee that it will work but this is how it should look like. Hope I helped :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T16:25:37.553",
"Id": "34964",
"Score": "1",
"body": "Your code seems to work great, and looks a billion times better too. I really wish I had started this project and hadn't inherited it otherwise I would use string. I only had to change 2 things in your code to make it work. one was to add const to the input parameter in Progress. And the other was to rename small to something else. small was predefined word in Visual studio."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-05-18T16:07:08.747",
"Id": "311159",
"Score": "0",
"body": "`GKY` is left uninitialized in the KeyInputParser constructor. If SetKeyString is never called, the destructor call will call `delete[]` on a random pointer, with unforeseeable consequences. if SetKeyString is called more than once, you will get a memory leak."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T16:06:52.250",
"Id": "22756",
"ParentId": "22734",
"Score": "2"
}
},
{
"body": "<p>To add to the previous poster, while some would say stay away from <code>#pragma once</code> and use include guards I say use away IF and only IF you know it will only be compiled on one compiler(assuming its a proprietary piece of software) if it is an open source project make sure to use include guards after you do the the pragma something like this</p>\n\n<pre><code>#pragma once\n#ifndef HEADER_H\n#define HEADER_H\n//class definition\n#endif //HEADER_H\n</code></pre>\n\n<p>At least then in that case pragma will be used first and speed up compilation if its supported, if not it will be ignored and the include guards will be used instead. <code>#pragma once</code> directive tells the compiler to include this file only once whereas include guards check to see if this macro has already been defined previously. Also I would do</p>\n\n<pre><code>std::string DIV;\nstd::string GKY;\nstd::string UID;\n</code></pre>\n\n<p>This would avoid needing to do any news or deletes in the constructor and destructor. std::string is a mutable data structure. Also separate the implementation and the class definition and avoid using too many C style functions if there is a C++ way of doing it. Also this method is much too long,</p>\n\n<pre><code>void SetKeyString(const char* str)\n{\n wcout << \"KeyInputParser::SetString()+\" << endl;\n wcout << \"\\t\" << str << endl;\n\n char* div;\n char* gky;\n char* uid;\n\n div = (char*)memchr(str, '>', strlen(str));\n div++;\n\n gky = (char*)memchr(div, '>', strlen(div));\n gky++;\n\n uid = (char*)memchr(gky, '>', strlen(gky));\n uid++;\n\n for(int i=0; i<strlen(div); i++)\n {\n if(div[i] == '<')\n {//DIV will always be 16bytes... but it is either not required\n memcpy(DIV, div, i);\n DIV[i] = '\\0';\n break;\n }\n }\n for(int i=0; i<strlen(gky); i++)\n {//gky will vary, but max out at 192 bytes\n if(gky[i] == '<')\n {\n GKY = new char[i+1];\n memcpy(GKY, gky, i);\n GKY[i] = '\\0';\n break;\n }\n }\n for(int i=0; i<strlen(uid); i++)\n {//uid will ALWAYS be 7 bytes and is required\n if(uid[i] == '<')\n {\n memcpy(UID, uid, i);\n UID[i] = '\\0';\n break;\n }\n }\n\n wcout << \"KeyInputParser::SetString()-\" << endl;\n}\n</code></pre>\n\n<p>break it up into smaller methods that pass the work between them, makes it more readable and maintainable. Also change the <code>char *</code>'s in the program to use <code>std::string</code> I'm going to assume you're a newish programmer so you might think \"nobody is going to be maintaining my code\" while that may be true, you should act like they will be and get into the habit of using best practices. Hope this helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T17:06:57.127",
"Id": "35747",
"Score": "0",
"body": "although I am not a new programmer, I am new to C++. I have learned the lesson that others will maintain my code but thank you for the reminder. I have had a few moments when reviewing my own code a few months after the fact that I was like...what was I thinking... which is about the same as someone else editing my code. I tried using string the other day with this and was having a hard time getting it to work properly. I tried only with one variable (UID) since it was always present, but I had problems. I should try again though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T18:08:39.237",
"Id": "35754",
"Score": "0",
"body": "Glad to be of help, changing those `char *`'s to std::string's should be easy enough and instead of using `strlen()` you can just do something like this\n`std::string whatever = \"abcdefgh\";\nwhatever.length();`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T15:34:27.417",
"Id": "23170",
"ParentId": "22734",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "22756",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T21:58:13.243",
"Id": "22734",
"Score": "2",
"Tags": [
"c++",
"parsing"
],
"Title": "String parser review"
}
|
22734
|
<p>As the title says, I'm trying to make my code less horrible looking! For a university practical, I've to use recursive methods to return the even references in a collection of Integer objects stored in an <code>ArrayList</code>.</p>
<p>For example, if the input is [1, 2, 3, 4], my method should return [1, 3] (i.e. elements 0 and 2, the even elements).</p>
<p>My code works, but I feel is horrible:</p>
<pre><code>import java.util.*;
public class ListMethods {
public static ArrayList<Integer> evenList (ArrayList<Integer> tList) {
ArrayList<Integer> newList = ListMethods.deepClone(tList);
int tempStorage = newList.size();
if (newList.size() <= 0)
return newList;
else
{
if (newList.size()%2==0)
tempStorage = newList.remove(newList.size()-2);
newList.remove(newList.size()-1);
newList = ListMethods.evenList(newList);
if (tempStorage!=0)
newList.add(tempStorage);
}
return newList;
}
public static ArrayList<Integer> deepClone (ArrayList<Integer> tList) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (Integer i : tList)
list.add(new Integer(i));
return list;
}
public static void main (String[] args) {
ArrayList<Integer> tempList = new ArrayList<Integer>();
tempList.add(1);
tempList.add(2);
tempList.add(3);
tempList.add(4);
tempList.add(5);
tempList.add(6);
for (Integer i : tempList)
{ System.out.println (i); }
ArrayList<Integer> evenList = ListMethods.evenList(tempList);
System.out.println();
for (Integer i : evenList)
{ System.out.println (i); }
}
}
</code></pre>
<p>The cloning section I have to include, at our lecturer's request. The real part I'm looking to tidy up is the <code>if/else</code> inside the <code>evenList</code> method.</p>
<p>Does anybody have any ideas?</p>
|
[] |
[
{
"body": "<p>I'm not sure if you're tied to having the method signature <code>public static ArrayList<Integer> evenList(ArrayList<Integer> tList)</code> and if you have to use the <code>deepClone</code> method you've got here, but if you aren't tied down to these restrictions, there are cleaner ways of doing this.</p>\n\n<p>Firstly, one of the main points of recursion is using the stack to store state - this doesn't seem to really come through in your example. Let's think about the problem a bit: we want to go over each element in our list, adding that element to another list if the index of that element is even. How would we do this in \"normal\" code? Well, we'd just loop over the <code>List</code> with a <code>for</code> loop, probably:</p>\n\n<p>(Note: I use <code>List<Integer></code> here instead of <code>ArrayList<Integer></code>. This may not make sense to you yet - if so, just mentally replace every <code>List<Integer></code> with <code>ArrayList<Integer></code>.)</p>\n\n<pre><code>public static List<Integer> evenList(List<Integer> tList) \n{\n List<Integer> result = new ArrayList<Integer>();\n for(int i = 0; i < tList.size(); ++i) {\n if(i % 2 == 0) {\n result.add(tList.get(i));\n }\n }\n return result;\n}\n</code></pre>\n\n<p>So converting this to recursive code, what state do we store in the function that we can store on the stack instead? Well, both the result and the index, <code>i</code>. So instead of creating a new <code>List</code> that we return, let's pass both of those in as parameters instead:</p>\n\n<pre><code>public static void evenList(List<Integer> tList, List<Integer> result, int index)\n</code></pre>\n\n<p>So, with this recursive method, how will we know when to stop? Well, exactly like in our <code>for</code> loop: when our index is at <code>tList.size()</code>:</p>\n\n<pre><code>public static void evenList(List<Integer> tList, List<Integer> result, int index)\n{\n if(index < tList.size()) {\n ...\n }\n}\n</code></pre>\n\n<p>Ok, so what about the logic? Well, it hasn't really changed much - we still want to do the exact same thing, that is, if index is even, add the element at that index to our result list:</p>\n\n<pre><code>public static void evenList(List<Integer> tList, List<Integer> result, int index)\n{\n if(index < tList.size()) {\n if(index % 2 == 0) {\n result.add(tList.get(index));\n }\n ...\n}\n</code></pre>\n\n<p>Now, we need a call to the function itself (otherwise it wouldn't be recursive!), but what parameters do we pass through? Well, we always need <code>tList</code>, so that should go through. We want to keep adding to the same <code>result</code>, so that should go through. However, our index needs to change - we want to test the next element - so that should be <code>++index</code>. So our final function looks like:</p>\n\n<pre><code>public static void evenList(List<Integer> tList, List<Integer> result, int index)\n{\n if(index < tList.size()) {\n if(tList.get(index) % 2 == 0) {\n result.add(tList.get(index));\n }\n evenList(tList, result, ++index);\n }\n}\n</code></pre>\n\n<p>I'm not really sure why your professor has you using <code>clone</code> methods here - it's really inefficient. Every single recursive call, you call <code>deepClone</code> on the <code>List</code> you pass in - this is a lot of wasted effort. </p>\n\n<p>In fact, if we were being really clever here, we would see that every second element gets added to our return list, so we can skip one of the <code>if</code> checks:</p>\n\n<pre><code>public static void evenList(List<Integer> tList, List<Integer> result, int index)\n{\n if(index < tList.size()) {\n result.add(tList.get(index));\n index += 2;\n evenList(tList, result, index);\n }\n}\n</code></pre>\n\n<p>Of course, this only works properly when the user passes in an even initial value, presumably 0. So let's make sure that happens. Let's make this method private and supply the starting index:</p>\n\n<pre><code>private static void evenList(List<Integer> tList, List<Integer> result, int index)\n{\n if(index < tList.size()) {\n result.add(tList.get(index));\n index += 2;\n evenList(tList, result, index);\n }\n}\n\npublic static void evenList(List<Integer> tList, List<Integer> result)\n{\n evenList(tList, result, 0);\n}\n</code></pre>\n\n<p>If you are tied to the original method signature, well, I've typed a lot of stuff for not much good I suppose, although I'd have to question why your professor had made you do it this way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T23:59:15.977",
"Id": "34926",
"Score": "0",
"body": "This is really useful to help me get better at recursion... ... ... unfortunately though, I am tied to the method parameter. I have to take it that way and I have to clone it. It's really just the other stuff that I can change (and I think he'll test it with both odd and even)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T00:18:39.483",
"Id": "34927",
"Score": "0",
"body": "@AndrewMartin Well, your code isn't horrible, given the restrictions placed on you. The restrictions themselves on the other hand seem very poor. Also, is there a reason you have `if (tempStorage!=0)` as a test? Nothing in your description mentions not adding elements with value `0`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T00:41:45.193",
"Id": "34929",
"Score": "0",
"body": "Well it was because originally it kept printing a 0 at the end, but that seems to have gone now, so I can take it out. Yeah, the restrictions are kinda arbitrary. It's quite confusing knowing what I'm allowed to do and what not. We're not allowed any guidance as its assessed. My code DOES work, i just don't like things like .size() - 2. Seems... too hacky"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T23:54:01.580",
"Id": "34983",
"Score": "0",
"body": "Just wanted to add that I found this solution really helpful and much easier. However, I've chosen not to use it, purely because I'm always cautious about doing something beyond what our lecturers have requested - if they say use ArrayList, I don't want to risk losing marks simply because they've decided I'm not following instructions."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T23:55:16.057",
"Id": "22737",
"ParentId": "22736",
"Score": "4"
}
},
{
"body": "<ol>\n<li><p>The original list is not changing. List has a subList(int fromIndex, int toIndex) method. So there is no need to clone the items in the list, or to write your own \"deepClone\" method.</p></li>\n<li><p>Recursion is a technique most often associated with functional programming, so there are a few things I'd do to make this example more \"functional.\"</p></li>\n</ol>\n\n<p>2.a. Replace tempList with an immutable list, call it \"inList\" for input-list:</p>\n\n<pre><code>final List<Integer> inList;\n{\n List<Integer> tempList = new ArrayList<Integer>();\n tempList.add(1);\n tempList.add(2);\n tempList.add(3);\n tempList.add(4);\n tempList.add(5);\n tempList.add(6);\n inList = Collections.unmodifiableList(tempList);\n}\n</code></pre>\n\n<p>2.b. @Yuushi had a lot of really good suggestions, but for this specific example, I'm not excited about his stylistic choice of making evenList() return void. We can make it a function, that evaluates to something, and for that, we want to keep closer to your original signature, just a slightly more generic version with Lists replacing ArrayLists (this accommodates the Unmodifiable list and is generally better style):</p>\n\n<pre><code>List<Integer> evenList (List<Integer> tList)\n</code></pre>\n\n<p>OK, now here's the recipe for a recursive function like this one that takes the place of a loop in imperative programming:</p>\n\n<p>How to write a recursive function.</p>\n\n<ol>\n<li><p>determine simplest possible input and output types for your method signature.</p></li>\n<li><p>(Optional) define invalid input conditions (throw exceptions for invalid input)</p></li>\n<li><p>define termination conditions (how to know from the input when you are done)</p></li>\n<li><p>define what to return when termination condition is reached</p></li>\n<li><p>(Optional) Sometimes you may have a special return for the pre-termination condition?</p></li>\n<li><p>define what to return in all other cases</p></li>\n</ol>\n\n<p>Like a loop, you want to define your exit condition up front, but unlike a loop, a tail-recursive function \"unrolls\" from the outside-in, like winding up a top and letting it go. So the exit condition of the loop will also be the creation condition for your first return value.</p>\n\n<pre><code>List<Integer> evenList (List<Integer> tList) {\n if (evenList.length() < 1) {\n return new ArrayList<Integer>();\n }\n // TODO: You have to handle the case where evenList.length() == 1\n // Since this is homework, I can't just give you the whole answer.\n // Without that case, there is a bug.\n</code></pre>\n\n<p>Replacing mutable variables with final ones is more functional. <a href=\"http://glenpeterson.blogspot.com/2013/01/ternary-operator-in-java.html\" rel=\"nofollow\">Using the ?: operator instead of if/else</a> for evaluation - this is more functional as well.</p>\n\n<pre><code> final int keeperIdx = (evenList.length() % 2) == 0 ?\n evenList.length() - 2 :\n evenList.length() - 1;\n\n // Here is the recursive call, passing a slice of the original list.\n // parameters to subList are first zero-based index inclusive, and last\n // index exclusive.\n // prepend the result of this recursive eventList() call to your output.\n return evenList(tList.subList(0, keeperIdx))\n .add(0, tList.get(keeperIdx));\n}\n</code></pre>\n\n<p>I did not test this code, and I left out one necessary condition (clearly marked with a TODO). I hope that it shows enough of the concepts for you to get it working. I'm assuming that your teacher wants to teach you some functional programming concepts, so I tried to lean as far in that direction as Java will comfortably go. I hope it helps!</p>\n\n<p>P.S. There is a small chance that I got confused and am returning your result in reverse order. See if you can mentally figure out whether that's the case, and what three characters to delete if it is.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T08:33:01.447",
"Id": "34938",
"Score": "0",
"body": "Thanks for this excellent post. I'll work my way through it and fix my work accordingly. The Deep Clone has to be in there though, at my lecturer's request, or else I'd gladly drop it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T23:49:42.117",
"Id": "34982",
"Score": "0",
"body": "I forgot to send the comment. @GlenPeterson: The return statement is not working this way in Java and some small typos. But the general idea will work. I would not use the way with the keeperIdx (and avoid the ternary, just do size - 1 - size%2 or size&1), but this is only a small point compared to the general idea."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T04:37:55.373",
"Id": "22739",
"ParentId": "22736",
"Score": "0"
}
},
{
"body": "<p>Well, what we want to do? Add every second element to the new list, starting with the first.<br>\nSo a simplified description could be:</p>\n\n<pre><code>function evenList(list)\n if list is empty or has only 1 element\n return list\n return new list(first element of list, evenList(all elements from the third to the end))\n</code></pre>\n\n<p>translate to algorithm in Java:</p>\n\n<pre><code>public static List<Integer> evenList(final List<Integer> list) {\n if (list.size() <= 1)\n return list;\n\n final List<Integer> newList = new ArrayList<>(Arrays.asList(list.get(0)));\n newList.addAll(evenList(list.subList(2, list.size())));\n return newList;\n}\n</code></pre>\n\n<p>This version has (after compilation) the exact same signature. If it must be the same before compilation, we could do this:</p>\n\n<pre><code>public static ArrayList<Integer> evenList2(final ArrayList<Integer> list) {\n if (list.size() <= 1)\n return list;\n\n final ArrayList<Integer> newList = new ArrayList<>(Arrays.asList(list.get(0)));\n newList.addAll(evenList2(new ArrayList<>(list.subList(2, list.size()))));\n return newList;\n}\n</code></pre>\n\n<p>I would suggest to use the first version.</p>\n\n<hr>\n\n<p>About your code:</p>\n\n<pre><code>public static ArrayList<Integer> evenList (ArrayList<Integer> tList) {\n</code></pre>\n\n<p>The name is not that helpful. I would suggest <code>getNewListFromEvenIndices</code>. But ok, you are forced to use this name. You could propose it at least.</p>\n\n<hr>\n\n<pre><code>ArrayList<Integer> newList = ListMethods.deepClone(tList);\n</code></pre>\n\n<p>Could be:</p>\n\n<pre><code>ArrayList<Integer> newList = new ArrayList<Integer>(tList);\n</code></pre>\n\n<hr>\n\n<pre><code>int tempStorage = newList.size();\n</code></pre>\n\n<p>You could name it <code>size</code> or <code>newListSize</code>, this would be a more clear name.\n(As we see later, this variable is not needed)</p>\n\n<hr>\n\n<pre><code>if (newList.size() <= 0)\n return newList;\n</code></pre>\n\n<p>Either use your variable or even better, use <code>newList.isEmpty()</code> to make the meaning clear.</p>\n\n<hr>\n\n<pre><code>else \n{ \n</code></pre>\n\n<p>You do not need to specify an else clause here. Save braces, save intendation.</p>\n\n<hr>\n\n<pre><code> if (newList.size()%2==0) \n</code></pre>\n\n<p>Even if it is quite clear, I would suggest in such case to introduce a private method which is called <code>isEven</code>. Because it is not clear for all readers.\nAnd if we make it this way, we could also switch to a logical and:</p>\n\n<pre><code>private boolean isEven(int number)\n{\n return (number & 1) == 0;\n}\n</code></pre>\n\n<hr>\n\n<pre><code> tempStorage = newList.remove(newList.size()-2);\n</code></pre>\n\n<p>This does not make any sense. Before, <code>tempStorage</code> was the size, now it is the value of a list element. This are 2 completely different meanings.<br>\nYou should not do such things. (And It will obviously fail for the example [0, 0])</p>\n\n<hr>\n\n<pre><code> newList.remove(newList.size()-1); \n newList = ListMethods.evenList(newList); \n if (tempStorage!=0)\n newList.add(tempStorage); \n</code></pre>\n\n<p>I am not sure about the plan behind this. You want to remove the last element, which should have an uneven index here?\nAfter this, you want to add the element at the probably even index?\nYou can not do it in this way then, you have to introduce for example some boolean variable which could be named <code>elementFromSecondLastIndexMustBeAdded</code> and add it only if it is true.<br>\nAnd you do not need to save it temporally, you could just access the original list <code>tList</code>.</p>\n\n<hr>\n\n<p>So if we try to keep your way, we could have something like:</p>\n\n<pre><code>public static ArrayList<Integer> evenList(final ArrayList<Integer> tList) {\n // plan: if list is empty, return. If not look at the last indices.\n // Remove the uneven one, add the even one to a new list.\n // Do this in recursion until we do not have any last indices.\n if (tList.isEmpty())\n return newList;\n ArrayList<Integer> newList = new ArrayList<>(tList);\n boolean elementFromSecondLastIndexMustBeAdded = false;\n if (isEven(newList.size())) { // if size is even, the last is uneven, the second last is even\n elementFromSecondLastIndexMustBeAdded = true;\n newList.remove(newList.size() - 2);\n }\n newList.remove(newList.size() - 1);\n newList = ListMethods.evenList(newList);\n if (elementFromSecondLastIndexMustBeAdded)\n newList.add(tList.get(tList.size() - 2));\n return newList;\n}\n\nprivate static boolean isEven(final int number) {\n return (number & 1) == 0;\n}\n</code></pre>\n\n<p>The method is still rather complex and needs some comments, because your recursion goes over the end, which is a bit unusual if both cases are possible.</p>\n\n<hr>\n\n<p>And just because I do not like such question were seomone is forced to make bad solutions:</p>\n\n<pre><code>public static List<Integer> evenList(final List<Integer> list) {\n final List<Integer> newList = new ArrayList<>();\n for (int i = 0; i < list.size(); i += 2)\n newList.add(list.get(i));\n return newList;\n}\n</code></pre>\n\n<p>This is valid according to the method signature.</p>\n\n<hr>\n\n<p>If you really have to add a deepClone method, add one with an empty body. Hint: If we are exact, this is not a clone method. For int, yes. For Integer, no.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T17:27:30.220",
"Id": "35373",
"Score": "0",
"body": "why do you say it is not a clone method, I don't get it and I'm curious..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T14:15:27.297",
"Id": "22750",
"ParentId": "22736",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "22737",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-02-14T23:00:32.623",
"Id": "22736",
"Score": "4",
"Tags": [
"java",
"recursion"
],
"Title": "Finding objects with even references tidier"
}
|
22736
|
<p>So I am working on a LMS project and I have a User class that will handle everything about the user such as registration, login, showing list of courses that they are subscribed to, etc.</p>
<p><b>User.class.php</b></p>
<pre><code>class User {
protected $_firstName;
protected $_lastName;
protected $_email;
protected $_username;
protected $_password;
protected $_createdOn;
protected $_userLevel;
protected $_salt = '}$YY lGC6&wib=w{dpqgzXv>{)A3w)5@mi`/Q7HK|/GwZ6)K<4I~Ey-bQ';
public function getFirstName() { return $this->_firstName; }
public function setFirstName($value) {
$this->_firstName = $value;
if (empty($value)) {
setError('firstName', 'Enter your first name.');
} else if (strlen($value) < 2) {
setError('firstName', 'The name you provided is too short.');
} else if (!ctype_alpha(str_replace(array('-',' '), '', $value))) {
setError('firstName', 'The name you provided can only contain letters.');
}
}
public function getLastName() { return $this->_lastName; }
public function setLastName($value) {
$this->_lastName = $value;
if (empty($value)) {
setError('lastName', 'Enter your last name.');
} else if (strlen($value) < 2) {
setError('lastName', 'The name you provided is too short.');
} else if (!ctype_alpha(str_replace(array('-',' '), '', $value))) {
setError('lastName', 'The name you provided can only contain letters.');
}
}
public function getEmail() { return $this->_email; }
public function setEmail($value) {
$this->_email = $value;
$pattern = '!^.{1,}@.{2,}$!i';
if (empty($value)) {
setError('email', 'Enter your email.');
} else if (substr_count($value, '@') != 1 and !preg_match($pattern, $value)) {
setError('email', 'The email you provided is not valid.');
}
}
public function getUsername() { return $this->_username; }
public function setUsername($value) {
$this->_username = strtolower($value);
if (empty($value)) {
setError('username', 'Enter your username.');
} else if (strlen($value) < 6) {
setError('username', 'The username you provided must have at least 6 characters.');
} else if (!ctype_alnum(str_replace('_', '', $value))) {
setError('username', 'The username you provided can only contain letters, numbers, and underscores.');
}
}
public function getPassword() { return $this->_password; }
public function setPassword($value) {
$this->_password = $value;
if (empty($value)) {
setError('password', 'Enter a password.');
} else if (strlen($value) < 6) {
setError('password', 'The password you provided must have at least 6 characters.');
}
}
public function setConfirmPassword($value) {
if (empty($value)) {
setError('confirmPassword', 'Re-enter your password again.');
} else if ($this->_password != $value) {
setError('confirmPassword', 'This does not match your password.');
}
}
private function _encrypt($value) {
return sha1(md5($this->_salt.md5($value)));
}
public function register() {
if (!hasErrors()) {
try {
$core = Core::getInstance();
$sth = $core->dbh->prepare(<<<SQL
INSERT IGNORE INTO `users` SET
`first_name` = :first_name, `last_name` = :last_name, `email` = LOWER(:email),
`username` = LOWER(:username), `password` = :password,
`created_on` = NOW()
SQL
);
$sth->bindValue(':first_name', propercase($this->_firstName), PDO::PARAM_STR);
$sth->bindValue(':last_name', propercase($this->_lastName), PDO::PARAM_STR);
$sth->bindValue(':email', $this->_email, PDO::PARAM_STR);
$sth->bindValue(':username', $this->_username, PDO::PARAM_STR);
$sth->bindValue(':password', $this->_encrypt($this->_password), PDO::PARAM_STR);
$sth->execute();
} catch (Exception $e) {
// print $e->getMessage();
}
}
}
public function login() {
if (!hasErrors()) {
try {
$core = Core::getInstance();
$sth = $core->dbh->prepare(<<<SQL
SELECT *
FROM `users`
WHERE `username` = :username
LIMIT 1
SQL
);
$sth->bindValue(':username', $this->_username, PDO::PARAM_STR);
$sth->execute();
$row = $sth->fetch();
$sth->closeCursor();
if ($row and $row->password == $this->_encrypt($this->_password)) {
$_SESSION['uid'] = $row->id;
$_SESSION['user'] = $row->username;
$_SESSION['pass'] = $row->password;
$_SESSION['level'] = $row->user_level;
}
} catch (Exception $e) {
// print $e->getMessage();
}
}
}
private function _destroySession() {
session_unset();
session_destroy();
}
public function logout() {
$this->_destroySession();
redirect('index.php');
}
public function check() {
if (isset($_SESSION['pass'])) {
try {
$core = Core::getInstance();
$sth = $core->dbh->prepare(<<<SQL
SELECT * FROM `users` WHERE `username` = :username
LIMIT 1
SQL
);
$sth->bindValue(':username', $_SESSION['user'], PDO::PARAM_STR);
$sth->execute();
$row = $sth->fetch();
$sth->closeCursor();
if (!$row or $row->password != $_SESSION['pass']) {
$this->logout();
}
} catch (Exception $e) {
// print $e->getMessage();
}
}
}
public function isLoggedIn() {
return (isset($_SESSION['pass']));
}
public function getCourseSubscriptions() {
$rows = array();
try {
$core = Core::getInstance();
$sth = $core->dbh->prepare(<<<SQL
SELECT c.`id` AS id, c.`code` AS code, c.`name` AS name,
IF(`u_id` IS NULL, 0, 1) AS subscribed
FROM `courses` c
LEFT JOIN `course_subscriptions` s
ON c.id = s.`c_id` AND s.`u_id` = :u_id
ORDER BY `code`
SQL
);
$sth->bindValue(':u_id', $_SESSION['uid'], PDO::PARAM_INT);
$sth->execute();
$rows = $sth->fetchAll();
$sth->closeCursor();
} catch (PDOException $e) {
// print $e->getMessage();
}
return $rows;
}
public function addCourseSubscription($c_id) {
try {
$core = Core::getInstance();
$sth = $core->dbh->prepare(<<<SQL
INSERT IGNORE INTO `course_subscriptions`(c_id, u_id)
VALUES(:c_id, :u_id)
SQL
);
$sth->bindValue(':c_id', $c_id, PDO::PARAM_INT);
$sth->bindValue(':u_id', $_SESSION['uid'], PDO::PARAM_INT);
$sth->execute();
return true;
} catch (PDOException $e) {
// print $e->getMessage();
}
return false;
}
}
</code></pre>
<p>Everything is working fine but I feel.. stuck with how to use this object properly with a session. Below is an example on how I am currently using my class.</p>
<p><b>course_catalog.php</b></p>
<pre><code>$userObj = new User();
$userObj->check();
$list = $userObj->getCourseSubscriptions();
</code></pre>
<p>Any suggestions on how I can improve any of this?</p>
|
[] |
[
{
"body": "<p>First of all I would split the <code>User</code> class in 2 or 3 classes <code>User</code>, <code>Authentication</code> and <code>Registration</code>. The setter error could easily become Exceptions, which you could collect in you Registration class.</p>\n\n<p>At the end you will have a smaller User object you can attach to the session.</p>\n\n<p>Please also check <a href=\"http://www.phpbuilder.com/columns/validating_php_user_sessions.php3\" rel=\"nofollow\">http://www.phpbuilder.com/columns/validating_php_user_sessions.php3</a> for some hint regarding session validation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T19:19:46.800",
"Id": "35014",
"Score": "0",
"body": "Thanks for the suggestion about splitting the class. That really helped me. I don't quite understand though when you say change the setter error to Exceptions. Should I be creating a custom exception for each property that I'm trying to set e.g. throw InvalidFirstNameException()? Though, if I am calling the setters one after the other, wouldn't throwing an exception cause not all setters to be called."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T20:22:26.713",
"Id": "35018",
"Score": "0",
"body": "I think the is something like an InvalidParameterException. You would catch this exception in you Registration class and transform them to an error message for the user."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T06:43:53.093",
"Id": "22741",
"ParentId": "22738",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "22741",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T03:48:55.227",
"Id": "22738",
"Score": "4",
"Tags": [
"php",
"object-oriented",
"session"
],
"Title": "How to properly make a user class with a session"
}
|
22738
|
<p>I wanted to write a multi-threaded sort, but unfortunately I don't know much about threads, especially in C++11. I managed to make something work, but I would be highly surprised if it was the best way to do it.</p>
<pre><code>template<class T>
void ___sort(T *data, int len, int nbThreads){
if(nbThreads<2){
std::sort(data, (&(data[len])), std::less<T>());
}
else{
std::future<void> b = std::async(std::launch::async,___sort<T>, data, len/2, nbThreads-2);
std::future<void> a = std::async(std::launch::async,___sort<T>, &data[len/2], len/2, nbThreads-2);
a.wait();
b.wait();
std::inplace_merge (data,&data[len/2],&data[len],std::less<T>());
}
}
</code></pre>
<p>Some of the tests I did sorting integers:</p>
<p><code>size</code> is the number of <code>int</code>s sorted, and the time is in seconds.</p>
<blockquote>
<pre><code>size : 2097152
time with 1 thread : 4.961
time with 2 thread : 3.191
time with 4 thread : 2.377
size : 4194304
time with 1 thread : 10.002
time with 2 thread : 6.214
time with 4 thread : 4.689
size : 8388608
time with 1 thread : 19.975
time with 2 thread : 12.332
time with 4 thread : 9.29
size : 16777216
time with 1 thread : 38.712
time with 2 thread : 25.257
time with 4 thread : 18.706
</code></pre>
</blockquote>
<p>Also, I tried using <code>std::qsort</code> instead of <code>std::sort</code>, and the results were at least twice as long as that. Any reasons why?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T20:53:17.247",
"Id": "35093",
"Score": "3",
"body": "Don't use '__' in an identifer name.http://stackoverflow.com/a/228797/14065"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T15:09:04.170",
"Id": "62801",
"Score": "0",
"body": "I think that one additional optimisation could be to avoid \"false sharing\" of cache line between threads.\nThe way the buffer is divided this could happen with the current code.."
}
] |
[
{
"body": "<p>Something like this is probably more efficient:</p>\n<pre><code>template<class T>\nvoid parallel_sort(T* data, int len, int grainsize)\n{\n // Use grainsize instead of thread count so that we don't e.g.\n // spawn 4 threads just to sort 8 elements.\n if(len < grainsize)\n {\n std::sort(data, data + len, std::less<T>());\n }\n else\n {\n auto future = std::async(parallel_sort<T>, data, len/2, grainsize);\n\n // No need to spawn another thread just to block the calling \n // thread which would do nothing.\n parallel_sort(data + len/2, len - len/2, grainsize);\n\n future.wait();\n\n std::inplace_merge(data, data + len/2, data + len, std::less<T>());\n }\n}\n</code></pre>\n<p>You could set grain size to something like, <code>std::max(256, len/nb_threads)</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T19:40:19.503",
"Id": "35086",
"Score": "0",
"body": "Yes I don't want 4 threads to sort 8 items. But then again I don't want to spawn more threads than I have parallelism available (not more ((1.0 -> 1.5) * <available cores>)). So I would use a combination of these two techniques."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T19:50:26.487",
"Id": "35089",
"Score": "0",
"body": "@LokiAstari: See my suggestion below the code, set grainsize to e.g. `std::max(256, len/nb_threads)`:"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-24T10:47:01.793",
"Id": "241703",
"Score": "4",
"body": "parallel_sort(data + len/2, len/2, grainsize); should be: parallel_sort(data + len/2, len - len/2, grainsize);"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-02-15T13:14:46.020",
"Id": "22749",
"ParentId": "22744",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "22749",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T09:20:26.287",
"Id": "22744",
"Score": "7",
"Tags": [
"c++",
"multithreading",
"c++11",
"sorting"
],
"Title": "Multi-threaded sort"
}
|
22744
|
<p>How can I make my model DRY and KISS?</p>
<pre><code>class Rating < ActiveRecord::Base
attr_accessible :item_type, :item_id, :rating, :voters_up, :voters_down
serialize :voters_up, Hash
serialize :voters_down, Hash
belongs_to :ranks, :polymorphic => true
def self.up(item, user, iteration = 1)
@rating = Rating.where(item_type: item.class.name, item_id: item.id).first
@rating = Rating.create(item_type: item.class.name,
item_id: item.id,
rating: 0,
voters_up: {users:[]}, voters_down: {users:[]}) unless @rating
changed = nil
if !@rating.voters_up[:users].include?(user.id) && !@rating.voters_down[:users].include?(user.id)
if changed.nil?
@rating.increment(:rating, 1)
@rating.voters_up[:users] << user.id
changed = true
end
end
if @rating.voters_up[:users].include?(user.id) && !@rating.voters_down[:users].include?(user.id)
if changed.nil?
@rating.decrement(:rating, 1)
@rating.voters_up[:users].delete user.id
changed = true
end
end
if @rating.voters_down[:users].include?(user.id) && !@rating.voters_up[:users].include?(user.id)
if changed.nil?
@rating.voters_up[:users] << user.id
@rating.voters_down[:users].delete user.id
@rating.increment(:rating, 2)
changed = true
end
end
@rating.save
item.update_attribute(:rating_value, @rating.rating)
end
def self.down(item, user, iteration = 1)
@rating = Rating.where(item_type: item.class.name, item_id: item.id).first
@rating = Rating.create(item_type: item.class.name,
item_id: item.id,
rating: 0,
voters_up: {users:[]}, voters_down: {users:[]}) unless @rating
changed = nil
if !@rating.voters_down[:users].include?(user.id) && !@rating.voters_up[:users].include?(user.id)
if changed.nil?
@rating.decrement(:rating, 1)
@rating.voters_down[:users] << user.id
changed = true
end
end
if @rating.voters_down[:users].include?(user.id) && !@rating.voters_up[:users].include?(user.id)
if changed.nil?
@rating.increment(:rating, 1)
@rating.voters_down[:users].delete user.id
changed = true
end
end
if @rating.voters_up[:users].include?(user.id) && !@rating.voters_down[:users].include?(user.id)
if changed.nil?
@rating.voters_down[:users] << user.id
@rating.voters_up[:users].delete user.id
@rating.decrement(:rating, 2)
changed = true
end
end
@rating.save
item.update_attribute(:rating_value, @rating.rating)
end
end
</code></pre>
|
[] |
[
{
"body": "<p>Here's a 2-part answer: First, a direct answer to your question, and then an alternative approach to the whole thing.</p>\n\n<p><strong>DRYing the current implementation</strong><br>\nFirstly, I'd make sure that every \"item\" <code>has_one :rating</code>. Right now, you're doing a lot of manual record creation, and <code>Rating</code> has to leave all of its attributes accessible to mass-assignment. It'd also be nicer to simply say <code>question.upvote</code> or <code>answer.upvote</code> directly, instead of \"manually\" calling the <code>Rating.up</code> method and having to supply both user and item.</p>\n\n<p>That can be done, provided you can store the current user somewhere that's accessible to the models. But let's keep it a little simpler and just go for a syntax like <code>question.upvote(user)</code></p>\n\n<p>To DRY out the \"vote-enabled\" models, try this:</p>\n\n<pre><code># in app/concerns/votable.rb\nrequire 'active_support/concern'\n\nmodule Votable\n extend ActiveSupport::Concern\n\n included do\n has_one :rating, :as => :item\n end\n\n module ClassMethods\n def upvote(user)\n # Build the Rating record if it's missing\n build_rating if rating.nil?\n # Pass the user on\n rating.upvote user\n end\n\n def downvote(user)\n build_rating if rating.nil?\n rating.downvote user\n end\n end\nend\n</code></pre>\n\n<p>Then, in a record that users can vote on, include that concern:</p>\n\n<pre><code>class Question < ActiveRecord::Base\n include Votable\n # ...\nend\n\nclass Answer < ActiveRecord::Base\n include Votable\n # ...\nend\n</code></pre>\n\n<p>Now the <code>Question</code> and <code>Answer</code> records will automatically build their own <code>Rating</code> record, if they don't have one already, and then pass the upvote/downvote calls on to that rating record.</p>\n\n<p>As for <code>Rating</code> itself, here's what I'd do (I've changed the attribute names a little, but you can of course keep using yours):</p>\n\n<pre><code>class Rating < ActiveRecord::Base\n belongs_to :item, :polymorphic => true\n # Serialize stuff as straight-up Array\n serialize :upvoters, Array\n serialize :downvoters, Array\n # Create arrays after record initialization, so they're not nil on new records\n after_initialize :initialize_voters\n # Update the \"owner's\" rating cache after every save\n after_save :update_item\n\n # Note: No attr_accessible at all; it's not needed.\n\n # I'll skip the comments, as this should all be very easily readable.\n\n def upvote(user)\n if upvoted_by?(user)\n decrement :rating\n remove_upvoter(user)\n elsif downvoted_by?(user)\n increment :rating, 2\n add_upvoter user\n remove_downvoter user\n else\n increment :rating\n add_upvoter user\n end\n save\n end\n\n def downvote(user)\n if downvoted_by?(user)\n increment :rating\n remove_downvoter user\n elsif upvoted_by?(user)\n decrement :rating, 2\n remove_upvoter user\n add_downvoter user\n else\n decrement :rating\n add_downvoter user\n end\n save\n end\n\n def upvoted_by?(user)\n upvoters.include? user.id\n end\n\n def downvoted_by?(user)\n downvoters.include? user.id\n end\n\n private\n\n def add_upvoter(user)\n upvoters << user.id\n end\n\n def add_downvoter(user)\n downvoters << user.id\n end\n\n def remove_upvoter(user)\n upvoters.delete user.id\n end\n\n def remove_downvoter(user)\n downvoters.delete user.id\n end\n\n def initialize_voters\n upvoters ||= []\n downvoters ||= []\n end\n\n def update_item\n if item.present?\n item.update_attribute :rating_value, rating\n end\n end\n\nend\n</code></pre>\n\n<p>And that's pretty much it. Now you can do <code>Question.find(23).upvote(current_user)</code> or whatever, and it should work out.</p>\n\n<hr>\n\n<p><strong>Going straight to the database</strong><br>\nAlternatively, I'd suggest using \"raw\" database queries instead of models with serialized attributes and all that. All you really need is a simple table. It doesn't need an <code>id</code> column or a model-layer abstraction. All it needs to is have 4 columns: <code>user_id</code>, <code>vote</code>, <code>item_type</code>, and <code>item_id</code>. You can skip ActiveRecord models and such, since all you need to do is check for a certain user/item combo.</p>\n\n<p>Make <code>user_id</code>, <code>item_id</code> and <code>item_type</code> the primary key (or add a uniqueness constraint) and you can do the entire logic in SQL (at least MySQL). If, for instance, user 23 votes on answer 42, it'd look like this:</p>\n\n<pre><code>INSERT INTO `votes` (`user_id`, `item_id`, `item_type`, `vote`)\nVALUES (23, 42, \"Answer\", X)\nON DUPLICATE KEY UPDATE `vote`=IF(`vote`=X, 0, X);\n</code></pre>\n\n<p>where <code>X</code> is <code>1</code> for an upvote, or <code>-1</code> for a downvote. That's actually all the upvote/downvote logic in one query.</p>\n\n<p>Right after that, update the total rating for the post:</p>\n\n<pre><code>UPDATE `answers`\nSET `rating_value`=(\n SELECT IFNULL(SUM(`vote`), 0)\n FROM `votes`\n WHERE `item_id`=42 AND `item_type`= \"Answer\"\n)\nWHERE id=42;\n</code></pre>\n\n<p>From time to time, you may want to do some clean-up to keep the table a little leaner (i.e. delete rows where the vote is zero, or when an associated item is deleted), but otherwise you should have a pretty robust solution with none of the overhead of Rails and ActiveRecord. And it can all be abstracted into a mixin like the concern above, and you can easily add the <code>upvoted_by?(user)</code>/<code>downvoted_by?(user)</code> methods there too with some simple SQL:</p>\n\n<pre><code>SELECT * FROM `votes` WHERE `vote`<>0 AND `user_id`=23 AND `item_id`=42 AND `item_type`=\"Answer\";\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T23:57:11.043",
"Id": "22774",
"ParentId": "22746",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "22774",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T10:46:40.037",
"Id": "22746",
"Score": "1",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "ActiveRecord model for upvotes and downvotes"
}
|
22746
|
<p>The idea is that i want any size string to put the corresponding hex value into a byte array. I've seen a million ways to do it. Some of them didn't look to clean. My needs are speed over memory, so chose to try and implement a lookup table. Tell me what you think</p>
<pre><code>const BYTE HEX[0x80] = //This is the ASCII table in number value form
{ //0 1 2 3 4 5 6 7 8 9 A B C D E F
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,//0
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,//1
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,//2
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,//3
0x00, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,//4
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,//5
0x00, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,//6
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 //7
};
void ByteUtil::StringToHex(const char* str, BYTE* hex)
{
int len = strlen(str)/2;
for(int i=0; i<len; i++)
{
hex[i] = (HEX[*str++] << 4);
hex[i] += (HEX[*str++]);
}
}
</code></pre>
<p>This method assumes you've already figured out the length of the array. So to use it it would look somethign like this.</p>
<pre><code>char* gky = "55D38577093A88F3B5EA40BBF11158813A2C662EB71FBAB9";
int len = strlen(gky)/2;
BYTE* GKY = new BYTE[len];
ByteUtil::StringToHex(gky, GKY);
ByteUtil::LogArray("GKY", GKY, len);
delete[] GKY;
</code></pre>
<p>this particular code snippet outputted this</p>
<p><code>2013-02-15.10:03:19 GKY(24)- 55:D3:85:77:09:3A:88:F3:B5:EA:40:BB:F1:11:58:81:3A:2C:66:2E:B7:1F:BA:B9:</code></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T23:58:37.097",
"Id": "34986",
"Score": "0",
"body": "Looks to me like you're opening yourself up to potential sign-extension vulnerabilities."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T00:29:27.057",
"Id": "34988",
"Score": "0",
"body": "@OJ. Although i have not heard about this vulnerability before (and was good research for myself) the likely hood of that happening in the program this is used for is very unlikely. The input is generated off of encrypted data using AES standards. The use of this is never converted to a useable number. meaning it is sent to a device for verification. everything revolving around this is strictly unsigned. Thank you though for you insight into this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T09:40:17.330",
"Id": "34999",
"Score": "0",
"body": "No worries mate, glad you enjoyed the learning :)"
}
] |
[
{
"body": "<p>Some minor comments:</p>\n\n<ul>\n<li><p>you are assuming there are no invalid chars in the input string.</p></li>\n<li><p>why not pass the string length into the function; the caller has to know it in order to allocate the hex buffer.</p></li>\n<li><p><code>len</code> could be <code>const</code></p></li>\n<li><p>unnecessary brackets around RHS expressions in hex[i] assignments</p></li>\n<li><p>I would prefer the second assignment to be <code>|=</code> not <code>+=</code></p></li>\n<li><p>it is usual to use uppercase names only for <code>#define</code>d constants</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T01:01:53.783",
"Id": "23048",
"ParentId": "22757",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "23048",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T16:11:23.103",
"Id": "22757",
"Score": "7",
"Tags": [
"c++",
"parsing",
"converting"
],
"Title": "Char* hex string to BYTE Array"
}
|
22757
|
<p>I'm trying to write a JMS Consumer using Akka-Camel. </p>
<p>For now, I'm using <a href="http://ffmq.sourceforge.net/" rel="nofollow">FFMQ</a> as a JMS server. I want to listen on the JMS queue <code>myqueue</code>.</p>
<p>Creating the JMS consumer actor is quite straightforward:</p>
<pre><code>import akka.camel.{CamelMessage, Consumer}
import akka.event.Logging
class JMSConsumer extends Consumer {
val log = Logging(context.system, this)
def endpointUri = "jms:queue:myqueue"
def receive = {
case m: CamelMessage => {
log.info(s"JMS Received $m")
}
case other => {
log.info(s"JMS Received unknown message type : $other")
}
}
}
</code></pre>
<p>But I'm struggling with the configuration of the JMS component. </p>
<p>In order to connect to JMS server, I need to specify a few properties as specified in <a href="http://ffmq.sourceforge.net/doc.html#III_2_1" rel="nofollow">FFMQ documentation</a>.</p>
<p>So far I have only managed to do this by specifying parameters using some Camel internals:</p>
<pre><code>import akka.actor.{Props, ActorSystem}
import akka.camel.CamelExtension
import org.apache.camel.component.jms.{JmsConfiguration, JmsComponent}
import java.util.Hashtable
import javax.naming.{InitialContext, Context}
import net.timewalker.ffmq3.FFMQConstants
import javax.jms.{Session, ConnectionFactory}
object MainApp extends App {
val system = ActorSystem("TestSystem")
def jmsConnectionFactory() : ConnectionFactory = {
val env = new Hashtable[String, String]();
env.put(Context.INITIAL_CONTEXT_FACTORY, FFMQConstants.JNDI_CONTEXT_FACTORY);
env.put(Context.PROVIDER_URL, "tcp://localhost:10002");
val context: Context = new InitialContext(env);
context.lookup(FFMQConstants.JNDI_CONNECTION_FACTORY_NAME).asInstanceOf[ConnectionFactory];
}
val jmsConfiguration = new JmsConfiguration(jmsConnectionFactory)
val jmsComponent = new JmsComponent(jmsConfiguration)
val camel = CamelExtension(system)
camel.context.addComponent("jms", jmsComponent)
val jmsConsumer = system.actorOf(Props[JMSConsumer], name="myqueueConsumer")
}
</code></pre>
<p>I'm wondering if this is the way that akka-camel is intended to be used.</p>
<p>It seems that I'm just putting random things together, possibly going into too low-level detail when doing JNDI lookup myself?</p>
<p>Unfortunately, <a href="http://doc.akka.io/docs/akka/2.1.0/scala/camel.html" rel="nofollow">akka-camel</a> documentation doesn't go into details here.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-16T07:57:52.940",
"Id": "223681",
"Score": "0",
"body": "I found Gist with code sample of how to configure akka-camel jms for weblogic. https://gist.github.com/cjjavellana/2b422e694e5acf253d22"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T18:05:58.787",
"Id": "22761",
"Score": "4",
"Tags": [
"scala",
"jms",
"akka"
],
"Title": "Configuring a JMS Component in akka-camel"
}
|
22761
|
<h1>Background</h1>
<p>Would like to create a two-key map that is fairly generic. In the existing system, there are a number of ways to name a parameter for a report. Rather than re-writing each report (too much effort), we'd like to simply map the old parameter names to new names.</p>
<p>For example, old names might include <code>STARTDATE</code>, <code>FROM_DT</code>, <code>P_DATE_START</code>, and countless more variations thereof each being mapped to a single, equivalent <code>P_START_DATE</code>.</p>
<p>By using a consistent naming scheme, we could, for example, detect the data type (e.g., by following a convention such as ending parameters in the data type, as in <code>_DATE</code>) and then automatically generate a corresponding web page complete with validation for the report's form submission. This is otherwise an arduous task with an inconsistent naming scheme across hundreds of legacy reports.</p>
<h1>Code</h1>
<p>The existing code resembles:</p>
<pre><code>public class TwoKeyMap {
private enum Parameter {
P_START_DATE,
P_END_DATE;
}
private static final Map<String, Map<Enum, String>>
REPORT_PARAMETER_MAP = new HashMap<String, Map<Enum, String>>() {
{
put("ReportName", new HashMap<Enum, String>() {
{
put(Parameter.P_START_DATE, "P_DATE_START");
put(Parameter.P_END_DATE, "P_DATE_END");
}
});
}
};
/**
* Retrieves the old parameter name based on the report using the new parameter name.
*
* @param report - The report name having a parameter mapped to a new name.
* @param key - The new name of the parameter.
* @return The report's old parameter name.
*/
public static String lookupParameter(String report, Parameter key) {
return getReportParameterMap().get(report).get(key);
}
</code></pre>
<h1>Question</h1>
<p>How would you improve the code so that it is easier for new and intermediate Java developers to maintain?</p>
<p>For example, would this be easier:</p>
<pre><code>TwoKeyMap tkm = new TwoKeyMap();
tkm.put( ReportNames.REPORT1, Parameter.P_START_DATE, "P_DATE_START" );
tkm.put( ReportNames.REPORT1, Parameter.P_END_DATE, "P_DATE_END" );
tkm.put( ReportNames.REPORT2, Parameter.P_START_DATE, "P_FROM_DT" );
tkm.put( ReportNames.REPORT3, Parameter.P_START_DATE, "DATE_FROM" );
tkm.put( ReportNames.REPORT4, Parameter.P_START_DATE, "P_BEGIN_DATE" );
</code></pre>
<h1>Related Links</h1>
<ul>
<li><a href="http://commons.apache.org/collections/apidocs/org/apache/commons/collections/keyvalue/MultiKey.html">http://commons.apache.org/collections/apidocs/org/apache/commons/collections/keyvalue/MultiKey.html</a></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T23:04:43.657",
"Id": "34979",
"Score": "1",
"body": "I am not sure if codereview is the right place. You are more asking for a solution, not to review some code. Nevertheless I do not really understand the problem. If you want to have 2 keys for a Hashmap, you should create some container class (with 2 fields in this case) which implements equals and hashcode properly. In some cases, you could avoid this class if you use `field1<separator>field2` as key, with separator some unique constant not appearing in field1 or field2."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T01:19:19.813",
"Id": "34989",
"Score": "0",
"body": "Guava has a data structure called a Table that you can reference: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/HashBasedTable.html"
}
] |
[
{
"body": "<p>I'd go with something which is similar to the mentioned <code>MultiKey</code>: create a <code>ReportParameter</code> class and use it as the key of the map:</p>\n\n<pre><code>public class ReportParameter {\n\n private final String reportName;\n private final Parameter parameter;\n\n public ReportParameter(final String reportName, final Parameter parameter) {\n this.reportName = reportName;\n this.parameter = parameter;\n }\n\n // equals and hashCode here\n}\n</code></pre>\n\n<p>(Make sure that is has proper <code>hashCode</code> and <code>equals</code> methods.)</p>\n\n<p>I think it's easier to understand than the nested maps (for example, <code>Map<String, Map<Enum, String>></code>).</p>\n\n<p>Furthermore, I'd consider creating and using different types (!= string) for the report name and the parameter names. String identifiers are hard to follow and it's easy to accidentally mix them up. Different types (for example, enums, like <code>Parameter</code>) and type safety help here.</p>\n\n<p>A sidenote from Code Complete 2nd Edition, Chapter 5: Design in Construction, Value of Information Hiding, page 96:</p>\n\n<blockquote>\n <p>[...]</p>\n \n <p>Most programmers would decide, “No, it isn’t worth creating a whole class just \n for an ID. I’ll just use ints.”</p>\n \n <p>[...]</p>\n \n <p>Rather, the difference is one of heuristics—thinking about information \n hiding inspires and promotes design decisions that thinking about objects \n does not.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T10:37:46.873",
"Id": "35113",
"Score": "0",
"body": "@DaveJarvis: (1) I don't exactly understand this. Anyway, is memory consumption really an issue? (2) I've updated the answer a little bit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T12:36:33.493",
"Id": "35261",
"Score": "2",
"body": "@DaveJarvis There is always exactly one instance of every String content in Java. All Strings with the same content refer to the same internal string. If you can reduce this to an Enum it should be even cheaper."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T17:05:33.927",
"Id": "35369",
"Score": "1",
"body": "@mnhg: you can have several String instances with the same content, try this:String one = \"one\";\n String alsoOne = new String(\"one\");\n System.out.println(\"same: \" + (one == alsoOne) + \", equals: \" + (one.equals(alsoOne)));"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T04:56:42.573",
"Id": "35443",
"Score": "1",
"body": "@pgras You are comparing the wrong objects: [String.intern()](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#intern%28%29)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T09:32:19.857",
"Id": "35453",
"Score": "0",
"body": "@mnhg: you wrote \"There is always exactly one instance of every String content in Java.\" maybe I don't exactly understand what you mean by \"String content\". I know you can intern() Strings but as long as you don't the \"content\" of the string is a private char array from the String. So in my example both strings have their own copy of the \"one\" content..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T09:34:38.557",
"Id": "35454",
"Score": "0",
"body": "Not a copy, but a reference to the internal. So the a identical String will add a reference and not the complete content again to you memory consumption."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T09:38:39.033",
"Id": "35630",
"Score": "0",
"body": "@mnhg: if I understand you, you say the String value (the inner char array) is unique (the same array instance) for all Strings with the same content, so creating a new String with the same content will not add a new char array to the memory. In fact it really depends on how you create your String, if you look at the String class code you can see that some of the constructors use Arrays.copyOf which creates a new char[] object. So, you can have several String instances containing different char[] all with the same lexicographical content. Only the char instances are the same..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-26T05:16:43.937",
"Id": "35700",
"Score": "0",
"body": "You are right, you also can avoid this behaviour, but you can also make use of it. (Or use a Enum.)"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T23:39:28.093",
"Id": "22840",
"ParentId": "22769",
"Score": "4"
}
},
{
"body": "<p>A possible solution using <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Table.html\" rel=\"nofollow\"><code>Table</code></a> as the backing structure (you could use your existing <code>TwoKeyMap</code>). This adds a touch of abstraction over what you already have to make the intent a little more clear for someone new. I've also included a couple different setup possibilities.</p>\n\n<pre><code>import com.google.common.collect.Table;\n\npublic class ParamTranslator {\n private Table<ReportName, Parameter, String> table = HashBasedTable.create();\n\n public ParamTranslator addRule(ReportName report, Parameter param, String oldName) { \n table.put(report, param, oldName);\n return this; // Method chaining\n }\n\n public String getOldFor(ReportName report, Parameter param) {\n return table.get(report, param);\n }\n}\n\n// ... somewhere in config land\nfor(String line : /*list of file lines*/) {\n String[] lineParts = line.split(\",\"); // store as a csv?\n // (more validation would need to be added here)\n translate.addRule(ReportName.valueOf(linesParts[0]), \n Parameter.valueOf(lineParts[1]), lineParts[2]);\n}\n\n// ... maybe inline using method chaining\nParamTranslator translate = new ParamTranslator() \n .addRule( ReportName.REPORT1, Parameter.P_END_DATE, \"P_DATE_END\")\n .addRule( ReportName.REPORT2, Parameter.P_START_DATE, \"P_FROM_DT\")\n .addRule( ReportName.REPORT3, Parameter.P_START_DATE, \"DATE_FROM\")\n .addRule( ReportName.REPORT4, Parameter.P_START_DATE, \"P_BEGIN_DATE\");\n\n// ... later in the program\nString oldParam = translate.getOldFor(reportName, dateParam);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T12:26:12.793",
"Id": "35259",
"Score": "1",
"body": "Note that `Table` is an interface, so `new Table<>()` would not compile. You should have a look at the different implementations and recommend one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T12:41:39.127",
"Id": "35263",
"Score": "1",
"body": "A silly mistake on my part, updated with the proper factory call."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T13:07:03.960",
"Id": "35588",
"Score": "1",
"body": "I think it is easiest to understand version. Furthermore, the `getOldFor()` method accepts only the proper types. Thanks for the answer and enjoy the bounty and +1 :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T14:45:37.330",
"Id": "22860",
"ParentId": "22769",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p>By using a consistent naming scheme, we could, for example, detect the data type (e.g., by following a convention such as ending parameters in the data type, as in _DATE) and then automatically generate a corresponding web page complete with validation for the report's form submission.</p>\n</blockquote>\n\n<p>It is not the best idea to rely on a naming scheme to do this. It looks like you need some metadata for your parameters.</p>\n\n<p>You already gave an example using an enum, you could go further an add the metadata directly in the enum:</p>\n\n<pre><code>public enum Parameter {\n P_START_DATE(Date.class),\n P_END_DATE(Date.class);\n\n private final Type type;\n\n Parameter(Type type) {\n this.type = type;\n }\n\n public Type getType() {\n return type;\n }\n}\n</code></pre>\n\n<p>Then there is a perfect Map implementation when using enum keys: <a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/util/EnumMap.html\" rel=\"nofollow\">EnumMap</a>. You could even subclass it to have a type representing all the parameters for one report. I guess you use one report at a time so it is easier to first get the report parameters and then get the individual parameters:</p>\n\n<pre><code>public class ReportParameters extends EnumMap<Parameter, String> {\n final Report report;\n public ReportParameters(Report report) {\n super(Parameter.class);\n this.report = report;\n }\n}\n</code></pre>\n\n<p>Finally to go further with type safety you could add an enum representing the reports so you could store all the reportsParameters instances in another enumMap:</p>\n\n<pre><code>public enum Report {\n FIRST_REPORT,\n SECOND_REPORT;\n}\n</code></pre>\n\n<p>and:</p>\n\n<pre><code>Map<Report, ReportParameters> reportParametersMap = \n new EnumMap<Report, ReportParameters>(Report.class);\n</code></pre>\n\n<p>Using this would look like (with static imports of the enums):</p>\n\n<pre><code>ReportParameters firstReport = new ReportParameters(FIRST_REPORT);\nreportParametersMap.put(firstReport.report, firstReport);\nfirstReport.put(P_START_DATE, \"P_DATE_START\");\nfirstReport.put(P_END_DATE, \"P_DATE_END\");\n\nReportParameters secondReport = new ReportParameters(SECOND_REPORT);\nreportParametersMap.put(secondReport.report, secondReport);\nsecondReport.put(P_START_DATE, \"FROM\");\nsecondReport.put(P_END_DATE, \"TO\");\n</code></pre>\n\n<p>With that you can also add more helper methods if you want or need (like a check if you have declared all mappings, or helper methods to populate or access the information.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T17:33:00.690",
"Id": "35375",
"Score": "0",
"body": "I prefer this solution because it does not depend on external libraries."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T13:14:28.227",
"Id": "35590",
"Score": "0",
"body": "+1 and thanks for the answer! An improvement idea: The `ReportParameters` class, instead of extending `EnumMap`, could have delegate methods for `get` and `put` with an `EnumMap<Parameter, String>` field. This way the `get` method could be `public String get(final Parameter key) { ... }` (instead of `public String get(final Object key) { ... }`) which would improve type safety and prevent completely invalid calls, like: `reportParametersMap.get(\"string1\").get(\"string2\");`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-25T09:13:00.040",
"Id": "35629",
"Score": "0",
"body": "@palacsint: good suggestion, in fact I thought Map<K,V> had a get(<K> key) method but it is get(Object key)... BTW there is a lot to improve in my solution but to improve in the right direction one should know more about how the code will be used."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T16:51:55.700",
"Id": "22971",
"ParentId": "22769",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "22971",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T22:17:31.060",
"Id": "22769",
"Score": "7",
"Tags": [
"java",
"hash-map"
],
"Title": "Two Key HashMap"
}
|
22769
|
<p><a href="https://codereview.stackexchange.com/questions/22736/trying-to-make-recursive-code-designed-to-find-objects-with-even-references-tidi">Follow on from this question</a></p>
<p>This is a follow on question from one I asked a few days ago. I am making (or rather have made) a recursive method that takes a list of ArrayList objects as its parameters. There can be any number of them, but let's pretend there are five. They are numbered from 1 to 5, so the Array contains: [1 2 3 4 5].</p>
<p>The Array is then passed through a recursive method which returns only the numbers at odd indices in the Array, i.e. [2 4] (as they are at indices 1 and 3).</p>
<p>This is the code for the recursive method:</p>
<pre><code>public static ArrayList<Integer> oddList (ArrayList<Integer> tList) {
ArrayList<Integer> oddList = ListMethods.deepClone(tList);
int tempStorage = -1;
if (oddList.size() <= 0)
return oddList;
else
{
if (oddList.size()%2==0)
tempStorage = oddList.remove(oddList.size()-1);
oddList.remove(oddList.size()-1);
oddList = ListMethods.oddList(oddList);
if (tempStorage >= 0)
oddList.add(tempStorage);
}
return oddList;
}
</code></pre>
<p>There are two things I am curious about:</p>
<ul>
<li>Firstly, is there an alternative to that if statement at the very end, to check that tempStorage >= 0. </li>
<li>Secondly, and probably more importantly, should I care? In other words, is what I've done there a cheap, easy fix, or is that common coding practice? It just seems strange having an initialised variable that will always be either changed or ignored.</li>
</ul>
<p>Any feedback would be fantastic, thanks (and to the guys who posted on my previous post, I'm still reviewing all the information - not allowed to use most of it in this assignment, but thanks anyway!)</p>
|
[] |
[
{
"body": "<p>I already explained in my other post, not to use this <code>tempStorage</code>variable in this way. At least (compared to the other version) you do not change the meaning of it in this version.<br>\nIf you rename it to something like <code>removedItemFromEvenIndex</code> it could be fine. If and really if the requirement is that all values inside the lists are >= 0. </p>\n\n<p>If all values are allowed, I would suggest to stick to the solution with the boolean I suggested in the other post. Because if all values are allowed, You can not find any \"check\" value to see if you removed or something or not.</p>\n\n<p>From where comes this problem? You try to do 2 things together with the <code>tempStorage</code>:</p>\n\n<ul>\n<li>Transport the removed value</li>\n<li>Status flag if you removed something or not</li>\n</ul>\n\n<p>You can not address both things with the same Integer, because you already need everything from your Integer for the first part.</p>\n\n<p>Rest is the same as for the other question.</p>\n\n<hr>\n\n<p>To handle this one, same approach as other question: </p>\n\n<p>What we want to do here? Add every second element to the new list, starting with the second.</p>\n\n<p>So a simplified description could be:</p>\n\n<pre><code>function oddList(list)\n if list is empty or has only 1 element\n return empty list\n return new list(second element of list, oddList(all elements from the third to the end))\n</code></pre>\n\n<p>translate to algorithm in Java:</p>\n\n<pre><code>public static List<Integer> oddList(final List<Integer> list) {\n if (list.size() <= 1)\n return new ArrayList<>();\n\n final List<Integer> newList = new ArrayList<>(Arrays.asList(list.get(1)));\n newList.addAll(oddList(list.subList(2, list.size())));\n return newList;\n}\n</code></pre>\n\n<hr>\n\n<p>If we take into account the other question, this could be a clever way (you should always try to reuse existing and working solutions):</p>\n\n<pre><code>public static List<Integer> oddList(final List<Integer> list) {\n final List<Integer> newList = new ArrayList<>(list); //we create a copy, otherwise list is modified for the caller\n newList.remove(0); //all indices shifted one to the left\n return even(newList);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T23:48:43.150",
"Id": "34981",
"Score": "0",
"body": "Thanks for this. You've already put a lot of effort into helping me on both questions and I appreciate it. I guess I've been trying to fix the problem whilst changing the bare minimum, because you never know how fussy your lecturers are going to be in marking!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T23:55:45.720",
"Id": "34985",
"Score": "0",
"body": "Meant to add that the reason why I posted this question on the first place was basically because I was hesistant (and still am) about using .addAll and subLists (which I've never used before) simply because I;m worried I'll lose marks due to fussy lecturers not being happy that I've not done exactly what they've requested.\nHowever, those techniques look really interesting and I'll look them up in the Java API and if I don't use them here, store them for future reference."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T00:11:02.937",
"Id": "34987",
"Score": "0",
"body": "One last thing (sorry!) - your line addAll(oddList(list.subList(2, list.size()))); Just to ensure I understand propertly, addAll is used to add a Collection. In this case the collection is the entire ArrayList, and sublist is used to send entire array from second element to the end, thus recursively getting smaller each time it is called?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T01:38:50.880",
"Id": "34990",
"Score": "0",
"body": "@AndrewMartin: nearly correct. We add all the results from the method call to the list. And the method is called with the sublist from third until last element (not from second. index 2 is third element) . See the simplified description. And asking questions is completely fine, you do not need to apologize."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T23:36:00.950",
"Id": "22773",
"ParentId": "22770",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "22773",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T22:29:55.543",
"Id": "22770",
"Score": "3",
"Tags": [
"java",
"recursion"
],
"Title": "Avoiding use of an initialized variable that will either be changed or ignored"
}
|
22770
|
<p>So I took a stab at this task to begin learning common lisp. </p>
<p>The idea is that you give it a written representation of a number such as "three thousand and forty nine" and it will output 3049.</p>
<p>I was looking for some input on my lisp and where I'm being daft or even what parts are good.</p>
<p>So without further a due, my code:</p>
<pre><code>(defmacro do-push (result value)
`(if (not (eq ,value 0))
(progn (setf ,result (append ,result (cons ,value nil)))
(setf ,value 0))))
(defun should-push (string)
(or (equalp string "and")) (not (should-multiply string)))
(defmacro sum-list (L)
`(reduce '+ ,L))
(defun get-input ()
(princ "Please enter a number: ")
(read-line))
(defun tokenize (string)
(loop for i = 0 then (incf j)
as j = (position #\Space string :start i)
collect (subseq string i j)
while j))
(defun should-multiply (string)
(or (equalp string "hundred") (equalp string "thousand") (equalp string "million")))
(defun get-needed-operation (string)
(cond ((should-multiply string) (symbol-function '*))
((equalp string "and") (symbol-function '+))
(t nil)))
(defun string-value (string)
(cond ((equalp string "one") 1)
((equalp string "two") 2)
((equalp string "three") 3)
((equalp string "four") 4)
((equalp string "five") 5)
((equalp string "six") 6)
((equalp string "seven") 7)
((equalp string "eight") 8)
((equalp string "nine") 9)
((equalp string "ten") 10)
((equalp string "eleven") 11)
((equalp string "twelve") 12)
((equalp string "thirteen") 13)
((equalp string "fourteen") 14)
((equalp string "fifteen") 15)
((equalp string "sixteen") 16)
((equalp string "seventeen") 17)
((equalp string "eighteen") 18)
((equalp string "nineteen") 19)
((equalp string "twenty") 20)
((equalp string "thirty") 30)
((equalp string "forty") 40)
((equalp string "fifty") 50)
((equalp string "sixty") 60)
((equalp string "seventy") 70)
((equalp string "eighty") 80)
((equalp string "ninety") 90)
((equalp string "hundred") 100)
((equalp string "thousand") 1000)
((equalp string "million") 1000000)))
(let ((result '())
(current 0))
(loop for word in (tokenize "one million three hundred thousand eighteen thousand six hundred and seventy three") do
(let ((operation (get-needed-operation word))
(value (string-value word)))
(progn (when (and (eq value nil) (eq operation nil))
(format t "Unexpected token: ~a~c" word #\newline))
(if (eq operation nil) (setq operation (symbol-function '+)))
(when (should-push word)
(do-push result current))
(when (not (eq value nil))
(setq current (funcall operation value current)))))
finally (do-push result current))
(format t "Result: ~a" (sum-list result)))
</code></pre>
<p>My logic is to have a list that contains all the detected "sub-numbers" which are just added together to get the final number.</p>
<p>Certain words (hundred, thousand, etc) imply a multiply operation to the current number such that three hundred becomes 3 * 100 = 300</p>
<p>Certain words (and, one, two, etc) imply an addition operation such that sixty seven becomes 60 + 7 = 67</p>
<p>Some words cause the current number to be pushed to the result list, resetting the current number.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-24T22:52:57.900",
"Id": "135971",
"Score": "0",
"body": "If you were bothered by the speed, you could simply generate the numbers representing the N first distinct letters of the words representing numbers, and then or them up to build an efficient `case` (which could be optimized by a compiler into a fixed size hash-table) giving much faster comparison rates."
}
] |
[
{
"body": "<p>There are a couple of issues with your code. Let me describe a few:</p>\n\n<ul>\n<li><p>numbers are not <code>EQ</code>, use <code>EQL</code> or <code>=</code>.</p></li>\n<li><p>Common Lisp has documentation strings. Use them.</p></li>\n<li><p><code>if</code> <code>not</code> <code>progn</code> can be replaced with a single <code>unless</code></p></li>\n</ul>\n\n<p>The next function does not work as expected. I have inserted a newline and you see that the parentheses are wrong.</p>\n\n<pre><code>(defun should-push (string)\n (or (equalp string \"and\"))\n (not (should-multiply string)))\n</code></pre>\n\n<p>Don't write trivial macros. If you want to have a name for a trivial function, then use a function - not a macro. If the calling overhead bothers you, then declare it <code>inline</code>.</p>\n\n<pre><code>(defmacro sum-list (L)\n `(reduce '+ ,L))\n</code></pre>\n\n<p>The next may or may not work as you think. Since Common Lisp output streams can be buffered, call <code>FORCE-OUTPUT</code> when you actually want to see the output.</p>\n\n<pre><code>(defun get-input ()\n (princ \"Please enter a number: \")\n (read-line))\n</code></pre>\n\n<ul>\n<li><p><code>or</code> <code>equalp</code> can be replaced with <code>(member foo '(\"a\" \"b\" \"c\") :test #'equalp)</code>. Get the data out of the logic.</p></li>\n<li><p>instead of <code>(symbol-function '+)</code> use <code>#'+</code></p></li>\n<li><p>instead of <code>COND</code> <code>EQUALP</code> use <code>ASSOC</code> with the <code>:test</code> keyword. Get the data out of the code. Alternatively use a macro similar to CASE, which works for strings.</p></li>\n<li><p>for the last form, write a function, too. Always provide functions. Don't print the result. Just return the result.</p></li>\n<li><p>inside a <code>LET</code> you don't need a <code>PROGN</code></p></li>\n<li><p><code>EQ nil</code> is better replaced with the <code>NULL</code> predicate.</p></li>\n<li><p><code>format t \"~c\" #\\newline</code> is just <code>format t \"~%\"</code></p></li>\n<li><p><code>when not</code> is <code>unless</code></p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T14:39:51.570",
"Id": "22966",
"ParentId": "22775",
"Score": "1"
}
},
{
"body": "<p>Here's a tiny example of how you could optimize your string matching a bit (since you know all your strings in advance, this seems like a good thing to do):</p>\n\n<pre><code>(defun make-token (word)\n (loop\n :for char :across word\n :for i :below 7\n :for result := 0 \n :then (logior (ash result 8) (char-code char))\n :finally (return result)))\n\n(defmacro word-case (word &body body)\n `(case (make-token ,word)\n ,@(loop :for (head tail) :in body\n :collect (list (make-token head) tail))))\n\n(defun match-words (to-word)\n (word-case to-word\n (\"one\" 1)\n (\"two\" 2)\n (\"three\" 3)\n (\"four\" 4)\n (\"five\" 5)\n (\"six\" 6)\n (\"seven\" 7)\n (\"eight\" 8)\n (\"nine\" 9)\n (\"ten\" 10)\n (\"eleven\" 11)\n (\"twelve\" 12)\n (\"thirteen\" 13)\n (\"fourteen\" 14)\n (\"fifteen\" 15)\n (\"sixteen\" 16)\n (\"seventeen\" 17)\n (\"eighteen\" 18)\n (\"nineteen\" 19)\n (\"twenty\" 20)\n (\"thirty\" 30)\n (\"forty\" 40)\n (\"fifty\" 50)\n (\"sixty\" 60)\n (\"seventy\" 70)\n (\"eighty\" 80)\n (\"ninety\" 90)\n (\"hundred\" 100)\n (\"thousand\" 1000)\n (\"million\" 1000000)))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-24T23:11:41.403",
"Id": "74820",
"ParentId": "22775",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "22966",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T02:09:52.907",
"Id": "22775",
"Score": "3",
"Tags": [
"beginner",
"converting",
"common-lisp",
"numbers-to-words"
],
"Title": "Written numbers to numerical representation"
}
|
22775
|
<p>I am building an app for android to control VLC (mediaplayer) that runs on my computer.
At the moment it's just a prototype that works, but I was wondering if I am correctly managing my HandlerThread and Socket.</p>
<p>My fear is that the thread keeps running too long or that I cause memory leaks. I have looked at a lot of examples and questions on Stack Overflow, but I want to be sure before I complete the app in this way.</p>
<p>The Java program that runs on the desktop runs only on the main thread, so I will just post my Android code.</p>
<p>VlcRemoteActivity.java:</p>
<pre><code>package be.zweetinc.PcController;
import android.app.Activity;
import android.os.Bundle;
import android.os.HandlerThread;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
public class VlcRemoteActivity extends Activity {
private ImageButton volumeUpButton;
private ImageButton volumeDownButton;
private EditText messageText;
private Message message;
private Button sendButton;
private Button killServerButton;
private HandlerThread connectionHandlerThread;
private ConnectionHandler connectionHandler;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
volumeDownButton = (ImageButton) findViewById(R.id.downButton);
volumeUpButton = (ImageButton) findViewById(R.id.upButton);
messageText = (EditText) findViewById(R.id.message);
sendButton = (Button) findViewById(R.id.sendButton);
killServerButton= (Button) findViewById(R.id.killServerButton);
connectionHandlerThread = new HandlerThread("ConnectionThread");
connectionHandlerThread.start();
connectionHandler = new ConnectionHandler(connectionHandlerThread.getLooper());
message = Message.obtain(connectionHandler);
message.what = MessageCode.CLASS_CONNECTION; // EventClass CONNECTION
message.arg1 = MessageCode.CONNECTION_CONNECT; // EventAction CONNECT
connectionHandler.sendMessage(message);
volumeUpButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
message = Message.obtain(connectionHandler, MessageCode.CLASS_VLC, MessageCode.VLC_VOLUME_UP, 0);
connectionHandler.sendMessage(message);
}
});
volumeDownButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
message = Message.obtain(connectionHandler, MessageCode.CLASS_VLC, MessageCode.VLC_VOLUME_DOWN, 0);
connectionHandler.sendMessage(message);
}
});
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String textToSend = messageText.getText().toString();
Bundle data = new Bundle();
data.putString(ConnectionHandler.MESSAGE_DATA, messageText.getText().toString());
// TODO: change arg1 and arg2 parameter when feature is not limited to logging only
message = Message.obtain(connectionHandler, MessageCode.CLASS_VLC, MessageCode.VLC_VOLUME_UP, 0, data);
connectionHandler.sendMessage(message);
}
});
killServerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
message = Message.obtain(connectionHandler, MessageCode.CLASS_SERVICE, 0, 0);
connectionHandler.sendMessage(message);
}
});
}
@Override
protected void onPause() {
super.onPause();
message = Message.obtain(connectionHandler, MessageCode.CLASS_CONNECTION, MessageCode.CONNECTION_DISCONNECT, 0);
connectionHandler.sendMessage(message);
// connectionHandlerThread.quit();
}
}
</code></pre>
<p>ConnectionHandler.java:</p>
<pre><code>package be.zweetinc.PcController;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
public class ConnectionHandler extends Handler {
public static final String MESSAGE_DATA = "be.zweetinc.PcController.Message_Data";
private Socket client;
private PrintWriter printwriter;
private Message message;
public ConnectionHandler(Looper looper){
super(looper);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg); //To change body of overridden methods use File | Settings | File Templates.
message = msg;
if(message.what != MessageCode.CLASS_CONNECTION){
sendMessageToServer();
} else {
handleConnection();
}
}
private void handleConnection(){
if(message.arg1 == MessageCode.CONNECTION_CONNECT) {
makeConnection();
} else {
closeConnection();
}
}
private void sendMessageToServer(){
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("eventClass", message.what);
jsonObject.put("eventAction", message.arg1);
jsonObject.put("eventActionType", message.arg2);
jsonObject.put("eventText", message.getData().getString(MESSAGE_DATA));
} catch (JSONException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
printwriter.println(jsonObject.toString());
Log.d("ConnectionInfo", "printwriter error: " + printwriter.checkError());
// printwriter.write(jsonObject.toString()+"\n");
}
protected void quit(){
getLooper().quit();
}
private void makeConnection(){
try {
client = new Socket("192.168.1.195", 4444);
Log.d("ConnectionInfo", client.toString());
printwriter = new PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
private void closeConnection(){
printwriter.close();
try {
client.close();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
quit();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>From what I can see, it seems like you are doing it correctly.</p>\n\n<p>On some exceptions, you might want to alert your user with a message about what went wrong (for example, \"Connection failed\"). Few users can read stack traces while using an app.</p>\n\n<p>I only have a few comments regarding your code style:</p>\n\n<p>You're inconsistent in putting spaces around <code>{</code>-characters, and also with if-statements. There should always be a space after <code>if</code> and before a <code>{</code><br>\nAs in, <code>private void makeConnection(){</code> <-- insert space here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T10:22:07.867",
"Id": "58555",
"Score": "0",
"body": "Thanks for the answer, I will indeed be adding user alerts, the code I posted was a simple proof of concept to test what the best way for the use of a socket would be.\n\nAs for my coding style, fair points, I will keep them in mind for my future coding/refactoring."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T21:17:08.710",
"Id": "35879",
"ParentId": "22778",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "35879",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T13:50:32.317",
"Id": "22778",
"Score": "5",
"Tags": [
"java",
"multithreading",
"android",
"socket"
],
"Title": "Socket handling in a thread"
}
|
22778
|
<p>I am working on converting a PHP application to MVC, and have a couple questions!</p>
<p>1) I have a main Model object, that I require a database connection for, as well as a User object that uses a database object also. Is it a bad practice to create a new database object for each of these classes, like the following?</p>
<p>or should I create a $databaseObject variable on the index.php page and pass that same variable in as a construct parameter for both User and Model? What is the difference?</p>
<p>Is there anything else that sticks out as something that I am doing wrong?</p>
<pre><code>class Model {
function __construct() {
$this->user = new User();
$this->db = new Database( DB_TYPE, DB_HOST, DB_NAME, DB_USER, DB_PASS );
}
}
class User {
public function getUserId(){
return $this->_userid;
}
public function __construct( ){
$this->db = new Database( DB_TYPE, DB_HOST, DB_NAME, DB_USER, DB_PASS );
$this->_userid = 1;
}
}
</code></pre>
<p>Thanks in advance for the help!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T20:52:25.947",
"Id": "35009",
"Score": "3",
"body": "Yes, this is [WET code](http://en.wikipedia.org/wiki/Don%27t_repeat_yourself), bad code. Also consider: [How Not To Kill Your Testability Using Statics](http://kunststube.net/static/)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T21:05:59.840",
"Id": "35010",
"Score": "2",
"body": "Model is a layer, that contains multitudes of different instances from different types, not a class or object. [Also](http://stackoverflow.com/q/5863870/727208), you code completely ignores [SOLID](http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)) principles. Is completely [untestable](https://www.youtube.com/watch?v=wEhu57pih5w) and relays on global state for configuration."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T21:15:11.893",
"Id": "35011",
"Score": "0",
"body": "so I should pass in the database object into the constructor?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T21:40:44.133",
"Id": "35012",
"Score": "2",
"body": "@user1582882 Yes, it's called dependency injection. Also, pass in the userid to the User object."
}
] |
[
{
"body": "<p>In general, using the \"new\" keyword in any class is bad practice, because you're creating an implicit dependency. Instead, you should follow the \"ask, don't look\" design philosophy and require that the database object be passed to the class, rather than letting the class fetch it. Dependency injection is a common solve to this problem, and I'd recommend looking at how <a href=\"http://pimple.sensiolabs.org/\" rel=\"nofollow\">PIMPLE</a> is used. Here's a good article: \"<a href=\"http://phpmaster.com/dependency-injection-with-pimple/\" rel=\"nofollow\">Dependency Injection with Pimple</a>\".</p>\n\n<p>Many people, like deceze, will deride you (rightfully so) for doing things like this, because it's one of the easiest (and probably most common) things you can do to kill the possibility of testing your code. If you were to write a unit test for this model, you'd have a database object being constructed with each test. Since the whole point of unit tests is to run code in isolation (to verify the tested code's accuracy), it would be impossible to test this model without a database.</p>\n\n<p>On that note, the JavaScript guru, Misko Hevery, published a really superb article on writing testable code: \"<a href=\"http://misko.hevery.com/2008/07/30/top-10-things-which-make-your-code-hard-to-test/\" rel=\"nofollow\">Top 10 things which make your code hard to test</a>\". While this is specifically in the context of code testing, it's also very good general programming information.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T18:58:47.953",
"Id": "26172",
"ParentId": "22783",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-15T20:49:01.690",
"Id": "22783",
"Score": "2",
"Tags": [
"php",
"object-oriented",
"mvc"
],
"Title": "Instantiating objects in a MVC in PHP"
}
|
22783
|
<p>I have written a piece of python code in response to the following question and I need to know if it can be "tidied up" in any way. I am a beginner programmer and am starting a bachelor of computer science.</p>
<blockquote>
<p><strong>Question:</strong> Write a piece of code that asks the user to input 10 integers, and then prints the largest odd number that was entered. if no odd number was entered, it should print a message to that effect.</p>
</blockquote>
<p>My solution:</p>
<pre><code>a = input('Enter a value: ')
b = input('Enter a value: ')
c = input('Enter a value: ')
d = input('Enter a value: ')
e = input('Enter a value: ')
f = input('Enter a value: ')
g = input('Enter a value: ')
h = input('Enter a value: ')
i = input('Enter a value: ')
j = input('Enter a value: ')
list1 = [a, b, c, d, e, f, g, h, i, j]
list2 = [] # used to sort the ODD values into
list3 = (a+b+c+d+e+f+g+h+i+j) # used this bc all 10 values could have used value'3'
# and had the total value become an EVEN value
if (list3 % 2 == 0): # does list 3 mod 2 have no remainder
if (a % 2 == 0): # and if so then by checking if 'a' has an EVEN value it rules out
# the possibility of all values having an ODD value entered
print('All declared variables have even values')
else:
for odd in list1: # my FOR loop to loop through and pick out the ODD values
if (odd % 2 == 1):# if each value tested has a remainder of one to mod 2
list2.append(odd) # then append that value into list 2
odd = str(max(list2)) # created the variable 'odd' for the highest ODD value from list 2 so i can concatenate it with a string.
print ('The largest ODD value is ' + odd)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T21:02:21.650",
"Id": "35021",
"Score": "0",
"body": "Thanks everyone for your input, i really appreciate that ! i will take a look at the extra code and try to understand how, where and why it fits in. !"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T21:09:03.643",
"Id": "35024",
"Score": "17",
"body": "If you have 10 lines that are pretty much the same chances are good that you are doing it wrong and want a loop instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T21:28:17.270",
"Id": "35026",
"Score": "1",
"body": "great site great people ! :) whoever cant become a skilled programmer these days with all this help deserves to sit and wonder why they not moving forward.. thank you !"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T02:00:32.880",
"Id": "35040",
"Score": "4",
"body": "You seem to have a logic problem is your solution. Entering `2,1,1,2,2,2,2,2,2,2` returns `All declared variables have even values`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T07:21:04.357",
"Id": "35049",
"Score": "0",
"body": "AHA . never saw that ! thought i had removed the logic error... good eye!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T11:07:09.847",
"Id": "35057",
"Score": "0",
"body": "@Caramdir: I think this kind of comments should be answers. I'd upvote it :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T04:16:35.020",
"Id": "35170",
"Score": "1",
"body": "@palacsint at least we can up vote the comments 0:)"
}
] |
[
{
"body": "<p>some advice:</p>\n\n<ul>\n<li>you don't need 10 named variables for the input, use an array instead, and a loop to do it</li>\n<li>use list comprehension to filter out all odd numbers</li>\n<li>take a look at the string formatting docs of python</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T20:12:03.453",
"Id": "35016",
"Score": "2",
"body": "Fivesheep, thanks for answering questions on Code Review. I hope you enjoy it. :) Your answer is already very useful as Ryan noted it, but I think it could use a bit more details: eg. you what string formatting functions do you recommend? Is it possible to show how the list comprehension would look like?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T20:19:50.487",
"Id": "35017",
"Score": "1",
"body": "Can you explain to me how to define the variables without having to type them all, is it just a=0, b=0 etc. do i use a FOR loop, to loop through the questions, Ive tried using the variables as ive mentioned and used a FOR loop, and it looped through the questions, but my output was totally wrong :8"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T21:02:54.460",
"Id": "35022",
"Score": "0",
"body": "@Ryan You do not need to define the variables per se. You merely need to create a list with 10 inputs. In other words, you would want something like this: [input('Enter a value: ') for i in range(0,10)]. This list comprehension would be converted to a list of 10 values without having to define 10 separate variables."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T11:12:55.730",
"Id": "35059",
"Score": "0",
"body": "@user1775603, yes, thanks, i am starting to become aware of that now. it is WAAYY easier to do that. its very cool."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T19:44:34.390",
"Id": "22785",
"ParentId": "22784",
"Score": "7"
}
},
{
"body": "<p>A tip: check immediately after asking each single question. No list to store values is needed, because you can forget each even number immediately, and follow the biggest odd number only.</p>\n\n<p>And: there is listobject.append() BTW, see <a href=\"http://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range\">http://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T05:31:18.310",
"Id": "35232",
"Score": "1",
"body": "A wonderful tip: forget what you don't need to know for the problem at hand. Just keep the largest odd so far or an indicator that you don't have one yet (like start the largest at zero and test for zero at the end)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T19:03:55.757",
"Id": "22790",
"ParentId": "22784",
"Score": "13"
}
},
{
"body": "<p>Here are a couple of places you might make your code more concise:</p>\n\n<p>First, lines 2-11 take a lot of space, and you repeat these values again below when you assign list1. You might instead consider trying to combine these lines into one step. A <a href=\"http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions\">list comprehension</a> might allow you to perform these two actions in one step:</p>\n\n<pre><code>>>> def my_solution():\n numbers = [input('Enter a value: ') for i in range(10)]\n</code></pre>\n\n<p>A second list comprehension might further narrow down your results by removing even values:</p>\n\n<pre><code> odds = [y for y in numbers if y % 2 != 0]\n</code></pre>\n\n<p>You could then see if your list contains any values. If it does not, no odd values were in your list. Otherwise, you could find the max of the values that remain in your list, which should all be odd:</p>\n\n<pre><code> if odds:\n return max(odds)\n else:\n return 'All declared variables have even values.'\n</code></pre>\n\n<p>In total, then, you might use the following as a starting point for refining your code:</p>\n\n<pre><code>>>> def my_solution():\n numbers = [input('Enter a value: ') for i in range(10)]\n odds = [y for y in numbers if y % 2 != 0]\n if odds:\n return max(odds)\n else:\n return 'All declared variables have even values.'\n\n\n>>> my_solution()\nEnter a value: 10\nEnter a value: 101\nEnter a value: 48\nEnter a value: 589\nEnter a value: 96\nEnter a value: 74\nEnter a value: 945\nEnter a value: 6\nEnter a value: 3\nEnter a value: 96\n945\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T21:35:24.023",
"Id": "35028",
"Score": "2",
"body": "Good answer, but `if len(list2) != []:` is not really pythonic. You could simply do: `if len(list2):`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T22:18:00.027",
"Id": "35030",
"Score": "1",
"body": "Welcome to Code Review and thanks for the excellent answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T22:34:17.333",
"Id": "35031",
"Score": "0",
"body": "Thanks to you both for sharing your knowledge and improvements. I updated the answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T23:37:45.727",
"Id": "35034",
"Score": "8",
"body": "@Zenon couldn't you just do `if list2:`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T08:08:14.357",
"Id": "35050",
"Score": "1",
"body": "@SnakesandCoffee yes you could and shouldd, because it's much better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T10:27:11.087",
"Id": "35110",
"Score": "0",
"body": "@user1775603 A micro optimization to test whether a number is odd is y & 1 == 1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T13:35:10.643",
"Id": "58320",
"Score": "0",
"body": "For further optimisation, generators and trys could replace lists and conditionals: `n = (input('Enter..') for i in xrange(10))` and `o = (y for y in n if n%2)`. `try: return max(o)` `except ValueError: return 'All declared...'`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T13:42:03.050",
"Id": "58324",
"Score": "0",
"body": "This gist shows the above changes. https://gist.github.com/ejrb/7581712"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T20:55:48.690",
"Id": "22793",
"ParentId": "22784",
"Score": "31"
}
},
{
"body": "<p>No-one has given the code I would write, which doesn't create a list but instead tracks the answer in a loop. The logic is a little more complex, but it avoids storing values (here it doesn't really matter, since it's only 10 values, but a similar problem with input from another program, might have more data than fits in memory).</p>\n\n<pre><code>maxOdd = None\nfor _ in range(10):\n value = int(input('Enter a value: '))\n if (value % 2 and (maxOdd is None or value > maxOdd)):\n maxOdd = value\nif maxOdd:\n print('The largest odd value entered was', maxOdd)\nelse:\n print('No odd values were entered.')\n</code></pre>\n\n<p>Note that I am treating non-zero values as <code>True</code>, so <code>value % 2</code> is a test for oddness (because it gives a non-zero remainder, and Python treats non-zero values as <code>true</code>). Similarly, <code>if maxOdd</code> tests that <code>maxOdd</code> is not <code>None</code> (nor zero, but it cannot be zero, because that is even).</p>\n\n<p>Another way, closer to the other answers, in that it treats the numbers as a sequence, but still avoiding storing everything in memory, is to use a generator:</p>\n\n<pre><code>from itertools import islice\n\ndef numbers():\n while True:\n yield input('Enter a value: ')\n\ndef odd(n):\n return n % 2\n\ntry:\n print('The largest odd value entered was',\n max(filter(odd, map(int, islice(numbers(), 10)))))\nexcept ValueError:\n print('No odd values were entered.')\n</code></pre>\n\n<p>This is more \"advanced\", but <code>numbers()</code> creates a <em>generator</em>, and the chain of functions <code>max, filter, map, islice</code> effectively call that for each value (simplifying slightly). So the end result is a kind of pipeline that, again, avoids keeping everything in memory.</p>\n\n<p>(The <code>ValueError</code> happens when <code>max</code> doesn't receive any values.)</p>\n\n<p>Another way of writing that would be (note the lack of square brackets):</p>\n\n<pre><code>try:\n print('The largest odd value entered was',\n max(filter(odd,\n map(int, (input('Enter a value: ')\n for _ in range(10))))))\nexcept ValueError:\n print('No odd values were entered.')\n</code></pre>\n\n<p>where <code>(input ...)</code> is a generator expression.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T06:50:55.897",
"Id": "35048",
"Score": "0",
"body": "thank you, ur right, it is a little advanced for me right now, although i like the idea of not storing the values. any suggestions on a good reading material related to computer logic?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T23:19:37.690",
"Id": "22798",
"ParentId": "22784",
"Score": "14"
}
},
{
"body": "<p>I would do it something like this:</p>\n\n<pre><code>def is_odd(x):\n return x & 1 and True or False\n\n\nolist = []\n\nfor i in xrange(10):\n while True:\n try:\n n = int(raw_input('Enter a value: '))\n break\n except ValueError:\n print('It must be an integer.')\n continue\n\n if is_odd(n):\n olist.append(n)\n\ntry:\n print 'The largest ODD value is %d' % max(olist)\nexcept ValueError:\n print 'No ODD values were entered'\n</code></pre>\n\n<p>The <code>is_odd</code> function is checking the last bit of the integer to see if it is set (1) or not (0). If it's set then it must be odd. Eg: 010 (2 is not odd) 011 (3 is odd).</p>\n\n<p>Also, I would filter odds on the fly so I don't need to parse the list multiple times and I would use xrange (a generator) to keep memory \"safe\".</p>\n\n<p>For this case those \"optimizations\" wouldn't be necessary as the list is only size 10 and there isn't much computation but if you had to take a lot of integers you would need to consider it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T09:11:16.157",
"Id": "35051",
"Score": "0",
"body": "With python3, I prefer range since it is optimized to do lazy evaluation. xrange.. doesn't feel good while reading. :P"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T23:49:21.817",
"Id": "22800",
"ParentId": "22784",
"Score": "3"
}
},
{
"body": "<p>Since you didn't specify whether you're using Python 2 or Python 3, I'm not sure if the below answer is relevant. In Python 2, <code>input</code> is risky. In Python 3, <code>input</code> is fine.</p>\n\n<p>Although some answers have replaced <code>input(...)</code> by <code>int(raw_input(...))</code>, I don't think anybody has explained yet <em>why</em> this is recommended.</p>\n\n<h2><code>input</code> considered harmful in Python 2.x</h2>\n\n<p>In Python 2.x, <code>input(x)</code> is equivalent to <code>eval(raw_input(x))</code>. See, for example, the documentation for <code>input</code> in <a href=\"http://docs.python.org/2/library/functions.html#input\" rel=\"nofollow\">Python 2.7</a>, and <a href=\"http://docs.python.org/2/library/functions.html#raw_input\" rel=\"nofollow\">the documentation for <code>raw_input</code></a>. This means that <em>a user can execute an arbitrary Python expression</em>, such as:</p>\n\n<pre><code>>>> input(\"Number? \")\nNumber? os.unlink(\"/path/to/file\") \n</code></pre>\n\n<p>Therefore, in Python 2, <strong>always use <code>raw_input</code> rather than <code>input</code></strong>.</p>\n\n<p>Some explanation: <code>raw_input</code> returns a string, for example, <code>'10'</code>. This string you need to convert to a number. The function <code>int</code> can do this for you (<a href=\"http://docs.python.org/2/library/functions.html#int\" rel=\"nofollow\">see documentation in Python 2.7</a>). So wherever you use <code>input</code> to get a whole number, you would rather want <code>int(raw_input(...))</code>. This will take the input as a string, and immediately convert it to an integer. This will raise an exception if the input cannot be converted to an integer: </p>\n\n<pre><code>>>> int(raw_input(\"Number? \"))\nNumber? os.unlink(\"/path/to/file\")\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nValueError: invalid literal for int() with base 10: 'os.unlink(\"/path/to/file\")'\n</code></pre>\n\n<p>In Python 3, <code>input</code> is equivalent to Python 2 <code>raw_input</code>, see for example, the documentation for <code>input</code> in <a href=\"http://docs.python.org/3.3/library/functions.html#input\" rel=\"nofollow\">Python 3.3</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T10:56:15.807",
"Id": "35055",
"Score": "0",
"body": "I see. i was trying to create this program and it wouldnt run when i used raw_input, im using python2.7, but it took input and worked. why would that be? and thanks for the insight"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T11:00:31.163",
"Id": "35056",
"Score": "0",
"body": "@RyanSchreiber I added some explanation"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T11:07:20.883",
"Id": "35058",
"Score": "0",
"body": "fantastic, okay, i understand now why it never worked! another note on that, why would i as a programmer, want to have the text inputted as a string and converted to an integer ? is this a secure way of programming and if so what is the reason behind that? and btw, yes, i will read the documentation, would just like another outside view on it :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T13:55:48.423",
"Id": "35062",
"Score": "0",
"body": "surely you mean `raw_input` rather than `input`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T14:39:29.230",
"Id": "35065",
"Score": "0",
"body": "@Ysangkok Oops, yes I do of course, now fixed."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T10:54:05.937",
"Id": "22813",
"ParentId": "22784",
"Score": "3"
}
},
{
"body": "<p>Why not multiply each value by its least-significant bit (aka that number in modulo 2), so that even numbers are zero and odd numbers stay what they are, then use <code>max()</code> to return the largest number (which has to be odd because all the evens were multiplied by zero)</p>\n\n<p>**Note, assuming no negative-numbers, if there are than just use max but strip all \"0\" from your array.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-09T05:54:45.327",
"Id": "54802",
"Score": "0",
"body": "Modulo 2 maps everything to 0 or 1, which is not useful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-09T06:40:46.967",
"Id": "54803",
"Score": "0",
"body": "@200_success If you read the full answer you would see that I said MULTIPLY the number by itself in modulo 2... which would make all even numbers 0 and all odd numbers would stay what they were (since they were multiplied by 1), THEN use max() and return the largest number (which would, by definition, be the largest ODD number)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-09T06:43:11.117",
"Id": "54804",
"Score": "0",
"body": "@200_success If you could undo your down-vote it would be greatly appreciated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-09T06:54:50.933",
"Id": "54805",
"Score": "0",
"body": "I've changed the wording for clarity and reversed my vote."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-10T05:54:40.030",
"Id": "56836",
"Score": "0",
"body": "@200_success Thankyou very much :) It means alot to me haha!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T04:20:16.557",
"Id": "22882",
"ParentId": "22784",
"Score": "0"
}
},
{
"body": "<p>I think in this case, performance is of no concern and so the priority is making workings of the program as immediately obvious as possible.</p>\n\n<pre><code>user_input = [input('Enter a value: ') for x in range(10)]\nnumbers = map(int, user_input)\nodd_numbers = [n for n in numbers if n % 2 != 0]\nif odd_numbers:\n print(max(odd_numbers))\nelse:\n print(\"All the numbers are even\")\n</code></pre>\n\n<p>Here each line is a new logical and concise step.</p>\n\n<ol>\n<li>Get numbers from user as strings using <code>input</code> in Python 3 or <code>raw_input</code> in Python 2.</li>\n<li>Convert the strings to ints.</li>\n<li>Extract all the odd numbers from the list of numbers.</li>\n<li>Print the biggest odd number or a message.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T15:08:23.043",
"Id": "29591",
"ParentId": "22784",
"Score": "0"
}
},
{
"body": "<p>This is the finger exercise from Ch.2 of Introduction to Computation and Programming Using Python by John V. Guttag. It's the recommended text for the MITx: 6.00x Introduction to Computer Science and Programming. The book is written to be used with Python 2.7.</p>\n\n<p>At this point the book has only introduced variable assignment, conditional branching programs and while loops as well as the print function. I know as I'm working through it. To that end this is the code I wrote:</p>\n\n<pre><code>counter = 10\nwhile counter > 0:\n x = int(raw_input('Please type in integer: '))\n if counter == 10 or (x%2 and x > ans):\n ans = x\n if ans%2 == 0: # Even Number Safeguard\n ans = x \n counter = counter -1\nif ans%2 != 0:\n print 'The largest odd number entered was', str(ans)\nelse:\n print 'No odd number was entered'`\n</code></pre>\n\n<p>Seems to work. It can probably be shortened but the idea was to use only the limited concepts that have been covered in the book.</p>\n\n<p><strong>EDITED</strong> to include commments to shorten code. Still meets the criteria of using the limited concepts introduced in the book.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-09T02:46:29.453",
"Id": "54795",
"Score": "0",
"body": "I was referring to the exact question from the text. I've change it now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-09T02:48:00.240",
"Id": "54796",
"Score": "0",
"body": "Oh, okay. It seemed like a new question at first."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-10T14:04:03.893",
"Id": "56860",
"Score": "1",
"body": "`ans = ans` does nothing, and you could simplify all the `if...else...elif` conditions to a single one: `if counter == 10 or (x % 2 and x > ans): ans = x`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T04:29:15.283",
"Id": "57106",
"Score": "0",
"body": "Yep, it can definitely be shortened. I'll get my head round the computational way of thinking, eventually."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T18:26:33.670",
"Id": "57316",
"Score": "0",
"body": "I suggest: `ans = None` at the top, `if x % 2 and (ans is None or x > ans)` inside the loop, and `if ans is not None` after the loop. Not repeating `10` and `% 2` makes the code more maintainable. (That ends up being @andrewcooke's answer, except without using `range()`.)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-09T02:42:19.557",
"Id": "34087",
"ParentId": "22784",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T19:07:26.577",
"Id": "22784",
"Score": "28",
"Tags": [
"python",
"beginner"
],
"Title": "Asks the user to input 10 integers, and then prints the largest odd number"
}
|
22784
|
<p>if node[i] and node[i+1] are present in the neighbor[i], then store the 'i' position of node and print the 'i' value of node.</p>
<p>this is also done by reversing the node array(only) and same type of check and print is done with the neighbor[i].</p>
<p>This code is written by me and works well, is there any other efficient method to perform this.</p>
<pre><code>#include <stdio.h>
int main()
{
int node[5] = {44,5,4,6,40};
int neighbor[4]= {40,3,4,6};
int i=0,j=0,k=0;
int found_indices[5]; // array used to store indices of found entries..
int count = 0; //n entries found;
int fwd_count=0;
int postn;
int find;
// to find in forward direction
for (i=0; i<4; i++) {
for (j=0; j<4; j++) {
if (node[i]==neighbor[j]) {
postn=node[i];
for (k=0; k<4; k++) {
if (node[i+1]==neighbor[k]) {
found_indices[fwd_count ++] = postn; // storing the index of found entry
}
}
}
}
}
if (fwd_count!=0) {
for (i=0; i<fwd_count; i++)
printf("forward relay for ==%d\n", found_indices[i]);
} else{
printf("Relay not found in forward\n");
}
// to find in backward direction
for (i=4; i>0; i--) {
for (j=0; j<4; j++) {
if (node[i]==neighbor[j]) {
postn=node[i];
for (k=0; k<4; k++) {
if (node[i-1]==neighbor[k]) {
found_indices[count ++] = postn; // storing the index of found entry
}
}
}
}
}
if (count!=0) {
for (i=0; i<count; i++)
printf("backward relayy for ==%d\n", found_indices[i]);
}else{
printf("Relay not found in backward \n");
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T23:38:12.813",
"Id": "35035",
"Score": "0",
"body": "Does it really work? Can I suggest that you separate the two cases (forward/reverse) into two functions, remove the assumed array sizes (pass them to the functions) and then define and run some (many) more test cases. Also explain more carefully what you expect as results."
}
] |
[
{
"body": "<p>They key here is to to be able to abstract common functionality away. You're not expressing \"node[i] is in the neighbor array\" nicely. Simply write a function which does it for you:</p>\n\n<pre><code>int node_in_neighbors(int node, int neighbor[], int length) {\n int i;\n\n for(i = 0; i < length; i++) {\n if (neighbor[i] == node) { \n return 1; \n }\n }\n return 0;\n}\n</code></pre>\n\n<p>In a more \"high-level\" language, you wouldn't have to write this function, and it would be in the library. You can now rewrite your forward/backward loops easily:</p>\n\n<pre><code>// to find in forward direction\nfor (i = 0; i < 4; i++) {\n // keep a node if his successor and him are in the neighbors array\n if (node_in_neighbors(node[i], neighbor, 4)\n && node_in_neighbors(node[i+1], neighbor, 4)) {\n found_indices[fwd_count ++] = node[i]; \n }\n} \n\n// to find in backward direction\nfor (i = 4; i > 0; i--) {\n // keep a node if his predecessor and him are in the neighbors array\n if (node_in_neighbors(node[i], neighbor, 4)\n && node_in_neighbors(node[i-1], neighbor, 4)) {\n found_indices[count ++] = node[i];\n }\n}\n</code></pre>\n\n<p>This makes the code clearer, since it's way easier to understand the logic now.</p>\n\n<p>One issue is that you still have lots of <code>4</code> around. You should replace those in the loop with <code>node_length - 1</code> and those in the <code>node_in_neighbors</code> call by <code>neighbor_length</code>, otherwise you could confuse them.</p>\n\n<p>Define those lengths like this:</p>\n\n<pre><code>int node_length = sizeof(node) / sizeof(node[0])\nint neighbor_length = sizeof(neighbor) / sizeof(neighbor[0])\n</code></pre>\n\n<p>This trick only works on static arrays, be careful.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T13:11:24.407",
"Id": "22858",
"ParentId": "22786",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "22858",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-16T19:50:05.293",
"Id": "22786",
"Score": "3",
"Tags": [
"c",
"array"
],
"Title": "Matching element of arrays on a condition"
}
|
22786
|
<p>I would like to turn the following:</p>
<pre><code><div>this is a $test</div>
</code></pre>
<p>into</p>
<pre><code><div>this is a <div>$test</div></div>
</code></pre>
<p>currently I have </p>
<pre><code>var regexp = new RegExp('$([^\\s]*)','g'),
html = '<div>this is a $test</div>',
matched = html.match(regexp)[0]
if (matched){
html = html.replace(match, '<div>' + match + '</div>')
}
</code></pre>
<p>which works, but is there a more concise way of doing this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T00:31:51.643",
"Id": "35037",
"Score": "0",
"body": "Maybe you are optimizing too early here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T01:15:40.240",
"Id": "35039",
"Score": "0",
"body": "`match` only returns an array if it found anything, otherwise it just returns `null`. So be careful there, `html.match(regexp)[0]` will give you a `typeError` if no match was found."
}
] |
[
{
"body": "<p>Sure, use <a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace\" rel=\"nofollow\">String.replace</a>. As an added bonus, it doesn't fail when there is no match:</p>\n\n<pre><code>'<div>this is a $test</div>'.replace(/(\\$\\w+)/g, '<div>$1</div>')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T12:32:43.213",
"Id": "22856",
"ParentId": "22801",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "22856",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T00:00:46.873",
"Id": "22801",
"Score": "2",
"Tags": [
"javascript",
"regex"
],
"Title": "Encapsulate results in div tags"
}
|
22801
|
<p>This is a user JavaScript for YouTube. The point is to make the thumbnail bigger on mouseover. I just want some help making it better because I don't want it to waste resources with all the extensions I have and other scrips. I also added Iframes because I have another extension that makes a preview of the video in the thumbnail. I also use Opera so make sure it works on Opera.</p>
<pre><code>/*! settings begin */
//Makes the name of the video apear bellow the image if false (false/true)
var WideSideBar = true;
/*! settings end */
//Get the sidebar were the thumbnails are and the main
var videos = document.getElementById("watch7-sidebar");
var main = document.getElementById("watch7-main");
//Make the SideBar wider
if (WideSideBar) {
main.style.width = "1117px";
videos.style.width = "472px";
}
videos.addEventListener("mouseover", function (a) {
if (a.target.tagName == "IMG") {
//Make image bigger
a.target.style.width = "292px";
a.target.style.height = "163px";
a.target.style.WebkitTransition = 'width 0.5s, height 0.5s';
a.target.parentNode.parentNode.parentNode.style.width = "292px";
a.target.parentNode.parentNode.parentNode.style.height = "163px";
a.target.parentNode.parentNode.parentNode.style.WebkitTransition = 'width 0.5s, height 0.5s';
//Get a higher resolution image of the thumbnail
var video_id = a.target.parentNode.parentNode.parentNode.parentNode.parentNode.href.split('v=')[1];
var ampersandPosition = video_id.indexOf('&');
if (ampersandPosition != -1) {
video_id = video_id.substring(0, ampersandPosition);
}
a.target.src = "http://img.youtube.com/vi/" + video_id + "/0.jpg";
} else if (a.target.tagName == "IFRAME") {
//Make Iframe AKA:(Thumbnail preview) bigger
a.target.parentNode.style.WebkitTransition = 'width 0.5s, height 0.5s';
a.target.parentNode.style.width = "292px";
a.target.parentNode.style.height = "163px";
}
}, false);
videos.addEventListener("mouseout", function (a) {
if (a.target.tagName == "IMG") {
//Make image normal size.
a.target.style.width = "120px";
a.target.style.height = "67px";
a.target.parentNode.parentNode.parentNode.style.width = "120px";
a.target.parentNode.parentNode.parentNode.style.height = "67px";
} else if (a.target.tagName == "IFRAME") {
//Make Iframe AKA:(Thumbnail preview) normal size
a.target.parentNode.style.width = "120px";
a.target.parentNode.style.height = "67px";
}
}, false);
</code></pre>
|
[] |
[
{
"body": "<p>I don't see anything in your code that should cause any performance issues. You're not doing anything iterative, or performing any complex operations; your code just executes linearly and changes some CSS properties. That shouldn't kill performance. </p>\n\n<p>Have you seen anything to indicate that this code <em>does</em> kill performance? If so then the only thing I could suggest is changing the events that you listen for (or maybe, adding some logic to ensure that you don't start a new transition while the current one is still running), as perhaps the page is triggering more <code>mouseover</code> and <code>mouseout</code> events than you expect.</p>\n\n<p>Premature optimization is the root of all evil, and all that.</p>\n\n<p>Also, you should be able to do:</p>\n\n<pre><code> video_id = video_id.split('&')[0]; //this works whether or not an `&` is present\n</code></pre>\n\n<p>...instead of:</p>\n\n<pre><code> var ampersandPosition = video_id.indexOf('&');\n if (ampersandPosition != -1) {\n video_id = video_id.substring(0, ampersandPosition);\n }\n</code></pre>\n\n<p>That (probably) won't perform any better, but it's less code to accomplish the same thing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T01:11:02.777",
"Id": "22804",
"ParentId": "22803",
"Score": "0"
}
},
{
"body": "<p>Why not use the :hover pseudo class and have that trigger the size change? Probably easier than having to worry about event binding.\n<a href=\"http://jsfiddle.net/nhzNM/\" rel=\"nofollow\">http://jsfiddle.net/nhzNM/</a></p>\n\n<pre><code><iframe class=\"videoPlayer\" width=\"560\" height=\"315\" src=\"http://www.youtube.com/embed/90Omh7_I8vI?controls=0&rel=0\" frameborder=\"0\" allowfullscreen></iframe>\n<style type=\"text/css\">\n.videoPlayer {\n width: 560px;\n height: 315px;\n -webkit-transition: height,width 1s ease;\n -moz-transition: height,width 1s ease;\n -ms-transition: height,width 1s ease;\n -o-transition: height,width 1s ease;\n transition: height,width 1s ease;\n}\n\n.videoPlayer:hover {\n width: 650px;\n height: 365px;\n}\n</style>\n</code></pre>\n\n<p>You could use the same setup for a thumbnail positioned in front of the video embed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T14:28:04.740",
"Id": "35064",
"Score": "0",
"body": "One of the problems is that in youtube I have to change the width and the height of another element so it works.\n a.target.style.height = \"163px\"; \n a.target.parentNode.parentNode.parentNode.style.height = \"163px\";"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T03:58:00.830",
"Id": "22809",
"ParentId": "22803",
"Score": "1"
}
},
{
"body": "<p>If you only need IE9+ support, you can use the <code>transform: scale</code> property in CSS, and avoid JavaScript altogether:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>img {\n transition: all .2s;\n margin: 50px;\n}\n\nimg:hover {\n -ms-transform: scale(1.2); /* IE 9 */\n -webkit-transform: scale(1.2) /* Safari, iOS, Android */\n transform: scale(1.2);\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><img src=\"http://lorempizza.com/380/240\"></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>IE10 users will not enjoy the transition, but will still see the scale.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-25T08:49:58.710",
"Id": "70781",
"ParentId": "22803",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T00:18:08.850",
"Id": "22803",
"Score": "1",
"Tags": [
"javascript",
"optimization",
"performance",
"video"
],
"Title": "Increasing size of video thumbnail on mouseover"
}
|
22803
|
<p>I have recently finished creating my own <code>Deck</code> class for my Poker game. It works the way I want it to, but I would like to know if I can make it better and/or more efficient.</p>
<p><strong>Deck.h</strong></p>
<pre><code>#ifndef DECK_H
#define DECK_H
#include "Card.h"
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
class Deck
{
private:
static const string RANKS[13], SUITS[4];
int size;
Card cards[52];
void build();
public:
Deck();
~Deck();
void shuffle();
Card drawCard();
int getDeckSize() const {return size;}
friend ostream& operator<<(ostream&, const Deck&);
};
#endif
</code></pre>
<p><strong>Deck.cpp</strong></p>
<pre><code>#include "Deck.h"
const string Deck::RANKS[13] = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
const string Deck::SUITS[4] = {"H","D","C","S"};
Deck::Deck() : size(0) {build();}
Deck::~Deck() {}
void Deck::build()
{
srand((unsigned int)time(NULL));
string card;
bool isSameCard;
while (size < 52)
{
isSameCard = false;
card = RANKS[rand()%13] + SUITS[rand()%4];
for (int i = 0; i < size; i++)
{
if (cards[i].getCard() == card)
{
isSameCard = true;
break;
}
}
if (!isSameCard)
{
cards[size].setCard(card);
size++;
}
}
}
void Deck::shuffle()
{
build();
srand((unsigned int)time(NULL));
for (int i = 0; i < size; i++)
{
int j = rand() % 52;
swap(cards[i], cards[j]);
}
}
Card Deck::drawCard()
{
if (size == 0)
{
cerr << "ERROR *** DECK EMPTY";
Card card;
return card;
}
size--;
return cards[size];
}
ostream& operator<<(ostream &out, const Deck &aDeck)
{
for (int i = aDeck.size-1; i >= 0; i--)
cout << *((aDeck.cards)+i) << endl;
return out;
}
</code></pre>
<p>Shuffling a <code>Deck</code> object only requires a call to <code>shuffle()</code>, so the object does not need to be destroyed for that. The shuffling algorithm works, and I tested this by making a separate check to make sure the deck never contains duplicates.</p>
<p>The driver for the class is in my Poker game itself, but I have tested each function sufficiently. I have both displayed the <code>Deck</code> and its size, and have drawn some cards, a few times each run.</p>
<p>I'm paying particular attention to this class because I want to be able to reuse it for future programs. That is one of my biggest interests in this post.</p>
<p><strong>====== REVISED ======</strong></p>
<p><strong>Deck.h</strong></p>
<pre><code>#ifndef DECK_H
#define DECK_H
#include "Card.h"
#include <ostream>
#include <string>
#include <vector>
using std::ostream;
using std::string;
using std::vector;
class Deck
{
private:
static const int MAX_SIZE = 52;
static const string RANKS[13];
static const string SUITS[4];
int size;
vector<Card> cards;
public:
Deck();
~Deck();
Card drawCard();
void shuffle();
int getDeckSize() const {return size;}
friend ostream& operator<<(ostream&, const Deck&);
};
#endif
</code></pre>
<p><strong>Deck.cpp</strong></p>
<pre><code>#include "Deck.h"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using std::ostream;
using std::vector;
const string Deck::RANKS[13] = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
const string Deck::SUITS[4] = {"H","D","C","S"};
Deck::Deck() : size(0)
{
for (int i = 0; i < 13; i++)
{
for (int j = 0; j < 4; j++)
{
Card t;
t.setCard(RANKS[i] + SUITS[j]);
cards.push_back(t);
size++;
}
}
shuffle();
}
Deck::~Deck() {}
void Deck::shuffle()
{
size = MAX_SIZE;
std::random_shuffle(&cards[0], &cards[MAX_SIZE-1]);
}
Card Deck::drawCard()
{
if (size == 0)
{
std::cerr << "ERROR *** DECK EMPTY";
Card card;
return card;
}
size--;
return cards[size];
}
ostream& operator<<(ostream &out, const Deck &aDeck)
{
for (int i = aDeck.size-1; i >= 0; i--)
out << aDeck.cards[i] << "\n";
return out;
}
</code></pre>
|
[] |
[
{
"body": "<p>Never use <code>using namespace X;</code> in a header file. If I have to include your header you are polluting the global namespace for me and that can cause all sorts of problems in the code. As this is a potential source for bugs I will never use your header file (until you fix it).</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>Even doing it in a normal *.cpp file is bad as it can cause problems for you. So it is better to fully qualify stuff <code>std::string</code> (the extra five letters is not so bad). If you must save those five letters you can bring specific objects into the current scope with <code>using std::cout;</code>.</p>\n\n<p>Read all about it here: <a href=\"https://stackoverflow.com/q/1452721/14065\">Why is 'using namespace std;' considered a bad practice in C++?</a></p>\n\n<p>You are not using anything specific from <code>iostream</code>. All you seem to be using is the <code>std::ostream</code> but it has its own header file so just include that:</p>\n\n<pre><code>#include <ostream> // rather than <iostream>\n</code></pre>\n\n<p>You re not using time in the header file. So don;t include the in the header file. Only include the header files that you must include to get it to compile. In this case I would move <code>ctime</code> into the Deck.cpp file.</p>\n\n<pre><code>#include <ctime> // Move to Deck.cpp\n</code></pre>\n\n<p>Please one variable per line:</p>\n\n<pre><code>static const string RANKS[13], SUITS[4];\n</code></pre>\n\n<p>It makes the code easier to read. There is also one corner case (not hit here) that can hit you so best just not to do this.</p>\n\n<p>If your destructor is not doing anything. Then don't write one:</p>\n\n<pre><code>Deck::~Deck() {}\n</code></pre>\n\n<p>Only use srand() <strong>once</strong> in an application.</p>\n\n<pre><code>void Deck::build()\n{\n srand((unsigned int)time(NULL));\n</code></pre>\n\n<p>You are not doing yourself any favors with randomness by doing it more than once in an application. By putting it one place (probably just after main()) you know that you will not accidentally get two different pieces of code doing srand() and when debugging is being done you will want to make sure that you use the same sequence so putting srand() where it is easy to find and turn off can be useful.</p>\n\n<p>Your build card could take a long time build the deck (if you get unlucky). An easier way is to put all the cards into the deck then shuffle it. </p>\n\n<p>Good attempt at shuffle. But technically not correct (OK. for the people that complain about the last sentence I am merely quoting (from memory (so in spirit)) Knuth).</p>\n\n<p>To do it correctly.</p>\n\n<ul>\n<li>Create an empty shuffled deck.\n\n<ul>\n<li>You pick a card at random from your deck. </li>\n<li>Remove card from your deck.</li>\n<li>Put it on the top of the shuffled deck.</li>\n<li>If your deck is not empty repeat.</li>\n</ul></li>\n</ul>\n\n<p>Or you can use the <code>std::random_shuffle()</code> algorithm. Which basically does the above algorithm (in place).</p>\n\n<p>In your output operator. You pass the stream but don't use it (I assume that's just a type). Also I would prefer to use \"\\n\" rather than std::endl. std::endl prints a newline then flushes the output. Probably not a performance problem here but in general unless you want to flush the stream prefer \"\\n\". </p>\n\n<pre><code>cout << *((aDeck.cards)+i) << endl; // for some reason you are\n // using std::cout\n\n// Use `out` the stream passed in.\n</code></pre>\n\n<p>This is correct.</p>\n\n<pre><code>out << *((aDeck.cards)+i) << \"\\n\";\n</code></pre>\n\n<p>But I think this is easier to read:</p>\n\n<pre><code>out << aDeck.cards[i] << \"\\n\";\n</code></pre>\n\n<p>I would take this a step further and use a standard algorithm:</p>\n\n<pre><code>std::copy(std::begin(aDeck.cards), std::end(aDeck.cards),\n std::ostream_iterator<Card>(out, \"\\n\"));\n\n// Note: If you are using C++03 std::begin() and std::end() are\n// easily replaced with array index and address operations.\n</code></pre>\n\n<p>==========</p>\n\n<h3>Updated Code</h3>\n\n<p>static const integers can be defined and initialized in the class file:</p>\n\n<pre><code>// Deck.h\nstatic const int MAX_SIZE = 52;\n</code></pre>\n\n<p>I would not try and do manual memory management:</p>\n\n<pre><code>Card *cards; // New'ed on constructor and delete'd in destructor.\n</code></pre>\n\n<p>This is slightly more complex. Owned RAW pointers (this is one) means you need to implement the rule of three. This means you need to implement (or disable) the copy constructor and assignment operator. Otherwise you open yourself up to problems with double delete.</p>\n\n<p>Note: An \"Owned RAW pointer\" is a pointer that you are responsible for deleting (this is to distinguish it from pointers that you are not responsible for deleting). Anything you create is usually owned. In most situations in C++ we use either smart pointers or containers to actually own the pointer so that our code can be concerned with business logic.</p>\n\n<p>But a better solution is to use an existing container object:</p>\n\n<pre><code>std::vector<Card> cards;\n</code></pre>\n\n<p>The principle of <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">separation of Concerns</a> means you should use the <code>std::vector</code> as the Deck is really an object that deals with business logic it should not also be handling resource management.</p>\n\n<p>The shuffle is better:</p>\n\n<pre><code>void Deck::shuffle()\n{\n Card *temp = new Card[MAX_SIZE];\n int counter = MAX_SIZE;\n\n for (int i = 0; i < MAX_SIZE; i++)\n {\n int j = rand() % MAX_SIZE; // Note: The size is getting smaller\n // each time you remove a card.\n // So you should use %(MAX_SIZE - i);\n\n temp[i].setCard(cards[j].getCard());\n swap(cards[j], cards[counter-1]);\n counter--;\n }\n\n *cards = *temp; // Note: You have made a call to new.\n // As a result you should call delete\n // to avoid a memory leak.\n //\n // A better way to do this is:\n // std::swap(cards, temp);\n // delete [] temp;\n\n // Note 2: Note your code here merely swaps\n // the first card from the two arrays.\n\n // Note 3: You should probably use std::vector<Card>\n // for `temp`. It will handle the memory\n // management correctly.\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T02:57:59.327",
"Id": "35041",
"Score": "0",
"body": "Thank you! I'll make the necessary changes and report back if I need more help. I sort of found out about the namespace thing on my own, but it was never stressed in any of my classes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T06:06:29.180",
"Id": "35046",
"Score": "0",
"body": "@JamalA: See update at bottom."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T06:27:36.470",
"Id": "35047",
"Score": "0",
"body": "I'm working on the vector now (I'm also very new to that), and I'm getting a \"vector subscript out of range\" error. I'm trying to find the problem now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T11:38:04.793",
"Id": "35061",
"Score": "0",
"body": "Couldn't you just use the in-place [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm)? Am I missing something?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T17:14:40.053",
"Id": "35077",
"Score": "0",
"body": "@codesparkle: That's how std::random_shuffle works. But the first step in learning it is to use two stacks. Once you have it working then move on to the in place shuffle. You will notice that he is practically there (he just has not noticed yet)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T18:50:02.003",
"Id": "35085",
"Score": "0",
"body": "@Loki: I have actually read about that shuffle, but I had trouble understanding it. I was also trying std::random_shuffle, but I just haven't put much effort in getting it working. Sorting is something I can polish over time, but I am more interested in figuring out vectors."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T19:42:59.453",
"Id": "35087",
"Score": "0",
"body": "As @codesparkle is suggesting you don't actually need to decks. If you move the shuffled cards to one end (and don't include them in subsequent random picks) you achieve the same result. If you look at your code now it actually does this already (assuming you add my fixes). Just remove the swap and references to temp and it should work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T19:45:00.587",
"Id": "35088",
"Score": "0",
"body": "@JamalA: `std::random_shuffle(&cards[0], &cards[MAX_SIZE])`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T19:57:32.423",
"Id": "35090",
"Score": "0",
"body": "I got it working now! The vector of objects is starting to make sense, and I'll try to add it to the rest of my program. The shuffling function was added as well. I needed to reset the size because my tests didn't otherwise show a full size after a shuffle."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T02:44:38.157",
"Id": "22808",
"ParentId": "22805",
"Score": "15"
}
},
{
"body": "<p>When talking about efficiency, it's useful knowledge that the standard representation of a hand or deck in poker programs is a 64-bit integer. </p>\n\n<p>You assign to each card in a deck one bit, and set it to 1 if the card is present in the deck, or 0 if it's not.</p>\n\n<p>For example like this:</p>\n\n<pre><code>23456789TJQKA___23456789TJQKA___23456789TJQKA___23456789TJQKA___ // ranks per bit\nCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDDDHHHHHHHHHHHHHHHHSSSSSSSSSSSSSSSS // colors per bit\n1111111111111000111111111111100011111111111110001111111111111000 // full deck\n1000000000100000000000010000000000000000000010000000000000001000 // 2cQc9dAhAs\n</code></pre>\n\n<p>It is useful in a way that you can easily access information:</p>\n\n<pre><code>bitcount(hand) // number of cards\nhand & 0x00ff0000 // all diamonds from a hand\nhand & 0x08080808 // all aces from the hand\nhand1 & hand2 != 0 // true if two hands share the same card.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-17T11:50:47.680",
"Id": "54492",
"ParentId": "22805",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "22808",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T01:34:43.907",
"Id": "22805",
"Score": "13",
"Tags": [
"c++",
"playing-cards"
],
"Title": "Card Deck class for a Poker game"
}
|
22805
|
<p>I have a class that I am using to initialize a form for editing. Once the form is submitted, data validation is done through the setters of my class. Good or bad input will be set in order to re-display them in the form (is this bad?). Everything works fine, but I am not too happy with how I am storing and displaying the error messages.</p>
<p>Any suggestions on how I can improve?</p>
<p><strong>Course.class.php</strong></p>
<pre><code><?php
class Course {
protected $_code;
protected $_name;
protected $_errors = array();
public function __constructor($id) {
if (is_int($id)) {
$this->_load($id);
}
}
public function getCode() { return $this->_code; }
public function setCode($value) {
$this->_code = $value;
if (empty($value)) {
$this->setError('code', 'Enter a code.');
} else if (strlen($value) > 10) {
$this->setError('code', 'The code you provided must be less than 10 characters.');
}
}
public function getName() { return $this->_name; }
public function setName($value) {
$this->_name = $value;
if (empty($value)) {
$this->setError('name', 'Enter a name.');
} else if (strlen($value) > 50) {
$this->setError('name', 'The name you provided must be less than 50 characters.');
}
}
public function getError($name) {
return isset($this->_errors[$name]) ? $this->_errors[$name] : '';
}
public function setError($name, $value) {
$this->_errors[$name] = $value;
}
public function hasErrors() {
return !empty($this->_errors);
}
public function _load($id) {
// load record from database
}
public function save() {
if (!this->hasErrors()) {
// save record to database
}
}
}
?>
</code></pre>
<p>I have looked around and many have suggest to use exceptions. However, I don't quite get how I can use them because wouldn't throwing an exception in one setter cause the subsequent setters from not being called.</p>
<ul>
<li><a href="https://stackoverflow.com/questions/1651964/oop-design-question-validating-properties">OOP Design Question - Validating properties</a></li>
<li><a href="https://stackoverflow.com/questions/5506033/validate-on-entry-or-before-saving">Validate on entry or before saving?</a></li>
</ul>
<p>Here is how I am currently using my class:</p>
<p><strong>edit_course.php</strong></p>
<pre><code><?php
$filter = array(
'hidSubmit' => FILTER_VALIDATE_BOOLEAN,
'code' => FILTER_SANITIZE_STRING,
'name' => FILTER_SANITIZE_STRING
);
$c = filter_input(INPUT_GET, 'c', FILTER_VALIDATE_INT);
$course = new Course($c);
$inputs = filter_input_array(INPUT_POST, $filter);
if ($inputs['hidSubmit']) {
$course->setName($inputs['name']);
$course->setDescription($inputs['description']);
$course->save();
refreshPage();
}
require_once 'header_admin.php';
?>
<form id="editForm" name="editForm" action="" method="post">
<fieldset>
<legend>Edit Course</legend>
<label>Code</label>
<input type="text" name="code" value="<?php echo $course->getCode(); ?>" maxlength="10" size="8" />
<span class="error"><?php echo $course->getError('code'); ?></span>
<label>Name</label>
<input type="text" name="name" value="<?php echo $course->getName(); ?>" maxlength="45" size="25" />
<span class="error"><?php echo $course->getError('name'); ?></span>
<input type="submit" value="Save" />
<input type="hidden" name="hidSubmit" value="1" />
</fieldset>
</form>
<?php
require_once 'footer_admin.php';
?>
</code></pre>
|
[] |
[
{
"body": "<p>The big disadvantage of putting the validation to the setter is that you are never able to set invalid values. In most cases this is fine, but in some scenarios a valid user input differs from a more general valid field content. In addition the validation is also executed to internal setter uses where know that they are valid.</p>\n\n<p>That said, I recommend setters to be only setters and not more.</p>\n\n<p>The validation itself can be placed in a separate method or even in a separate class (depending on the complexity).</p>\n\n<p>If you only want to display one error message, throwing an exception within the validation should be fine.</p>\n\n<p>If you want to collect multiple error messages, you might want to build a generic validation class:</p>\n\n<pre><code>$valid=new Validation();\n$valid->assertNotEmpty($name,\"name\",\"Insert a name please\");\n$valid->assertLength($name,3,50,\"name\",\"...\");\n...\nif ($valid->hasErrors()) ...\n</code></pre>\n\n<p>You could extend this to a CourseValidation if you need it at multiple locations.</p>\n\n<pre><code>$valid=new CourseValidation($code,$name);\n...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T16:30:42.630",
"Id": "35075",
"Score": "0",
"body": "Thank you, it works but I am not sure if I am understanding your suggestion correctly. I have updated my code to show what I did. Is that what you mean? Any more improvements that can be made?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T17:59:19.777",
"Id": "35082",
"Score": "0",
"body": "You should also consider Robs comments. Creating a Form class will help you to get rid of the duplication in your HTML."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T07:52:01.757",
"Id": "22812",
"ParentId": "22810",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "22812",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T04:19:24.693",
"Id": "22810",
"Score": "2",
"Tags": [
"php",
"object-oriented",
"validation"
],
"Title": "Properly storing error messages and displaying them with OOP"
}
|
22810
|
<p>Does this part look clean enough? Any suggestions on how to make it cleaner?</p>
<pre><code>if (isCheck)
{
if (isStuck)
{
return GameState.Mate;
}
else
{
return GameState.Check;
}
}
else
{
if (isStuck)
{
return GameState.Stalemate;
}
else
{
return GameState.Ok;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T13:56:49.563",
"Id": "35063",
"Score": "19",
"body": "I think this is one of the cases where leaving out (some of) braces would improve your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T20:33:32.903",
"Id": "35091",
"Score": "2",
"body": "I don't think any of the answers are more readable than the original code. And it looks like it's a standalone method already, so elsewhere you'll just be calling `GetGameState(isCheck, isStuck)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T05:01:34.277",
"Id": "35099",
"Score": "3",
"body": "I do not think you need this enum. Ennum is an intermediate value, not a goal. With just IsStuck and IsCheck your code can: `if (isStuck) { displayReason(); GameOver();}` ... else ... `if (IsCheck) { SayCheck(); }`. If you generate the enum, then you still need to run a bunch of conditions on it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T08:19:20.693",
"Id": "35104",
"Score": "2",
"body": "@James It fills half the screen, and it can cleanly be written in three lines (nested ternary). I don’t understand why there’s even a *discussion* about the relative benefits of these solutions."
}
] |
[
{
"body": "<p>It depends on what you consider more readable, but you could use a binary-like way of expressing the variables as in a truth table:</p>\n\n<pre>isCheck isStuck Value\n=======================\nT T Mate\nT F Check\nF T Stalemate\nF F Ok\n</pre>\n\n<p>Which would translate to something more compact:</p>\n\n<pre><code>if (isCheck && isStuck) return GameState.Mate;\nif (isCheck && !isStuck) return GameState.Check;\nif (!isCheck && isStuck) return GameState.Stalemate;\nif (!isCheck && !isStuck) return GameState.OK;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T17:32:50.937",
"Id": "35080",
"Score": "9",
"body": "This is actually much more complex and error-prone than the original code. Here is why: four ifs instead of three; four 2-literal boolean expressions instead of three 1-literal ones; mutual exclusion not structurally obvious."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T00:12:52.703",
"Id": "35096",
"Score": "3",
"body": "I can agree on the complexity based on those metrics.\nHowever, take the example of design patterns: can you say they introduce complexity in the form of number of classes, for example? Sure they do. \n\nThat's why I pointed out where the design decision comes from: a truth table. Just as you could be baffled by looking at the many classes used for,say, Java streams, when you figure out they follow the decorator pattern everything seems more clear all of a sudden.\n\nI proposed that answer since I've wound up with a need for that kind of functions where clarity and compacity are the most valued."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T10:12:58.610",
"Id": "35108",
"Score": "3",
"body": "Since `return` actually returns, you can make this slightly less verbose by skipping all the `else` keywords :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T10:34:31.160",
"Id": "35112",
"Score": "0",
"body": "Some added whitespace to line things up could help with the readability a lot."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T18:44:22.077",
"Id": "35150",
"Score": "1",
"body": "@JavierVilla: you can remove the isCheck from test 3 and turn test 4 into a simple return. That makes it no more complex than the original."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T15:27:04.080",
"Id": "35199",
"Score": "1",
"body": "One problem with this is that you need to add something below the four `if`s, since the compiler doesn't understand that they handle every possible case."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T12:37:58.103",
"Id": "22816",
"ParentId": "22815",
"Score": "9"
}
},
{
"body": "<p>I think <code>?</code> operator will make your code more compact and readable:</p>\n\n<pre><code>return isCheck\n ? isStuck ? GameState.Mate : GameState.Check\n : isStuck ? GameState.Stalemate : GameState.Ok\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T17:18:58.797",
"Id": "35078",
"Score": "12",
"body": "THis one isn't too bad; but I find ternary operators become hard to follow when nested much faster than other operators and try very hard to avoid doing so."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T08:18:16.590",
"Id": "35103",
"Score": "1",
"body": "This is how I’d always write it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T10:41:27.997",
"Id": "35115",
"Score": "4",
"body": "I'd bracket the code for clarity but I think this is perfectly acceptable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T10:51:25.410",
"Id": "35118",
"Score": "3",
"body": "@DanNeely Agree with you, but 1-level nesting seems reasonable in this case. Decision table as for me is an overkill here, especially given that you need to map `bool`->`int` first, or use `Dictionary` to map booleans directly"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T14:05:42.550",
"Id": "22820",
"ParentId": "22815",
"Score": "29"
}
},
{
"body": "<p>I'd use a decision table here:</p>\n\n<pre><code>GameState[,] decisionTable = new GameState[2,2];\ndecisionTable[0,0] = GameState.Ok;\ndecisionTable[0,1] = GameState.Stalemate;\ndecisionTable[1,0] = GameState.Check;\ndecisionTable[1,1] = GameState.Mate;\nreturn decisionTable[Convert.ToInt32(isCheck), Convert.ToInt32(isStuck)];\n</code></pre>\n\n<p>From Code Complete 2nd Edition, Chapter 19: General Control Issues, page 431:</p>\n\n<blockquote>\n <p><strong>Use decision tables to replace complicated conditions</strong></p>\n \n <p>Sometimes you have a complicated test involving several variables. It can be helpful to use a decision table to perform the test rather than using ifs or cases. A decision-table lookup is easier to code initially, having only a couple of lines of code and no tricky control structures. This minimization of complexity minimizes the opportunity for mistakes. If your data changes, you can change a decision table without changing the code; you only need to update the contents of the data structure.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T18:43:15.387",
"Id": "35084",
"Score": "8",
"body": "Just remember to isolate this in a function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T10:40:37.687",
"Id": "35114",
"Score": "7",
"body": "I think with just two cases like this, a decision tree is actually harder to follow. A more compact presentation of the OPs code would be cleaner and easier to understand."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T20:25:57.613",
"Id": "35397",
"Score": "2",
"body": "palacsint, I took the liberty to turn your pseudocode into real, compiling C#. If you have any objections, feel free to rollback my edit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T21:39:38.617",
"Id": "35403",
"Score": "0",
"body": "@codesparkle: I'm glad that somebody did it :) Thank you!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T14:12:26.600",
"Id": "22821",
"ParentId": "22815",
"Score": "80"
}
},
{
"body": "<p>As an alternative variant to @palacsint solution of decision table, the situation of a series of bool^n is traditionally represented using flags.</p>\n\n<pre><code>// in a global constants file somewhere\nconst Stuck = 1 << 0; // 1\nconst Check = 1 << 1; // 2\nconst ..... = 1 << n; // 2^n\n\nint decisionTable[] = {\n GameState.Ok, // 0b00\n GameState.Stalemate, // 0b01\n GameState.Check, // 0b10\n GameState.Mate, // 0b11\n};\n\n\n// in code\nint flags = 0;\nif (isStuck(board)) flags |= Stuck;\nif (isCheck(board)) flags |= Check;\n\nreturn decisionTable[flags];\n</code></pre>\n\n<p>There is also an alternative way to construct the decision table that may be more readable and less error prone, though perhaps more verbose:</p>\n\n<pre><code>int decisionTable[] = new int[4];\ndecisionTable[0] = GameState.Ok;\ndecisionTable[Stuck] = GameState.StaleMate;\ndecisionTable[Check] = GameState.Check;\ndecisionTable[Stuck | Check] = GameState.Mate;\n</code></pre>\n\n<p>The issue with the decision table used by @palacsint or with writing it as functions with a series of argument (e.g. <code>getState(isCheck, isStuck)</code>) is that you have to remember the precise order of the arguments, which gets unwieldy when you have a large number of flags. For example, if you accidentally swapped the indices like: <code>decisionTable[(int)isStuck][(int)isCheck];</code> you may find yourself into a lengthy debugging session without ever realizing the swap. Bitwise OR is commutative so it doesn't have this issue.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T17:55:48.680",
"Id": "35081",
"Score": "8",
"body": "honestly looking at the OP's code I can understand that better than this code. Bit shifting has its place in lots of different contexts, but I don't see this one being beneficial for this purpose."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T23:54:47.173",
"Id": "35095",
"Score": "0",
"body": "@RobertSnyder: you only need to write those global constants once, but you used the flag and the flag tables much more often. An alternative to bit shifting would be to use `power(2, n)` but IMO bit shifting translates intent more clearly than `pow()` because flags are not really integers/numbers but a series of booleans (a series of bits)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T10:18:22.270",
"Id": "35109",
"Score": "2",
"body": "More recent versions of C# support named parameters, so you can write something like `getGameState(isStuck: this.isStuck, isCheck: this.isCheck)`. Then the exact parameter order does not matter."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T16:49:35.293",
"Id": "22827",
"ParentId": "22815",
"Score": "19"
}
},
{
"body": "<p>Just to add on to <a href=\"https://codereview.stackexchange.com/a/22821/6219\">the answer by @palacsint</a>, if the language you are working with allows array literals, you can make it look like more a table:</p>\n\n<pre><code>var decisionTable = new GameState[][] {\n new GameState[] { GameState.Checkmate, GameState.Check } // isCheck\n new GameState[] { GameState.Stalemate, GameState.Ok }\n // isStuck\n}\nreturn decisionTable[(int)isCheck][(int)isStuck];\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T18:00:33.997",
"Id": "35083",
"Score": "0",
"body": "I think you could even simplify this more if you consider that his arguments are a rudimentary binary counting exercise. That being said if you could change isCheck and isStuck to a simple flag enum, you could just OR the numbers and return the appropriate GameState."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T10:55:55.033",
"Id": "35119",
"Score": "0",
"body": "Don't forget that original @palacsint answer is a pseudocode, you can't cast `bool` to `int`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T17:38:58.317",
"Id": "22828",
"ParentId": "22815",
"Score": "4"
}
},
{
"body": "<p>inline if statement is shorter but I don't know about cleaner</p>\n\n<pre><code>return isCheck\n ? (isStuck ? GameState.Mate : GameState.Check)\n : (isStuck ? GameState.Stalemate : GameState.Ok);\n</code></pre>\n\n<p>And to expand and simply the bitwise</p>\n\n<pre><code>int result = (isCheck ? 1 : 0) + (isStuck ? 2 : 0);\nreturn (GameState) result;\n\nenum GameState\n{\n Ok = 0,\n Check = 1,\n Stalemate = 2,\n Mate = 3,\n}\n</code></pre>\n\n<p>You can use the enum \"as\" your decision tree!</p>\n\n<p>I arranged them </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T18:26:34.807",
"Id": "22829",
"ParentId": "22815",
"Score": "4"
}
},
{
"body": "<p>First of all, I think your solution is fine.</p>\n\n<p>That being said, I can understand why the solution is frustrating. As the many other, varied answers suggest, this is one of those problems that just <em>feels</em> like it should have a simple, elegant, one-liner style solution. But, it just doesn't. There are shorter solutions, but they all sacrifice readability.</p>\n\n<p>Like I said above, I think your approach is good, and if I came across it in code I was reviewing at work, I wouldn't bother to comment on it. But I do think it could be cleaned up just a little. When approaching a nested <code>if</code> I think it's best to start with the broadest question/condition in the outer <code>if</code>, then ask the more narrow question(s) below. Also, I think it's usually better to put the most common case near the top, because when someone is reading the code (perhaps trying to debug an issue), it's this branch that they're most likely to be interested in...also it just seems more logical to me. Finally don't be afraid to drop in a well named variable just to make the code more readable. </p>\n\n<p>With all that in mind, here's my solution:</p>\n\n<pre><code> var gameShouldContinue = ! isStuck;\n if (gameShouldContinue) {\n return isCheck ? GameState.Check : GameState.Ok;\n } else {\n return isCheck ? GameState.Mate : GameState.Stalemate;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T17:05:08.830",
"Id": "35145",
"Score": "1",
"body": "“ There are shorter solutions, but they all sacrifice readability.” – wrong. The nested ternary solution doesn’t. It’s idiomatic in about any language and directly communicates what it does."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T22:12:41.703",
"Id": "35161",
"Score": "3",
"body": "Eh... In this case nested conditional operators wouldn't be too terribly hard to read if it's well formatted, but as a general rule of thumb, I think it's bad practice. Not because it can't be understood, but because it takes more time to understand and offers very little benefit. YMMV"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T11:54:16.620",
"Id": "35181",
"Score": "0",
"body": "We’re talking about the specific case of one level of nesting here though. There isn’t any problem with that – and in general *chaining* the ternary operator is never hard to read if properly formatted (except in PHP because the language sucks and gets the precedence wrong) – in fact, it reads just like a `switch` statement. [Here’s an example in C++](https://gist.github.com/klmr/4985197). Again, this is *idiomatic* code in most languages."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T15:25:12.727",
"Id": "35198",
"Score": "2",
"body": "@KonradRudolph I for one thing this is much easier to read than a nested conditional operators (at least with C#'s ugly `?:` syntax.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T15:42:18.283",
"Id": "35201",
"Score": "0",
"body": "@CodesInChaos Did you take a look at the linked code? If you have trouble reading this then this suggests lack of familiarity with the language rather than lack of readability of the idiom. Sorry, but that’s just it. Incidentally, I agree that the `?:` operator in the C-family languages is really ugly, and that there is better syntax for this in other languages."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T22:49:04.793",
"Id": "35218",
"Score": "1",
"body": "@KonradRudolph I'm pretty impressed with your example and agree that it is readable. However, I don't think it's applicable here. In this case GameState depends upon two variables and in your example there's only one. Nesting conditionals here would require both the `true` and `false` branches of the outer conditional to contains nested conditional operators."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T23:02:18.593",
"Id": "35219",
"Score": "0",
"body": "@Andy Yes, granted, I agree that it’s not quite the same as OP’s example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-24T11:45:35.587",
"Id": "365167",
"Score": "0",
"body": "@Andy Your else is redundant here."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T22:39:53.113",
"Id": "22837",
"ParentId": "22815",
"Score": "14"
}
},
{
"body": "<p>I think decision tables are good enough. If you want to go esoteric you can also define enum values as bit values and mapping would be automatic (which is very specific to the given example, so not a good idea in general):</p>\n\n<pre><code>enum GameState\n{\n Ok = 0,\n Stalemate = 1,\n Check = 2\n Mate = 3\n}\n</code></pre>\n\n<p>the code becomes:</p>\n\n<pre><code>return (GameState)(((int)isCheck << 1)|(int)isStuck);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T18:21:33.933",
"Id": "35149",
"Score": "0",
"body": "Why would he want to \"go esoteric\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T21:15:45.793",
"Id": "35158",
"Score": "0",
"body": "He wouldn't probably. But knowing all alternatives might expand our horizon when looking for solutions in similar problems in the future. And that could be a perfect solution for different set of constraints."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T04:15:17.110",
"Id": "22845",
"ParentId": "22815",
"Score": "1"
}
},
{
"body": "<p>Not really recommending this, but you could use the fact that you are always using both variables to generate a string representaion of the four states, and then have either a dictionary or switch statement return the correct value.</p>\n\n<pre><code>string checkStuck = isCheck.ToString() + isStuck.ToString();\nswitch(checkStuck) {\n case \"TrueFalse\":\n return GameState.Mate;\n case \"TrueTrue\":\n return GameState.Check;\n case \"FalseFalse\":\n return GameState.Ok;\n case \"FalseTrue\":\n return GameState.Stalemate;\n}\n</code></pre>\n\n<p>You could do the same with integers, but at that point you might as well go with Andy's answer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T08:46:52.493",
"Id": "35105",
"Score": "15",
"body": "To all future developers, please don't _ever_ use strings like this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T05:52:27.643",
"Id": "35174",
"Score": "0",
"body": "@JeffMercado: what's your objection? I don't want to defend it, it's not what I would typically implement. It really has nothing to recommend it except possibly readability for someone without experience with the alternatives. But it also doesn't seem to be an abuse of strings either."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T18:05:20.043",
"Id": "35287",
"Score": "1",
"body": "The objection is clearly that the code is literally undefendable. It is inefficient and inelegant."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T19:08:11.977",
"Id": "35289",
"Score": "1",
"body": "Clear sign of the need to have pattern matching in C#."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T06:02:45.463",
"Id": "22846",
"ParentId": "22815",
"Score": "-7"
}
},
{
"body": "<p>Any time you have multiple independent boolean variables representing a state, consider using a bitfield through the use of an enum with the <code>FlagsAttribute</code> applied. That way you don't need to maintain multiple variables to represent a single state.</p>\n\n<pre><code>[Flags]\npublic enum BoardState\n{\n None = 0x0,\n IsCheck = 0x1,\n IsStuck = 0x2,\n}\n</code></pre>\n\n<p>Then you could map these board states to the appropriate game state. Just make sure you map out every valid combination if you plan on using a dictionary.</p>\n\n<pre><code>private Dictionary<BoardState, GameState> transition = new Dictionary<BoardState, GameState>\n{\n { BoardState.None, GameState.Ok },\n { BoardState.IsCheck, GameState.Check },\n { BoardState.IsStuck, GameState.Stalemate },\n { BoardState.IsCheck | BoardState.IsStuck, GameState.Mate },\n};\npublic GameState Next(BoardState boardState)\n{\n GameState nextState;\n if (!transition.TryGetValue(boardState, out nextState))\n throw new ArgumentOutOfRangeException(\"boardState\");\n return nextState;\n}\n</code></pre>\n\n<p>Otherwise use a switch statement if the mapping gets too unruly or you want to map multiple combinations to a single value (it's not necessary in this case).</p>\n\n<pre><code>public GameState Next(BoardState boardState)\n{\n switch (boardState)\n {\n case BoardState.None:\n return GameState.Ok;\n case BoardState.IsCheck:\n return GameState.Check;\n case BoardState.IsStuck:\n return GameState.Stalemate;\n case BoardState.IsCheck | BoardState.IsStuck:\n return GameState.Mate;\n default:\n throw new ArgumentOutOfRangeException(\"boardState\");\n }\n}\n</code></pre>\n\n<p>Then use regular bit manipulation to set/clear the flags. Do take care in using this if you have values that represent multiple values</p>\n\n<pre><code>BoardState boardState = ...;\n// to set a flag\nboardState |= BoardState.IsCheck;\n// to clear a flag\nboardState &= ~BoardState.IsStuck;\n// to test a flag\nboardState.HasFlag(BoardState.IsCheck);\n</code></pre>\n\n<p>You can clean keep this nice and clean exposing this through boolean properties.</p>\n\n<pre><code>private BoardState internalBoardState;\npublic bool IsCheck\n{\n get { return internalBoardState.HasFlag(BoardState.IsCheck); }\n set\n {\n if (value)\n internalBoardState |= BoardState.IsCheck;\n else\n internalBoardState &= ~BoardState.IsCheck;\n }\n}\npublic bool IsStuck\n{\n get { return internalBoardState.HasFlag(BoardState.IsStuck); }\n set\n {\n if (value)\n internalBoardState |= BoardState.IsStuck;\n else\n internalBoardState &= ~BoardState.IsStuck;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T08:45:39.060",
"Id": "22849",
"ParentId": "22815",
"Score": "5"
}
},
{
"body": "<p>I think decision trees are unnecessary and over-complicated for a case this simple - although they have clear advantages if it gets more complicated than this, personally I'd do this:</p>\n\n<pre><code>if (isCheck)\n return isStuck ? GameState.Mate : GameState.Check;\nelse\n return isStuck ? GameState.StaleMate : GameState.Ok;\n</code></pre>\n\n<p>Which I find clearer than a pure ternary operator solution and more compact and thus more directly readable than a pure <code>if</code> solution.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-24T11:43:58.727",
"Id": "365166",
"Score": "0",
"body": "Your `else` is redundant here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-24T12:04:23.687",
"Id": "365168",
"Score": "0",
"body": "@VadimOvchinnikov You are correct. However, I think it makes the flow and intent of the code easier to read so I would leave it in."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T10:44:28.027",
"Id": "22854",
"ParentId": "22815",
"Score": "3"
}
},
{
"body": "<p>You could simply make GameState a Flags enum, which is merely a more compact version of the decision table palacsint proposed.</p>\n\n<pre><code>[Flags]\npublic enum GameState\n{\n None = 0x0,\n IsCheck = 0x1,\n IsStuck = 0x2,\n\n Ok = None,\n Check = IsCheck,\n Stalemate = IsStuck,\n Checkmate = IsCheck | IsStuck,\n}\n</code></pre>\n\n<p>When using the enum, you can set your two flags with bitwise or operators:</p>\n\n<pre><code>GameState current = GameState.Ok;\ncurrent |= GameState.IsStuck;\ncurrent |= GameState.IsCheck;\n</code></pre>\n\n<p>If you want to check the two bit flags on it, you can either use bitwise operators as follows:</p>\n\n<pre><code>var isStuck = ((current & GameState.IsStuck) == GameState.IsStuck);\n</code></pre>\n\n<p>or, in more recent versions of .NET, you can use the Enum.HasFlag method:</p>\n\n<pre><code>var isStuck = current.HasFlag (GameState.IsStuck);\n</code></pre>\n\n<p>The end result is that all your reading/writing of the flags is done entirely with your variable storing GameState, rather than having separate booleans floating around and a muti-dimensional array to look things up.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T18:57:34.337",
"Id": "22869",
"ParentId": "22815",
"Score": "1"
}
},
{
"body": "<p>So many crazy answers! I'll add another one! :D</p>\n\n<p>The most important property of good code is no code duplication. In the original solution it is <code>if (isStuck)</code> condition, which is duplicated. We can avoid code duplication by making a clever (not so much in this case) abstraction!</p>\n\n<pre><code>T if_<T>(bool b, Tuple<T,T> t) {\n return b ? t.Item1 : t.Item2;\n}\nGameState choose (bool isCheck, bool isStuck) {\n return if_(isStuck, if_(isCheck, \n Tuple.Create(\n Tuple.Create(GameState.Mate, GameState.Check),\n Tuple.Create(GameState.Stalemate, GameState.Ok)\n )));\n}\n</code></pre>\n\n<p>Now the <code>if_(isStuck,...</code> is no longer duplicated. Win!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T19:03:20.527",
"Id": "22936",
"ParentId": "22815",
"Score": "1"
}
},
{
"body": "<p>Personally, I'd just collapse the tree.</p>\n\n<pre><code>if (isCheck && isStuck)\n{\n return GameState.Mate;\n}\nelse if (isCheck)\n{\n return GameState.Check;\n}\nelse if (isStuck)\n{\n return GameState.Stalemate;\n}\nelse\n{\n return GameState.Ok;\n}\n</code></pre>\n\n<p>or even </p>\n\n<pre><code>if (isCheck && isStuck) return GameState.Mate;\nelse if (isCheck) return GameState.Check;\nelse if (isStuck) return GameState.Stalemate;\nelse return GameState.Ok;\n</code></pre>\n\n<p>I find this much more readable than trying to do conversions to an Enum, and more straightforward than a decision grid. That being said, it doesn't scale as well as either option.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T21:02:22.983",
"Id": "22981",
"ParentId": "22815",
"Score": "0"
}
},
{
"body": "<p>No need to talk much I think,</p>\n\n<pre><code> stuck\n |--------- mate (11)\n check |\n|---------|\n| |\n| |--------- check (10)\n| \n| stuck\n| |--------- stalemate (01)\n| |\n|---------|\n |\n |--------- ok (00)\n\nenum GameState\n{\n Ok = 0, // 0x00\n Stalemate = 1, // 0x01\n Check = 2, //0x10\n Mate = 3 //0x11\n}\n\nreturn (GameState) (0x10 * isCheck + isStuck);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T17:29:04.343",
"Id": "48251",
"ParentId": "22815",
"Score": "3"
}
},
{
"body": "<p>If you like the idea of decision tables (like in <a href=\"https://codereview.stackexchange.com/a/22821/119568\">palacsint's answer</a>), then you could use more elegant approach using <a href=\"https://msdn.microsoft.com/en-us/library/system.valuetuple(v=vs.110).aspx\" rel=\"nofollow noreferrer\"><code>ValueTuple</code></a> and <code>Dictionary</code> combo.</p>\n\n<pre><code>GameState GetGameState(bool isCheck, bool isStuck)\n{\n var decisionDictionary = new Dictionary<(bool, bool), GameState>\n {\n [(true, true)] = GameState.Mate,\n [(true, false)] = GameState.Check,\n [(false, true)] = GameState.Stalemate,\n [(false, false)] = GameState.Ok\n };\n\n return decisionDictionary[(isCheck, isStuck)];\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-23T23:00:16.170",
"Id": "190341",
"ParentId": "22815",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "22821",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T12:25:24.370",
"Id": "22815",
"Score": "74",
"Tags": [
"c#",
"enum"
],
"Title": "BOOL×BOOL→ENUM mapping"
}
|
22815
|
<p>I'm coding a 2D collision engine, and I need to merge adjacent axis-aligned bounding boxes depending on a direction (left, right, top, bottom).</p>
<p>The four cases are very similar, except for the if condition, and the push_back argument.
Is there any way I can refactor this code without compromising performance? </p>
<pre><code>vector<AABB> getMergedAABBSLeft(vector<AABB> mSource)
{
vector<AABB> result;
while(!mSource.empty())
{
bool merged{false}; AABB a{mSource.back()}; mSource.pop_back();
for(auto& b : mSource)
if(a.getRight() == b.getRight())
{
result.push_back(getMergedAABBVertically(a, b));
eraseRemove(mSource, b); merged = true; break;
}
if(!merged) result.push_back(a);
}
return result;
}
vector<AABB> getMergedAABBSRight(vector<AABB> mSource)
{
vector<AABB> result;
while(!mSource.empty())
{
bool merged{false}; AABB a{mSource.back()}; mSource.pop_back();
for(auto& b : mSource)
if(a.getLeft() == b.getLeft())
{
result.push_back(getMergedAABBVertically(a, b));
eraseRemove(mSource, b); merged = true; break;
}
if(!merged) result.push_back(a);
}
return result;
}
vector<AABB> getMergedAABBSTop(vector<AABB> mSource)
{
vector<AABB> result;
while(!mSource.empty())
{
bool merged{false}; AABB a{mSource.back()}; mSource.pop_back();
for(auto& b : mSource)
if(a.getBottom() == b.getBottom())
{
result.push_back(getMergedAABBHorizontally(a, b));
eraseRemove(mSource, b); merged = true; break;
}
if(!merged) result.push_back(a);
}
return result;
}
vector<AABB> getMergedAABBSBottom(vector<AABB> mSource)
{
vector<AABB> result;
while(!mSource.empty())
{
bool merged{false}; AABB a{mSource.back()}; mSource.pop_back();
for(auto& b : mSource)
if(a.getTop() == b.getTop())
{
result.push_back(getMergedAABBHorizontally(a, b));
eraseRemove(mSource, b); merged = true; break;
}
if(!merged) result.push_back(a);
}
return result;
}
</code></pre>
|
[] |
[
{
"body": "<p>Without knowing much about the <code>AABB</code> type, I'm assuming it has the operations <code>getBottom()</code>, and it's top-left-right couterparts.</p>\n\n<p>What you could do is set up functions which returns the appropiate result and pass it as an argument to the general function. I only show the process for the top/left/right/bottom. The horizontally/vertically part goes the same way. Something like: </p>\n\n<pre><code> typedef elem_type (*selector)(AABB*);\n elem_type getRightSelector(AABB* obj)\n {\n return obj->getRight(); // Return value is of elem_type\n }\n // Same for the others (left, top...)\n\nvector<AABB> getMergedAABBS(vector<AABB> mSource, selector sel )\n{\n (...)\n for(auto& b : mSource)\n if(sel(a) == sel(b))\n {\n // We'd need another pointer here\n result.push_back(getMergedAABBHorizontally(a, b));\n eraseRemove(mSource, b); merged = true; break;\n }\n\n (...)\n return result;\n}\n\n // Any particular one:\n vector<AABB> getMergedAABBSRight(vector<AABB> mSource )\n{\n return getMergedAABBS(mSource, getRightSelector);\n}\n</code></pre>\n\n<p>Then you'd call the general function from each suffixed function (ie. getMergedAABBTop, etc.) passing the appropriate selector function.</p>\n\n<p>Note this may be achieved in a cleaner way with C++11 features, what I'm not so certain about is the performance impact. Here you are adding one function call with respect to your code inside the loop, plus one function call from the specialized functions to the general one. Consider inlining, too.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T13:30:15.560",
"Id": "22818",
"ParentId": "22817",
"Score": "2"
}
},
{
"body": "<p>I find this line hard to read:</p>\n\n<pre><code>bool merged{false}; AABB a{mSource.back()}; mSource.pop_back();\n</code></pre>\n\n<p>Please split variables up 1 per line.<br>\nYes the new syntax allows {} for list initialization. But these are not lists so it seems confusing to me (this one is more personal bias so feel free to ignore).</p>\n\n<pre><code>bool merged(false);\nAABB a(mSource.back());\nmSource.pop_back();\n</code></pre>\n\n<p>Pass large parameters by const reference if you can.<br>\nIt saves a copy and you don't seem to need the copy (since you are not modifying the value (Note the eraseRemove() call has no effect externally and does not effect the rest of the code)).</p>\n\n<pre><code>vector<AABB> getMergedAABBSLeft(vector<AABB> const& mSource)\n // ^^^^^^^^\n</code></pre>\n\n<p>Since your four functions are identical apart from one method call you could write a generic version and pass that method as a parameter:</p>\n\n<pre><code>vector<AABB> getMergedAABBSLeft(vector<AABB> mSource)\n{ return getMergedAABBSGeneric(mSource, &AABB::getRight);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T09:47:50.403",
"Id": "35107",
"Score": "0",
"body": "Why isn't eraseRemove doing anything? It takes a (std::vector&) as a parameter, so I'm sure it is removing AABBs from mSource. Are you sure I can safely delete it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T14:38:22.117",
"Id": "35129",
"Score": "0",
"body": "Its doing something locally. But mSource is not exported from this function so has no effect on anything else. The fact that you remove an element does not affect this algorithm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-28T19:00:48.877",
"Id": "35887",
"Score": "0",
"body": "@Loki Astari: You discourage the use of the {} because you say it is used for C++11's list initialization. This recommendation isn't correct, it's called the new C++11 \"Uniform initialization\" ( http://en.wikipedia.org/wiki/C%2B%2B11#Uniform_initialization ). It is encouraged for any type of initialization now, as it avoids problems from type narrowing, or the notorious Most Vexing Parse ( http://en.wikipedia.org/wiki/Most_vexing_parse )."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T19:08:57.880",
"Id": "35952",
"Score": "0",
"body": "@Piotr99: Thanks for the extra information. That was a personal one for me (I am still learning C++11) and nothing I would have rejected code from a code review on. It would be helpful if you had a reference for `\"encouraged for any type of initialization now\"`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-01T19:27:12.100",
"Id": "35953",
"Score": "0",
"body": "The most authoritative source for C++ always is Bjarne Stroustrup ;) http://www.stroustrup.com/C++11FAQ.html#uniform-init . OK, in this case he points out which problems uniform initialization solves, but he doesn't provide a clear recommendation (I still believe his statement _is_ an implicit recommendation). Herb Sutter (also involved in the C++ standardization committee) states regarding uniform initialization \"Use {} unless you have a reason not to.\" See his talk (and slides) advocating the new C++11 here: http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/C-11-VC-11-and-Beyond"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T09:44:59.950",
"Id": "35983",
"Score": "0",
"body": "@LokiAstari: yep, I understood that it was a personal preference of yours. Still thought it'd be worth pointing it out in this context."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-02T15:55:00.717",
"Id": "35993",
"Score": "0",
"body": "@Piotr99: Absolutely. All your links are worth reading."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T21:08:37.767",
"Id": "22833",
"ParentId": "22817",
"Score": "3"
}
},
{
"body": "<p>This looks like a perfect opportunity for templates, maybe something like this:</p>\n\n<pre><code>template<typename C, typename T, T(C::*Selector)() const, C(*MergeFn)(C, C)> struct static_merger {\n\n std::vector<C> run(std::vector<C> mSource) {\n std::vector<C> result;\n while(!mSource.empty())\n {\n bool merged = false;\n AABB a = mSource.back();\n mSource.pop_back();\n\n for(auto & b : mSource) {\n if((a.*Selector)() == (b.*Selector)())\n {\n result.push_back((*MergeFn)(a, b));\n eraseRemove(mSource, b);\n merged = true;\n break;\n }\n }\n if(!merged) {\n result.push_back(a);\n }\n }\n return result;\n }\n};\n</code></pre>\n\n<p>Usage is simple:</p>\n\n<pre><code>std::vector<AABB> orig / * = ... */;\nstatic_merger<AABB, int, &AABB::getLeft, &mergeVertically> mergl;\nstatic_merger<AABB, int, &AABB::getRight, &mergeVertically> mergr;\nstatic_merger<AABB, int, &AABB::getTop, &mergeHorizontally> mergt;\nstatic_merger<AABB, int, &AABB::getBottom, &mergeHorizontally> mergb;\nstd::vector<AABB> mergedl = mergl.run(orig);\nstd::vector<AABB> mergedr = mergr.run(orig);\nstd::vector<AABB> mergedt = mergt.run(orig);\nstd::vector<AABB> mergedb = mergb.run(orig);\n</code></pre>\n\n<p>Notice that with this approach, you need to create 4 different instances of our static_merger since the callbacks are being passed as template arguments.</p>\n\n<p>If you want to be able to decide at runtime which callbacks to use, you can use this one:</p>\n\n<pre><code>template<typename C, typename T> struct dynamic_merger {\n\n std::vector<C> run(std::vector<C> const & mSource, T(C::*selector)() const, C(*merge_fn)(C, C)) {\n std::vector<C> result;\n while(!mSource.empty())\n {\n bool merged = false;\n AABB a = mSource.back();\n mSource.pop_back();\n\n for(auto & b : mSource) {\n if((a.*selector)() == (b.*selector)())\n {\n result.push_back((*merge_fn)(a, b));\n eraseRemove(mSource, b);\n merged = true;\n break;\n }\n }\n if(!merged) {\n result.push_back(a);\n }\n }\n return result;\n }\n};\n</code></pre>\n\n<p>Usage is also simple:</p>\n\n<pre><code>std::vector<AABB> orig / * = ... */;\ndynamic_merger<AABB, int> merg;\nstd::vector<AABB> mergedl = merg.run(orig, &AABB::getLeft, &mergeVertically);\nstd::vector<AABB> mergedr = merg.run(orig, &AABB::getRight, &mergeVertically);\nstd::vector<AABB> mergedt = merg.run(orig, &AABB::getTop, &mergeHorizontally);\nstd::vector<AABB> mergedb = merg.run(orig, &AABB::getBottom, &mergeHorizontally);\n</code></pre>\n\n<p>One last thing, as Loki Astari suggested you should pass your original data by (const) reference instead of by value, this avoids expensive copying, resulting in (possibly) faster execution times.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T09:50:37.577",
"Id": "22851",
"ParentId": "22817",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "22833",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T13:08:23.567",
"Id": "22817",
"Score": "3",
"Tags": [
"c++",
"performance",
"c++11"
],
"Title": "Remove code duplication inside of a loop preserving performance"
}
|
22817
|
<p>I have been trying to make a simple "quiz" program in Python. What I plan to make is, say, a quiz of 3 rounds and each round having 3 questions. And at the end of the every round, the program will prompt the user to go for the "bonus" question or not.</p>
<pre><code>print("Mathematics Quiz")
question1 = "Who is president of USA?"
options1 = "a.Myslef\nb. His dad\nc. His mom\nd. Barack Obama\n"
print(question1)
print(options1)
while True:
response = input("Hit 'a', 'b', 'c' or 'd' for your answer\n")
if response == "d":
break
else:
print("Incorrect!!! Try again.")
while True:
response = input("Hit 'a', 'b', 'c' or 'd' for your answer\n")
if response == "d":
stop = True
break
else:
print("Incorrect!!! You ran out of your attempts")
stop = True
break
if stop:
break
# DO the same for the next questions of your round (copy-paste-copy-paste).
# At the end of the round, paste the following code for the bonus question.
# Now the program will ask the user to go for the bonus question or not
while True:
bonus = input("Would you like to give a try to the bonus question?\nHit 'y' for yes and 'n' for no.\n")
if bonus == "y":
print("Who invented Facebook?")
print("a. Me\nb. His dad\nc. Mark Zuckerberg\nd. Aliens")
while True:
response = input("Hit 'a', 'b', 'c' or 'd' for your answer\n")
if response == "c":
break
else:
print("Incorrect!!! Try again.")
while True:
response = input("Hit 'a', 'b', 'c' or 'd' for your answer\n")
if response == "c":
stop = True
break
else:
print("Incorrect!!! You ran out of your attempts")
stop = True
break
if stop:
break
break
elif bonus == "n":
break
else:
print("INVALID INPUT!!! Only hit 'y' or 'n' for your response")
# Now do the same as done above for the next round and another bonus question.
</code></pre>
<p>Now this code is very long for a single question and I don't think this is the "true" programming. I don't want to copy-paste it again and again. I was wondering is there any way to shorten the code using <code>class</code> or defining functions or something like that?</p>
|
[] |
[
{
"body": "<pre><code>asking = True\nattempts = 0\nwhile asking == True:\n response = input(\"Hit 'a', 'b', 'c' or 'd' for your answer\\n\")\n\n if response == \"d\":\n asking = False\n else:\n if attempts < 1: # 1 = Max Attempts\n print(\"Incorrect!!! Try again.\")\n attempts += 1\n else:\n print(\"Incorrect!!! You ran out of your attempts\")\n asking = False\n</code></pre>\n\n<p>The second part follows the same pattern and serves as a good exercise.</p>\n\n<p>The main thing here is to note you're chaining while loops to loop, instead of actually letting the while loop loop. :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T12:44:04.697",
"Id": "35066",
"Score": "0",
"body": "Yeah, but still I have to copy-paste the code for every question, don't I?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T12:45:23.540",
"Id": "35067",
"Score": "0",
"body": "@PreetikaSharma Look into functions, I gave you a link in the comments to your question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T12:48:31.787",
"Id": "35068",
"Score": "0",
"body": "Just parametrize what varies for each question and move it into a function, as suggested."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T12:49:07.120",
"Id": "35069",
"Score": "0",
"body": "@JonasWielicki Oops, I thought, that was just the comment. Let me see now."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T12:31:41.907",
"Id": "22823",
"ParentId": "22822",
"Score": "1"
}
},
{
"body": "<p>As Jonas Wielicki said, your best option would be to use <a href=\"http://docs.python.org/2/tutorial/controlflow.html#defining-functions\" rel=\"nofollow\">functions</a>.</p>\n\n<p>However, you can shorten the code first to the answer Javier Villa gave: </p>\n\n<pre><code> asking = True\n attempts = 0\n while asking == True:\n response = input(\"Hit 'a', 'b', 'c' or 'd' for your answer\\n\")\n\n if response == \"d\":\n asking = False\n else:\n if attempts < 1: # 1 = Max Attempts\n print(\"Incorrect!!! Try again.\")\n attempts += 1\n\n else: print(\"Incorrect!!! You ran out of your attempts\")\n asking = False\n</code></pre>\n\n<p>For more tips on improving the speed and performance, see <a href=\"http://wiki.python.org/moin/PythonSpeed/PerformanceTips\" rel=\"nofollow\">performance tips</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T13:24:00.153",
"Id": "22824",
"ParentId": "22822",
"Score": "0"
}
},
{
"body": "<pre><code>import string\n\nNUMBER_OF_ATTEMPTS = 2\nENTER_ANSWER = 'Hit %s for your answer\\n'\nTRY_AGAIN = 'Incorrect!!! Try again.'\nNO_MORE_ATTEMPTS = 'Incorrect!!! You ran out of your attempts'\n\ndef question(message, options, correct, attempts=NUMBER_OF_ATTEMPTS):\n '''\n message - string \n options - list\n correct - int (Index of list which holds the correct answer)\n attempts - int\n '''\n optionLetters = string.ascii_lowercase[:len(options)]\n print message\n print ' '.join('%s: %s' % (letter, answer) for letter, answer in zip(optionLetters, options))\n while attempts > 0:\n response = input(ENTER_ANSWER % ', '.join(optionLetters)) # For python 3\n #response = raw_input(ENTER_ANSWER % ', '.join(optionLetters)) # For python 2\n if response == optionLetters[correct]:\n return True\n else:\n attempts -= 1\n print TRY_AGAIN\n\n print NO_MORE_ATTEMPTS\n return False\n\n\nprint(\"Mathematics Quiz\")\n\n# question1 and question2 will be 'True' or 'False' \nquestion1 = question('Who is president of USA?', ['myself', 'His Dad', 'His Mom', 'Barack Obama'], 3)\nquestion2 = question('Who invented Facebook?', ['Me', 'His Dad', 'Mark Zuckerberg', 'Aliens', 'Someone else'], 2)\n</code></pre>\n\n<p>I'm not sure which python you are using. Try both line 20 or line 21 to see which works best for you. </p>\n\n<p>Overall this function allows you to enter in questions with as many responses as you want and it will do the rest for you.</p>\n\n<p>Good luck.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T14:32:26.023",
"Id": "35070",
"Score": "0",
"body": "Thank you. It worked. Only I had to change `string.lowercase` to `string.ascii_lowercase` since I am using Python 3x. I think I need some good practice with defining functions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T14:56:31.683",
"Id": "35071",
"Score": "0",
"body": "Good spot, I updated my answer. Seems both Python 2 and 3 have ascii_lowercase, but lowercase got removed in 3. Indeed use functions where ever you can."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T16:03:20.920",
"Id": "35074",
"Score": "0",
"body": "You still skipped the print parentheses at these places: \n`print(message)`, `print` statement below that, `print` statements after `attempts -=1`. I apologize for not mentioning them before."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T14:13:41.547",
"Id": "22825",
"ParentId": "22822",
"Score": "4"
}
},
{
"body": "<p>You can also use dictionary to prepare questions and then simply ask them in some order (random in this case):</p>\n\n<pre><code>import random\n\n# Dictionary of questions and answers\n\nquestions = {\n 'Who is president of USA?':\n ('\\na. Myslef\\nb. His dad\\nc. His mom\\nd. Barack Obama\\n', 'd'),\n 'What is the capital of USA?':\n ('\\na. Zimbabwe\\nb. New York\\nc. Washington\\nd. Do not exist', 'c')\n }\n\ndef ask_question(questions):\n '''Asks random question from 'questions 'dictionary and returns\n players's attempt and correct answer.'''\n\n item = random.choice(list(questions.items()))\n question = item[0]\n (variants, answer) = item[1]\n print(question, variants)\n attempt = input('\\nHit \\'a\\', \\'b\\', \\'c\\' or \\'d\\' for your answer\\n')\n return (attempt, answer)\n\n# Questions loop\ntries = 0\nfor questions_number in range(5):\n while True: # Asking 1 question\n attempt, answer = ask_question(questions)\n if attempt not in {'a', 'b', 'c', 'd'}:\n print('INVALID INPUT!!! Only hit \\'y\\' or \\'n\\' for your response')\n elif attempt == answer:\n print('Correct')\n stop_asking = False\n break\n elif tries == 1: # Specify the number of tries to fail the answer \n print('Incorrect!!! You ran out of your attempts')\n stop_asking = True\n break\n else:\n tries += 1\n print('Incorrect!!! Try again.')\n if stop_asking:\n break\n</code></pre>\n\n<p>You can use this as template and modify code a bit to add bonus check or just enclose part of loop in another function which will be called in main loop.</p>\n\n<p>Plus with minor edit you can import questions and answers from text file.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-30T11:08:19.820",
"Id": "142894",
"ParentId": "22822",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "22825",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T12:25:37.470",
"Id": "22822",
"Score": "3",
"Tags": [
"python",
"quiz"
],
"Title": "Simple quiz program"
}
|
22822
|
<p>I have written my own for practice and also some tweaks for my specific requirement. There is an insert which can copy a range (well array copy really) which I am hoping is more efficient than individual element insert.</p>
<p>Can anyone make any comments specifically as regards efficiency and code elegance. I need to use this with Java 1.6 and am getting a warning on the <code>array = newArray(size);</code> line in the constructor. But that is the only issue I am currently aware of.</p>
<pre><code>import java.util.Arrays; //copyOf
public class CircularBuffer<T> {
private T[] array; //storage
private int put_idx, get_idx, count; //get/put & internal num elements counter
private final int size; //size of internal array storage
public CircularBuffer(int size) {
get_idx = 0;
put_idx = 0;
count = 0;
this.size = size;
//Type safety: A generic array of T is created for a varargs parameter - investigate how to remove warning
array = newArray(size);
}
//@SafeVarargs - ok in java 1.7
static <T> T[] newArray(int length, T... array)
{
return Arrays.copyOf(array, length);
}
void reset(){
get_idx=put_idx=count=0;
}
public boolean empty() { return count == 0; }
public boolean full() { return count == size; }
int get_count() { return count; }
//inserts a single new element
public void insert(T element)
{
if(full())
throw new ArrayIndexOutOfBoundsException("buffer full");
array[put_idx++] = element;
put_idx %= size;
++count;
}
//insert array of specified length
public void insert(T[] thearray) {
if(thearray.length + count > size)
throw new ArrayIndexOutOfBoundsException("insufficient space to insert array");
//first copy to end - contiguous array copy
int remaining = size - put_idx;
if(remaining >= thearray.length) {
System.arraycopy(thearray, 0, array, put_idx, thearray.length);
put_idx += thearray.length;
put_idx %= size;
} else {
System.arraycopy(thearray, 0, array, put_idx, remaining);
int rest = thearray.length - remaining;
System.arraycopy(thearray, remaining, array, 0, rest);
put_idx = rest;
}
count += thearray.length;
}
//get the oldest element, move read pointer
public T get()
{
if(empty())
throw new ArrayIndexOutOfBoundsException("buffer empty");
final T ret = array[get_idx++];
get_idx %= size;
--count;
return ret;
}
}
</code></pre>
<p>Code to exercise class:</p>
<pre><code>public class TestCircularBuffer {
static public void main(String args[]) {
new TestCircularBuffer().go();
}
void go() {
int SIZE = 1000;
int arr[] = new int[SIZE];
for(int i = 0; i < SIZE; ++i) {
arr[i] = i;
}
CircularBuffer<Integer> cb = new CircularBuffer<Integer>(10);
//exercise circ buffer
int i = 0;
while(i < SIZE) {
while(!cb.full())
cb.insert(arr[i++]);
while(!cb.empty())
System.out.print(cb.get() + " ");
}
//now exercise array insert
System.out.println("\nrange insert test");
Integer marr[] = {1,2,3,4};
i = 0;
while(i < 20) {
//will only be able to fit 2 lots
cb.insert(marr);
cb.insert(marr);
while(!cb.empty())
System.out.print(cb.get() + " ");
++i;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>A few minor notes:</p>\n\n<ol>\n<li><p>Comments like the following are unnecessary:</p>\n\n<pre><code>private T[] array; // storage\n</code></pre>\n\n<p>You could call the field as <code>storage</code> and remove the comment.</p></li>\n<li><p>A \"solution\" for the warning in the constructor:</p>\n\n<pre><code>@SuppressWarnings(\"unchecked\")\nprivate T[] newArray(int length) {\n return (T[]) new Object[length];\n}\n</code></pre>\n\n<p>Reference: <a href=\"https://stackoverflow.com/a/530289/843804\">Java how to: Generic Array creation</a></p></li>\n<li><p><code>camelCase</code> variable and method names are more common in Java than underscored ones. (<a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367\" rel=\"nofollow noreferrer\">Code Conventions for the Java Programming Language, 9 - Naming Conventions</a>)</p></li>\n<li><p>From <em>Code Complete, 2nd Edition</em>, p761:</p>\n\n<blockquote>\n <p><strong>Use only one data declaration per line</strong></p>\n \n <p>[...] </p>\n \n <p>It’s easier to modify declarations because each declaration is self-contained.</p>\n \n <p>[...]</p>\n \n <p>It’s easier to find specific variables because you can scan a single\n column rather than reading each line. It’s easier to find and fix\n syntax errors because the line number the compiler gives you has \n only one declaration on it.</p>\n</blockquote></li>\n<li><p>Setting default integer field values to zero is unnecessary in the constructor since zero is the default int value:</p>\n\n<pre><code>getIdx = 0;\nputIdx = 0;\ncount = 0;\n</code></pre></li>\n<li><p>Does it make sense to create a <code>CircularBuffer</code> instance with zero size? If not check it and throw an <code>IllegalArgumentException</code> in the constructor.</p></li>\n<li><p>The second <code>insert</code> method might be a <a href=\"https://softwareengineering.stackexchange.com/a/80092/36726\">premature optimization</a>. </p></li>\n<li><p>I'd throw <code>IllegalStateException</code> instead of <code>ArrayIndexOutOfBoundsException</code>. The clients of the class should not know that it uses an array (or anything else) for storage.</p></li>\n<li><p>Here are a few unit tests:</p>\n\n<pre><code>@Test(expected = IllegalArgumentException.class)\npublic void testZeroSize() {\n new CircularBuffer<String>(0);\n}\n\n@Test\npublic void testIsEmptyOnNewBuffer() {\n final CircularBuffer<String> buffer = new CircularBuffer<String>(3);\n assertTrue(buffer.isEmpty());\n}\n\n@Test\npublic void testIsFullOnNewBuffer() {\n final CircularBuffer<String> buffer = new CircularBuffer<String>(3);\n assertFalse(buffer.isFull());\n}\n\n@Test\npublic void testIsEmpty() {\n final CircularBuffer<String> buffer = new CircularBuffer<String>(3);\n buffer.insert(\"a\");\n assertFalse(buffer.isEmpty());\n}\n\n@Test\npublic void testIsFull() {\n final CircularBuffer<String> buffer = new CircularBuffer<String>(3);\n buffer.insert(\"a\");\n buffer.insert(\"b\");\n buffer.insert(\"c\");\n assertTrue(buffer.isFull());\n}\n\n@Test\npublic void testIsEmptyAfterReset() {\n final CircularBuffer<String> buffer = new CircularBuffer<String>(3);\n buffer.insert(\"a\");\n buffer.reset();\n assertTrue(buffer.isEmpty());\n}\n\n@Test\npublic void testIsFullAfterReset() {\n final CircularBuffer<String> buffer = new CircularBuffer<String>(3);\n buffer.insert(\"a\");\n buffer.insert(\"b\");\n buffer.insert(\"c\");\n buffer.reset();\n assertFalse(buffer.isFull());\n}\n\n@Test\npublic void testIsEmptyOnUsedBuffer() {\n final CircularBuffer<String> buffer = new CircularBuffer<String>(3);\n buffer.insert(\"a\");\n buffer.insert(\"b\");\n buffer.insert(\"c\");\n\n assertFalse(\"isEmpty 1\", buffer.isEmpty());\n buffer.get();\n assertFalse(\"isEmpty 2\", buffer.isEmpty());\n buffer.get();\n assertFalse(\"isEmpty 3\", buffer.isEmpty());\n buffer.get();\n assertTrue(\"isEmpty 4\", buffer.isEmpty());\n}\n\n@Test\npublic void testIsFullOnUsedBuffer() {\n final CircularBuffer<String> buffer = new CircularBuffer<String>(3);\n buffer.insert(\"a\");\n buffer.insert(\"b\");\n buffer.insert(\"c\");\n buffer.get();\n\n assertFalse(\"isFull 1\", buffer.isFull());\n buffer.get();\n assertFalse(\"isFull 2\", buffer.isFull());\n buffer.get();\n assertFalse(\"isFull 3\", buffer.isFull());\n}\n\n@Test\npublic void testInsert() {\n final CircularBuffer<String> buffer = new CircularBuffer<String>(3);\n buffer.insert(\"a\");\n buffer.insert(\"b\");\n buffer.insert(\"c\");\n}\n\n@Test(expected = IllegalStateException.class)\npublic void testInsertFull() {\n final CircularBuffer<String> buffer = new CircularBuffer<String>(3);\n buffer.insert(\"a\");\n buffer.insert(\"b\");\n buffer.insert(\"c\");\n buffer.insert(\"d\");\n}\n\n@Test(expected = IllegalStateException.class)\npublic void testGetOnEmptyBuffer() {\n final CircularBuffer<String> buffer = new CircularBuffer<String>(3);\n buffer.get();\n}\n\n@Test(expected = IllegalStateException.class)\npublic void testGetOnEmptyUsedBuffer() {\n final CircularBuffer<String> buffer = new CircularBuffer<String>(3);\n buffer.insert(\"a\");\n buffer.get();\n\n buffer.get();\n}\n\n@Test\npublic void testGet() {\n final CircularBuffer<String> buffer = new CircularBuffer<String>(3);\n buffer.insert(\"a\");\n assertEquals(\"a\", buffer.get());\n buffer.insert(\"b\");\n buffer.insert(\"c\");\n}\n\n@Test\npublic void testDelayedGet() {\n final CircularBuffer<String> buffer = new CircularBuffer<String>(3);\n buffer.insert(\"a\");\n buffer.insert(\"b\");\n buffer.insert(\"c\");\n assertEquals(\"a\", buffer.get());\n}\n\n@Test\npublic void testInsertAndGetTwice() {\n final CircularBuffer<String> buffer = new CircularBuffer<String>(3);\n buffer.insert(\"a\");\n buffer.insert(\"b\");\n buffer.insert(\"c\");\n assertEquals(\"a\", buffer.get());\n assertEquals(\"b\", buffer.get());\n assertEquals(\"c\", buffer.get());\n\n buffer.insert(\"d\");\n buffer.insert(\"e\");\n buffer.insert(\"f\");\n assertEquals(\"d\", buffer.get());\n assertEquals(\"e\", buffer.get());\n assertEquals(\"f\", buffer.get());\n}\n\n@Test\npublic void testGetAndInsert() {\n final CircularBuffer<String> buffer = new CircularBuffer<String>(3);\n buffer.insert(\"a\");\n assertEquals(\"a\", buffer.get());\n\n buffer.insert(\"b\");\n assertEquals(\"b\", buffer.get());\n\n buffer.insert(\"c\");\n assertEquals(\"c\", buffer.get());\n\n buffer.insert(\"d\");\n buffer.insert(\"e\");\n assertEquals(\"d\", buffer.get());\n assertEquals(\"e\", buffer.get());\n\n buffer.insert(\"f\");\n assertEquals(\"f\", buffer.get());\n\n assertTrue(\"empty\", buffer.isEmpty());\n}\n</code></pre>\n\n<p>(I've renamed a few methods.)</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T22:20:24.943",
"Id": "22874",
"ParentId": "22826",
"Score": "2"
}
},
{
"body": "<p>I agree with everything from palacsint (7. could be discussed. If it is a requirement, then it is fine)<br>\nI will add some more thoughts.</p>\n\n<hr>\n\n<pre><code>import java.util.Arrays; //copyOf\n</code></pre>\n\n<p>This comment is not necessary. Even more, noone (with an IDE) will read comments in the import section.</p>\n\n<hr>\n\n<pre><code>public class CircularBuffer<T> {\n</code></pre>\n\n<p>As far as I see it, your implementation is a fixed size (FIFO) queue. If I am right, I would choose this name instead of <code>CircularBuffer</code>.<br>\nWith this name, even if it is not well defined, I would expect some circularity. There is none. (Not for the caller, the inside details are not interesting for anyone using this class.)<br>\nOne could even argument, that using java collection (implement an interface, using collection classes) would be a good way to integrate it inside the java world.</p>\n\n<hr>\n\n<pre><code>private T[] array; //storage\nprivate int put_idx, get_idx, count; //get/put & internal num elements counter\nprivate final int size; //size of internal array storage\n</code></pre>\n\n<p>I would change the names, the <code>array</code> is in fact the <code>buffer</code>, <code>put_idx</code> the <code>head</code>, <code>get_idx</code> the <code>tail</code>, <code>count</code> the number of elements and <code>size</code> is not needed:</p>\n\n<pre><code>private final T[] buffer;\nprivate int headIndex = 0;\nprivate int tailIndex = 0;\nprivate int numberOfElements = 0;\n</code></pre>\n\n<hr>\n\n<pre><code>void reset(){\n get_idx=put_idx=count=0;\n}\n</code></pre>\n\n<p>Do you need this method? If no, remove it. If you need it, it could be a good idea to clear the buffer, too. The garbage collector would appreciate this.</p>\n\n<hr>\n\n<pre><code>public boolean empty() { return count == 0; }\n\npublic boolean full() { return count == size; }\n</code></pre>\n\n<p>A typical and good name for a method returning a method is <code>isSomething()</code> or <code>hasSomething()</code>. So in this case <code>isEmpty()</code>, <code>isFull()</code>.</p>\n\n<hr>\n\n<pre><code>int get_count() { return count; }\n</code></pre>\n\n<p>If we look at java collections, the typical and expected name would bet <code>getSize()</code></p>\n\n<hr>\n\n<pre><code>//inserts a single new element\npublic void insert(T element)\n{\n if(full())\n throw new ArrayIndexOutOfBoundsException(\"buffer full\");\n\n array[put_idx++] = element;\n put_idx %= size;\n ++count;\n}\n</code></pre>\n\n<p>I would throw an <code>IllegalStateException</code> exception. <code>ArrayIndexOutOfBoundsException</code> is not true, the buffer is full, it can not be out of bounds, unless the implementation is wrong.<br>\nIn this case, the expected state is \"not full\", but it is \"full\".<br>\nRemark: Depending on the requirements, you could start to overwrite old entries. This would be typical for a circular buffer.</p>\n\n<p>I would add some javadoc comments, at least to tell the caller about the exception he could catch.</p>\n\n<hr>\n\n<pre><code>//insert array of specified length\npublic void insert(T[] thearray) {\n</code></pre>\n\n<p>This comment is already clear from the method signature.<br>\nIf we look at java collections again, I would rename it to <code>addAll</code>.<br>\nWhich is quite important if you try to add for example <code>null</code>. Does it go to <code>insert(T element)</code> or <code>insert(T[] thearray)</code> ? Should it be there?</p>\n\n<p>And again, javadoc</p>\n\n<hr>\n\n<pre><code> if(thearray.length + count > size)\n throw new ArrayIndexOutOfBoundsException(\"insufficient space to insert array\"); \n</code></pre>\n\n<p>See above</p>\n\n<hr>\n\n<pre><code> //first copy to end - contiguous array copy\n int remaining = size - put_idx;\n if(remaining >= thearray.length) {\n System.arraycopy(thearray, 0, array, put_idx, thearray.length);\n put_idx += thearray.length;\n put_idx %= size;\n } else {\n System.arraycopy(thearray, 0, array, put_idx, remaining);\n int rest = thearray.length - remaining;\n System.arraycopy(thearray, remaining, array, 0, rest);\n put_idx = rest;\n }\n</code></pre>\n\n<p>This could be simplified, you do not need 2 complex cases: </p>\n\n<pre><code> final int remaining = Math.min(thearray.length, size - put_idx);\n System.arraycopy(thearray, 0, buffer, put_idx, remaining);\n final int rest = thearray.length - remaining;\n System.arraycopy(thearray, remaining, buffer, 0, rest);\n put_idx = (put_idx + thearray.length) % size;\n numberOfElements += thearray.length;\n</code></pre>\n\n<p>And because the name and argument behavior of <code>System.arraycopy</code> is awful, I would introduce a small method. So anyone reading it could understand it without spending time on thinking about <code>arraycopy</code>:</p>\n\n<pre><code>private void copyNumberOfElementsFromArraySourceStartToBuffer(final int numberOfElements, final T[] arraySource, final int sourceStart) {\n System.arraycopy(arraySource, sourceStart, buffer, head, numberOfElements);\n head = (head + numberOfElements) % buffer.length;\n}\n</code></pre>\n\n<hr>\n\n<pre><code>//get the oldest element, move read pointer\npublic T get()\n{\n if(empty())\n throw new ArrayIndexOutOfBoundsException(\"buffer empty\");\n\n final T ret = array[get_idx++];\n get_idx %= size;\n --count;\n return ret;\n} \n</code></pre>\n\n<p>If we look at java collections again, I would rename it too <code>removeOldest()</code>. Or if you want to be very specific <code>removeAndGetOldest()</code>.<br>\nIt is not the typical expectation to remove the element if get is called. If you do so, add at least some javadoc comment indicating this behavior.<br>\nException: See above.</p>\n\n<hr>\n\n<pre><code>arr[var++]\n</code></pre>\n\n<p>This is only a personal opinion: I would avoid using the postincrement operator overall. This case looks simple, but you can easily get complicated cases because of side effects in all languages.<br>\nAnd with current compilers, it does (in most of the scenarios) not make any change in size, speed or whatever.<br>\nSo I would go for readability.</p>\n\n<hr>\n\n<p>All together, it could be something like this:</p>\n\n<pre><code>/**\n * A circular buffer. This is practically a fixed size FIFO queue. Which means you can enter a maximum amount of overall elements and can get the oldest.\n */\npublic class CircularBuffer<T> {\n private final T[] buffer;\n private int headIndex = 0;\n private int tailIndex = 0;\n private int numberOfElements = 0;\n\n public CircularBuffer(final int size) {\n buffer = newArray(size);\n }\n\n @SuppressWarnings(\"unchecked\")\n // generics and arrays do not mix. we should be safe here.\n private T[] newArray(final int length) {\n return (T[]) new Object[length];\n }\n\n public boolean isEmpty() {\n return numberOfElements == 0;\n }\n\n public boolean isFull() {\n return numberOfElements == buffer.length;\n }\n\n /** Returns the current number of elements inside the buffer */\n public int getSize() {\n return numberOfElements;\n }\n\n /**\n * Inserts the given element.\n * @throws IllegalStateException if buffer has not enough free space\n */\n public void add(final T newElement) {\n if (isFull())\n throw new IllegalStateException(\"buffer full\");\n\n buffer[headIndex] = newElement;\n headIndex = (headIndex + 1) % buffer.length;\n ++numberOfElements;\n }\n\n /**\n * Inserts the given elements.\n * @throws IllegalStateException if buffer has not enough free space\n */\n public void addAll(final T[] newElements) {\n if (newElements.length + numberOfElements > buffer.length)\n throw new IllegalStateException(\"insufficient space to insert array\");\n\n // or: call add() method for all elements. Which should be the favored way.\n final int elementsToFillAtHead = Math.min(newElements.length, buffer.length - headIndex);\n copyNumberOfElementsFromArraySourceStartToBuffer(elementsToFillAtHead, newElements, 0);\n final int rest = newElements.length - elementsToFillAtHead;\n copyNumberOfElementsFromArraySourceStartToBuffer(rest, newElements, elementsToFillAtHead);\n numberOfElements += newElements.length;\n }\n\n private void copyNumberOfElementsFromArraySourceStartToBuffer(final int numberOfElements, final T[] arraySource, final int sourceStart) {\n System.arraycopy(arraySource, sourceStart, buffer, headIndex, numberOfElements);\n headIndex = (headIndex + numberOfElements) % buffer.length;\n }\n\n /** \n * Get and remove the oldest element\n * @throws IllegalStateException if buffer is empty\n */\n public T removeOldest() {\n if (isEmpty())\n throw new IllegalStateException(\"buffer empty\");\n\n final T oldest = buffer[tailIndex];\n tailIndex = (tailIndex + 1) % buffer.length;\n --numberOfElements;\n return oldest;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T21:32:31.043",
"Id": "22904",
"ParentId": "22826",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "22904",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T15:33:13.640",
"Id": "22826",
"Score": "7",
"Tags": [
"java",
"circular-list"
],
"Title": "Circular buffer implementation for buffering TCP socket messages"
}
|
22826
|
<p>I would like to advise if the following production code is good to be unit tested. The segment of the production code gets data from a backend service and displays it on the page. It is a class:</p>
<pre><code>...
// Extract this code into a separate method because it is called in more than 1 place
Keywords.prototype.addKeyword = function(keyword) {
$("ul").append("<li>" + keyword + "</li>");
}
// This is the method that I want to test
Keywords.prototype.getKeywords = function(forGroup) {
// AppDao contains a bunch of methods that get data
var keywords = AppDao.getKeywords(forGroup),
that = this;
$.each(keywords, function(i, keyword) {
that.addKeyword(keyword);
};
}
...
</code></pre>
<p>I'm planning to test it in the following way:</p>
<ul>
<li>Stub Keywords.prototype.addKeyword() and make sure that it will be called with 3 arguments: "KW A", "KW B", and "KW C"</li>
<li>Stub AppDao.getKeywords() and make sure that it will be called with "Test Group" and will return 3 keywords: "KW A", "KW B", and "KW C"</li>
<li>Invoke Keywords.prototype.getKeywords() and verify the stubs</li>
</ul>
<p>I didn't start the actual implementation of the test yet because I would like to advise with you guys if you think that something can be better done. Thanks.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T23:45:32.543",
"Id": "42786",
"Score": "0",
"body": "A general tip: Write the unit test first, then write the code that makes the unit test pass. That's the spirit of proper TDD, and that ensures that the code is easily testable."
}
] |
[
{
"body": "<p>You're off to a bad start. You don't have a definition of what your <code>getKeywords()</code> method is supposed to do, which means you can't even begin to test it. On top of that, it seems to be named backwards - <code>getKeywords()</code> calls <code>addKeyword()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T14:30:10.640",
"Id": "35128",
"Score": "0",
"body": "I don't understand what you mean. Keywords.getKeywords() is the method under test and I wrote its implementation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T20:50:11.580",
"Id": "35157",
"Score": "1",
"body": "Yes, and its description is \"the method I want to test\". Not \"returns the list of keywords from the database\", or something else formal. Plus, you've got a \"getWhatever\" method that doesn't return anything to the caller, so it's badly named to boot."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T22:12:49.807",
"Id": "22835",
"ParentId": "22830",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T18:45:02.707",
"Id": "22830",
"Score": "1",
"Tags": [
"javascript",
"unit-testing"
],
"Title": "Production code to be good for unit testing"
}
|
22830
|
<p>Inspired by <a href="http://jqueryboilerplate.com" rel="nofollow">jqueryboilerplate.com</a>, I extended their boilerplate to fit my needs. Coming from PHP development, I wanted to have a good starting point for writing jQuery plugins with a defined API/interface (more at <a href="http://jquib.web-sav.de" rel="nofollow">jquib.web-sav.de</a>).</p>
<pre><code>/**
* JQUIB - JQUERY INTERFACEPLUGIN BOILERPLATE
*
* This is a solid starter template for your jQuery plugins. Its designed
* to keep all logic and data hidden from public access except the set of
* functions you defined inside its interface function namespace.
*
* Inspired by http://jqueryboilerplate.com
*
* @see http://web-sav.de/jquib-boilerplate
* @copyright Andr&eacute; Kroll
* @license MIT
*/
;
(function ($, window, document, undefined) {
const PLUGIN_NAME = 'your_plugin';
const defaults = {
option_one: 'value_1',
option_two: 'value_2'
};
/* PLUGIN - CONSTRUCTOR AND INSTANCE METHODS ............................... (scope: private) */
var Plugin = {
options: {},
/* ... more plugin properties here ... */
// Gets called whenever a new plugin instance is created
__construct: function (options) {
this.options = this.initOptions(options);
/* ... you can define more parameters for your constructor */
/* - the bootstrap process will pass them through */
/* ... start writing your plugin logic ... */
/* From here you have access to a plugin */
/* .. member with "this.propertyName;" */
/* .. method with "this.methodName();" */
/* .. interface method with "this.public_interface.interfaceMethodName();" */
/* .. helper function with "helperFunctionName();" */
/* P e a c e */
},
// Validate options and merge with defaults
initOptions: function (options) {
/* ... put your option validation logic here ... */
return $.extend({}, defaults, options);
}
};
/* PLUGIN - PUBLIC / INTERFACE METHODS ...................................... (scope: public) */
Plugin.public_fn = {
// Get the jQuery-wrapped plugin container
get$: function () {
return $(this.container);
}
};
/* HELPER FUNCTIONS ------------------------------------------------- (scope: private static) */
{
// Simple and safe function to log/debug elements
function log(elementToLog) {
if ( window.console && window.console.log ) {
window.console.log(elementToLog);
}
}
}
/* BOOTSTRAP AND PLUGIN REGISTRATION ======================================================== */
{
// Register the plugin at jQuerys function namespace
$.fn[PLUGIN_NAME] = function (options) {
var origArgs = arguments;
this.each(function () {
if ( undefined == $.data(this, "plugin_" + PLUGIN_NAME) ) {
// First call by this element: create new instance of the plugin
$.data(this, "plugin_" + PLUGIN_NAME, (function (container, options) {
var plugin = Object.create(Plugin);
plugin['container'] = container;
plugin['public_interface'] = {};
for ( prop in plugin.public_fn ) {
if ( typeof plugin.public_fn[prop] === 'function' ) {
// Register all interface functions to call within the plugin object context
plugin['public_interface'][prop] = $.proxy(plugin.public_fn[prop], plugin);
}
}
plugin.__construct.apply(plugin, origArgs);
return plugin;
})(this, options));
}
});
// Return plugin interface of the first element
return $.data(this.get(0), "plugin_" + PLUGIN_NAME).public_interface;
};
}
})(jQuery, window, document);
</code></pre>
|
[] |
[
{
"body": "<p>Very interesting and fun question. Boilerplate code is a reason to close questions down, but this code is a perfectly valid question.</p>\n\n<p><strong>Naming</strong></p>\n\n<ul>\n<li>JavaScript uses lowerCamelCase variable and function names, avoid names like <code>public_interface</code> and <code>option_one</code>.</li>\n<li>You have anonymous functions, this makes stack-traces needlessly complicated, go for <code>__construct: function pluginConstructor (options) {</code></li>\n<li>Prefixing with <code>_</code> should be avoided. If you do it, ensure <code>_</code> items are 'private' unlike <code>__construct</code></li>\n</ul>\n\n<p><strong>Idioms and Custom</strong></p>\n\n<ul>\n<li>Yoda conditionals like <code>if ( undefined == $.data(this, \"plugin_\" + PLUGIN_NAME) )</code> are hard to read</li>\n<li>Worse, your conditionals are not consistently Yoda: <code>if ( typeof plugin.public_fn[prop] === 'function' )</code></li>\n</ul>\n\n<p><strong>Comments</strong></p>\n\n<ul>\n<li>I like your approach to commenting</li>\n</ul>\n\n<p><strong>JSHint.com</strong></p>\n\n<ul>\n<li>Your have problems in your code:\n\n<ul>\n<li>Unnecessary semicolon</li>\n<li>Declaring functions in an extra set of <code>{}</code> is bad practice</li>\n<li>Use <code>plugin.container</code>, not <code>plugin['container']</code></li>\n<li><code>prop</code> leaks in to the global namespace here: <code>for ( prop in plugin.public_fn ) {</code></li>\n</ul></li>\n</ul>\n\n<p>Finally, having <code>undefined</code> as a parameter is silly. If you were to pass anything but <code>undefined</code>, then your yoda condition would fail. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-01-11T18:25:04.547",
"Id": "152374",
"ParentId": "22831",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T19:25:51.273",
"Id": "22831",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"api",
"plugin",
"interface"
],
"Title": "jQuery plugin boilerplate jquib"
}
|
22831
|
<p>I'm writing a markup for: <br>
<a href="https://i.stack.imgur.com/XiRcL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XiRcL.jpg" width="200" height="260"></a><br><br>
And I've split it for these sections:</p>
<pre><code><header>
<div id="logo"></div>
<nav id="mainNav"></nav>
</header>
<div id="banner"></div>
<div id="content">
<section id="advantages">
<section class="advantage"></section>
<section class="advantage"></section>
<section class="advantage"></section>
<section class="advantage"></section>
</section>
<div id="main"></div>
<aside></aside>
</div>
<footer>
<div id="extra">
<article class="extra"></article>
<article class="extra"></article>
<article class="extra"></article>
<article class="extra"></article>
</div>
<div id="credit"></div>
</footer>
</code></pre>
<p>Is it semantically correct(<code>div</code>, <code>section</code>, <code>article</code>) and are my identifiers explicit?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T07:02:15.467",
"Id": "35102",
"Score": "1",
"body": "The template is here: http://templates.websitetemplatesonline.com/Progress-business/index.html and I don't know if it's OK to rip it off like this."
}
] |
[
{
"body": "<p>After writing html structure, I explicitly check for at least two things.</p>\n\n<ul>\n<li>Are there any <code>div</code>s that can go away?</li>\n<li>Can I remove any <code>class</code> or <code>id</code>? </li>\n</ul>\n\n<p>Let's try to apply this to your code:</p>\n\n<pre><code><header>\n <div id=\"logo\"></div>\n <nav id=\"mainNav\"></nav> \n</header>\n</code></pre>\n\n<p>You can replace <code><div id=\"logo\"></div></code> whith <code><h1>Progress Business Company</h1></code>. Your CSS will hide the text anyway, but it will be visible for people that don't see the logo (images disabled or screen reader).</p>\n\n<pre><code><div id=\"banner\"></div>\n</code></pre>\n\n<p>This one seems OK, but keep my advices in mind when you feel it.</p>\n\n<pre><code><div id=\"content\">\n</code></pre>\n\n<p>What about <code><article></code>?</p>\n\n<pre><code> <section id=\"advantages\">\n <section class=\"advantage\"></section>\n <section class=\"advantage\"></section>\n <section class=\"advantage\"></section>\n <section class=\"advantage\"></section>\n </section>\n</code></pre>\n\n<p>You don't need all those <code>class</code> here. In CSS, <code>#advantages section</code> will select your subsections and will make explicit the relation between the big section and the subsections. This also frees your HTML from unnecessary clutter.</p>\n\n<pre><code> <div id=\"main\"></div>\n <aside></aside>\n</code></pre>\n\n<p>This applies to the rest of the HTML and could be the most important remark: the image you're trying to integrate has been designed with a <strong>grid</strong> in mind. See how the A, B, C, D subsections are laid out? How \"Testimonials\" aligns with D? And so on. Using a grid such as Bootstrap or 960 grid will help you a lot here.</p>\n\n<pre><code><div id=\"extra\">\n <article class=\"extra\"></article>\n <article class=\"extra\"></article>\n <article class=\"extra\"></article>\n <article class=\"extra\"></article>\n</div>\n</code></pre>\n\n<p>Same issue than with \"advantages\".</p>\n\n<pre><code><div id=\"credit\"></div>\n</code></pre>\n\n<p>What about a paragraph (<code>p</code>) instead of a <code>div</code>?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T07:02:07.137",
"Id": "22847",
"ParentId": "22832",
"Score": "4"
}
},
{
"body": "<h3><code>#logo</code> → <code>h1</code></h3>\n\n<p>Your <code><div id=\"logo\"></div></code> should be a <code>h1</code>, otherwise the document outline wouldn't be correct:</p>\n\n<pre><code><h1><img id=\"logo\" src=\"logo.png\" alt=\"Progress Business Company\"></h1>\n</code></pre>\n\n<p>See <a href=\"https://stackoverflow.com/a/14920215/1591669\">https://stackoverflow.com/a/14920215/1591669</a> for an explanation.</p>\n\n<h3><code>#banner</code> → <code>header</code> or <code>aside</code></h3>\n\n<p>If your <code><div id=\"banner\"></div></code> doesn't contain main content, it should go in an <code>aside</code> element, or, if it can be understood as part of the header (probably on each page of the site), in the <code>header</code> element.</p>\n\n<h3><code>#main</code> → <code>section</code> (or <code>article</code>)</h3>\n\n<p>Instead of <code><div id=\"main\"></div></code> you could use a sectioning element here. I assume your <code>div</code> contains a heading (\"Welcome, dear visitor!\"), so you have something like an implict section anyhow. Why not make it explicit? So use a <code>section</code> instead of the <code>div</code> (depending on the actual content, <code>article</code> might be suitable instead).</p>\n\n<h3><code>#content > aside</code> → <code>section</code></h3>\n\n<p>I'd say on the front page the testimonials <em>could</em> be considered part of the main content (in the end it depends on the real content/context), so instead of <code>aside</code> you could use <code>section</code> then.</p>\n\n<p>Each single testimonial should be in its own <code>article</code>, of course.</p>\n\n<h3><code>#extra > article</code> → <code>section</code></h3>\n\n<p>I don't think <code>article</code> elements in the <code>footer</code> are suitable for that kind of content (unless your actual page contains something different). (Only the newsletter form could possibly get <code>article</code> instead of <code>section</code>, but that's not that clear; personally I'd use <code>section</code> for it, too).</p>\n\n<p>So, I'd go with <code>section</code> here. If the contact details listed under \"Address\" are relevant for the whole page, you should use the <code>address</code> element, too.</p>\n\n<pre><code><div id=\"extra\">\n <section class=\"extra\"></section>\n <section class=\"extra\">\n <h1>Address</h1>\n <address>…</address>\n </section>\n <section class=\"extra\"></section>\n <section class=\"extra\"></section>\n</div>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T08:23:50.177",
"Id": "22848",
"ParentId": "22832",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "22848",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T19:45:05.187",
"Id": "22832",
"Score": "4",
"Tags": [
"html",
"html5"
],
"Title": "HTML5 semantic layout (div, article, section) and explicit identifiers"
}
|
22832
|
<p>I have just started to learn programming with Python. I have been going through several online classes for the last month or two. Please bear with me if my questions are noobish.</p>
<p>One of the classes I am taking asked us to solve this problem.</p>
<pre><code># Define a procedure, check_sudoku,
# that takes as input a square list
# of lists representing an n x n
# sudoku puzzle solution and returns the boolean
# True if the input is a valid
# sudoku square and returns the boolean False
# otherwise.
# A valid sudoku square satisfies these
# two properties:
# 1. Each column of the square contains
# each of the whole numbers from 1 to n exactly once.
# 2. Each row of the square contains each
# of the whole numbers from 1 to n exactly once.
# You may assume the the input is square and contains at
# least one row and column.
</code></pre>
<p>After a while of trying to come up with the best code I can, this is what I ended up with.</p>
<pre><code>def check_sudoku(sudlist):
x = range(1, len(sudlist)+1) # makes a list of each number to be found
rows = [[row[i] for row in sudlist] for i in range(len(sudlist))] # assigns all the rows to a flat list
z = range(len(sudlist))
for num in x:
for pos in z:
if num not in sudlist[pos] or num not in rows[pos]:
return False
return True
</code></pre>
<p>This code does work and passed all checks the class asked for. I just wonder what problems could the code have or how would you improve it?</p>
<p>I am just trying to improve by getting input from others. I appreciate any suggestions.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T22:58:29.257",
"Id": "35094",
"Score": "0",
"body": "The problem seems poorly stated. A Sudoku grid has *three* types of constraint: rows, columns, and *blocks*. A grid that only has row and column constraints is known as a [Latin square](http://en.wikipedia.org/wiki/Latin_square)."
}
] |
[
{
"body": "<p>I would use <a href=\"http://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset\"><code>set</code></a> to do the checks, and you can build the columns using some <a href=\"http://docs.python.org/2/library/functions.html#zip\"><code>zip</code></a> magic:</p>\n\n<pre><code>def check_sudoku(sudlist) :\n numbers = set(range(1, len(sudlist) + 1))\n if (any(set(row) != numbers for row in sudlist) or\n any(set(col) != numbers for col in zip(*sudlist))) :\n return False\n return True\n</code></pre>\n\n<p>I have tested it with the following samples:</p>\n\n<pre><code>a = [[1, 2, 3, 4, 5],\n [2, 3, 5, 1, 4],\n [3, 5, 4, 2, 1],\n [4, 1, 2, 5, 3],\n [5, 4, 1, 3, 2]] # latin square\n\nb = [[1, 2, 3, 4, 5],\n [2, 3, 5, 1, 4],\n [3, 5, 4, 2, 1],\n [4, 1, 2, 5, 3],\n [3, 4, 1, 5, 2]] # 1st and 4th elements of last row interchanged\n\nc = [[1, 2, 3, 4, 5],\n [2, 4, 5, 1, 4],\n [3, 5, 4, 2, 1],\n [4, 1, 2, 5, 3],\n [5, 3, 1, 3, 2]] #1st and 5th elements of second column intechanged\n\n\n>>> check_sudoku(a)\nTrue\n>>> check_sudoku(b)\nFalse\n>>> check_sudoku(c)\nFalse\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T23:58:31.987",
"Id": "22841",
"ParentId": "22834",
"Score": "8"
}
},
{
"body": "<pre><code>def check_sudoku(sudlist):\n x = range(1, len(sudlist)+1) # makes a list of each number to be found'\n</code></pre>\n\n<p>Avoid storing things in single-letter variable names. It just makes it hearder to folllow your code</p>\n\n<pre><code> rows = [[row[i] for row in sudlist] for i in range(len(sudlist))] # assigns all the rows to a flat list\n</code></pre>\n\n<p>You could actually do <code>rows = zip(*sudlist)</code> which will do the same thing. Admittedly, if you've not seen the trick before its non-obvious.</p>\n\n<pre><code> z = range(len(sudlist))\n for num in x:\n</code></pre>\n\n<p>There's not really any reason to store the list in x, and then iterate over it later. Just combine the lines.</p>\n\n<pre><code> for pos in z:\n</code></pre>\n\n<p>Instead use <code>for column, row in zip(sudlist, rows):</code> and you won't need to use the pos index</p>\n\n<pre><code> if num not in sudlist[pos] or num not in rows[pos]:\n return False\n return True\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T11:00:25.527",
"Id": "35121",
"Score": "1",
"body": "You're right that the OP's variable names are poorly chosen, but I don't think that \"avoid single-letter names\" is quite the right criterion. What names would you prefer here: `def quadratic(a, b, c): return [(-b + sign * sqrt(b ** 2 - 4 * a * c)) / (2 * a) for sign in (-1,+1)]`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T15:08:02.440",
"Id": "35133",
"Score": "1",
"body": "@GarethRees, agreed that its not absolute, that's why I said \"avoid\" not \"never do this\""
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T03:52:05.883",
"Id": "22844",
"ParentId": "22834",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T21:28:47.017",
"Id": "22834",
"Score": "5",
"Tags": [
"python",
"beginner",
"sudoku"
],
"Title": "Check_sudoku in Python"
}
|
22834
|
<p>Sadly <a href="https://connect.microsoft.com/VisualStudio/feedback/details/752794/std-chrono-duration-cast-lacks-double-support">VS2012's <code>duration_cast</code> is broken</a>, and I actually need the functionality which is broken. So, I wrote my own: </p>
<pre><code>template<typename ToUnit, typename Rep, typename Period>
ToUnit duration_cast_2(const std::chrono::duration<Rep, Period>& right)
{
typedef std::ratio_divide<Period, typename ToUnit::period>::type ratio;
typedef std::common_type<std::common_type<typename ToUnit::rep, Rep>::type, intmax_t>::type common_type;
return ToUnit(static_cast<typename ToUnit::rep>(static_cast<common_type>(right.count()) * static_cast<common_type>(ratio::num) / static_cast<common_type>(ratio::den)));
}
</code></pre>
<p>But I'm not entirely confident that it's correct.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T16:06:01.957",
"Id": "35136",
"Score": "0",
"body": "Links don;t work for me. What is a duration_cast<> supposed to do?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T16:28:06.807",
"Id": "35140",
"Score": "0",
"body": "@LokiAstari Turn a `std::chrono::duration<long long, std::micro>` into a `std::chrono::duration<double, std::milli>`, for example. That conversion cannot be done implicitly, and needs the cast."
}
] |
[
{
"body": "<p>I can't say for sure about the internal logic but I can point some problems or things that could be improved in your piece of code:</p>\n\n<ul>\n<li><p>First of all, <code>typename</code> is missing before the names, making your code non-working with some compilers. I would also use <code>using</code> instead of <code>typedef</code>, but that's a mere matter of taste. Updated version:</p>\n\n<pre><code>using ratio = typename std::ratio_divide<Period, typename ToUnit::period>::type;\nusing common_type = std::common_type<typename std::common_type<typename ToUnit::rep, Rep>::type, intmax_t>::type;\n</code></pre></li>\n<li><p><code>std::common_type</code> is variadic. You don't have to bother with nested <code>std::common_type</code>s:</p>\n\n<pre><code>using common_type = typename std::common_type<typename ToUnit::rep, Rep, intmax_t>::type;\n</code></pre></li>\n<li><p>I know that MSVC has not a full support for <code>constexpr</code>, but <code>duration_cast</code> is supposed to be <code>constexpr</code> (it <em>should</em> work with the November 2013 CTP though):</p>\n\n<pre><code>template<typename ToUnit, typename Rep, typename Period>\nconstexpr ToUnit duration_cast_2(const std::chrono::duration<Rep, Period>& right)\n{\n // ...\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-27T12:09:25.717",
"Id": "79345",
"Score": "0",
"body": "This was actually more than a year ago, and at the time I was using VS2010, so limited to not doing anything you mentioned above. I was most interested in the correctness of the internal logic. The whole thing was actually because there was a bug in the VS2010 duration_cast implementation. I don't know if it's fixed yet, probably is."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-27T12:18:31.077",
"Id": "79347",
"Score": "0",
"body": "@Dave From the link in your question, the problem seems to have been solved :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-27T12:25:54.023",
"Id": "79348",
"Score": "0",
"body": "Oh, lol. Thanks. Also I guess I was using 2012 not 2010. I didn't reread my question, it was a long time ago =P"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T11:11:29.897",
"Id": "44560",
"ParentId": "22836",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-17T22:33:13.260",
"Id": "22836",
"Score": "7",
"Tags": [
"c++",
"c++11",
"casting"
],
"Title": "Is this a conforming implementation of duration_cast?"
}
|
22836
|
<p>I've used EF-DB first approach and have written a simple app to retrieve the data from the database and show it in the view. The code is simple and ok for a beginner like me, but how can I implement an effective design-pattern like interface-specification pattern or generic repository pattern, and possibly dependency injection to improve the code below ? I'd like to know because when extending the project I might have to get data from different databases, and would like to implement an effective pattern for maintainability.</p>
<p>Please note that I've started looking into topics like interfaces, design patterns, etc only recently, So I'd greatly appreciate it if you could please break down the explanation to a beginner level. </p>
<p>Below are my view-model and the controller. My model contains a stored-procedure and a table in the .edmx file - Thanks</p>
<p><strong>View-Model</strong> </p>
<pre><code> public class OfficeDTO
{
public IEnumerable<EmployeeDTO> Employees { get; set; }
public IEnumerable<DepartmentDTO> Departments { get; set; }
}
public class EmployeeDTO
{
public int EmpId { get; set; }
public string EmpName { get; set; }
}
public class DepartmentDTO
{
public string DeptCode { get; set; }
public string DeptName { get; set; }
}
</code></pre>
<p><strong>Controller</strong></p>
<pre><code> public ActionResult Index()
{
EF.OfficeEntities ctx = new EF.OfficeEntities();
Models.OfficeDTO office = new Models.OfficeDTO();
using (ctx)
{
var empList = ctx.GetEmployeesByYearJoined("2009")
.ToList();
var empResults = (from q in empList
select new Models.EmployeeDTO
{
EmpId = q.EmpID,
EmpName = q.FirstName + q.LastName
}).ToList();
office.Employees = empResults;
var depResults = (from q in ctx.Departments
select new Models.DepartmentDTO
{
DeptCode = q.DepartmentCode,
DeptName = q.DepartmentName
}).ToList();
office.Departments = depResults;
}
return View(office);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T09:25:57.347",
"Id": "35106",
"Score": "1",
"body": "If you want to improve performance, you can start by removing the intermediate `ToList()` calls, you probably don't even need em. If EF complains about the operations you're doing and you're not doing any more filtering beyond that, use `AsEnumerable()` instead to make it a LINQ to Objects query."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T10:42:47.033",
"Id": "35117",
"Score": "0",
"body": "@JeffMercado In the current implementation, if the `.ToList()` calls are removed then there will be an error as the context is disposed before the view is rendered."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T15:01:51.367",
"Id": "35132",
"Score": "0",
"body": "@TrevorPilley: Not between `empList` and `empResults`, the `ToList()` call there is superfluous."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T22:22:17.330",
"Id": "35163",
"Score": "0",
"body": "@JeffMercado yes, the one on `var empList...` is unnecessary overhead the other two calls however are still needed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T16:29:30.243",
"Id": "35280",
"Score": "0",
"body": "I need the empList because I want to concatenate the firstname and lastname in empResults. do you think it'll still work if i make empList AsEnumerable() ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T02:32:48.367",
"Id": "35433",
"Score": "0",
"body": "yes, EF can translate string concatenation to SQL"
}
] |
[
{
"body": "<p>The only way DI (IoC) is going to improve this code is by extracting the creation and disposal of your data context. This also means you can mock it for your unit tests.</p>\n\n<p>You could argue the DataContext already is a Repository.</p>\n\n<p>You could do one of:</p>\n\n<ul>\n<li>Leave it as it is. No reason to complicate it just for the sake of it. It's small, pretty easy to follow and easily found.</li>\n<li>Extract a Query object (Query Pattern)</li>\n<li>Wrap the query and creation of the OfficeDTO in an OfficeDTO factor</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T02:39:42.220",
"Id": "23000",
"ParentId": "22850",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "23000",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T09:08:05.167",
"Id": "22850",
"Score": "1",
"Tags": [
"c#",
"performance",
".net",
"asp.net",
"entity-framework"
],
"Title": "How can I implement the generic repository pattern and improve the performance for the code below?"
}
|
22850
|
<p>I've written an implementation of the back-propagation algorithm in Clojure (<a href="https://gist.github.com/m0a0t0/4976438" rel="nofollow">here</a>). This is my first attempt at Clojure where the code totals more than ten lines and so it is not very idiomatic; specifically in one of my functions I have this:</p>
<pre><code>; example neural-network: {:inputs [{:weights [1] :delta -0.2 :activation 1}] :outputs [{:activation 0.645}]}
(defn train-layer
[neural-network layer-index next-layer-index rate]
(let [layer (get neural-network layer-index)
next-layer (get neural-network next-layer-index)]
(loop [neuron 0
net neural-network]
(if (< neuron (count layer))
(recur (inc neuron) (loop [next-neuron 0
net-1 net]
(if (< next-neuron (count next-layer))
(let [change (* (get-in next-layer [next-neuron :delta]) (get-in layer [neuron :activation]))
weight (+ (get-in layer [neuron :weights next-neuron]) (* rate change))]
(recur (inc next-neuron) (assoc-in net-1 [layer-index neuron :weights next-neuron] weight)))
net-1)))
net))))
</code></pre>
<p>Where I need to change a neural network inside a nested for loop; making it an argument to each loop seems like a bad idea. It is also really rather dense (and therefore probably quite difficult to understand, so apologies). How should this be implemented to make it easier to read and more idiomatic?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T03:54:30.170",
"Id": "85574",
"Score": "0",
"body": "Refactor the inner loop into another function. Also, the loops could be turned into reducers. These would clean up the code considerably :)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T14:19:58.913",
"Id": "22859",
"Score": "3",
"Tags": [
"clojure",
"neural-network"
],
"Title": "Back-propagation implementation"
}
|
22859
|
<p>I'm creating a CRUD page. My first approach was use the same class editCategory.php for doing these actions:</p>
<ul>
<li>If this file is called via GET and categoryId parameter doesn't exist -> shall show a empty form</li>
<li>If this file is called via GET and categoryId parameter is provided -> shall show a form with the data of this category.</li>
<li>If this file is called via POST and there is no categoryId parameter -> shall create a new category.</li>
<li>If this file is called via POST and categoryId parameter is provided -> shall update this category.</li>
</ul>
<p>The code works ok, but I have the sense that the code is cluttered and that it could be organized better. </p>
<pre><code> <?php
require_once "../include_dao.php";
$action = isset($_POST["action"]);
$category = new Category();
$categoryDao = new CategoryMySqlDAO();
$categoryName = "";
if ($action == "save") { // DO_POST
$categoryName = $_POST["name"];
$category->name=$categoryName;
if (isset($_POST["categoryId"])) { // update
$categoryId = (int) $_POST["categoryId"];
$category->categoryId=$categoryId;
$categoryDao->update($category);
} else { // insert
$categoryDao->insert($category);
}
$messageSuccess = "Category saved";
} else { // DO_GET
if (isset($_GET["categoryId"])) {
$categoryId = (int) $_GET["categoryId"];
$category = $categoryDao->load($categoryId);
$categoryName = $category->name;
}
?>
<html>
HTML code here showing the form
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T21:24:48.417",
"Id": "35159",
"Score": "1",
"body": "I'm not quite sure everything is wrong here. I'd expect `$action = isset($_POST[\"action\"]);` to assign a boolean value to $action as per http://php.net/manual/fr/function.isset.php but then you compare it to a string : `if ($action == \"save\")`. If anyone has an explanation, I'm pretty intested."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T22:20:01.553",
"Id": "35162",
"Score": "1",
"body": "@Josay I suspect you know this since you're already questioning it, but for the OP's sake: The string will be casted to a boolean. It's essentially equivalent to: `if ($action === ((bool) \"save\"))` which is in turn equivalent to `if ($action === true)` which is of course loosely equal to `if ($action)`. In other words, if `$_POST['action']` is set, despite the value, that branch will be followed. Interestingly, `isset('') === true` meaning if the field is provided at all that branch will be followed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T22:55:07.910",
"Id": "35164",
"Score": "1",
"body": "@Corbin Thanks for the explanation. I wasn't too sure about what was happening because I was expecting this not to work but OP was saying that everything was fine. I understand now. Thanks again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T08:34:07.047",
"Id": "35178",
"Score": "0",
"body": "OMG, it's working by chance! When submit the form, I have an input hidden with name=\"action\" and value=\"save\". So, when this script is called by POST, $_POST[\"action\"] is set to \"save\" and when this script is called by GET, $_POST[\"action\"] is not set. I don't know if there is a better way to know if script is called by GET or by POST"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T17:07:45.510",
"Id": "35211",
"Score": "0",
"body": "$action = isset($_POST[\"action\"]); will return either true or false, so the test if ($action == \"save\") later will always be false meaning all request will be a 'get'"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T08:00:20.387",
"Id": "35245",
"Score": "0",
"body": "@RichardAtHome As I said before, the code is working well, has been tested and when $_POST[\"action\"] is set, the 'post' request is done correctly. I only ask if there is a better way to organize this CRUD code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T09:22:50.990",
"Id": "35249",
"Score": "0",
"body": "@user674887 If that's true mate, your working code is different to the code you have posted here ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T09:44:10.480",
"Id": "35251",
"Score": "0",
"body": "@RichardAtHome The code is the same, it works, and has been in production during long time. Please, have a look the comment of Corbin that I think he explains very well. And, if you still don't believe me, maybe you can try for yourself. It's not a lot of code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T14:10:19.340",
"Id": "35341",
"Score": "0",
"body": "@user674887 Yes, I agree it works but the point I'm making is, it works because of a side effect, not because of intent. \n\nThis is a code review site, not a 'help me get my code working' site. \n\nThe line if ($action == \"save\") is wrong/missleading because $action can never equal \"save\". It should read something like: if ($action && $_POST['action'] == \"save\") .\n\nHope that clears up any misunderstanding :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T14:15:20.240",
"Id": "35342",
"Score": "0",
"body": "Better yet, change the original test to: $action = isset($_POST['action']) ? $_POST['action'] : \"\";"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T14:56:36.950",
"Id": "35343",
"Score": "0",
"body": "@RichardAtHome Ok, but that is not what you said in previous messages ;) Anyway, thank you for your help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-24T19:50:53.110",
"Id": "35601",
"Score": "1",
"body": "If you want to check for POST requests, use `$_SERVER['REQUEST_METHOD']`. When comparing strings, get in the habit of strict comparisons, e. g. `$_POST['action'] === 'save'`."
}
] |
[
{
"body": "<p>Your concept using the HTTP verbs is pretty much the idea behind REST. You could go one step further and use the less known verbs like PUT, DELETE, UPDATE. </p>\n\n<p>Also u could use the $_SERVER['REQUEST_METHOD'] to switch between the HTTP modes you would like to process. </p>\n\n<p>I would suggest to write a \"class Request\" to be reused by all your CRUD pages or use / get inspired by (for example) symfony2 </p>\n\n<p><a href=\"https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/Request.php\" rel=\"nofollow\">https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/Request.php</a></p>\n\n<p>u are using classes like CategoryMySqlDAO why do not u use a CRUD class? u could implement an abstract class CRUD with \"create, update, delete\" methodes and then use subclasses for each crud page. Then you would inject the DAO and stuff in the constructor and use autoload to get them instead of a smelly required statement in each file. </p>\n\n<p>also having HTML and logic in the same file never is a good idea. </p>\n\n<p>i hope i could give you some inspiration how to improve your current state</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T13:49:05.007",
"Id": "22927",
"ParentId": "22864",
"Score": "1"
}
},
{
"body": "<p>I am not a php developer, but I think that your objects should encapsulate a more logic, I made a small simple example:</p>\n\n<pre><code>$category = new Category();\n$categoryDao = new CategoryMySqlDAO();\n\nif ($_SERVER['REQUEST_METHOD'] === 'POST') \n{\n if (isset($_POST[\"action\"])\n {\n //$category has logic with get varialbles in method fill \n $category->fill($_POST);\n\n //$categoryDao has logic insert or update $category\n $result = $categoryDao->process($category);\n\n //.. do something with $result\n }\n} else if (isset($_GET[\"categoryId\"]))\n{\n $categoryId = (int) $_GET[\"categoryId\"];\n $category = $categoryDao->load($categoryId);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T08:30:07.913",
"Id": "22955",
"ParentId": "22864",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "22955",
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T16:41:41.330",
"Id": "22864",
"Score": "1",
"Tags": [
"php"
],
"Title": "Insert, update and get in the same php file?"
}
|
22864
|
<p>I've written a short program to find solutions to the <a href="http://en.wikipedia.org/wiki/36_cube" rel="nofollow">36 Cube puzzle</a>.</p>
<p>I'm trying to break away from my normal Java / imperative style, and would like some feedback on how I'm doing.</p>
<p><strong>Puzzle.scala</strong></p>
<pre><code>package cube36
/**
* An immutable class representing the state of a 36 Cube puzzle
*/
case class CubePuzzle(val board: Board, val availablePieces: List[Piece]) {
/**
* Add a piece to this puzzle, to create new instance of the puzzle
* @param rowNum row to add piece to
* @param colNum column to add piece to
* @param piece piece to add
* @param checkSuitable check if the position will accept this piece (default true if omitted)
* @return a new puzzle instance, with the specified piece added
*/
def addPiece(rowNum: Int, colNum: Int, piece: Piece, checkSuitable: Boolean = true): CubePuzzle = {
val newBoard = board.addPiece(rowNum, colNum, piece,checkSuitable)
CubePuzzle(newBoard, availablePieces.filterNot(_ == piece))
}
/**
* Find solutions to the puzzle which satisfy the rules
* @param solutionsSoFar
* @return a list of all valid solutions
*/
def solve(solutionsSoFar: List[Board]=List[Board]()): List[Board] = {
if (this.availablePieces.size == 0) this.board :: solutionsSoFar
else {
val nextPiece = availablePieces.head
val availableSpots = board.spaces.filter(space => board.suitable(space, nextPiece))
val sols = for (spot <- availableSpots) yield addPiece(spot._1, spot._2, nextPiece,false).solve(solutionsSoFar)
sols.flatten.toList
}
}
}
object CubePuzzle {
// Have to put two pieces in 'special' positions, where they wouldn't be expected to fit.
// No solution otherwise.
private val startingBoard = Board().addPiece(1, 2, Piece(Yellow, 5),false).addPiece(3, 2, Piece(Orange, 6),false)
private val availablePieces = (List[Piece]() ++
getPieces(Yellow, 6) ++
getPieces(Red, 6) ++
getPieces(Purple, 6) ++
getPieces(Blue, 6) ++
getPieces(Green, 6) ++
getPieces(Orange, 6)).
filterNot(_ == Piece(Yellow, 5)).
filterNot(_ == Piece(Orange, 6))
private def getPieces(colour: Colour, maxSize: Int): Set[Piece] = (for (x <- 1 to 6) yield Piece(colour, x)).toSet
def apply() = new CubePuzzle(startingBoard, availablePieces)
}
sealed trait Colour;
case object Red extends Colour;
case object Purple extends Colour;
case object Blue extends Colour;
case object Green extends Colour;
case object Yellow extends Colour;
case object Orange extends Colour;
case class Piece(val colour: Colour, val size: Int) {
require(size <= 6 && size >= 1,"Piece size out of range")
override def toString: String = colour.toString().head.toString + size.toString
}
</code></pre>
<p><strong>Board.scala</strong></p>
<pre><code>package cube36
case class Board(val placedPieces: IndexedSeq[IndexedSeq[Option[Piece]]] /*rows of cols*/ ) {
val row1Heights = List[Int](1, 3, 4, 5, 2, 0)
val row2Heights = List[Int](2, 5, 0, 4, 1, 3)
val row3Heights = List[Int](0, 1, 3, 2, 5, 4)
val row4Heights = List[Int](5, 4, 1, 3, 0, 2)
val row5Heights = List[Int](4, 2, 5, 0, 3, 1)
val row6Heights = List[Int](3, 0, 2, 1, 4, 5)
val contours = List[List[Int]](row1Heights, row2Heights, row3Heights, row4Heights, row5Heights, row6Heights)
private[cube36] def spaces: Seq[(Int, Int)] = for (row <- 0 to 5; col <- 0 to 5; if (placedPieces(row)(col)).isEmpty) yield (row, col)
private[cube36] def suitable(space: (Int, Int), piece: Piece): Boolean = {
lazy val spaceEmpty = placedPieces(space._1)(space._2).isEmpty
lazy val height = contours(space._1)(space._2)
lazy val rightHeight = height + piece.size == 6
lazy val colour = piece.colour
lazy val cl = placedPieces.map(row => row(space._2))
lazy val matches = cl.map(x => x.map(p => p.colour == colour))
lazy val colourAlreadyInCol = matches.contains(Some(true))
lazy val rw = placedPieces(space._1)
lazy val rmatches = rw.map(x => x.map(p => p.colour == colour))
lazy val colourAlreadyInRow = rmatches.contains(Some(true))
val unsuitable = (!spaceEmpty) || (!rightHeight) || colourAlreadyInCol || colourAlreadyInRow
!unsuitable
}
private[cube36] def addPiece(rowNum: Int, colNum: Int, piece: Piece, checkSuitable: Boolean = true): Board = {
if (checkSuitable && !suitable((rowNum, colNum), piece)) throw new IllegalArgumentException("Not suitable for this poition")
val newRow = placedPieces(rowNum).updated(colNum, Some(piece))
Board(placedPieces.updated(rowNum, newRow))
}
private[this] def rowString(row:IndexedSeq[Option[Piece]]):String = {
val r=for(p<-row) yield p match {
case Some(pc) => "|" + pc
case None => " _ "
}
r.foldLeft("")((a,b)=>a+b) + "|"
}
override def toString: String = {
val border = "==================="
val content = for (row <- placedPieces) yield rowString(row)
val folded=content.foldLeft(border)((a,b)=> a +"\n" + b)
folded + "\n" + border
}
}
object Board {
def apply(): Board = {
val emptyRow = IndexedSeq[Option[Piece]](None, None, None, None, None, None)
val emptyPieces = IndexedSeq(emptyRow, emptyRow, emptyRow, emptyRow, emptyRow, emptyRow)
Board(emptyPieces)
}
}
</code></pre>
|
[] |
[
{
"body": "<h2>Puzzle.scala</h2>\n\n<pre><code>case class CubePuzzle(val board: Board, val availablePieces: List[Piece]) \n</code></pre>\n\n<p>Case classes don't need \"val\" before field names.</p>\n\n<pre><code>def solve(solutionsSoFar: List[Board]=List[Board]()): List[Board] =\n</code></pre>\n\n<p>More idiomatic is <code>Nil</code> instead of <code>List[Board]()</code>. Although sometimes I use <code>List.empty[Board]</code> in case I change the collection type (<code>Nil</code> is only available on <code>List</code>)</p>\n\n<pre><code>if (this.availablePieces.size == 0) this.board :: solutionsSoFar\n</code></pre>\n\n<p>Instead, how about </p>\n\n<pre><code>availablePieces match {\n case Nil => board :: solutionsSoFar\n case nextPiece :: tail => ...\n</code></pre>\n\n<p>Also, I suspect the for loop in solve() can be rewritten so that you do not need to call flatten.</p>\n\n<h2>Board.scala</h2>\n\n<pre><code>val unsuitable = ...\n</code></pre>\n\n<p>This seems backward, why not just return </p>\n\n<pre><code>spaceEmpty && rightHeight && !colourAlreadyInCol && !colourAlreadyInRow\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T12:08:16.613",
"Id": "40619",
"Score": "0",
"body": "Agree on the case class vals, Nil and pattern matching. The \"val unsuitable =...\" was an attempt to use lazy evaluation to avoid doing all the checks every time - does that make sense?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T20:09:05.150",
"Id": "22902",
"ParentId": "22865",
"Score": "3"
}
},
{
"body": "<p>A more scala idiomatic-way to write the for loop in your solve(...) method such that it is unnecessary to call flatten:</p>\n\n<pre><code> val sols =\n availableSpots flatMap (spot =>\n addPiece(spot._1, spot._2, nextPiece, false).solve(solutionsSoFar))\n sols.toList\n</code></pre>\n\n<p>Essentially what flatMap is doing is traversing through <code>availableSpots</code> applying some function to each of its values, and concatenating the results.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-08T06:51:10.890",
"Id": "59480",
"ParentId": "22865",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "22902",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T17:52:59.637",
"Id": "22865",
"Score": "5",
"Tags": [
"scala"
],
"Title": "How idiomatic is this Scala 36 Cube Solver?"
}
|
22865
|
<p>At work, we have a "pair programming ladder" where you can keep track of who is pairing with whom (based on check-ins). The idea is to promote "promiscuous pairing" where each developer eventually pairs with every other developer.</p>
<p>In our team, this was being updated <em>manually</em>, so I thought of writing a script that will parse the logs and generate a table.</p>
<p>Given these are the names of the developers:</p>
<blockquote>
<p>"Adam", "Bill", "Carl", "David", "Eddie", "Frank", "George"</p>
</blockquote>
<p>The output would look like so:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code> |Adam
Bill |0 |Bill
Carl |0 |2 |Carl
David |1 |0 |0 |David
Earl |0 |0 |3 |0 |Earl
Frank |0 |0 |0 |2 |1 |Frank
George |0 |0 |0 |0 |2 |0 |George
Solo |1 |0 |0 |0 |0 |1 |0 |Solo
Other |1 |0 |0 |0 |0 |2 |1 |0 |Other
</code></pre>
</blockquote>
<p>This is my script:</p>
<pre class="lang-python prettyprint-override"><code>from git import *
import re
from collections import Counter
list = ["Adam", "Bill", "Carl", "David", "Eddie", "Frank", "George"]
def build():
repo = Repo("/home/developer/work/commerce-git/commerce-project")
master = repo.heads.master
pairsDict = {}
for commit in repo.iter_commits(master, since='2013-02-06+14:00', reverse=True):
for person in list:
if person not in pairsDict:
pairsDict[person] = Counter()
if person in commit.message:
pairedWith = ""
m = re.search('(\w+)/(\w+)\s', commit.message)
if not m:
pairedWith = "Solo"
else:
if m.group(1) == person:
pairedWith = m.group(2) #pair is right of slash
else:
pairedWith = m.group(1) #pair is left of slash
if pairedWith not in list:
pairedWith = "Other"
pairsDict[person][pairedWith] += 1
if pairedWith not in pairsDict:
pairsDict[pairedWith] = Counter()
pairsDict[pairedWith][person] += 1
break;
return pairsDict
def print_table():
pairsList = list + ["Solo", "Other"]
pairsDict = build()
str = ""
for index,person in enumerate(pairsList):
if (index == 0):
str += '|'.rjust(8) + person.ljust(7) + '\n'
else:
str += person.ljust(7) + '|'
for paired in pairsList[:index]:
count = pairsDict[person][paired]
str += '{:<7}|'.format(count)
str += person.ljust(7)+'\n'
print str
return str
if __name__ == "__main__":
print_table();
</code></pre>
<p>The scripts parses the git logs using GitPython, where a commit message is expected to look like this:</p>
<blockquote>
<p>"Adam/David - Refactored app to be more polyglot-y"</p>
</blockquote>
<p>From there it constructs a <code>HashMap</code> of <code>Counter</code>s to keep track of who has paired with whom. I'm going to eventually feed this data structure into a simple Django web-app so people can view it in a browser.</p>
<p>Do you have any suggestions for this script? Could it be more "pythonic"? Is there anything I could do to refactor it to be simpler to read, or better performance-wise?</p>
|
[] |
[
{
"body": "<pre><code>from git import *\n</code></pre>\n\n<p>Generally import from * is frowned upon as it makes it more difficult to figure out where stuff comes from</p>\n\n<pre><code>import re\nfrom collections import Counter\n\nlist = [\"Adam\", \"Bill\", \"Carl\", \"David\", \"Eddie\", \"Frank\", \"George\"]\n</code></pre>\n\n<p>Don't names things after types. Global constants should also be in ALL_CAPS. So this should probably be DEVELOPERS = [...]</p>\n\n<pre><code>def build():\n repo = Repo(\"/home/developer/work/commerce-git/commerce-project\")\n</code></pre>\n\n<p>Putting an absolute path to the repository is probably not all that great. It makes more assumptions about the setup of the machine than we'd like.</p>\n\n<pre><code> master = repo.heads.master\n pairsDict = {}\n</code></pre>\n\n<p>Python convention is lowercase_with_underscores for local names</p>\n\n<pre><code> for commit in repo.iter_commits(master, since='2013-02-06+14:00', reverse=True):\n for person in list:\n if person not in pairsDict:\n pairsDict[person] = Counter()\n</code></pre>\n\n<p>Use <code>pairsDict = collections.defaultdict(Counter)</code> so you don't need to do this.\nAlternately use a two element tuple as the key.</p>\n\n<pre><code> if person in commit.message:\n</code></pre>\n\n<p>Shouldn't you do something like look at the username recorded by git as to who did the comment rather then checking the commit message?</p>\n\n<pre><code> pairedWith = \"\"\n</code></pre>\n\n<p>Don't assign variables with meaningless content if you are just going to reassign it later</p>\n\n<pre><code> m = re.search('(\\w+)/(\\w+)\\s', commit.message)\n</code></pre>\n\n<p>This is an okay use of a single letter variable name, but I'd still call it match.</p>\n\n<pre><code> if not m:\n pairedWith = \"Solo\"\n else:\n if m.group(1) == person:\n pairedWith = m.group(2) #pair is right of slash\n else:\n pairedWith = m.group(1) #pair is left of slash\n</code></pre>\n\n<p>This would be simpler if you didn't iterate over the list the developers. Just figure out who the developers were by regexing the message.</p>\n\n<pre><code> if pairedWith not in list:\n pairedWith = \"Other\"\n pairsDict[person][pairedWith] += 1\n if pairedWith not in pairsDict:\n pairsDict[pairedWith] = Counter()\n pairsDict[pairedWith][person] += 1\n break;\n\n return pairsDict\n\ndef print_table():\n pairsList = list + [\"Solo\", \"Other\"]\n pairsDict = build()\n str = \"\" \n for index,person in enumerate(pairsList):\n if (index == 0):\n str += '|'.rjust(8) + person.ljust(7) + '\\n'\n</code></pre>\n\n<p>Don't build up strings by adding, that's inefficent. You are better off just printing here</p>\n\n<pre><code> else:\n str += person.ljust(7) + '|'\n for paired in pairsList[:index]:\n count = pairsDict[person][paired]\n str += '{:<7}|'.format(count)\n str += person.ljust(7)+'\\n'\n print str\n return str\n</code></pre>\n\n<p>Don't both return a print. Either return the string and let the caller print or print the string and return nothing.</p>\n\n<pre><code>if __name__ == \"__main__\":\n print_table();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T19:31:02.260",
"Id": "35154",
"Score": "0",
"body": "Thanks for the review!\nAs for \"Shouldn't you do something like look at the username recorded by git as to who did the comment rather then checking the commit message?\"\nI want to the filter the commit messages from my team specifically, as other teams commit to the same branch."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T19:58:48.460",
"Id": "35155",
"Score": "2",
"body": "@Atif, but it would still seem less error prone to check the username against a list your team's usernames"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T19:05:33.453",
"Id": "22870",
"ParentId": "22866",
"Score": "4"
}
},
{
"body": "<h3>1. Comments on your code</h3>\n\n<ol>\n<li><p>No docstrings! What do these functions do and what kind of values do they return?</p></li>\n<li><p>Python statements don't need to be terminated with a semicolon: they finish at the end of a line.</p></li>\n<li><p>Is it really necessary to do <code>from git import *</code> given that you only actually use <code>git.Repo</code>?</p></li>\n<li><p>There's a <a href=\"http://docs.python.org/2/library/functions.html#list\">built-in function</a> called <code>list</code>, so it's a bad idea to use that as the name of a variable. Also, <code>list</code> is a vague name: list of what? I suggest something like <code>users</code>.</p></li>\n<li><p>Similarly, <code>build</code> is a vague name. Build what? I suggest something descriptive like <code>count_commit_pairings</code>.</p></li>\n<li><p>It's conventional (following <a href=\"http://www.python.org/dev/peps/pep-0008/\">PEP8</a>) for Python variables to use lower case with underscores. If you plan to collaborate with other Python programmers, use variable names like <code>pairs_dict</code> and <code>paired_with</code> instead of <code>pairsDict</code> and <code>pairedWith</code>.</p></li>\n<li><p>Constants like <code>'2013-02-06+14:00'</code> shouldn't be buried deep in the code, but should be pulled out to become global variables or function parameters.</p></li>\n<li><p>You could avoid having to write these lines:</p>\n\n<pre><code>if person not in pairsDict:\n pairsDict[person] = Counter()\n</code></pre>\n\n<p>and these lines:</p>\n\n<pre><code>if pairedWith not in pairsDict:\n pairsDict[pairedWith] = Counter()\n</code></pre>\n\n<p>if you made <code>pairsDict</code> into a <code>defaultdict(Counter)</code>. See <a href=\"http://docs.python.org/2/library/collections.html#collections.defaultdict\"><code>collections.defaultdict</code></a>.</p></li>\n<li><p>Since you're going to be looking up users to see whether they need to be replaced with <code>'Other'</code>, it's good practice to convert the list of users into a set, so that looking up a name can be done in constant time.</p></li>\n<li><p>It's wasteful to iterate over the users and try to match each one against the commit message. Why not do a regular expression match against the commit message just once and then figure out which users are mentioned?</p></li>\n<li><p>You use the line</p>\n\n<pre><code>if person in commit.message:\n</code></pre>\n\n<p>to determine if <code>person</code> is the committer. But what if someone makes a commit without writing their name in the commit message (false negative)? What if someone's name appears in the commit message by coincidence (false positive)? It seems to me that looking at <code>commit.committer.name</code> would be more reliable.</p></li>\n<li><p>Backslash is an escape character in Python strings, so you should generally use the <code>r</code> modifier in front of strings where you want to preserve the backslashes. So write:</p>\n\n<pre><code>m = re.search(r'(\\w+)/(\\w+)\\s', commit.message)\n</code></pre></li>\n<li><p>It's better to use the regular expression <code>\\b</code> (word boundary) rather than <code>\\s</code> (whitespace) to detect the end of a word. This is because <code>\\b</code> matches if the word is followed by punctuation, or by the end of the string, whereas <code>\\s</code> would fail in those cases.</p></li>\n<li><p>If the name of the pairing is supposed to be at the start of the commit message, you should use <code>re.match</code> to ensure this. But if it is allowed to be anywhere in the commit message you should write:</p>\n\n<pre><code>m = re.search(r'\\b(\\w+)/(\\w+)\\b', commit.message)\n</code></pre>\n\n<p>to ensure that the match starts at the beginning of a word.</p></li>\n<li><p>Each time you call <code>re.search</code> it has to compile the regular expression. Since you're going to do this for each commit, it makes sense to compile the regular expression just once by calling <a href=\"http://docs.python.org/2/library/re.html#re.compile\"><code>re.compile</code></a>.</p></li>\n<li><p>In the section of code</p>\n\n<pre><code>if m.group(1) == person:\n pairedWith = m.group(2) #pair is right of slash\nelse:\n pairedWith = m.group(1) #pair is left of slash\n</code></pre>\n\n<p>you assume that if <code>person</code> is in the message, and not to the left of the slash, then they must be to the right of the slash. But that doesn't follow at all. Suppose Gabrielle commits a change with the message</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Gabrielle/Frank -- fixed bug 123 found by Alice\n</code></pre>\n\n<p>it looks to me as though your code will incorrectly deduce that this is a change committed by Alice and Frank. So I think it would be worth taking more care to detect (and perhaps report?) errors in the commit messages. People make mistakes!</p></li>\n</ol>\n\n<h3>2. Revised build function</h3>\n\n<p>Addressing all the issues discussed above yields the following code. But beware: I haven't tested this, so most likely there are mistakes.</p>\n\n<pre><code>from git import Repo\nimport re\nfrom collections import Counter, defaultdict\nimport sys\n\ndef count_commit_pairings(repository = '/home/developer/work/commerce-git/commerce-project',\n since = '2013-02-06+14:00',\n users = 'Alice Bill Clare David Emma Frank Gabrielle'.split()):\n \"\"\"\n Count the number of times each pair of users has made a commit.\n\n `repository` is the git repository to examine.\n `since` is the date at which to start looking at the commits.\n `users` is a list of users to count commits for.\n\n Return the counts in the form of a dictionary mapping user name to\n a dictionary mapping partner name to count of commits by that\n pair. Commits not made by a pair are filed as if by the committer\n and the fake user 'Solo'. User names not found in `users` are\n replaced by 'Other'.\n \"\"\"\n repo = Repo(repository)\n pairs = defaultdict(Counter)\n users = set(users)\n pair_re = re.compile(r'(\\w+)/(\\w+)\\b')\n\n def username(name):\n \"\"\"Return the username to use for `name`.\"\"\"\n return name if name in users else 'Other'\n\n def partner(commit):\n \"\"\"Return the partner of the committer, or 'Solo' if none found.\"\"\"\n m = pair_re.match(commit.message)\n if not m:\n return 'Solo'\n if commit.committer.name not in m.groups():\n sys.stderr.write(\"Bad commit {0.hexsha}: committer {0.committer.name} \"\n \"missing from pair {1}.\"\n .format(commit, m.group(0)))\n return username(m.group(1))\n partner = set(m.groups()).difference([commit.committer.name])\n if len(partner) != 1:\n sys.stderr.write(\"Bad commit {0.hexsha}: duplicate pair {1}.\"\n .format(commit, m.group(0)))\n return 'Solo'\n return username(partner.pop())\n\n for commit in repo.iter_commits(repo.heads.master, since=since, reverse=True):\n u1 = username(commit.committer.name)\n u2 = partner(commit)\n pairs[u1][u2] += 1\n pairs[u2][u1] += 1\n\n return pairs\n</code></pre>\n\n<p>(This seems like plenty for one answer. Maybe some other person can look at <code>print_table</code>.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T21:36:30.200",
"Id": "35160",
"Score": "0",
"body": "Regarding print_table, that was more of a 'test method' for me, so I'm not as concerned about that. \nI've taken suggestions from both answers, but your answer is more thorough and simplified my code a lot. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T20:12:14.377",
"Id": "22872",
"ParentId": "22866",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "22872",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T18:27:25.200",
"Id": "22866",
"Score": "3",
"Tags": [
"python",
"parsing",
"matrix",
"git"
],
"Title": "Pair programming matrix"
}
|
22866
|
<h3>Premise</h3>
<p>Consider the following method:</p>
<pre><code>static String formatMyDate(Date date) {
return new SimpleDateFormat("yyyy-MM-dd").format(date);
}
</code></pre>
<p>It's often desirable to memoize <code>DateFormat</code> objects so they can be reused rather than repeatedly instantiating new ones. This frequently leads to the following naive refactor:</p>
<pre><code>private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
static String formatMyDate(Date date) {
return DATE_FORMAT.format(date);
}
</code></pre>
<p>But this is wrong for multithreaded applications. From the <a href="http://docs.oracle.com/javase/6/docs/api/java/text/DateFormat.html"><code>DateFormat</code></a> documentation:</p>
<blockquote>
<p>Date formats are not synchronized. It is recommended to create
separate format instances for each thread. If multiple threads access
a format concurrently, it must be synchronized externally.</p>
</blockquote>
<p>Assuming our application is using thread pooling, this leads us to memoize an object per thread, using <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/ThreadLocal.html"><code>ThreadLocal</code></a> (<a href="http://www.javacodegeeks.com/2010/07/java-best-practices-dateformat-in.html">see article</a>):</p>
<pre><code>private static final ThreadLocal<DateFormat> DATE_FORMAT_REF =
new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}
};
static String formatMyDate(Date date) {
return DATE_FORMAT_REF.get().format(date);
}
</code></pre>
<p>This works fine. But I've noticed it can still leave code duplication across a larger project. For example multiple developers could each write their own code using <code>"yyyy-MM-dd"</code> date formats in various classes. This led me to write the following helper class (using <a href="http://code.google.com/p/jsr-305/">JSR-305</a> and <a href="https://code.google.com/p/guava-libraries/">Guava</a>):</p>
<h3>Solution 1</h3>
<pre><code>public class DateFormats {
private static final ThreadLocal<Map<String, DateFormat>> DATE_FORMAT_MAP_REF =
new ThreadLocal<Map<String, DateFormat>>() {
@Override
protected Map<String, DateFormat> initialValue() {
return Maps.newHashMap();
}
};
private DateFormats() { }
/**
* Retrieves, and if necessary creates and caches, a {@code DateFormat} instance
* corresponding to the specified format string.
*
* @param dateFormatString The date format string.
* @return The date format.
*/
public static DateFormat get(String dateFormatString) {
Preconditions.checkNotNull(dateFormatString, "dateFormatString");
final Map<String, DateFormat> dateFormatMap = DATE_FORMAT_MAP_REF.get();
@Nullable DateFormat dateFormat = dateFormatMap.get(dateFormatString);
if (dateFormat == null) {
dateFormat = new SimpleDateFormat(dateFormatString);
dateFormatMap.put(dateFormatString, dateFormat);
}
return dateFormat;
}
}
</code></pre>
<p>And the usage would look like:</p>
<pre><code>static String formatMyDate(Date date) {
return DateFormats.get("yyyy-MM-dd").format(date);
}
</code></pre>
<p>One downside to this solution is that a new <code>HashMap</code> gets created for every calling thread. I'm considering using a Guava <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/cache/LoadingCache.html"><code>LoadingCache</code></a> to implement the following alternative:</p>
<h3>Solution 2</h3>
<pre><code>public class DateFormats {
private static final LoadingCache<String, ThreadLocal<DateFormat>> DATE_FORMAT_REF_CACHE =
CacheBuilder.newBuilder()
.concurrencyLevel(4) //how to compute this is up for debate
.build(new CacheLoader<String, ThreadLocal<DateFormat>>() {
@Override
public ThreadLocal<DateFormat> load(final String dateFormatString) {
return new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat(dateFormatString);
}
};
}
});
private DateFormats() { }
/**
* ...
*/
public static DateFormat get(String dateFormatString) {
Preconditions.checkNotNull(dateFormatString, "dateFormatString");
return DATE_FORMAT_REF_CACHE.getUnchecked(dateFormatString).get();
}
}
</code></pre>
<h3>Questions</h3>
<ul>
<li>Is the premise of this solution too pedantic, or is there value in implementing either solution?</li>
<li>Which solution is preferable for a web-scale application?</li>
<li>Is there anything about the solutions you would fix or otherwise change?</li>
<li>For solution 2, what are ways to better calculate concurrency level?</li>
</ul>
<p>I haven't had a chance to write unit tests, but will post them if requested when time allows.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T19:04:59.003",
"Id": "35151",
"Score": "2",
"body": "Is there a reason you have to use java.util.Date instead of JodaTime? The JodaTime library has a DateTimeFormat class that is thread-safe. As a side note, you can look at the source for how they implemented it as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T19:15:36.630",
"Id": "35153",
"Score": "0",
"body": "I've recommended adopting JodaTime to my team members on multiple occasions but it's simply not considered a priority. Thanks for recommending looking at their source though, I didn't think to do that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T07:09:06.553",
"Id": "35237",
"Score": "1",
"body": "I would like to thank you for you very well-written question, it was both informative and interesting. My advice: use the more elegant LoadingCache solution (maybe with another wrapper to make the usage simpler), and don't worry about tuning the parameters until you've shown it slows the application down."
}
] |
[
{
"body": "<p>It looks like the questions are very specific. You should probably formulate a goal. Is your main goal to reduce code duplicity? Memory usage? Speed (however we define it here)? Something else? A combination of previous items? (which makes life harder the more items you combine)\nThis affects the first two questions.</p>\n\n<hr>\n\n<p>For the first question, I could imagine, that you have some common date formats. If less than 5 formats make up to 90% of usage, I would supply a specific method like</p>\n\n<pre><code>/** \n * Formats the date exactly the same as SimpleDateFormat(\"yyyy-MM-dd\").format(date),\n * but is multi threaded safe without any penalties in subsequent calls.<br>\n * Example: 2012-09-30\n */\npublic static String (DateFormats.)formatDate_yyyy_MM_dd(Date date) { ... }\n</code></pre>\n\n<p>You could use <code>ThreadLocal</code> then.<br>\nThis would solve this the easiest way. If you need any more sophisticated solution, you could change the class internals without breaking any external code.</p>\n\n<hr>\n\n<p>For the last 2 questions, I do not have experience with <code>LoadingCache</code>, so I cannot help there.<br>\nI would have used a standard HashMap to store the ThreadLocal Version of DateFormat. As far as I thought about it, we do not need synchronization for the map, because we do not want to replace entries, we do not care if we put something multiple times in rare cases for the initialization part of a new datestring and we do not remove anything. </p>\n\n<hr>\n\n<p>A bit offtopic, but: One thing I do not get about your description. If they do not care about using yoda (which could be used inside this DateFormats class and no one would notice about it), how could you convince them to use this DateFormats class? </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T07:15:56.067",
"Id": "35238",
"Score": "0",
"body": "Thanks for the answer. I have a few questions, but I'm no Java expert. 1/ I don't understand how hardcoding the format in the method name makes things better. 2/ Why avoid `LoadingCache` only because you don't kow it? 3/ A 99% correct class is still not correct. You don't know how `SimpleDateFormat` is implemented, maybe `format()` itself isn't thread-safe? 4/ I think they will be more likely to use something designed by they coworker than something they don't know from a library. Close to the NIH syndrome."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T09:59:54.493",
"Id": "35252",
"Score": "0",
"body": "@Cygal: 1) It abstracts from the implementation. A caller knows what is happening, implementation could be done inside the method. Same as for example `toBinaryString()` from Integer. 2) I did not say to avoid it, I just can not answer the two questions from my past experience. 3) format() is not thread safe. The idea is to have a not-synchronized map, instead of the LoadingCache. The DateFormat must be safe. 4) I do not know, I just wanted to point at this thought, because it could affect the amount of work you spent into this. -- I have edited my post to clarify some roots for your questions"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T12:09:15.817",
"Id": "35461",
"Score": "0",
"body": "Thanks for your answer. I did consider the idea with the individual methods, but the naming would've been awkward for some formats and I didn't want it to be javadoc-dependent. Interesting point about just using `HashMap` instead of a `Cache`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T13:36:05.773",
"Id": "35465",
"Score": "0",
"body": "Yes, it could be an option only if you have a few easy main cases. I strongly agree to not start a 200 method class for different dates."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T22:38:02.263",
"Id": "22908",
"ParentId": "22867",
"Score": "3"
}
},
{
"body": "<p><a href=\"https://stackoverflow.com/questions/5038169/synchronizing-on-simpledateformat-vs-clone\">This</a> brings up the excellent idea of pooling the formatters instead. Have you tried that and seen differences between using a thread pool and a regular pool? If there's no difference perhaps it's better to use a general pool as you can then switch approach to how short/long lived threads you use without reimplementing your pool.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-08T12:03:36.843",
"Id": "25938",
"ParentId": "22867",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "22908",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T18:32:35.467",
"Id": "22867",
"Score": "7",
"Tags": [
"java",
"memoization",
"guava"
],
"Title": "Helper class to memoize DateFormats application-wide"
}
|
22867
|
<p>I'm trying to run a bit of code when my <code>loginManager</code> is logged in. It might be already, or I might be waiting:</p>
<pre><code>var loginManager = chrome.extension.getBackgroundPage().LoginManager;
// If the foreground is opened before the background has had a chance to load, wait for the background.
// This is easier than having every control on the foreground guard against the background not existing.
if (loginManager.get('loggedIn')) {
// Load foreground when the background indicates it has loaded.
require(['foreground']);
} else {
loginManager.once('loggedIn', function () {
// Load foreground when the background indicates it has loaded.
require(['foreground']);
});
}
</code></pre>
<p>and here's how loginManager looks:</p>
<pre><code>// TODO: Exposed globally for the foreground. Is there a better way?
var LoginManager = null;
define(['user'], function(User) {
'use strict';
var loginManagerModel = Backbone.Model.extend({
defaults: {
loggedIn: false,
user: null
},
login: function() {
if (!this.get('loggedIn')) {
var user = new User();
var self = this;
user.on('loaded', function() {
self.set('loggedIn', true);
self.set('user', this);
self.trigger('loggedIn');
});
}
}
});
LoginManager = new loginManagerModel();
return LoginManager;
});
</code></pre>
<p>I was hoping to try out jQuery's <code>.when()</code> as it seemed like it might be applicable here, but I wasn't sure if this was the right scenario since it does not involve AJAX request explicitly --- they're deeper down and at this level I am just triggering custom events.</p>
|
[] |
[
{
"body": "<p>I would recomend you watch <a href=\"https://tutsplus.com/lesson/custom-events-and-the-observer-pattern/\" rel=\"nofollow\">this video</a> about custom events and the Observer Pattern (Pub/Sub) by Jeffery Way. He does a great job of explaining this concept and also provides some good reading materials at the end.</p>\n\n<p>Basically how Pub/Sub works is after completing a task, it tells everyone that is interested, so they can start their tasks.</p>\n\n<p>The following example will provide some clarification on the subject as well:</p>\n\n<pre><code> init: function() {\n //Set up my Observer Pattern\n var o = $( {} );\n $.subscribe = o.on.bind(o);\n $.unsubscribe = o.off.bind(o);\n $.publish = o.trigger.bind(o);\n\n //Start here:\n this.login_user();\n },\n\n veryCoolFunction: function() {\n //Just like that you can create a loop for your triggers, if needed\n $.subscribe( \"done/with/this/baby\", login_user() );\n\n //To stop the loop you can just use the unsubscribe. It works like the .on/.off triggers you're familiar with.\n },\n\n login_user: function() {\n //Do your awesome stuff\n\n //I'm done \"loggingIn\", and I'm letting everyone that is subscribed know that.\n //You can also namespace easily with \"/\" like so: (\"LoginManager/background\") or (\"foreground/done\") etc.\n\n $.publish( \"loggedIn\" );\n },\n\n someOtherVeryCoolFunction: function() {\n //When user is logged in, the publish will run, and will trigger this function call:\n //Push the arguments you need with it\n $.subscribe( \"loggedIn\", this.login( argumentsIfNecessary ) );\n }, \n\n login: function( argumentsIfNecessary ) {\n user.on('loaded', function() {\n //You can use your Pub/Sub model anywhere, even in callbacks\n $.publish(\"done/with/this/baby\");\n });\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T15:42:20.683",
"Id": "22893",
"ParentId": "22868",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "22893",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T18:33:37.993",
"Id": "22868",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"backbone.js"
],
"Title": "Login manager model"
}
|
22868
|
<p>Could someone please point out the error(s) in the given code? It was downvoted on Stack Overflow without any explanation, but it seems to be working fine for me:</p>
<pre><code>int value(char roman)
{
switch(roman)
{
case 'I':return 1;
case 'V':return 5;
case 'X':return 10;
case 'L':return 50;
case 'C':return 100;
case 'D':return 500;
case 'M':return 1000;
}
}
int getdec(const string& input)
{
int sum=0; char prev='%';
for(int i=(input.length()-1); i>=0; i--)
{
if(value(input[i])<sum && (input[i]!=prev))
{ sum -= value(input[i]);
prev = input[i];
}
else
{
sum += value(input[i]);
prev = input[i];
}
}
return sum;
}
</code></pre>
<p>This was the output received from the code:</p>
<blockquote>
<p>I = 1<br> II = 2<br> III = 3<br> IV = 4<br> V = 5<br> VI = 6<br> VII = 7<br> VIII = 8<br> IX = 9<br> X = 10<br> XI = 11<br> XII = 12<br> XIII = 13<br> XIV = 14<br> XV = 15<br> XVI = 16<br> XVII = 17<br> XVIII = 18<br> XIX = 19<br> XX = 20<br> XXI = 21<br> XXII = 22<br> XXIII = 23<br> XXIV = 24<br> XXV = 25<br> XXVI = 26<br> XXVII = 27<br> XXVIII = 28<br> XXIX = 29<br> XXX = 30<br> XXXI = 31<br> XXXII = 32<br> XXXIII = 33<br> XXXIV = 34<br> XXXV = 35<br> XXXVI = 36<br> XXXVII = 37<br> XXXVIII = 38<br> XXXIX = 39<br> XL = 40<br> MMMMCMXCIX = 4999<br> CM = 900<br> XC = 90<br></p>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T02:57:24.213",
"Id": "35169",
"Score": "1",
"body": "Roman Numeral converter in 855 chars :-) http://codegolf.stackexchange.com/questions/797/roman-numeral-converter-function/828#828"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-09T02:38:22.460",
"Id": "59511",
"Score": "0",
"body": "I think IIX would break your code..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-10-14T09:57:11.707",
"Id": "270589",
"Score": "0",
"body": "Your code isn't complete: it has no `main()`, nor any definition of `string`. Is that supposed to be `std::string` from `#include <string>`? Post something that actually compiles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-14T10:25:31.160",
"Id": "471775",
"Score": "0",
"body": "Googling Marcus Caelius tombstone reveals that he was the leader of legion XIIX. Ancient Romans were essentially pragmatic people: The reason they would not write 40 as XXXX is that it was shorter to write CO"
}
] |
[
{
"body": "<p>There is a G++ compile warning (<code>g++ -Wall</code>):</p>\n\n<pre><code>roman.cpp: In function ‘int value(char)’:\nroman.cpp:18:1: warning: control reaches end of non-void function [-Wreturn-type]\n</code></pre>\n\n<p>It should handle invalid inputs too. (Furthermore, it returns 9 for <code>IIIIIIIII</code>.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T00:25:26.367",
"Id": "35165",
"Score": "0",
"body": "Thanks. So validation checks are needed but otherwise the logic is correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T00:41:41.247",
"Id": "35166",
"Score": "0",
"body": "@user1071840: To be honest, I don't know. I've checked it with 5-10 different Roman numerals and it worked fine but I don't know too much about the Roman numerals-decimal numbers conversion algorithms."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T00:05:48.287",
"Id": "22877",
"ParentId": "22876",
"Score": "5"
}
},
{
"body": "<p>If you have only <a href=\"http://en.wikipedia.org/wiki/Roman_numerals\">valid</a> Roman numbers you could use a simpler algorithms. (i.e IIV is invalid )</p>\n\n<blockquote>\n <ul>\n <li>The symbols \"I\", \"X\", \"C\", and \"M\" can be repeated three times in succession, but no more. (They may appear more than three times if\n they appear non-sequentially, such as XXXIX.) \"V\", \"L\", and \"D\" can\n never be repeated. A common exception to this is the use of IIII on\n clocks; see below.</li>\n <li>\"I\" can be subtracted from \"V\" and \"X\" only. \"X\" can be subtracted from \"L\" and \"C\" only. \"C\" can be subtracted from \"D\" and \"M\" only.\n \"V\", \"L\", and \"D\" can never be subtracted</li>\n <li>Only one small-value symbol may be subtracted from any large-value symbol.</li>\n </ul>\n</blockquote>\n\n<p>Just (string-)replace IV by IIII, IX by VIIII and so on. Afterwards you just have to sum the numbers from left to right.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T07:51:48.583",
"Id": "22886",
"ParentId": "22876",
"Score": "6"
}
},
{
"body": "<p>I didn't try to run it but it seems to me that this algorithm won't handle \"Double substractive\" forms. \nForms like XIIX instead of XVIII. \nHow described on wiki – it's not typical roman number usage, but it was used in the past so the program should probably be prepared for it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-10-13T16:11:46.513",
"Id": "270391",
"Score": "2",
"body": "Generally, `XIIX` is not considered to be a valid roman number. Each number can only be written in one and only one way with roman numerals."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-12-08T13:41:30.197",
"Id": "280768",
"Score": "0",
"body": "I am not expert but according to wiki there is nothing like a \"valid\" roman number. \n_... The \"standard\" forms described above reflect typical modern usage rather than a universally accepted convention. Usage in ancient Rome varied greatly and remained inconsistent in medieval and modern times..._"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-10-13T14:13:55.813",
"Id": "144111",
"ParentId": "22876",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "22886",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T23:04:13.313",
"Id": "22876",
"Score": "10",
"Tags": [
"c++",
"roman-numerals"
],
"Title": "Converting Roman numerals to decimal"
}
|
22876
|
<p>Could someone please help me make this code as professional as it can be? It works fine, but I feel there's a better way of doing this. I would really appreciate some guidance so I learn to code better.</p>
<pre><code> $(function () {
$('#subForm').submit(function (e) {
e.preventDefault();
$.getJSON(
this.action + "?callback=?",
$(this).serialize(),
function (data) {
if (data.Status === 400) {
$('#slidemarginleft p').append("" + data.Message);
$("#slidemarginleft p").append('<button class="css3button wee">OK&#44; I&#39;ll try again</button>');
$(function() {
var $marginLefty = $('.inner');
$marginLefty.animate({
marginLeft: parseInt($marginLefty.css('marginLeft'),10) == 0 ?
$marginLefty.outerWidth() : 0
});
});
//add click functionality for the button
$('#slidemarginleft button.wee').click(function() {
var $marginLefty = $('.inner');
$marginLefty.animate({
marginLeft: parseInt($marginLefty.css('marginLeft'),10) == 0 ?
$marginLefty.outerWidth() : 0
});
setTimeout(function() {
$('#slidemarginleft p').empty();}, 500);
});
} else { // 200
$(function() {
var $marginLefty = $('.inner');
$marginLefty.animate({
marginLeft: parseInt($marginLefty.css('marginLeft'),10) == 0 ?
$marginLefty.outerWidth() :
0
});
});
$('#slidemarginleft p').append("Thank you. " + data.Message);
}
});
});
if ($.browser.webkit) { $input.css('marginTop', 1); }
});
</code></pre>
<p>I have amended the code to this now (watching my indentation, adding a function, moving the default behaviour down but I think I have done it incorrectly as it doesn't work now):</p>
<pre><code>$(function () {
"use strict";
$('#subForm').submit(function (e) {
function moveDiv() {
var $marginLefty = $('.inner');
$marginLefty.animate({
marginLeft: parseInt($marginLefty.css('marginLeft'), 10) === 0 ?
$marginLefty.outerWidth() : 0
});
}
$.getJSON(
this.action + "?callback=?",
$(this).serialize(),
function (data) {
if (data.Status === 400) {
$('#slidemarginleft p').append(" " + data.Message);
$("#slidemarginleft p").append('<button class="css3button wee">OK&#44; I&#39;ll try again</button>');
$.change(moveDiv);
//add click functionality for the button
$('#slidemarginleft button.wee').click.change(moveDiv);
setTimeout(function () {
$('#slidemarginleft p').empty();
}, 500);
} else { // 200
$.change(moveDiv);
$('#slidemarginleft p').append("Thank you. " + data.Message);
}
});
e.preventDefault();
});
//if ($.browser.webkit) { $.browser.input.css('marginTop', 1); }
});
</code></pre>
<p>Here is the final code that works like a dream:</p>
<pre><code>$(function () {
"use strict";
$('#subForm').submit(function (e) {
function moveDiv() {
var $marginLefty = $('.inner');
$marginLefty.animate({
marginLeft: parseInt($marginLefty.css('marginLeft'), 10) === 0 ?
$marginLefty.outerWidth() : 0
});
}
$.getJSON(
this.action + "?callback=?",
$(this).serialize(),
function (data) {
if (data.Status === 400) {
$('#slidemarginleft p').append(" " + data.Message);
moveDiv();
//add click functionality for the button
$('#slidemarginleft button.wee').click(function () {
moveDiv();
setTimeout(function () {
$('#slidemarginleft p').empty();
}, 500);
});
} else { // 200
moveDiv();
$('#slidemarginleft p').append("Thank you. " + data.Message);
}
});
e.preventDefault();
});
//if ($.browser.webkit) { $.browser.input.css('marginTop', 1); }
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T16:56:55.790",
"Id": "35208",
"Score": "1",
"body": "Not sure where the bug is, but it looks much better already. I would just call `moveDiv()` instead of `$.change(moveDiv)`;"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T23:59:47.327",
"Id": "35224",
"Score": "0",
"body": "Thanks so much, tomdemuyt, that changed everything... Have a great day tomorrow. J"
}
] |
[
{
"body": "<p>This is typical jQuery mess. If you write a lot of code like this every day, consider switching to frameworks like Backbone or Ember.js which will make your life easier. Concerning this code, here are my remarks:</p>\n\n<ul>\n<li>Care more about indentation! All those callbacks are hard enough to read as they are.</li>\n<li>Only put <code>e.preventDefault();</code> at the end. If there's a bug in the JS code, the user will be able to use the fallback, that is submitting the form without JS.</li>\n<li>Don't build html elements with string concatenations, but write things like <code>$('<button/>').addClass('css3button')</code> and so on.</li>\n<li><p>Move this code into its own function:</p>\n\n<pre><code>var $marginLefty = $('.inner');\n$marginLefty.animate({\n marginLeft: parseInt($marginLefty.css('marginLeft'),10) == 0 ?\n $marginLefty.outerWidth() : 0\n});\n</code></pre></li>\n<li>More generally try to separate logic functions from display functions.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T15:08:03.663",
"Id": "35195",
"Score": "0",
"body": "Thank you so much for some guidance, tomdemuyt and Cygal...I really appreciate your time. I'm just learning (bodging) so this is infinately helpful in growing my knowledge. J"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T15:20:26.603",
"Id": "35197",
"Score": "0",
"body": "@James glad you like it! Consider upvoting questions that helped you now that you have 15 reputation. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T16:01:55.553",
"Id": "35202",
"Score": "0",
"body": "(I meant \"answers\".)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T16:07:28.183",
"Id": "35204",
"Score": "0",
"body": "hehe, I know, I have upvoted now right? Is the indentation better now? I have also put the function in a named function now but it doesn't work, any thoughts? I'm guessing I'm calling it incorrectly?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T14:06:29.050",
"Id": "22891",
"ParentId": "22879",
"Score": "2"
}
},
{
"body": "<p>In no particular order, these strike me as most worthy of solving:</p>\n\n<ul>\n<li><p>HTTP return codes, I would check for 200 and not-200, I would not assume that not-400 means 200 (when your web server dies, it will return 500's..)</p></li>\n<li><p>DRY Dont Repeat Yourself: the animation code seems copy pasted and could use a dedicated function</p></li>\n<li><p>Personally I would have the retry button be loaded with the html, with a 'hidden' css, less bytes, cleaner. Then you just have to unhide that button and voila..</p></li>\n<li><p>As Cygal said: fix your indentation</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T16:04:59.820",
"Id": "35203",
"Score": "0",
"body": "Hey thanks Tomdemuyt I'm gonna look to integrate your thoughts once I get this amended function code working, thanks for your advice. I have fixed the indentation haven't I? I have used JSLint to help."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T14:25:15.560",
"Id": "22892",
"ParentId": "22879",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T00:54:56.980",
"Id": "22879",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"json",
"form"
],
"Title": "jQuery form data"
}
|
22879
|
<p>I have a list of elements (well, nested lists of elements, really) that the user can reorder (using jQuery <code>sortable()</code>). A simplified view of the structure is something like:</p>
<pre><code><div class="contentList">
<div class="content" />
<div class="content">
<div class="contentListInner">
<div class="triggerContent" />
<div class="triggerContent" />
<div class="triggerContent" />
</div>
<div class="contentListInner">
<div class="triggerContent" />
<div class="triggerContent" />
<div class="triggerContent" />
</div>
</div>
<div class="content" />
<div class="contentListInner">
<div class="triggerContent" />
<div class="triggerContent" />
<div class="triggerContent" />
</div>
<div class="contentListInner">
<div class="triggerContent" />
<div class="triggerContent" />
<div class="triggerContent" />
</div>
<div class="content" />
<div class="content" />
</div>
</code></pre>
<p>Each <code>.content</code> inside of <code>.contentList</code> is sortable, and each <code>.triggerContent</code> inside of <code>.contentListInner</code> is also sortable (independently of the other sections). Each element within these sections is numbered according to its position <em>in its own list</em>. So to continue with the example above, the correct numbering is:</p>
<pre><code><div class="contentList">
<div class="content" /> <!-- 1 -->
<div class="content"> <!-- 2 -->
<div class="contentListInner">
<div class="triggerContent" /> <!-- 1 -->
<div class="triggerContent" /> <!-- 2 -->
<div class="triggerContent" /> <!-- 3 -->
</div>
<div class="contentListInner">
<div class="triggerContent" /> <!-- 1 -->
<div class="triggerContent" /> <!-- 2 -->
<div class="triggerContent" /> <!-- 3 -->
</div>
</div>
<div class="content" /> <!-- 3 -->
<div class="contentListInner">
<div class="triggerContent" /> <!-- 1 -->
<div class="triggerContent" /> <!-- 2 -->
<div class="triggerContent" /> <!-- 3 -->
</div>
<div class="contentListInner">
<div class="triggerContent" /> <!-- 1 -->
<div class="triggerContent" /> <!-- 2 -->
<div class="triggerContent" /> <!-- 3 -->
</div>
<div class="content" /> <!-- 4 -->
<div class="content" /> <!-- 5 -->
</div>
</code></pre>
<p>There's an additional complication, in that each <code>.triggerContent</code> can contain a new repetition of the entire structure, beginning again from <code>.contentList</code>. This nested content, however, is essentially spurious and should be ignored for all practical purposes. </p>
<p>Anyhow, to apply the numbering to the inner sections (and simultaneously ignore content in the aforementioned nested sections), I'm currently using the following code:</p>
<pre><code>$(".contentListInner").each(function() {
var taskNum = 1;
$(this).find(".triggerContent .taskTitle .left .number").each(function() {
if ($(this).parents(".triggerContent").length == 1) {
//FIXME: filtering on parents() is *slow*; find a faster approach
$(this).text("Task " + taskNum);
taskNum++;
}
});
});
</code></pre>
<p>This works, but as the <code>FIXME</code> notes I found that filtering using <code>.parents()</code> is incredibly slow. If I <em>don't</em> filter on <code>.parents()</code>, then what happens is that nested <code>.triggerContent</code> instances affect the count, and the numbering is incorrect (numbers jump like 1, 8, 17, 32, etc.). </p>
<p>Can anyone suggest an alternate approach that will produce the same results without the performance hit? </p>
|
[] |
[
{
"body": "<p>Try using the children selector: <a href=\"http://api.jquery.com/children/\" rel=\"nofollow\">http://api.jquery.com/children/</a>.</p>\n\n<p>This only retrieves the first set of nested items (one level down vs. find which goes all the way down). I'm not sure how you're nested exactly with your other classes, but it would be something like this.</p>\n\n<pre><code>$(\".contentListInner\").each(function() {\n $(this).children(\".triggerContent\").each(function(index, element) {\n $(element).text(\"Task \" + (index + 1));\n });\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T03:38:46.667",
"Id": "35231",
"Score": "0",
"body": "Thanks, I had to go through a couple sets of `children()` to get this to work with the actual page structure, but that still seems faster than filtering using the result of `parents()`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T06:36:47.190",
"Id": "22885",
"ParentId": "22881",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "22885",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T04:15:13.943",
"Id": "22881",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"optimization",
"performance"
],
"Title": "Optimize jQuery Iteration"
}
|
22881
|
<p>I'm trying to solve the <a href="http://en.wikipedia.org/wiki/Four_color_theorem" rel="nofollow">four color theorem</a> in Ruby.</p>
<p>A map is like this:</p>
<pre><code>ccaaaa
baaadc
babcdc
bbbcdc
abcccc
</code></pre>
<p>I have this, but it's slow. How can I make it better?</p>
<pre><code>#!/usr/bin/env ruby
class String
def visit
@visited = true
end
def visited?
@visited == true
end
def color
@color || "_"
end
def color=(newcolor)
@color = (newcolor)
end
def colored?
@color != nil
end
end
class ColoredMap
COLORS = %w(R G B Y)
def initialize(map)
@map = map
end
def color_map
# go through each square and color the region if not already colored
@map.each_with_index do |line, row|
line.each_with_index do |cell, col|
color_region(row, col, @map[row][col], {}) unless cell.colored?
end
end
end
def color_region(x, y, name, colors_seen)
# mark as visited
@map[x][y].visit
# pick a color that hasn't been seen
chosen_color = nil
# iterate over each neighboring cell - Recurse or note color
each_direction(x, y) do |xp, yp|
if (@map[xp][yp] == name) && !@map[xp][yp].visited? # same region
chosen_color = color_region(xp, yp, name, colors_seen) # recursive call
elsif @map[xp][yp].colored? # neighboring cell already colored
colors_seen[@map[xp][yp].color] = true
end
end
# set to the color already chosen or to a color not yet seen
@map[x][y].color = chosen_color || COLORS.select{|color| !colors_seen[color]}[0]
end
# Enumerator returning each available direction
def each_direction(x, y)
yield x-1, y if x > 0 #up
yield x, y-1 if y > 0 #left
yield x, y+1 if y < @map[x].length-1 #right
yield x+1, y if x < @map.length-1 #down
end
def to_s
@map.map do |line|
line.join + "\n"
end.join
end
def to_color
@map.map do |line|
line.map { |cell| cell.color }.join << "\n"
end.join
end
def to_debug
@map.map do |line|
line.map do |cell|
puts cell + cell.color + (cell.visited? ? "v" : ".") + " "
end
end.join
end
end
if __FILE__ == $PROGRAM_NAME
abort "NO ARGUMENTS GIVEN - map file must be provided" unless ARGV[0]
begin
mapfile = File.new(ARGV[0])
rescue
abort "Unable to open file '#{ARGV[0]}'"
end
# read in map file
regions = []
mapfile.each_with_index do |line, line_num|
regions[line_num] = line.chomp.split(//)
end
# color map
mymap = ColoredMap.new(regions)
mymap.color_map
# display colored map
puts mymap.to_color
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T12:23:46.087",
"Id": "35183",
"Score": "0",
"body": "How are you defining slow? The algorithm itself is optimal, and the code is fast! You could go for micro-optimizations, but how fast do you want the code to be? And for what map sizes? Have you consider writing this in a language like C?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T13:06:13.637",
"Id": "35186",
"Score": "0",
"body": "Here, it is `0,01s user 0,01s system 91% cpu 0,018 total` on an old Core 2 CPU. Profiling using ruby -rprofile shows that most of the time is spent in `each_direction`. But is it because of the tests? The Ruby VM? Something else? Hard to say! I can provide a few alternative ways to program `color_region` if you wish."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T14:32:45.580",
"Id": "35188",
"Score": "0",
"body": "Don't remove the question! It's not stupid, it can happen to anyone. You can simply say that it was indeed an I/O issue. No worries, everybody is here to learn and every programmer can be bitten by such issues."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T14:48:15.947",
"Id": "35190",
"Score": "0",
"body": "@Cygal Yeah Sorry, I was really thinking it was a stupid question after all but it might help others actually."
}
] |
[
{
"body": "<h1>I/O bottleneck</h1>\n\n<p>Your first bottleneck is not the algorithm. As you see from your <code>time</code> output (<code>0.29s user 0.11s system 10% cpu 3.723 total</code>), your program only spent 10% of his time in the CPU. This means that even if your program took 0ms, you would only gain 10%!</p>\n\n<p>You need to understand what takes that much time. Is it because the disk was busy? Or is it full? How long does it take when you run the program a second time? Is it faster? Is it still only spending 10% of its time in the CPU? Measure the time taken in the three main parts (read file, color map, display map) and see where it is slow (using <code>Time.now</code> which takes into account I/O latencies that the Ruby profiler does not).</p>\n\n<h1>Other bottlenecks</h1>\n\n<p><strong>Once the I/O bottleneck is solved</strong>, you can turn to other optimizations. They are called micro-optimizations since the algorithm doesn't change: you're trying to use a few tricks to make it faster. Since the your code was very fast with the provided map, I created a bigger one with a few copy/pastes and ran the standard Ruby profiler to see where it was spending time.</p>\n\n<pre><code>$ time ruby -rprofile colors.rb biggermap\n(colored map)\n% cumulative self self total\ntime seconds seconds calls ms/call ms/call name\n40.57 0.71 0.71 2082 0.34 10.12 ColoredMap#each_direction\n15.43 0.98 0.27 55881 0.00 0.00 Array#[]\n6.86 1.10 0.12 1141 0.11 0.14 Array#select\n6.86 1.22 0.12 2082 0.06 10.28 ColoredMap#color_region\n5.14 1.31 0.09 8219 0.01 0.03 String#colored?\n.....\n0.00 1.89 0.00 1 0.00 0.00 Kernel.puts\n0.00 1.89 0.00 1 0.00 1890.00 #toplevel\n\nruby -rprofile colors.rb biggermap 1,90s user 0,13s system 99% cpu 2,034 total\n</code></pre>\n\n<p>I don't know how the profiler works, so we need to be careful with the results. I <em>think</em> it works like gprof: it adds instrumenting code to every method call, and then reconstructs a table sorted by cumulative seconds which means that it's not too precise. Here, according to the profiler, 10ms/call is spent in each direction. I think it's mostly due to the yields.</p>\n\n<ul>\n<li>The first candidates for slowness are all those yields. They are elegant, but you can try to unroll the loop manually to see how it improves.</li>\n<li>The second candidate is the recursion. You can loop from (0,0) to (n,n) and look if there are existing neighbors with a color. If not, then assign a new color. This is essentially the same algorithm but this avoids having a huge call stack and only visits each node once.</li>\n<li>Now that your code is iterative, you can try to minimize the number of checks like <code>x > 0</code> and <code>y < ...</code>. If you find a simple way to predict that you are in the middle of the loop, then no checks are needed.</li>\n</ul>\n\n<p>The point is to run the profiler after each optimization and try to see if there is a new bottleneck arising.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T13:43:03.983",
"Id": "22890",
"ParentId": "22887",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "22890",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T10:47:25.910",
"Id": "22887",
"Score": "3",
"Tags": [
"optimization",
"ruby"
],
"Title": "Four color theorem"
}
|
22887
|
<p>Am I doing it fine?? Its only for setup not executed repeatedly</p>
<pre><code>CREATE TABLE #temp
(
id INT IDENTITY(1, 1),
name_file VARCHAR(500),
depth_tree VARCHAR(10),
is_folder_files VARCHAR(10)
)
/* xp_dirtree selects file from specific location
* depth_tree : depth of the search i.e. subfolders
* is_folder_files : selects folders only or files too
*/
INSERT INTO #temp(name_file, depth_tree, is_folder_files) EXEC xp_dirtree @source_path, 0, 1
-- Must concatenate to have permission for xp_cmdshell
SET @concatenate_string = 'RECONFIGURE EXEC sp_configure ''xp_cmdshell'',1 EXEC MASTER..xp_cmdshell '
-- Generating copy string in bulk
SELECT @cmd_string =
ISNULL(@cmd_string, '') +
CASE WHEN (LEN(REPLACE(t.name_file, @seperate_value, 1)) <> LEN(t.name_file)) -- if @seperate_value is not in image
THEN
(
SELECT CASE
WHEN REPLACE(t.name_file, 'Approach', 1) <> t.name_file OR REPLACE(t.name_file, 'CloseUp', 1) <> t.name_file -- if word Approach or CloseUp is not there in image
THEN
(
SELECT CASE
WHEN ((SELECT f.FaceID FROM Face f WHERE CAST(f.Notes AS VARCHAR) = SUBSTRING(t.name_file, 0, CHARINDEX(@seperate_value, t.name_file)-1)) IS NOT NULL) -- when extracted ID from image <> NotesID
THEN
(
@concatenate_string + '''copy ' + @source_path + t.name_file + ' '
+ @destination_path
+ (SELECT f.FaceID FROM Face f WHERE CAST(f.Notes AS VARCHAR) = SUBSTRING(t.name_file, 0, CHARINDEX(@seperate_value, t.name_file)-1)) -- Compares and gives the faceID
+ (SELECT CASE
WHEN REPLACE(t.name_file, 'Approach', 1) <> t.name_file THEN '-AS.jpg'' '
WHEN REPLACE(t.name_file, 'CloseUp', 1) <> t.name_file THEN '-BS.jpg'' '
ELSE
'Undefined'
END
)
)
ELSE
' '
END
)
ELSE
' '
END
)
ELSE
' '
END
FROM #temp t
SELECT @cmd_string + 'RECONFIGURE EXEC sp_configure ''xp_cmdshell'',0'
EXEC (@cmd_string)
</code></pre>
|
[] |
[
{
"body": "<p>I think it might be useful to separate comments about the code itself from comments about your general approach (here is your <a href=\"https://stackoverflow.com/questions/14919382/executing-xp-cmdshell-in-remote-server\">related question</a> on SO for reference).</p>\n\n<p>In general the code is fine, but there are some small points that you could consider:</p>\n\n<ul>\n<li>'concatenate' is a verb, not a noun, so <code>@concatenate_string</code> is a slightly awkward name for a variable; it would make more sense for a function or stored procedure.</li>\n<li>'seperate' is not correctly spelled, it should be 'separate'. I understand that English may not be your first language but it is extremely difficult to search code effectively if words are misspelled. In practice I know this isn't easy to check - because you may not even know you're making a mistake - but as a general suggestion, if you ever have a doubt about the spelling of a word while you're typing, you should take the time to check it.</li>\n<li>Code should not rely on undocumented language or platform features (<code>xp_dirtree</code> in this case) because they may change or disappear at any time</li>\n<li>You haven't included your variable declarations so I don't know what data type <code>@cmd_string</code> is, but you have declared <code>@concatenate_string</code> as <code>varchar</code> so I guess you may have done the same for <code>@cmd_string</code>. In this case <code>nvarchar</code> would be better: not only is it the <a href=\"http://msdn.microsoft.com/en-us/library/ms175046.aspx\" rel=\"nofollow noreferrer\">correct data type</a> for use with <code>xp_cmdshell</code> but it will avoid any issues with Unicode data. Note that when using <code>nvarchar</code> all literals <a href=\"http://msdn.microsoft.com/en-us/library/ms179899.aspx\" rel=\"nofollow noreferrer\">should be preceded with <code>N</code></a>: <code>N'literal'</code></li>\n<li>A <code>PRINT @cmd_string</code> statement would be useful for debugging</li>\n</ul>\n\n<p>As for your general approach:</p>\n\n<ul>\n<li>I understood from your SO question that this is a one-time script that will not be re-used, therefore you consider that using undocumented features (<code>xp_dirtree</code>) and features that by default only sysadmins can use (<code>xp_cmdshell</code>) is reasonable. In my experience, the idea that a one-time script can be written more 'casually' than other code is doubtful: 'one-time' scripts often turn out to be re-used or adapted for other purposes, and even genuinely one-time tasks are good practice for 'doing it right'. However everyone's situation is different, so this is only a general observation and you may have very good reasons for using <code>xp_cmdshell</code></li>\n<li>SQL Server is not a good tool for working with files. If I was going to use your approach, I would probably generate only the <code>copy</code> commands using SQL, save them as a .cmd file and run them outside the database. This would avoid messing with <code>xp_cmdshell</code> completely</li>\n<li><code>xp_cmdshell</code> can occasionally be useful but in general it has too many issues. In particular, since it executes under the SQL Server service account (for sysadmins) you may end up having to give that account permissions that it shouldn't have in order to make your script run. If you then forget to revoke the permissions afterwards, your service account can accumulate unnecessary permissions over time, to the point where it becomes a real risk</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-05T15:24:33.150",
"Id": "23488",
"ParentId": "22896",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T17:59:12.383",
"Id": "22896",
"Score": "-1",
"Tags": [
"sql",
"sql-server",
"t-sql"
],
"Title": "Using xp_cmdshell"
}
|
22896
|
<p>I have been trying to design a good data layer that will eventually be generated. I am wondering if I have missed anything. The basic architecture contains a service class that handles connecting and eventually transactions. I wrap the <code>IDbConnection</code> in the service class to make sure it gets disposed properly so that the user will not need to worry about that. Are there any drawbacks to wrapping the <code>IDbConnection</code> in a <code>using statement</code>?</p>
<p>Sample code:</p>
<pre><code>public abstract class SqlService
{
private readonly string _connectionString;
protected Service(string connectionString)
{
_connectionString = connectionString;
}
private IDbConnection CreateConnection()
{
var connection = new SqlConnection(_connectionString);
connection.Open();
return connection;
}
protected T Execute<IDbConnection, T>(Func<IDbConnection, T> query)
{
using(var connection = CreateConnection())
{
return query(connection);
}
}
protected T ExecuteTransaction<T>(Func<IDbConnection, IDbTransaction, T> query, IsolationLevel level)
{
return Execute(c =>
{
using (var transaction = c.BeginTransaction(level))
{
try
{
var result = query(c, transaction);
transaction.Commit();
return result;
}
catch (SqlException)
{
transaction.Rollback();
throw;
}
}
});
}
}
public interface ICanGetById<TEntity, TKey>
{
TEntity GetById(TKey id)
}
public interface IOrderService : ICanGetById<OrderDTO, int>
{
}
public sealed partial class OrderService : SqlService, IOrderService
{
public OrderService (string connectionString) : base(connectionString) { }
public OrderDTO GetById(int id)
{
var dynamicParameters = new DynamicParameters();
dynamicParameters.Add("@Id", id);
return Execute(c => c.Query<OrderDTO>(
"usp_OrderSelect",
dynamicParameters,
commandType: CommandType.StoredProcedure));
}
}
</code></pre>
|
[] |
[
{
"body": "<p>The drawback is that you are limiting the functionality of your service to perform one query per connection and you have no \"batch mode\"</p>\n\n<p>But maybe you can implement a query batching method!</p>\n\n<p>For this reason, the user of the database service perhaps should have the power to open and close the connection. Your SQLService could expose Open, Close, and Dispose.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T19:00:45.313",
"Id": "35213",
"Score": "0",
"body": "My vision of the batch insertion was using `DataTable` or maybe exposing a `SqlBulkCopy`. I might add query chaining if multiple queries per connection are necessary."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T18:57:03.520",
"Id": "22899",
"ParentId": "22898",
"Score": "1"
}
},
{
"body": "<blockquote>\n <p>I have been trying to design a good data layer that will eventually be generated. I am wondering if I have missed anything</p>\n</blockquote>\n\n<p>You have missed the Entity Framework and/or NHibernate :), both of them are good data layers that are mature enough. If you want to have a <em>good</em> data layer - the best you can do is start using one of them, and stop designing a wheel. Out of those two I would prefer NHibernate, but Entity Framework may be easier for beginner.</p>\n\n<p>Concerning your code - properties should not represent factories (like you do in <code>Connection</code>), in other words repeating calls to the property getter is assumed to return the same value. To fix that replace <code>Connection</code> property with <code>CreateConnection()</code> method</p>\n\n<p>Also you are missing the notion of transactions and unit-of-work here, and a whole object mappings story.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T13:05:43.880",
"Id": "35265",
"Score": "0",
"body": "EF and Nhibernate don't take a data-centric approach to ORM and they want to force their conventions and idioms how you communicate with the database. In order to address those shortfalls I wanted to create a service layer that is mostly decoupled by utilizing stored procedures and views."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T13:49:58.377",
"Id": "35270",
"Score": "1",
"body": "Both ORMs allow you to use stored procedures (but you loose part of flexibility in this case). Obviously any framework forces you to use some kind of conventions. \"I could do it better\" approach is viable, but very unlikely. You may optimize it for a certain very specific scenario, but bigger issues will appear when you try to step out of those specifics, and it will be too late to switch."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T14:19:08.890",
"Id": "35271",
"Score": "0",
"body": "It is true NH and EF have support for stored procedures, but they feel clunky and involve a lot intervention to use them. I would rather have my DTOs generated off stored procedures and views and have all the mapping done against the views and stored procedures."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T15:05:02.613",
"Id": "35272",
"Score": "0",
"body": "The fact that you're asking a question about `using` statement suggests that you don't have a lot of experience with .NET, thus most likely you don't realize all the complexity, drawbacks and support cost of [building your own ORM](http://lostechies.com/jimmybogard/2012/07/24/dont-write-your-own-orm/)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T15:34:52.743",
"Id": "35274",
"Score": "0",
"body": "The fact that you're calling out my inexperience as a reason for discouragement shows that's there's a lack of understanding that NH and EF don't meet my requirements which is why I'm using Dapper + Code Generation."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T22:20:08.273",
"Id": "22905",
"ParentId": "22898",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "22899",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T18:48:35.483",
"Id": "22898",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Is wrapping the service layer worthwhile?"
}
|
22898
|
<p>I'm creating a system and I'm using EF with Linq. I create my Model (<strong>.edmx</strong>) and using it, I generated my database and my classes. Like the Usuario (user in Portuguese going to keep the names in Portuguese to avoid some misleading).</p>
<pre><code>namespace SistemaBox.Model
{
public partial class Usuario
{
public int Codigo { get; set; }
public string Nome { get; set; }
public string Sobrenome { get; set; }
public string Senha { get; set; }
public DateTime DataCriacao { get; set; }
public DateTime DataUltimoLogin { get; set; }
public virtual PermissaoGrupo CodigoPermissaoGrupo { get; set; }
}
}
</code></pre>
<p>After this, I create my controller class:</p>
<pre><code>namespace SistemaBox.Controller
{
[Serializable]
public class ZUsuario : Usuario
{
String connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
/// <summary>
/// Cadastro e edição
/// </summary>
public void Cadastro()
{
if (Codigo != null && Codigo > 0)
{
// Cadastro
using (DataContext db = new DataContext(connString))
{
Table<Usuario> Usuarios = db.GetTable<Usuario>();
var query =
from usr in Usuarios
where usr.Nome == "Test"
select usr;
foreach (var usr in query)
Console.WriteLine("id = {0}, City = {1}", usr.Codigo, usr.Nome);
}
}
else
{
// Edição
}
}
}
}
</code></pre>
<p>Please ignore the fact that the class name is record and I'm doing a select. It is just for tests.</p>
<p>My question is about the controller. Is the right way to declare the connection <code>String</code> as global:</p>
<pre><code>String connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
</code></pre>
<p>and use the <code>using</code> like I'm doing?</p>
|
[] |
[
{
"body": "<p>Your connection string is actually a private class member. I would probably put private keyword explicitly to make it clear.</p>\n\n<p>connString is going to be initialized each time the class instance is created. But the connection string is not going to change in run time so it worth to make connStrint a static member.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T10:25:13.073",
"Id": "22956",
"ParentId": "22900",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "22956",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T19:41:47.257",
"Id": "22900",
"Score": "1",
"Tags": [
"c#",
"linq",
"controller"
],
"Title": "Linq to sql performance"
}
|
22900
|
<p>I'm basically trying to write a helper function that reads a whole file and returns the data and the number of bytes read.</p>
<p>Can you tell me if is correctly written and used?</p>
<pre><code>#include <iostream>
static char * ReadAllBytes(const char * filename, int * read)
{
ifstream ifs(filename, ios::binary|ios::ate);
ifstream::pos_type pos = ifs.tellg();
int length = pos;
char *pChars = new char[length];
ifs.seekg(0, ios::beg);
ifs.read(pChars, length);
ifs.close();
*read = length;
return pChars;
}
int _tmain(int argc, _TCHAR* argv[])
{
const char * filename = "polar00.map";
int read ;
char * pChars = ReadAllBytes(filename, &read);
delete[] pChars;
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>A few things I would do differently:</p>\n<pre><code>static char * ReadAllBytes(const char * filename, int * read)\n{\n ifstream ifs(filename, ios::binary|ios::ate);\n ifstream::pos_type pos = ifs.tellg();\n\n // What happens if the OS supports really big files.\n // It may be larger than 32 bits?\n // This will silently truncate the value/\n int length = pos;\n\n // Manuall memory management.\n // Not a good idea use a container/.\n char *pChars = new char[length];\n ifs.seekg(0, ios::beg);\n ifs.read(pChars, length);\n\n // No need to manually close.\n // When the stream goes out of scope it will close the file\n // automatically. Unless you are checking the close for errors\n // let the destructor do it.\n ifs.close();\n *read = length;\n return pChars;\n}\n</code></pre>\n<p>How I would do it:</p>\n<pre><code>static std::vector<char> ReadAllBytes(char const* filename)\n{\n std::ifstream ifs(filename, std::ios::binary|std::ios::ate);\n std::ifstream::pos_type pos = ifs.tellg();\n\n if (pos == 0) {\n return std::vector<char>{};\n }\n\n std::vector<char> result(pos);\n\n ifs.seekg(0, std::ios::beg);\n ifs.read(&result[0], pos);\n\n return result;\n}\n</code></pre>\n<p>Note:</p>\n<pre><code>static std::vector<char> ReadAllBytes(char const* filename)\n</code></pre>\n<p>It may seem like an expensive copy operation. But in reality NRVO will make this an in-place operation so no copy will take place (just make sure you turn on optimizations). Alternatively pass it as a parameter:</p>\n<pre><code>static void ReadAllBytes(char const* filename, std::vector<char>& result)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T07:53:30.470",
"Id": "35244",
"Score": "2",
"body": "I love this answer, never thought of referencing `vector[0]` to access the raw memory block underneath it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T16:20:06.007",
"Id": "35278",
"Score": "1",
"body": "This is very typical when using C++ containers and calling C code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T03:06:44.770",
"Id": "35304",
"Score": "0",
"body": "I typically used the `new unsigned char[size]` approach, which meant I had to ensure the cleanup afterwards. This is much nicer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T12:12:45.063",
"Id": "35334",
"Score": "0",
"body": "Thank you, it's much simpler and cleaner. I thought of using array<char> but since it is (from what I've read) allocated on the stack it was not a good idea as my data wouldn't necessarily be small. Well, I've forgot to apply this again : \"premature optimization is the root of all evil\" ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-18T17:38:48.343",
"Id": "178056",
"Score": "13",
"body": "An alternative to `&vector[0]` is [`vector.data()`](http://en.cppreference.com/w/cpp/container/vector/data)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-23T07:37:27.347",
"Id": "193089",
"Score": "2",
"body": "What about error checking. Both opening and reading might fail."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-23T11:42:26.163",
"Id": "193121",
"Score": "0",
"body": "@Zitrax: My answer is based on the context of the original question where no error checking is done. In real code you would do error checking, but there is not enough context for me to add it here as it will depend on how and where this code is used."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-28T14:39:38.210",
"Id": "249048",
"Score": "3",
"body": "In C++11, you can also get to the vector's memory by calling `vector.data()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-12T12:04:34.087",
"Id": "378232",
"Score": "0",
"body": "You actually can't use `tellg()` for the size of a file; it only kind-maybe-sometimes works. See the discussion [here](https://stackoverflow.com/questions/22984956/tellg-function-give-wrong-size-of-file/22986486#22986486)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-12T15:10:56.687",
"Id": "378266",
"Score": "0",
"body": "@einpoklum In reality this is going to work as expected in almost all situations. If you are worried about portability (which on non standard or minor distributions can be an issue) you can easily set up unit test to validate the functionality works as expected (autotools are your friends learn to use them so you can validate standard behaviors of libraries). I agree with the link that theoretically there may be an issue."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-12T15:12:24.210",
"Id": "378267",
"Score": "0",
"body": "But the proposed solution looks a bit hacky. I would have to test it but would not ignore() force a full scan of the file to reach the end? Also the suggested solution also suffers from the same problem suggested of `tellg()` when the file is opened in \"Text Mode\". I think a better solution may be to ask the filesystem for the size."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-12T15:19:40.303",
"Id": "378270",
"Score": "0",
"body": "@einpoklum You will also note that author also makes the same point I do: `in practice, on Unix systems, the value returned will be the offset in bytes from the beginning of the file, and under Windows, it will be the offset from the beginning of the file for files opened in binary mode.`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-15T14:33:25.827",
"Id": "530663",
"Score": "0",
"body": "Do NOT use `&vector[0]` if it may be empty."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-18T07:00:48.880",
"Id": "530807",
"Score": "0",
"body": "Well, vector[0] is non-existent in an empty vector so accessing it seems to be UB; and debugging implementations may throw an exception for that. And I remember having problems with it in the past."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-18T17:08:13.797",
"Id": "530849",
"Score": "1",
"body": "@HansOlsson: No. The standard guarantees you can take the address of one past the end."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-19T06:36:44.253",
"Id": "530886",
"Score": "0",
"body": "The problem is that taking the address of doesn't cancel the dereference in terms of UB and error checking. I used to think that myself - and got problems and thus changed to using .data and similar constructs that avoid this. Would you write &*((int*)(0)) ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-19T14:42:38.070",
"Id": "530928",
"Score": "0",
"body": "A Principal Engineer at Microsoft working on compilers thinks differently in the following answer: https://stackoverflow.com/questions/6485496/how-to-get-stdvector-pointer-to-the-raw-data"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-19T16:16:37.100",
"Id": "530941",
"Score": "0",
"body": "@HansOlsson I don't think we are going to persuade each other that we are wrong. I am confident in my reading of the standard. You have a firm stand on your position further discussion seems to be pointless."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-19T18:50:16.653",
"Id": "530956",
"Score": "0",
"body": "The final sentence (for .data() ) is \"The advantage of this member function is that it is okay to call it even if the container is empty.\" that's a pretty direct indication that &something[0] that is specifically stated to work for non-empty vector doesn't work for empty ones. It is also directly stated that it produces undefined results in item 16 in Scott Meyers \"Effective STL\" \nSo, at least I hope to convince some to be more careful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-19T21:00:17.850",
"Id": "530976",
"Score": "1",
"body": "@HansOlsson: [n4892](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/n4892.pdf) S`ection: 22.3.11.4 Data [vector.data]` This covers the fuction: `constexpr T* data() noexcept;` The requirement of this function is: `Returns: A pointer such that [data(), data() + size()) is a valid range.` There is no precondition on it not being empty. This has probably been updated since Scott M wrote his book."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-20T20:09:10.547",
"Id": "531080",
"Score": "0",
"body": "The point: The advantage of using `&something[0]` is that it works for all contiguous containers (and consistency is very important to maintainable code). Which includes C-Arrays; where `data()` does not work. And though `&something[0]` was not always guaranteed to work (the update to the standard was made in C++14) it worked in practice on all major compilers since C++11 (which was why the standard update was so simple)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-21T07:59:32.660",
"Id": "531111",
"Score": "0",
"body": "Don't use &vector[0] for possibly empty data:\nThe function std::vector::data() was added explicitly because &something[0] gave UB for empty vectors (name chosen based on as std::array that can be used for C-style arrays). http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#464\nThus I don't see that my other comments are needed.\n\nThe assumption that &something[0] is valid hinges on the assumption that taking the address of a non-dereferencable iterator is ok. However, only iterators in the range [begin,end) are defined as dereferencable in 24.2.1§5, in this case the range is empty"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-21T22:41:38.553",
"Id": "531173",
"Score": "0",
"body": "Except that for an empty vector, where begin()==end() and thus *begin() is not valid as begin() is not dereferenceable, or to quote about end() \"Such a value is called a past-the-end value. Values of an iterator i for which the expression *i is defined are called dereferenceable. The library never assumes that past-the-end values are dereferenceable.\" As for compilers: g++ -D_GLIBCXX_DEBUG fails on it as does Visual Studio 2019 debug-builds. So, if you don't care about empty vectors, or don't care about running your code with a debugger it may work; but that ends my interaction here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-24T10:41:34.143",
"Id": "531333",
"Score": "0",
"body": "The standard seem to be making the same \"mistake\": [iterator.iterators] table 94: Defines that `operator*` for iterator as \"`*r` Requires: r is dereferenceable.\" So, if you want code that works even for empty vectors, especially in debug-builds use `.data()` for vector. And that finally ends my interaction."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-25T17:17:41.557",
"Id": "531425",
"Score": "1",
"body": "@HansOlsson You are correct: **I was wrong**. You made me re-read all the way down to the definition of `contiguous_iterator Concept`. Getting the address for an iterator of one past the end is only defined if there exists a dereferencable iterator into the container. With an empty vector this does not exist so as you pointed out this is UB for empty vectors."
}
],
"meta_data": {
"CommentCount": "25",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-02-19T22:36:46.743",
"Id": "22907",
"ParentId": "22901",
"Score": "27"
}
},
{
"body": "<p>I would wrap the native memory-mapped file functionality instead. It’s available on all major platforms. In all cases it will be more efficient than any “read the whole file” code would be. If you absolutely need to keep the file’s contents yet close the file, you can then initialize a vector from the memory-mapped byte range, and close the range afterwards. It will still be faster and less cumbersome than reading the file.</p>\n<p>Typically, you won’t have to bother with errors once the file is open and mapped: read errors become page faults. You can of course trap those if needed, but if there’s no viable way for the application to proceed if the file cannot be read after successfully mapping it, then terminating is a good option. But, to be flexible, I’d ensure that while the file is mapped, any I/O errors that turned into page faults get caught and handled appropriately per the preference of the user of your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T16:54:07.753",
"Id": "530426",
"Score": "0",
"body": "Boost provides an abstraction of memory-mapped files, so if that's available to you, there's no need to write your own code for the various APIs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T17:59:59.507",
"Id": "530431",
"Score": "0",
"body": "On 32-bit systems you can only map about 2 GB this way. Also, for small files, this might actually be less efficient, as setting up the page tables and handling the initial page faults when accessing the mapped range for the first time isn't free."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-13T15:27:51.153",
"Id": "530495",
"Score": "0",
"body": "If the normal handle-based file I/O is implemented in terms of memory mapping for local files, then the page faults and page tables etc. is not any worse than it does anyway. The big deal is the overhead of keeping an open file if it's a small amount of data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-13T15:28:32.743",
"Id": "530496",
"Score": "0",
"body": "If the file to be slurped is not on the local file system, memory mapping may not work or be very inefficient. So you need a fallback for reading remote files anyway."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T15:27:40.217",
"Id": "268914",
"ParentId": "22901",
"Score": "2"
}
},
{
"body": "<h1>Missing error checking</h1>\n<p>Both your code and the code from Martin York's answer don't perform any error checking. Things can go wrong both when <em>opening</em> a file (it might not exist, you might not have the right permissions, and so on), and when <em>reading</em> from a file (less likely at this point, but read errors are still possible). You want to ensure two things:</p>\n<ul>\n<li>Your program doesn't crash while trying to read a file.</li>\n<li>Any errors are not silently ignored, as this might cause your program to give incorrect results without you knowing it.</li>\n</ul>\n<p>I recommend checking that <code>ifs.eof() == true</code> after reading all the data. If it's not, then you didn't succesfully reach the end of the file, and then report the error in some way; for example, <code>throw</code> an exception or use a <a href=\"https://en.cppreference.com/w/cpp/utility/optional\" rel=\"nofollow noreferrer\"><code>std::optional</code></a> for the return value.</p>\n<p><code>tellg()</code> will return <code>-1</code> in case of an error. When trying to allocate memory for the result, that <code>-1</code> might be cast to an unsigned <code>std::size_t</code> and become a huge number, causing the memory allocation to fail. This might cause your program to crash. So check the return value of <code>tellg()</code> before using it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T18:10:57.613",
"Id": "268922",
"ParentId": "22901",
"Score": "3"
}
},
{
"body": "<p>I would amend <a href=\"/a/22907/75307\">Martin York's answer</a>:</p>\n<ul>\n<li>use <code>std::filesystem::path</code> (standard as of C++17; part of Boost before that) instead of <code>std::string</code> for the parameter.</li>\n<li>use <code>vector::data</code> instead of taking the address of the first element.</li>\n</ul>\n<p>I'm also a little worried about using <code>ate</code> mode but then seeking back to the beginning. Is this guaranteed to only jump back to the end on any <em>write</em> operation, but allow me to read from any position? Also, what if the file is read-only? I'd rather open for reading only, not specify that I'll be writing to the end because I don't need write access at all!</p>\n<p>Reading the docs, I see that <code>ate</code> just seeks right after opening, as distinct from <code>app</code> which forces writes on the end (even though it stands for <em>append to end</em>). It can be combined with other flags without otherwise affecting the meaning. So, use</p>\n<p><code>std::ios::in|std::ios::binary|std::ios::ate</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-14T06:59:13.537",
"Id": "530542",
"Score": "0",
"body": "Don't be too harsh on that first point - that `std::filesystem` didn't exist in 2013. It's a good suggestion for updating to make it more type-safe in modern contexts, though. :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-14T07:01:04.680",
"Id": "530543",
"Score": "0",
"body": "And `std::ios::ate` (\"open __at e__ nd\") doesn't imply writing at all - and `std::ifstream` constructor always includes `std::ios::in`, so no need to redundantly specify that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-13T15:39:54.897",
"Id": "268954",
"ParentId": "22901",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "22907",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T19:42:14.297",
"Id": "22901",
"Score": "16",
"Tags": [
"c++",
"file-system"
],
"Title": "Reading all bytes from a file"
}
|
22901
|
<p>Example that could be turned into a button to view user's public ftp where initial page is "<a href="http://user.school.edu/" rel="nofollow">http://user.school.edu/</a>":</p>
<pre><code>javascript:(function( {
var h,i,t;
h=window.location.hostname;i=h.IndexOf('.school.edu');t=h.substring(0,i);
window.location.assign("ftp://ftp.school.edu/public/"+t
});
</code></pre>
<p>Help me refine this idea, please.</p>
|
[] |
[
{
"body": "<pre><code>(function () {\n var h = window.location.hostname;\n window.location = 'ftp://ftp.school.edu/public/' + h.substring(0, h.indexOf('.'));\n}());\n</code></pre>\n\n<ul>\n<li><p>In JS, you can merge declaration and definition. The compiler takes care of splitting them to declaration and definition during compile.</p></li>\n<li><p>Since <code>indexOf</code> returns the first occurrence of a string, you can use the first dot (<code>.</code>) instead of <code>.school.edu</code>. Both will return the same value, but using a single dot is shorter.</p></li>\n<li><p>You can change the browser location by assigning a url to <code>window.location</code> than using <code>assign()</code>. Although using <code>assign()</code> might be a more proper way to do it, changing the value of <code>window.location</code> is still shorter</p></li>\n<li><p>I JS, single and double quotes don't matter. However, single quotes look cleaner.</p></li>\n<li><p>I also prefer the comma-separated <code>var</code> notation since it will save you retyping <code>var</code> every time. However, don't ever forget the commas.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T12:21:14.003",
"Id": "35258",
"Score": "0",
"body": "`Both will return the same value` It won't, if you have address like `http://foo.bar.school.edu/`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T12:35:31.780",
"Id": "35260",
"Score": "0",
"body": "@LieRyan look at the OP's post. The url pattern given was `user.school.edu` and nothing more."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T13:36:44.717",
"Id": "35268",
"Score": "0",
"body": "The comma-separated approach does look much cleaner."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T12:16:41.073",
"Id": "22923",
"ParentId": "22903",
"Score": "0"
}
},
{
"body": "<p>It can also be written in \"one line\" using regular expression:</p>\n\n<pre><code>window.location = window.location.hostname.replace(\n /^(.*)\\.school\\.edu$/,\n \"ftp://ftp.school.edu/public/$1\"\n);\n</code></pre>\n\n<p>I believe in this case regular expression expresses the intent more clearly than using indexOf and string slicing, though tastes may vary.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T13:17:03.133",
"Id": "35267",
"Score": "0",
"body": "But then, regular expressions for this task is a bit overkill."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T13:38:10.337",
"Id": "35269",
"Score": "0",
"body": "Regex was not the way I was going, but it does what I want in a geeky-elegant kind of way. I also like that it maintains the replace method so that history is intact. I'm going to run with this. Thank you."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T12:35:51.720",
"Id": "22924",
"ParentId": "22903",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "22924",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T21:21:45.877",
"Id": "22903",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Parse and Redirect to uri in Javascript"
}
|
22903
|
<p>I have a simple servlet which merely serves some cached data back to the user. I also have a background thread which runs at fixed intervals to refresh the cached data. Is this a reasonable implementation?</p>
<pre><code>@WebServlet("/CachingServlet")
public class CachingServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static ScheduledExecutorService backgroundExecutor;
private static String cachedData = "";
public CachingServlet() {
super();
}
@Override
public void destroy() {
backgroundExecutor.shutdown();
super.destroy();
}
@Override
public void init() throws ServletException {
backgroundExecutor = Executors.newSingleThreadScheduledExecutor();
backgroundExecutor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
//implemention of fetchNewData() omitted for clarity
cachedData = fetchNewData();
}
}, 0, 1, TimeUnit.HOURS);
super.init();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println(cachedData);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T23:25:09.423",
"Id": "35222",
"Score": "0",
"body": "Seems reasonable to me."
}
] |
[
{
"body": "<p>you needn't call <code>super.init();</code> <a href=\"http://docs.oracle.com/javaee/6/api/javax/servlet/GenericServlet.html#init%28%29\" rel=\"nofollow\">according to docs</a>, it is a NOP . but as a rule calling initializers of some superclass at the beginning of the overriding method will save you headache in the future.</p>\n\n<p><code>backgroundExecutor</code> shouldn't be static. suppose you have multiple instances of this servlet in an application. destroying <strong><em>any</em></strong> one of those servlets shuts down <strong><em>the last created</em></strong> updater. what happens to the rest?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T16:18:58.823",
"Id": "35277",
"Score": "0",
"body": "Excellent point (regarding static). Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T16:10:53.217",
"Id": "22930",
"ParentId": "22906",
"Score": "2"
}
},
{
"body": "<ol>\n<li><p>There is no guarantee that the <code>doGet()</code> method will see the modified value of <code>cachedData</code>. You should synchronize the access of this field (both read and write) since the container calls the <code>doGet()</code> on separate threads than the <code>backgroundExecutor</code>'s thread. An <code>AtomicReference</code> seems the easiest solution here.</p>\n\n<pre><code>private final AtomicReference<String> cachedDataRef = \n new AtomicReference<String>(\"\");\n\n...\n\n\npublic void run() {\n // implemention of fetchNewData() omitted for clarity\n final String newData = fetchNewData();\n cachedDataRef.set(newData);\n}\n\n...\n\nout.println(cachedDataRef.get());\n</code></pre></li>\n<li><p>I'd create two local variables for the <code>0</code> and <code>1</code> magic numbers:</p>\n\n<pre><code>int initialDelay = 0;\nint period = 1;\n</code></pre>\n\n<p>Reference: <em>Chapter 6. Composing Methods</em>, <em>Introduce Explaining Variable</em> in <em>Refactoring: Improving the Design of Existing Code</em> by Martin Fowler:</p>\n\n<blockquote>\n <p>Put the result of the expression, or parts of the expression, \n in a temporary variable with a name that explains the purpose.</p>\n</blockquote>\n\n<p>And <em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G19: Use Explanatory Variables</em>.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-23T21:21:17.887",
"Id": "35574",
"Score": "0",
"body": "Thanks @Palacsint. Lack of synchonization was something I spotted myself after posting this and I have already added synchonization to the getting and setting of the cached data, so good spot. Also agree with your second point, but would make them static final constants and probably rename period, though not sure what's best: 'ONE_HOUR' possibly. Anyway, thanks for taking the time to look at my code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-22T18:31:09.227",
"Id": "23037",
"ParentId": "22906",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "22930",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T22:21:01.553",
"Id": "22906",
"Score": "1",
"Tags": [
"java",
"multithreading",
"servlets"
],
"Title": "Correct implementation for background task execution in web application?"
}
|
22906
|
<p>I tried to refactoring someone else's code and I found that there is alot of this pattern</p>
<pre><code>def train(a, b, c, d, e, f, g, h, i, j, k): #Real code has longer name and around 10-20 arguments
x = Dostuff()
y = DoMoreStuff(b,c,d,e,f,g,h,x)
z = DoMoreMoreStuff(a,b,d,e,g,h,j,y)
def DoMoreStuff(b,c,d,e,f,g,h):
DoPrettyStuff(b,c,d,e,f,g,h) # The actually depth of function call is around 3-4 calls
</code></pre>
<p>I though that it would it be better to collect all of that a,b,c,d into one dictionary. I got this idea when I was reading about rail rack's middleware. </p>
<pre><code>env = {"a":1, "b", 2.......}
def train(env):
x = Dostuff()
y = DoMoreStuff(env.update({"x":x}))
z = DoMoreMoreStuff(env.update({"y":y}))
def DoMoreStuff(env)
DoPrettyStuff(env)
</code></pre>
<p>But I am not sure if there is any downside about this approach ? If it does help, every function here has a side-effect.</p>
<p>EDIT: For more clarification. I think most of my problem are about the propagation of variables. The call pattern has very deep and wide hierarchy. Any further suggestion about this one ?</p>
<pre><code>def main(a,b,c,d,e,f,g,h,i,j,k,l,m....z):
Do(...)
#maybe other function()
def Do(a,b,c,d,e,f,g,h,i,j,k,l):
Do1(d,e,f,g,h,i,j,k,l)
def Do1(d,e,f,g,h,i,j,k,l)
Do2(f,g,h,i,j,k,l)
def Do2(f,g,h,i,j,k,l)
Do3(f,g,h,i)
Do4(j,k,l)
</code></pre>
<p>EDIT 2: Well, my intention is that I want the code more easier to read and followed. Performance in python code does not matter much since the program spend most of the time on SVM and machine learning stuff. If anyone interest and don't mind a very dirty code that I still working on it. Here is the real code <a href="https://github.com/yumyai/TEES/tree/30b3aeaab011e30dcdc3c1151062697861ddcae1" rel="nofollow">https://github.com/yumyai/TEES/tree/30b3aeaab011e30dcdc3c1151062697861ddcae1</a> </p>
<p>The code start with train.py (training model), classify.py (classify using model). In this case I'll use train.py as an example.
<a href="https://github.com/yumyai/TEES/blob/30b3aeaab011e30dcdc3c1151062697861ddcae1/train.py" rel="nofollow">https://github.com/yumyai/TEES/blob/30b3aeaab011e30dcdc3c1151062697861ddcae1/train.py</a>: line 136 where it start to call everything under it and pass a gigantic arguments to. These arguments are pass down to <a href="https://github.com/yumyai/TEES/blob/30b3aeaab011e30dcdc3c1151062697861ddcae1/Detectors/EventDetector.py" rel="nofollow">https://github.com/yumyai/TEES/blob/30b3aeaab011e30dcdc3c1151062697861ddcae1/Detectors/EventDetector.py</a>: line 49. And then EventDetector pass these argument to it members (line 24-28).</p>
<p>Some argument is reused throughout the code, for example, def train(.......exampleStyles). exampleStyles is passed around to several member that is called by train. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T07:31:48.753",
"Id": "35241",
"Score": "5",
"body": "If you asked me, if you have a function that requires that many independent parameters, it's trying to do too much. You could also consider changing it so the function uses keyword arguments, than way you can switch between the two forms easily."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T07:43:00.497",
"Id": "35243",
"Score": "0",
"body": "Thanks for the suggestion. I was planning to break down function into bite-side too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T10:21:09.700",
"Id": "35253",
"Score": "2",
"body": "I really would like to see your real methods signatures. I'm pretty sure we could help you in more detail if we know what your are going to do."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T10:54:34.020",
"Id": "35254",
"Score": "0",
"body": "@mnhg I want to make code more easier to follow and easy to read. This code is actually a NLP analysis pipeline that I fork from and several parameters/arguments are either\n1. Doing to many thing at one method as others suggest\n2. Keep everything in sync, because it rely alot on external file/arguments. Each function is bloat with argument mostly because of this.\nI'll EDIT my question to post a my code then."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T11:00:50.190",
"Id": "35255",
"Score": "0",
"body": "Pipeline is the keyword. If you follow a data-driven approach you should easily be able to pack your data in a kind of a work package which you can pipe throw your line. Has this to be parallelisable?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T11:17:49.470",
"Id": "35256",
"Score": "0",
"body": "Where can I learn more about this \"data-driven approach\" ? Parallelism is not needed but preferred, if it does not take much time or too hard. I haven't full understand the whole code yet but I think most of the function could run as a parallel pipeline."
}
] |
[
{
"body": "<p>Well, the answer depends on the meaning of the variables. If they are related (and they should be, since the same functions uses them!), then it's a good idea to group them in a dictionary since it makes the code more readable.</p>\n\n<p>However, even if it makes sense to group all variables into a dict, your <code>env.update()</code> solution is not satisfying because it is unlikely that <code>x</code> and <code>y</code> really belong to <code>env</code>. What have you gained here? Function definitions may be shortened, but you only moved the problem to make it less visible. The next developer will be very surprised to see that you simply replaced function arguments by a dict without thinking about readability. This does not respect the <a href=\"http://en.wikipedia.org/wiki/Principle_of_least_astonishment\" rel=\"nofollow\">Principle of least astonishment</a> and probably others too.</p>\n\n<p>You should try to group variables that really belong together, make use of <a href=\"http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/\" rel=\"nofollow\">*args and **kwargs</a> whenever it makes sense, and otherwise split/reorganize functions that take too much unrelated arguments: they probably break the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">Single responsibility principe</a> anyway.</p>\n\n<p>Now, be careful when refactoring such functions, make sure you really understand them, and write unit tests or integration tests before changing them to make sure you don't make the code worse than before.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T07:39:05.543",
"Id": "35242",
"Score": "0",
"body": "From my understanding. You suggest that updating env should be avoid. How about I use DoMoreStuff(env, x) instead ? That should do it since most functions in the code usually has some \"core\" argument that keep repeating throughout.\nFor about grouping some similar argument together, sadly, it is already grouped and still gigantic. You also hit a nail in the head about breaking a \"single responsibility principle\", that was what I called a \"side-effect\". And yes, I am about to refactor that out too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T08:07:33.103",
"Id": "35246",
"Score": "0",
"body": "Yeah, `DoMoreStuff(env, x)` should be OK if it makes sense."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T07:02:50.177",
"Id": "22912",
"ParentId": "22911",
"Score": "3"
}
},
{
"body": "<p>Sending parameters in an array/dictionary/hashmap is critical, as you have to take care that every necessary value is filled. You will have to document the content and the next developer has to read it. With parameters this is done by your compiler.</p>\n\n<p>You should concentrate on getting rid of some parameters in an other way. As you talk about some \"core\" arguments it seem that you might want to move your methods into a class, or at least some of your parameters should be grouped in a class/some classes. </p>\n\n<p>Sometime your are fetching values from an object and sending multiple parameter instead of sending the object itself. </p>\n\n<hr>\n\n<p>Reading about <a href=\"http://parlab.eecs.berkeley.edu/wiki/_media/patterns/pipeline-v1.pdf\" rel=\"nofollow noreferrer\">pipelines</a> might be interesting.</p>\n\n<hr>\n\n<p>Checking your real code this looks more like a configuration object that need to be extracted. You could create this object with a <a href=\"https://codereview.stackexchange.com/questions/21555/php-pdo-factory-classes/21564#21564\">builder</a> to address the issues from my first paragraph.</p>\n\n<p>In addition to that you should try to split you methods into smaller parts.</p>\n\n<p><strong>But first of all you need tests</strong>. I didn't found any in your repo?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T15:43:46.293",
"Id": "35276",
"Score": "0",
"body": "You got me there about the test. I \"forgot\" to do that... I should did it from the start, shouldn't I."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T05:58:18.403",
"Id": "35322",
"Score": "0",
"body": "Yes :) \"Test first\" should be your target."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T10:45:40.157",
"Id": "22921",
"ParentId": "22911",
"Score": "3"
}
},
{
"body": "<p>Just a quick note: As far as I see, nobody has mentioned yet that it's a <a href=\"https://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow\">code smell</a>: <em>Long Parameter List</em>. More details are there in Martin Fowler's <em>Refactoring: Improving the Design of Existing Code</em> book.</p>\n\n<p><em>Chapter 3. Bad Smells in Code, Long Parameter List</em> contains some suggested refactorings:</p>\n\n<blockquote>\n <p>Use <em>Replace Parameter with Method</em> when you can \n get the data in one parameter by making\n a request of an object you already know about. \n This object might be a field or it might be another\n parameter. Use <em>Preserve Whole Object</em> to take a \n bunch of data gleaned from an object and\n replace it with the object itself. If you have several\n data items with no logical object, use\n <em>Introduce Parameter Object</em>.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-21T06:00:41.350",
"Id": "35323",
"Score": "0",
"body": "Actually I did, but not as nice as you :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T13:20:13.080",
"Id": "22926",
"ParentId": "22911",
"Score": "2"
}
},
{
"body": "<blockquote>\n <p>I though that it would it be better to collect all of that a,b,c,d into one dictionary.</p>\n</blockquote>\n\n<p>In this particular case, rather than dictionary, I'd say it's probably better to declare a class. In python, objects is a syntax sugar for dictionary anyway.</p>\n\n<pre><code>class A(object):\n def __init__(self, **params):\n assert {'a', 'b'}.issubset(d) # required parameters\n for k,v in dict(c=None, d=4): params.setdefault(k,v)\n self.__dict__.update(params)\n\n def train(self):\n print self.a, self.b\n self.Dostuff()\n self.DoMoreStuff(self.c)\n self.DoMoreStuff(self.d)\n self.DoMoreMoreStuff()\n\na = A(a=1, b=2, ...)\n</code></pre>\n\n<p>of course you don't have to stuff it all in a single class, you might want to split the parameters into multiple classes where it makes sense to do so according to OOP principles.</p>\n\n<blockquote>\n <p>most functions in the code usually has some \"core\" argument that keep repeating throughout</p>\n</blockquote>\n\n<p>that is a good candidate to put them into a single class.</p>\n\n<blockquote>\n <p>Is there any downside to define a function that use one dictionary as an argument instead of several (+10) arguments?</p>\n</blockquote>\n\n<p>Yes, you lose parameter checking that is usually done by the interpreter so you'd have to do them yourself.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T14:02:53.457",
"Id": "22928",
"ParentId": "22911",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "22921",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T06:50:32.060",
"Id": "22911",
"Score": "3",
"Tags": [
"python"
],
"Title": "Is there any downside to define a function that use one dictionary as an argument instead of several (+10) arguments?"
}
|
22911
|
<p>I've written a class to make async SQL calls and it appears to work like a charm! But I'm a bit concerned about what it means to send a lot of queries to the server and then aborting them by throwing an abort exception on the calling thread. Is this a problem?</p>
<p>The code also launches a lot of threads. Is there any downside to this? Should I use ThreadPool instead, and if so, how?</p>
<p>I'm using .NET 4.</p>
<pre><code>//Class for asynchronous SQL calls
public class SqlAsync
{
private Thread LastAction { get; set; }
private string ConnectionString { get; set; }
public int Timeout { get; set; }
public SqlAsync(string connstring)
{
this.ConnectionString = connstring;
this.Timeout = 30;
}
public void AsyncSqlCall<T>(string sp, Action<T> Callback, Func<SqlDataReader, T> HandleResult, Dictionary<string, object> Params = null)
{
TryKillThread(this.LastAction);
this.LastAction = new Thread(() =>
{
T returnobj;
using (SqlConnection conn = new SqlConnection(this.ConnectionString))
using (SqlCommand cmd = new SqlCommand(sp, conn))
{
cmd.CommandTimeout = this.Timeout;
cmd.CommandType = CommandType.StoredProcedure;
if (Params != null)
{
foreach (KeyValuePair<string, object> kvp in Params)
{
cmd.Parameters.AddWithValue(kvp.Key, kvp.Value ?? DBNull.Value);
}
}
conn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
returnobj = HandleResult(rdr);
rdr.Close();
}
conn.Close();
}
new Thread(() => Callback(returnobj)).Start();
});
this.LastAction.Start();
}
private void TryKillThread(Thread thread)
{
if (thread != null && thread.IsAlive)
{
try
{
thread.Abort();
}
catch (ThreadStateException)
{ /*If thread ends between IsAlive check and Abort call, then just ignore*/ }
}
}
}
</code></pre>
<p>This is an example of how I use the class</p>
<pre><code>public class Example : Form
{
DbExample DbEx = new DbExample("");
public void tbExample_TextChanged(object sender, EventArgs e)
{
DbEx.BeginGetSomething(tbExample.Text, BindDgvSomething);
}
private void BindDgvSomething(DataTable dt)
{
dgvSomething.Invoke(new Action(() => dgvSomething.DataSource = dt));
}
}
public class DbExample
{
private SqlAsync SqlAsync;
private string Connstr;
public DbExample(string connstr)
{
this.Connstr = connstr;
this.SqlAsync = new SqlAsync(this.Connstr);
}
private DataTable LoadReader(SqlDataReader rdr)
{
DataTable dt = new DataTable();
dt.Load(rdr);
return dt;
}
public void BeginGetSomething(string name, Action<DataTable> Callback)
{
Dictionary<string, object> Params = new Dictionary<string, object>()
{
{ "@Name", name }
};
SqlAsync.AsyncSqlCall("spGetSomething", Callback, LoadReader, Params);
}
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>Your code does not follow naming conventions (private fields should be camelCased, and usually have an underscore prefix; parameters should be camelCased)</li>\n<li>there is no need in private properties, use fields instead (<code>ConnectionString</code>)</li>\n<li>It is not an <em>asynchronous</em> version of SQL access, it is <em>multithreaded</em> access. The difference is that you don't necessarily need to span new threads (and you should not, in fact) to make your code asynchronous.</li>\n<li>Stopping a thread using <code>Thread.Abort</code> is discouraged, and in general is very dangerous as it may lead to leaked resources and a lot of other side effects. It was explained in a lot of places, e.g. <a href=\"http://haacked.com/archive/2004/11/12/how-to-stop-a-thread.aspx\">How To Stop a Thread in .NET (and Why Thread.Abort is Evil)</a></li>\n<li>Killing a previous SQL action upon running the new one is the best way to get random issues all over your application</li>\n<li>You don't provide any means to control the execution of asynchronous request, so calling code has no idea whether SQL finished execution</li>\n<li>And finally, <code>AsyncSqlCall<T></code> method should not have <code>Action<T> Callback</code> parameter as it is a continuation action, you should return <code>Task<T></code> instead (so that caller can add a continuation)</li>\n</ul>\n\n<p>I don't like custom ORMs and would suggest you to use Entity Framework or NHibernate as a data layer, but as an exercise here are the fixes I would apply (.NET 4.5):</p>\n\n<pre><code>public class SqlAsync\n{\n private readonly string _connectionString;\n public int Timeout { get; set; }\n\n public SqlAsync(string connstring)\n {\n _connectionString = connstring;\n Timeout = 30;\n }\n\n public Task<T> AsyncSqlCall<T>(string sp, Func<SqlDataReader, Task<T>> handleResult, Dictionary<string, object> parameters = null)\n {\n return AsyncSqlCall<T>(sp, (reader, token) => handleResult(reader), CancellationToken.None, parameters);\n }\n\n public async Task<T> AsyncSqlCall<T>(string sp, Func<SqlDataReader, CancellationToken, Task<T>> handleResult, CancellationToken cancellationToken, Dictionary<string, object> parameters = null)\n {\n using (SqlConnection conn = new SqlConnection(_connectionString))\n using (SqlCommand cmd = new SqlCommand(sp, conn))\n {\n cmd.CommandTimeout = Timeout;\n cmd.CommandType = CommandType.StoredProcedure;\n\n if (parameters != null)\n {\n foreach (KeyValuePair<string, object> kvp in parameters)\n cmd.Parameters.AddWithValue(kvp.Key, kvp.Value ?? DBNull.Value);\n }\n\n await conn.OpenAsync(cancellationToken);\n\n using (SqlDataReader rdr = await cmd.ExecuteReaderAsync(cancellationToken))\n return await handleResult(rdr, cancellationToken);\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T09:04:19.050",
"Id": "35247",
"Score": "0",
"body": "Hi, thanks for your response! I realize await/async is the more modern approach to this problem but I'm not using .NET 4.5, I should've specified that in my question.\n\nHow else would you cancel an ongoing SQL query if not calling Thread.Abort? Since all disposable objects are wrapped in using statements, where could the leak occur? In the internal .NET sql classes?\n\nNotice the SqlAsync class is not static and the field in Example class is private so the call does not interfer with calls from any other class. How do you mean I could get random issues all over the application?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T09:13:03.910",
"Id": "35248",
"Score": "0",
"body": "@Mcb2000 If you read the article carefully you could have noticed the link to [Why Thread.Abort is Evil](http://www.interact-sw.co.uk/iangblog/2004/11/12/cancellation) where example of resource leak is shown for `using` statement. `Example` class may decide to issue several asynchronous SQL requests and all of them but last would be aborted"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T09:30:28.820",
"Id": "35250",
"Score": "0",
"body": "Ah, that's a very good point about exception being raised during disposal in finally. Though ugly, I could replace the using with a try-finally{try-catch} block. That needs to be thought through. Having all but the most recent SQL call aborted is the behaviour I want from this class. In the example I provided it is used to filter a datagrid based on textbox input. If the user writes 6 characters, I don't need all 6 queries to finish executing and returning the result of each one. Is there any danger of memory leak with starting this many threads, given they all finish at an acceptable point?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T15:07:00.950",
"Id": "423892",
"Score": "0",
"body": "I'm not a fan of multiple overloads with Func's of varying number of arguments. It creates hard to debug compiler messages."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T08:27:38.737",
"Id": "22916",
"ParentId": "22913",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "22916",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T07:37:40.250",
"Id": "22913",
"Score": "7",
"Tags": [
"c#",
".net",
"sql",
"asynchronous"
],
"Title": "Making async SQL calls"
}
|
22913
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.