body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I'm currently working on a project where I have a punch of raw data and multiple components that use that data for various tasks. I would like to separate the raw data from the components as much as possible and keep the raw data as only data (So no logic or functionality) but the components should be able to read and write to the raw data at any time.</p>
<p>The program will run each component and once all components have been run than the process repeats until the program shuts down. A component can be threaded, but it must join before the process repeats.</p>
<p>Each component will create objects based on the data that will do various things. To avoid having to create and delete those objects at each run for performance the objects must persist and synchronize it's data with the raw data at the beginning of the run.</p>
<p>So to summarize, the design should look something like this
<img src="https://i.stack.imgur.com/3Skup.png" alt="enter image description here"></p>
<p>This brings up the issue of synchronization as I need the component to synchronize its data with the raw data at beginning of each run.</p>
<p>Speed is some what important and so I can't go through each object and check if it it's members are equal to that of the component as that is process consuming especially considering the data will not change for the majority of the time.</p>
<p>What I thought about doing is give each object a GUID and every time one of it's values changes than I generate a new GUID. Therefore, if the GUID in the component is different than what it is in the raw data than the value must have changed.</p>
<p>This is simple to implement with getter and setter for each member and in the setter I just generate a new GUID.</p>
<p>Now, I wanted to avoid using getter and setter for two reasons. First, that increases the amount of typing I have to do and that will only increase my chance of getting arthritis sooner. Second, I'm scared my colleagues will take the lazy way and not add getter and setter for when they add members or passing the setter all together and setting the value directly causing a huge headache and waste of debugging time.</p>
<p>Therefore, I decided to create a template class that handles this for me.</p>
<p>This is what I came up with</p>
<pre><code>#include<iostream>
#include "uuid.hpp"
#include "uuid_generators.hpp"
#include "uuid_io.hpp"
template<typename T>
class MemberTracker
{
private:
T m_value;
boost::uuids::uuid& m_KeepingTrackOf;
public:
MemberTracker(boost::uuids::uuid& KeepTrackof)
: m_KeepingTrackOf(KeepTrackof)
{
}
operator T()
{
return m_value;
}
MemberTracker& operator=(T input)
{
this->m_KeepingTrackOf = boost::uuids::random_generator()();
this->m_value = input;
return *this;
}
};
class ObjectRawData
{
public:
boost::uuids::uuid guid;
MemberTracker<int> value;
ObjectRawData()
: value(guid)
{
guid = boost::uuids::random_generator()();
}
ObjectRawData(const ObjectRawData &obj)
: value(guid)
{
}
};
int main()
{
ObjectRawData h;
std::cout << h.guid << std::endl;
h.value = 4;
std::cout << h.guid << std::endl;
}
</code></pre>
<p>The only thing I don't like about this design is that I have to pass in the GUID as a parameter in the constructor.</p>
<p>So, my question is did I go in the right direction and what are the flaws of this design??</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T14:41:10.420",
"Id": "37692",
"Score": "1",
"body": "Do you really need a GUID? It seems like all you need is a dirty flag when data changes so the components know to re-sync."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T14:44:37.623",
"Id": "37693",
"Score": "0",
"body": "@Dave Yes, I could have used a bool to do that. But than I would need to reset it after all the components have updated and that could cause a lot of issue because there is no proper time to do that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T17:42:35.953",
"Id": "37706",
"Score": "1",
"body": "Ok, well then a counter is probably better than a GUID"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T17:46:47.347",
"Id": "37709",
"Score": "0",
"body": "@Dave Well have to consider that for the full implementation. It does simplify a lot of things and reduce memory and increase speed. :)"
}
] |
[
{
"body": "<p>I think you have two main choices, have the components throw events when they dirty the data. </p>\n\n<p>The plus here is that events are extremely multithreaded friendly.\nthe minus is the program might have to know about how to sync the dirty data.</p>\n\n<p>The other option is to have an abstract class with two methods doWork() and sync(). \nFirst run a parallel call to all the components.dowork\nThe when all completed run down each components.sync()</p>\n\n<p>This has the plus of the program not knowing about data sync but the component stores its own dirty list and is very customizable as a result..\nThis has the minus of the components knowing about data sync.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T15:07:14.047",
"Id": "24638",
"ParentId": "24414",
"Score": "1"
}
},
{
"body": "<p>I am not sure I fully understand your problem, but why not encapsulate Objects within a Component? \nThis would still keep the raw data pool separated from Components.\nAre Components being destroyed and re-initialized every time? \nAlso, is Object and Component data 1-to-1 (ie. Object1 data only consumed by Component1)?</p>\n\n<p>From what I understand, a dirty bit as mentioned by @Dave is a plausible and suitable solution.\nThis way Objects can track their own data and re-sync as necessary. \nThis can be done upon Component task completion and the bit can be reset afterwards.</p>\n\n<p>I am not sure if this helped. I think I may be overlooking some part of the problem... </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T18:58:48.277",
"Id": "24726",
"ParentId": "24414",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T11:14:50.140",
"Id": "24414",
"Score": "7",
"Tags": [
"c++"
],
"Title": "Efficent way of synchronizing between data"
}
|
24414
|
<p>I created a <em>class EmailParser</em> and check if a supplied string is an email or not with
the help of the standard librarie's email module. If the supplied string is not an
email I raise an exception. </p>
<ul>
<li><strong>Is this a pythonic way to deal with inappropiate input values an assertation error?</strong></li>
<li><strong>How do you generally check input values and report inappropiate states and values?</strong></li>
</ul>
<p>code:</p>
<pre><code>class EmailParser(object):
def __init__(self, message):
assert isinstance(message, basestring)
parsed_message = email.message_from_string(message)
if self._is_email(parsed_message):
self.email_obj = parsed_message
else:
assert False, 'The supplied string is no email: %s' % parsed_message
def __str__(self, *args, **kwargs):
return self.email_obj.__str__()
def _is_email(self, possible_email_obj):
is_email = False
if isinstance(possible_email_obj, basestring):
is_email = False
# I struggled a lot with this part - however, I came to the conclusion
# to ask for forgiveness than for permission, see Zen of Python and
# http://stackoverflow.com/questions/610883/how-to-know-if-an-object-has-an-attribute-in-python/610923#610923
try:
if '@' in possible_email_obj['To']:
is_email = True
except TypeError, e:
is_email = False
return is_email
</code></pre>
|
[] |
[
{
"body": "<p>Assertions are meant to help find bugs in the program. See <a href=\"http://wiki.python.org/moin/UsingAssertionsEffectively\" rel=\"nofollow\">Python Wiki: Using assertion effectively</a>. Quote:</p>\n\n<blockquote>\n <p>Assertions should <em>not</em> be used to test for failure cases that can\n occur because of bad user input or operating system/environment\n failures, such as a file not being found. Instead, you should raise an\n exception, or print an error message, or whatever is appropriate. One\n important reason why assertions should only be used for self-tests of\n the program is that assertions can be disabled at compile time.</p>\n \n <p>If Python is started with the -O option, then assertions will be\n stripped out and not evaluated. So if code uses assertions heavily,\n but is performance-critical, then there is a system for turning them\n off in release builds. (But don't do this unless it's really\n necessary. It's been scientifically proven that some bugs only show up\n when a customer uses the machine and we want assertions to help there\n too.)</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T13:31:44.490",
"Id": "24420",
"ParentId": "24419",
"Score": "4"
}
},
{
"body": "<pre><code>class EmailParser(object):\n\n def __init__(self, message):\n assert isinstance(message, basestring)\n</code></pre>\n\n<p>In python, we typically don't check types. Basically, we prefer duck typing. Let the user pass whatever they want.</p>\n\n<pre><code> parsed_message = email.message_from_string(message)\n\n if self._is_email(parsed_message):\n self.email_obj = parsed_message \n else:\n assert False, 'The supplied string is no email: %s' % parsed_message\n</code></pre>\n\n<p>As Janne mentioned, this is not a good use of an assertion.</p>\n\n<pre><code> def __str__(self, *args, **kwargs):\n return self.email_obj.__str__()\n</code></pre>\n\n<p>You shouldn't call <code>__str__</code> methods directly. Use the <code>str()</code> function.</p>\n\n<pre><code> def _is_email(self, possible_email_obj):\n is_email = False\n\n if isinstance(possible_email_obj, basestring):\n is_email = False\n</code></pre>\n\n<p>This is useless, because the only possible outcome is to set is_email to False which it already is. Furthermore, you know this has to be a Message object since it was returned from <code>message_from_string</code> so why are you checking whether it's a string? You know its not.</p>\n\n<pre><code> # I struggled a lot with this part - however, I came to the conclusion\n # to ask for forgiveness than for permission, see Zen of Python and\n # http://stackoverflow.com/questions/610883/how-to-know-if-an-object-has-an-attribute-in-python/610923#610923 \n try:\n if '@' in possible_email_obj['To']:\n is_email = True \n\n except TypeError, e:\n is_email = False\n</code></pre>\n\n<p>In what circumstances can this possibly happen?</p>\n\n<pre><code> return is_email\n</code></pre>\n\n<p>Don't needlessly set boolean flags. Just return True or False directly.</p>\n\n<p>Better yet, raise an exception with details on what exactly is wrong rather than returning false and raising a generic exception later.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T14:50:03.357",
"Id": "24426",
"ParentId": "24419",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "24426",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T13:23:24.860",
"Id": "24419",
"Score": "3",
"Tags": [
"python",
"exception"
],
"Title": "Raising an assertation error if string is not an email"
}
|
24419
|
<p>I am implementing a program that takes commands from a user and based on those commands, drives a Robot on a grid. To implement this program I have used the Command pattern. I have used this pattern because, most importantly, I want to be able to add to the list of possible commands in the future.</p>
<p>The program takes a string of commands from the user, and executes those commands, e.g. FFRFLF (forward x 2, turn right, forward, turn left, forward).</p>
<p>Can anyone give me their opinion on the quality of my design?</p>
<p>Robot Controller class:</p>
<pre><code> public void control(){
do{
process();
}while(tru);
}
public String process(){
// 1. Get user input
String cmds = get user input from console
// 2. Populate command list
populateCommandList(cmds);
// 3. Execute commands
executeCommands();
// 4. Display current location of robot
}
public void populateCommandList(String cmds) {
Command r = new TurnRightCommand(robot);
Command l = new TurnLeftCommand(robot);
Command f = new ForwardCommand(robot);
commands = new ArrayList<Command>();
for(int i=0; i<cmds.length(); i++){
char cmd = cmds.charAt(i);
switch(cmd){
case 'F':
commands.add(f);
break;
case 'R':
commands.add(r);
break;
case 'L':
commands.add(l);
break;
}
}
}
private void executeCommands() {
if(commands!=null && commands.size()>0){
for(Command cmd : commands){
cmd.execute();
}
}
}
</code></pre>
<p>Main class:</p>
<pre><code>public class Main {
public static void main(String[] args) {
RobotController r = new RobotController();
r.control();
}
}
</code></pre>
<p>Is this a good design? I need to know if the deign is good and that I can easily add new commands with minimal rework.</p>
|
[] |
[
{
"body": "<p>I think you've added an unnecessary layer of abstraction here.</p>\n\n<p>To me, <code>populateCommandList</code> looks completely unnecessary. You are converting a list of commands in one format (character string) into another format (an array of <code>Command</code> objects). Then, presumably, <code>executeCommands</code> just executes all of those command objects in order. This wastes time and memory by creating a bunch of unnecessary objects.</p>\n\n<p>Why not just have <code>executeCommands</code> take the string directly, and execute the appropriate command for each character that it encounters?</p>\n\n<p>In other words, I would have something like this in <code>executeCommands</code>:</p>\n\n<pre><code> for(int i=0; i<cmds.length(); i++){\n char cmd = cmds.charAt(i);\n switch(cmd){\n case 'F': \n robot.move(FORWARD,1);\n break;\n case 'R': \n robot.turn(RIGHT);\n break;\n case 'L': \n robot.turn(LEFT);\n break;\n }\n }\n</code></pre>\n\n<p>Either way looks equally extensible to me. Either way you will have a switch statement somewhere that defines what commands are possible, and that is what you have to change in order to add a new command.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T14:27:45.743",
"Id": "24422",
"ParentId": "24421",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24422",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T13:59:48.453",
"Id": "24421",
"Score": "1",
"Tags": [
"java",
"design-patterns"
],
"Title": "Opinions on my Command pattern design - is it extensible?"
}
|
24421
|
<p>My quick searching did not reveal anyone sharing their solution to <a href="http://tour.golang.org/#40" rel="nofollow">this exercise</a>, so am not sure if there are other (and better) approaches to mine:</p>
<pre><code>package main
import (
"code.google.com/p/go-tour/wc"
"strings"
)
func WordCount(s string) map[string]int {
foo := strings.Fields(s)
m := make(map[string]int)
for i := 0; i < len(foo); i++ {
v, ok := m[foo[i]]
if ok {
m[foo[i]] = v + 1
}
m[foo[i]] = v + 1
}
return m
}
func main() {
wc.Test(WordCount)
}
</code></pre>
|
[] |
[
{
"body": "<p>You can be more concise and readable using <code>range</code> and the fact that the default value of the int is <code>0</code> :</p>\n\n<pre><code>func WordCount(s string) map[string]int {\n m := make(map[string]int)\n for _, w := range(strings.Fields(s)) {\n m[w]++\n }\n return m\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T14:56:14.833",
"Id": "24427",
"ParentId": "24423",
"Score": "5"
}
},
{
"body": "<p>Programmers spend almost all their time reading code; code should be documented. API users need good documentation too.</p>\n\n<p>A meaningless name like <code>foo</code> is the first red flag; good names are an excellent form of code documentation.</p>\n\n<p>Go has a documentation tool: <a href=\"http://golang.org/doc/articles/godoc_documenting_go_code.html\" rel=\"nofollow\">Godoc: documenting Go code</a>. \"Documentation is a huge part of making software accessible and maintainable.\"</p>\n\n<p>Here's my solution:</p>\n\n<pre><code>// A Tour of Go. Exercise 40: Maps.\npackage main\n\nimport (\n \"code.google.com/p/go-tour/wc\"\n \"strings\"\n)\n\n// WordCount returns a map of the counts of each “word” in the string s.\nfunc WordCount(s string) map[string]int {\n counts := make(map[string]int)\n for _, word := range strings.Fields(s) {\n counts[word]++\n }\n return counts\n}\n\nfunc main() {\n wc.Test(WordCount)\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T14:03:16.170",
"Id": "24477",
"ParentId": "24423",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24427",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T14:29:21.847",
"Id": "24423",
"Score": "3",
"Tags": [
"go"
],
"Title": "exercise #40 in A Tour of Go"
}
|
24423
|
<p>I am writing an email parser and cannot decide how much logic should be included in the <code>__init__</code> function. I know that a constructor should make the object ready for use, but are there best practices?</p>
<p>I've added several statements to my constructor:</p>
<pre><code>def __init__(self, message):
assert isinstance(message, basestring)
parsed_message = email.message_from_string(message)
if self._is_email(parsed_message):
self.email_obj = parsed_message
email_payload = parsed_message.get_payload()
self.valid_urls = self._find_valid_urls(email_payload)
# ... some other stuff like looking for keywords etc.
</code></pre>
<p>What do you consider the most pythonic way:</p>
<ul>
<li>Should I create a simple email object which possesses several methods that extract and return keywords, included URLs etc?</li>
<li>Do you consider it better to process all this information in the <code>__init__</code> method and putting all results in object variables?</li>
</ul>
|
[] |
[
{
"body": "<p>Notes:</p>\n\n<ul>\n<li><p>Personally I prefer to keep the initialization method simple and lean. Just setup the minimum state of the object, let subsequent calls to methods do the real job when it's needed. Otherwise, why use a class? Maybe you don't need a class at all and just a function would do?</p></li>\n<li><p><code>assert isinstance(message, basestring)</code>: Python is a dynamic language, embrace the fact and don't lose a second checking whether every argument has the type you expect (instead, write good docstrigs so the user knows how to call it). Another question is checking that given values satisfy some precondition (i.e <code>assert len(s) >= 10</code>).</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T19:38:29.443",
"Id": "24441",
"ParentId": "24425",
"Score": "4"
}
},
{
"body": "<p>Actually, I think you should do something like</p>\n\n<pre><code>@classmethod\ndef parse(cls, message): \n parsed_message = email.message_from_string(message)\n\n cls._verify_email(parsed_message) # throws if something is wrong\n\n message = cls() # make an e-mail message object \n email_payload = parsed_message.get_payload()\n message.valid_urls = self._find_valid_urls(email_payload)\n # ... some other stuff like looking for keywords etc.\n\n return message\n</code></pre>\n\n<p>Which you would then use like</p>\n\n<pre><code> my_message = Message.parse(message_text)\n</code></pre>\n\n<p>I prefer to leave the constructor for just basic object construction. It shouldn't parse things or do complex logic. It gives you flexibility because it is now possible to construct an e-mail object that isn't just a parsed version of the message text. I often find that useful for testing, and it reduces the dependance on a particular source for e-mails.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T21:53:25.940",
"Id": "24442",
"ParentId": "24425",
"Score": "3"
}
},
{
"body": "<p>I think you should keep in mind these two principles in mind:</p>\n\n<ol>\n<li>DRY (Don't Repeat Yourself)</li>\n<li>SRP (Single Responsibility Principle)</li>\n</ol>\n\n<p>According to SRP, your init function should be just initializing your object. All other stuff should go into their respective functions and called as needed.</p>\n\n<pre><code>email = Email(message)\n\nif not email.is_valid: # Do some stuff\n\nurls = email._valid_urls # use property here\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T05:49:55.400",
"Id": "24457",
"ParentId": "24425",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24442",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T14:44:43.513",
"Id": "24425",
"Score": "3",
"Tags": [
"python",
"parsing",
"constructor",
"email"
],
"Title": "Logic for an init function in email parser"
}
|
24425
|
<p>I have a meta-search engine system, i implemented mainly using static classes. The query pre processing module consists of the following static methods</p>
<pre><code>function queryPreprocessing() { }
queryPreProcessing.removeStopWords = function (query){ // code here}
queryPreProcessing.stemmer = function (w) { //code here }
queryPreProcessing.convertBoolean = function (w){ //code here}
</code></pre>
<p>Technically the query pre processing modules takes as input a string (the query) and performs the above named functions on it. For example:</p>
<pre><code>var query = $("#textbox").val();
query = queryPreProcessing.removeStopWords(query) ;
query = queryPreProcessing.stemmer(query) ;
query = queryPreProcessing.convertBoolean(query) ;
</code></pre>
<p>For simplicity, it was easier for me to make all the methods static and call them when needed but my question is: Is this the best way of doing it?</p>
|
[] |
[
{
"body": "<p>Personally, I would make a custom type, <code>Query</code>, and define these as methods on the prototype of <code>Query</code>.</p>\n\n<pre><code>var Query = function(...);\nQuery.prototype.removeStopWords = function (query){ ... }\nQuery.prototype.stemmer = function (query){ ... }\nQuery.prototype.convertBoolean = function (query){ ... }\n</code></pre>\n\n<p>So you can call it as</p>\n\n<pre><code>var query = new Query()\n .removeStopWords()\n .stemmer()\n .convertBoolean();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T15:46:22.223",
"Id": "37697",
"Score": "0",
"body": "you can simplify this as `Query.prototype = { removeStopWords: function() { .. }, stemmer: function() { .. } ... };` I always like to add a `constructor` property to it as well. but it's not required."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T15:36:47.480",
"Id": "24429",
"ParentId": "24428",
"Score": "0"
}
},
{
"body": "<p>Prototype is a good way, in alternative this is the pattern I use:</p>\n\n<pre><code>var QueryPreprocessing = {\n\n init: function () {\n\n // set config variables for closures here\n var initparam = 'whatever';\n\n return {\n\n removeStopWords: function (query) {\n //code here\n },\n\n stemmer: function (w) {\n //code here\n },\n\n convertBoolean: function (w) {\n //code here\n }\n }\n\n}\n\nvar qp = QueryPreprocessing.init();\nqp.removeStopWord('thequerystring');\n//...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T16:15:42.690",
"Id": "37700",
"Score": "0",
"body": "Thank you. How is this any better than other design patterns like the Factory or Facade?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T15:46:30.460",
"Id": "24430",
"ParentId": "24428",
"Score": "0"
}
},
{
"body": "<p>Your code looks fine. The only change I would make is possibly factoring our a new function:</p>\n\n<pre><code>queryPreprocess.preProcessQuery = function preprocessQuery(query) {\n query = queryPreprocessing.removeStopWords(query);\n query = queryPreprocessing.stemmer(query);\n query = queryPreprocessing.convertBoolean(query);\n return query;\n};\n\nvar queryRaw = $(\"#textbox\").val();\nvar queryProcessed = queryPreprocess.preprocessQuery(queryRaw);\n</code></pre>\n\n<p>An object or class seems like way too much mental overhead for this task of composing functions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T16:41:12.267",
"Id": "24433",
"ParentId": "24428",
"Score": "0"
}
},
{
"body": "<p>Well if you want to use the Object prototype here is how I would structure it: </p>\n\n<pre><code>// uses Object.extend for the constructor https://gist.github.com/rlemon/5256375\n\nfunction Query(options) {\n this.value; // I would store the value in the object itself. Otherwise you should use this as a utility object and not deal with prototype. \n // other defaults\n Object.extend(this, options); // extend options to the object\n}\n\nQuery.prototype = {\n constructor: Query,\n removeStopWords: function() { .. return this;},\n stemmer: function() { .. return this;},\n convertBoolean: function() { .. return this;} // returns itself for chaining\n};\n\nvar q = new Query({ value: ' Foo Bar Hello World ' });\nq.removeStopWords().stemmer().convertBoolean();\nalert(q.value);\n</code></pre>\n\n<p>But this is how I would structure it based on how I am assuming you are using this. If the use cases changed or the requirements were not fully understood I would possibly write it a number of other ways. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T17:39:01.883",
"Id": "24439",
"ParentId": "24428",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T15:21:44.480",
"Id": "24428",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "Best design pattern for Javascript"
}
|
24428
|
<p><strong>Requirements</strong>:</p>
<blockquote>
<p>Given a long section of text, where the only indication that a paragraph has ended is a shorter line, make a guess about the first paragraph. The lines are hardwrapped, and the wrapping is consistent for the entire text.</p>
</blockquote>
<p>The code below assumes that a paragraph ends with a line that is shorter than the average of all of the other lines. It also checks to see whether the line is shorter merely because of word wrapping by looking at the word in the next line and seeing whether that would have made the line extend beyond the "maximum" width for the paragraph.</p>
<pre><code>def get_first_paragraph(source_text):
lines = source_text.splitlines()
lens = [len(line) for line in lines]
avglen = sum(lens)/len(lens)
maxlen = max(lens)
newlines = []
for line_idx, line in enumerate(lines):
newlines.append(line)
try:
word_in_next_line = lines[line_idx+1].split()[0]
except IndexError:
break # we've reached the last line
if len(line) < avglen and len(line) + 1 + len(word_in_next_line) < maxlen: # 1 is for space between words
break
return '\n'.join(newlines)
</code></pre>
<h2>Sample #1</h2>
<p><strong>Input:</strong></p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>This is a sample paragaraph. It goes on and on for several sentences.
Many OF These Remarkable Sentences are Considerable in Length.
It has a variety of words with different lengths, and there is not a
consistent line length, although it appears to hover
supercalifragilisticexpialidociously around the 70 character mark.
Ideally the code should recognize that one line is much shorter than
the rest, and is shorter not because of a much longer word following
it which has wrapped the line, but because we have reached the end of
a paragraph.
This is the next paragraph, and continues onwards for
more and more sentences.
</code></pre>
</blockquote>
<p><strong>Output:</strong></p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>This is a sample paragaraph. It goes on and on for several sentences.
Many OF These Remarkable Sentences are Considerable in Length.
It has a variety of words with different lengths, and there is not a
consistent line length, although it appears to hover
supercalifragilisticexpialidociously around the 70 character mark.
Ideally the code should recognize that one line is much shorter than
the rest, and is shorter not because of a much longer word following
it which has wrapped the line, but because we have reached the end of
a paragraph.
</code></pre>
</blockquote>
<p>Using other sample inputs I see there are a few issues, particularly if the text features a short paragraph or if there is more than one paragraph in the source text (leading to the trailing shorter lines reducing the overall average).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T16:46:31.510",
"Id": "37702",
"Score": "0",
"body": "Can you post example inputs and expected outputs?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T08:31:51.227",
"Id": "37739",
"Score": "0",
"body": "Why do you consider the average length at all? `if len(line) + len(word_in_next_line) < maxlen:` would seem better to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-15T20:44:00.083",
"Id": "191715",
"Score": "0",
"body": "I've updated the example to make it clearer. The inputs are originally text from PDFs, and the fonts used are proportional. As a result, the number of characters per line is not constant but rather based on the number of narrow vs wide characters. The sentence `Many OF These Remarkable Sentences are Considerable in Length.` is just 63 characters even though it takes up the whole width. Without the check for average length, it would be falsely identified as a new paragraph."
}
] |
[
{
"body": "<h2>Stating Your Requirements</h2>\n<p>It's important to have a clear defintion of what you want to achieve before you start writing code, even though there are many different ways of achieving that, for instance by practicing <a href=\"http://en.wikipedia.org/wiki/Test-driven_development\" rel=\"noreferrer\">Test-Driven Development</a> or <a href=\"http://www.joelonsoftware.com/articles/fog0000000036.html\" rel=\"noreferrer\">writing a formal specification</a>.</p>\n<p>The important part is that without a clear definition, you can't validate whether you're done. In your case, the question contains a description that is completely different than the code and quite unclear.</p>\n<p>The above is vital even if you're only writing the code as an exercise for personal use or learning.</p>\n<h2>Testing and Edge Cases</h2>\n<p>In the following code:</p>\n<pre><code>word_in_next_line = lines[li+1].split()[0]\n</code></pre>\n<p>Why are you assuming that</p>\n<ul>\n<li>there will be a next line? What if the text consists of only one paragraph?</li>\n<li>the next line will not be empty?</li>\n</ul>\n<p>These assumptions are unreasonable and when I first tried out your code on some text, it immediately threw an exception.</p>\n<h2>Naming</h2>\n<ul>\n<li><p>Be careful with historically significant terms such as <code>ss</code> (Google it if you don't know what I mean).</p>\n</li>\n<li><p>Expressive names are better than abbreviations! Replace:</p>\n<ul>\n<li><code>ss</code> with <code>source_text</code></li>\n<li><code>ll</code> with <code>line</code> (this looks like the number <code>11</code>!)</li>\n<li><code>lens</code> with <code>line_lengths</code></li>\n<li><code>avglen</code> with <code>average_length</code></li>\n<li><code>maxlen</code> with <code>maximum_length</code></li>\n<li>in the for loop, <code>li</code> with <code>index</code> and <code>ll</code> with <code>line</code></li>\n</ul>\n</li>\n</ul>\n<h2>Conclusion</h2>\n<p>Without a clear explanation of what you are trying to accomplish, how the input data looks and how you define a paragraph, it's impossible to show you a better way of solving the problem.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T20:38:10.983",
"Id": "37721",
"Score": "0",
"body": "Good point about `word_in_next_line`. I now check for an IndexError and stop if it's reached. If the next line is empty then the check will still succeed and I'll have identified the first paragraph."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T17:27:05.700",
"Id": "24436",
"ParentId": "24431",
"Score": "6"
}
},
{
"body": "<p>Below is a small hash-up for this problem. I have modified the assumptions slightly, in that:</p>\n\n<ul>\n<li><p>Considering the MODE of the line lengths (i.e. taken the most common\nline length as the 'average' length)</p></li>\n<li><p>Tested the length of each line + the next word against the MODE (this is loose, I am assuming that the end of paragraph line is\nSIGNIFICANTLY shorter than the MODE - but I think you could refine\nthis :) )</p></li>\n</ul>\n\n<p>So here we go:</p>\n\n<pre><code>source_lines = source_text.split('\\n')\n\n# add the length of each line to a dictionary, incrementing common lengths\nline_lengths = {}\nfor each_line in source_lines:\n line_size = len(each_line)\n\n # increment a common line length:\n if line_size in line_lengths:\n line_lengths[line_size] += 1\n\n # or add a new line length to dictionary\n else:\n line_lengths[line_size] = 1\n\n# find the most common length (mode)\nmode_length = max(line_lengths, key=line_lengths.get)\n\n# loop through all lines, and test length against MODE\nfor index in range(0, len(source_lines) -1):\n try:\n # length = this line + next word\n length = len( source_lines[index] + source_lines[index + 1].split()[0] )\n except IndexError:\n # ie. end of file\n length - len( source_lines[index] )\n\n # test length against MODE\n if length < mode_length:\n # is end of paragraph\n print('\\n'.join( source_lines[:index + 1] ) )\n # break loop once first paragraph identified\n break\n</code></pre>\n\n<p>There is more than likely a more elegant way to implement this using list comprehension. But conceptually, does this work for your needs?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T22:16:27.507",
"Id": "37723",
"Score": "0",
"body": "Revised: the mode_length is not actually the mode here! `max(line_lengths)` is actually the longest line. Still think this is appropriate however. I will revise and calculate the mode correctly"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T23:02:59.457",
"Id": "37728",
"Score": "0",
"body": "Will use `mode_length = max(line_lengths, key=line_lengths.get)` to get an accurate value for MODE (c.f. just the longest line)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T22:09:18.093",
"Id": "24443",
"ParentId": "24431",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T16:10:13.113",
"Id": "24431",
"Score": "4",
"Tags": [
"python",
"strings"
],
"Title": "Given a random section of text delimited by line breaks, get the first paragraph"
}
|
24431
|
<p>I just coded this formatter to format timestamps in javascript (I tied it to underscore for convenience), any remark?</p>
<pre><code>_.toDate = function(epoch, format, locale) {
var date = new Date(epoch),
format = format || 'dd/mm/YY',
locale = locale || 'en'
dow = {};
dow.en = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
];
var formatted = format
.replace('D', dow[locale][date.getDay()])
.replace('dd', ("0" + date.getDate()).slice(-2))
.replace('mm', ("0" + (date.getMonth() + 1)).slice(-2))
.replace('yyyy', date.getFullYear())
.replace('yy', (''+date.getFullYear()).slice(-2))
.replace('hh', date.getHours())
.replace('mn', date.getMinutes());
return formatted;
}
</code></pre>
<p>usage</p>
<pre><code>_.toDate($.now(), "dd-mm-yy at hh:mn");
// Will output:
"27-03-13 at 17:20"
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T22:34:55.150",
"Id": "37724",
"Score": "2",
"body": "I like it (except that I'll stick to some commonly used format, for instance [the one php](http://php.net/date) uses)"
}
] |
[
{
"body": "<p>I would use a library that is designed for this, such as <a href=\"http://momentjs.com/\" rel=\"nofollow\">Moment.js</a>. It is a lot more flexible, and has internationalization support also.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T19:17:39.577",
"Id": "24603",
"ParentId": "24435",
"Score": "1"
}
},
{
"body": "<p>What happens when you add the Hungarian locale</p>\n\n<pre><code>dow.hu = [\n 'vasárnap',\n 'hétfő',\n 'kedd',\n 'szerda',\n 'csütörtök',\n 'péntek',\n 'szombat'\n]\n</code></pre>\n\n<p>and try to format</p>\n\n<pre><code>_.toDate(new Date(2013, 07, 30, 12, 0, 0, 0), 'D dd mm, yy', 'hu');\n</code></pre>\n\n<p>?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T17:09:29.887",
"Id": "29236",
"ParentId": "24435",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T17:21:28.460",
"Id": "24435",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"datetime",
"underscore.js"
],
"Title": "Date formatter for javascript"
}
|
24435
|
<p>After watching Raymond Hettinger, I decided to go through my code and make it faster and more beautiful. The example given on the slides is, unfortunately, not good enough to get me going (ref. <a href="https://speakerdeck.com/pyconslides/transforming-code-into-beautiful-idiomatic-python-by-raymond-hettinger" rel="nofollow noreferrer">https://speakerdeck.com/pyconslides/transforming-code-into-beautiful-idiomatic-python-by-raymond-hettinger</a>)</p>
<p>Here's my code. Do you know how I can make it faster? It's from my django code that inserts data from a list.</p>
<pre><code>FiveMin(timestamp=datetime.strptime(s[0], "%m/%d/%Y %H:%M:%S"),
station=stat,
district=s[2],
fwy=s[3],
fdir=s[4],
ftype=s[5],
length=float_or_zero(s[6]),
samples=int_or_zero(s[7]),
p_observed=float_or_zero(s[8]),
total_flow=int_or_zero(s[9]),
avg_occupancy=float_or_zero(s[10]),
avg_speed=float_or_zero(s[11])).save()
</code></pre>
<p>If not, are there any significant speed losses?</p>
<blockquote>
<p><em>Note:</em> originally hosted in <a href="https://stackoverflow.com/questions/15665364/unpacking-sequences-for-functions">https://stackoverflow.com/questions/15665364/unpacking-sequences-for-functions</a> </p>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T17:34:52.260",
"Id": "37704",
"Score": "1",
"body": "Insufficient context: what is s? where did come from?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T17:40:47.120",
"Id": "37705",
"Score": "0",
"body": "data is downloaded and parsed from a text file (not shown). Code above shows data insertion in django. Is there a faster/more beautiful way to do this using python's sequence unpacking?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T17:43:44.833",
"Id": "37707",
"Score": "1",
"body": "If it is already parsed, why are you doing conversions there?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T17:47:28.840",
"Id": "37710",
"Score": "1",
"body": "Show us the download and parse steps. Then we'll have a better idea of what options are available. Making code beautiful requires looking at more then just one line at a time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T17:48:09.697",
"Id": "37711",
"Score": "0",
"body": "@codesparkle sorry, by parsed, I meant broken down using a delimiter. Now to save, the db expects a certain format hence the conversions"
}
] |
[
{
"body": "<p>There's not enough context here to review your code. For example, all those calls to <code>int_or_zero</code> and <code>float_or_zero</code> look suspicious (Django ought to be able to do that kind of conversion for you if you set up the model correctly), but without being able to see the model definition, or the source code for those functions, or the format of the data in <code>s</code>, it's impossible to say whether they are necessary or not.</p>\n\n<p>If you're doing bulk database insertion from a file, then:</p>\n\n<ol>\n<li><p>Use the database's own bulk insertion tool, for example <a href=\"http://www.postgresql.org/docs/8.1/static/sql-copy.html\" rel=\"nofollow\"><code>COPY</code> in PostgreSQL</a> or <a href=\"http://dev.mysql.com/doc/refman/5.5/en/load-data.html\" rel=\"nofollow\"><code>LOAD DATA INFILE</code> in MySQL</a>.</p></li>\n<li><p>Or, if you must do it via Django's object–relationship mapping engine, use Django's <a href=\"https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.bulk_create\" rel=\"nofollow\"><code>bulk_create()</code></a> method instead of saving objects one at a time.</p></li>\n<li><p>Or, if you must save objects one at a time using Django's <code>save()</code> method, then at least do it inside a single transaction instead of a sequence of individual transactions. Use Django's <a href=\"https://docs.djangoproject.com/en/1.5/topics/db/transactions/#django.db.transaction.commit_on_success\" rel=\"nofollow\"><code>@transaction.commit_on_success</code></a> decorator (or <a href=\"https://docs.djangoproject.com/en/dev/topics/db/transactions/#django.db.transaction.atomic\" rel=\"nofollow\"><code>@transaction.atomic</code></a> in version 1.6).</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T14:41:25.300",
"Id": "38254",
"Score": "0",
"body": "Thanks for the heads up. I'll change a lot of my code to reflect this."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T08:12:06.197",
"Id": "24463",
"ParentId": "24437",
"Score": "0"
}
},
{
"body": "<p>You can use sequence unpacking instead of numeric indexing:</p>\n\n<pre><code>(timestamp, dummy, district, fwy, fdir, ftype, length, samples, \n p_observed, total_flow, avg_occupancy, avg_speed) = s\n\nFiveMin(timestamp=datetime.strptime(timestamp, \"%m/%d/%Y %H:%M:%S\"),\n station=stat,\n district=district,\n fwy=fwy,\n fdir=fdir,\n ftype=ftype,\n length=float_or_zero(length),\n samples=int_or_zero(samples),\n p_observed=float_or_zero(p_observed),\n total_flow=int_or_zero(total_flow),\n avg_occupancy=float_or_zero(avg_occupancy),\n avg_speed=float_or_zero(avg_speed)).save()\n</code></pre>\n\n<p>This avoids a couple of problems of the indexing approach:</p>\n\n<ol>\n<li>It is easy to make the mistake of using a wrong number </li>\n<li>If you need to add or remove a variable in the middle, you would need to update many numbers, possibly making a mistake.</li>\n</ol>\n\n<p>Unpacking may also be <em>slightly</em> faster, but the difference is rather negligible.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T08:18:41.660",
"Id": "24465",
"ParentId": "24437",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24465",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T17:31:26.097",
"Id": "24437",
"Score": "-1",
"Tags": [
"python",
"django"
],
"Title": "Unpacking sequences for functions"
}
|
24437
|
<p>I've just implemented a cache for my server, and I'd like your thoughts about performance improvements and maybe some possible bug fixes:</p>
<pre><code>public class Cache<CacheKey, CacheValue>
{
private Dictionary<CacheKey, KeyValuePair<CacheValue, DateTime>> _map;
/// <summary>
/// The first element is the least recently used.
/// </summary>
private List<CacheKey> _lru;
private int _maxSize;
private ReaderWriterLock _lock;
private int _minutes;
public Cache(int maxNumberOfRecords, int minutes)
{
_maxSize = Math.Max(maxNumberOfRecords, 1);
_lru = new List<CacheKey>(_maxSize + 1);
_map = new Dictionary<CacheKey, KeyValuePair<CacheValue, DateTime>>();
_lock = new ReaderWriterLock();
_minutes = minutes;
}
public CacheValue find(CacheKey key)
{
_lock.AcquireReaderLock(-1);
CacheValue ans;
if (_map.ContainsKey(key) && (DateTime.Now - _map[key].Value).Minutes < _minutes)
{
ThreadPool.QueueUserWorkItem(o => //don't wait for lru to update
{
_lock.AcquireWriterLock(-1);
_lru.Remove(key);
_lru.Add(key);
_lock.ReleaseWriterLock();
});
ans = _map[key].Key;
}
else
{
ans = default(CacheValue);
}
_lock.ReleaseReaderLock();
return ans;
}
public void insert(CacheKey key, CacheValue value)
{
_lock.AcquireWriterLock(-1);
if (_map.ContainsKey(key)) //if exists
{
_map.Remove(key);
_map.Add(key, new KeyValuePair<CacheValue, DateTime>(value, DateTime.Now)); //update value
}
else
{ //if not
_lru.Add(key);
_map.Add(key, new KeyValuePair<CacheValue, DateTime>(value, DateTime.Now)); //add to cache
if (_lru.Count > _maxSize)
{
_map.Remove(_lru[0]); //and delete least recently used
_lru.RemoveAt(0);
}
}
_lock.ReleaseWriterLock();
}
}
</code></pre>
<p>I've used <code>ThreadPool</code> because the <code>List</code> operations are expensive, but I think that this hurts the LRU integrity. I'm also thinking to implement a queue with \$O(1)\$ <code>Remove</code> to replace the <code>List</code> class.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T19:20:43.277",
"Id": "37992",
"Score": "1",
"body": "Don't use `DateTime.Now`. Use `DateTime.UtcNow`. You don't want to introduce caching bugs when daylight savings changes kick in."
}
] |
[
{
"body": "<p>If you are using .NET 4 or above drop your code, and use <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache%28v=vs.100%29.aspx\">MemoryCache</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T23:40:31.730",
"Id": "24447",
"ParentId": "24444",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "24447",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T22:21:54.710",
"Id": "24444",
"Score": "4",
"Tags": [
"c#",
"performance",
"cache"
],
"Title": "Implementing cache for server"
}
|
24444
|
<p>I've recently written a program for Python 3 that I'm using to practice my newly-acquired object-oriented knowledge. It's a simple text game that is really easy to play and can be run straight out of IDLE with no modules (except the <code>Random</code> module). I realize that beginner code can sometimes be sloppy and difficult to read, so lately I've really been trying to improve the beauty in my code. I'd love advice on my code as well as any bugs you may have spotted. Please be as honest (brutally honest, if necessary) as possible, here.</p>
<pre><code># Alien Battle
# 3/26/13
import random
# player class
class Player(object):
health = 20
damage_points = 8
cash = 0
# initial
def __init__(self):
print("You jump out of the window of your crashed ship. "\
"Your fellow soldiers scramble behind cover. " \
"The aliens are coming!")
@staticmethod
def damage_upgrade(points):
Player.damage_points += points
print("Your weapon has been upgraded! Your weapon now does " + str(Player.damage_points) + "damage!")
@staticmethod
def get_cash(cash):
Player.cash += cash
print("Your new balance is $" + str(Player.cash) + "!")
@staticmethod
def get_health(health_pack):
if Player.health >= 20:
Player.health == 20
print("Your health is at maximum, so you give the health pack to a wounded soldier instead.")
else:
Player.health += health_pack
print("Your health is now " + str(Player.health) + "!")
def __str__(self):
stat = "||\\ Player Info /|| \n"
stat += "Health: " + str(Player.health) + "| MAX HEALTH: 20\n"
stat += "Damage: " + str(Player.damage_points) + " | MAX DAMAGE: 20\n"
stat += "Money: $" + str(Player.cash) + " | MAX CASH: Unlimited"
return stat
def check_for_death(self):
if Player.health <= 0:
print("You failed to survive against the alien horde. As you and your soldiers fall, not a single man gets to the ship alive.")
input("Press the [ENTER] key to exit the program.")
else:
GameLoop()
# Enemy class(Alien)
class Aliens(object):
# initial
def __init__(self, damage, enemies):
self.damage = damage
self.enemies = enemies
self.__upgrade_damage(self.damage)
def __upgrade_damage(self, damage):
upgrade = random.randrange(1, 8)
if upgrade == 2:
self.damage = 7
# attack methods
def attack1(self):
self.next_wave()
print("The alien leaps at you and begins biting you. Your fellow soldiers pulls it off of you and you shoot it in the head before it can stand back up.")
Player.health -= self.damage
Player1.get_cash(2)
self.enemies -= Player.damage_points
def attack2(self):
self.next_wave()
print("You and two other soldiers blast 3 aliens as they leap at you through a door. When you check the bodies, you find a health pack!")
Player1.get_cash(3)
Player1.get_health(2)
self.enemies -= Player.damage_points * 1.5
def attack3(self):
self.next_wave()
print("A large horde manages to flank you and take our three of your men along with severely hurting you. The medics aren't sure if you'll make it.")
Player1.get_cash(1)
def next_wave(self):
if self.enemies <= 0:
print("You and your team have wiped out all of the enemies, but you feel another horde coming.")
self.enemies += 15
Player1.get_cash(4)
GameLoop()
else:
pass
Ali = Aliens(damage = 5, enemies = 17)
# Move loop
def MoveLoop():
randmove = random.randrange(1,16)
if randmove == 1 or randmove == 2 or randmove == 3 or randmove == 4 or randmove == 5 or randmove == 6:
Ali.attack1()
Player1.check_for_death()
elif randmove == 7 or randmove == 8 or randmove == 9:
print("While on the battlefield, you manage to grab some extra money from a dead soldier while your teammates fight back the horde.")
Player1.get_cash(2)
GameLoop()
elif randmove == 10 or randmove == 11:
print("While you have some extra time, you scavenge for supplies. You find a small health pack among the wreckage.")
Player1.get_health(2)
GameLoop()
elif randmove == 12 or randmove == 13 or randmove == 14:
Ali.attack2()
Player1.check_for_death()
else:
Ali.attack3()
Player1.check_for_death()
# check damage, make sure it doesn't go over 20
def check_damage():
if Player.damage_points >= 20:
Player.damage_points = 20
print("Your weapon is fully upgraded!")
else:
pass
def check_health():
if Player.health >= 20:
Player.health == 20
print("Your health is at the maximum level!")
else:
pass
# store function
def store():
print("\n Store Menu")
print("Your balance: $" + str(Player.cash))
print("""
1 - Upgrade Weapon (+1 damage) - $6
2 - Upgrade Weapon (+3 damage) - $10
3 - Buy health (+3 health) - $4
4 - Buy Health (+5 health) - $6
5 - Go back to main menu
"""
)
store_choice = input("What would you like to buy?: ")
while store_choice != "5":
if store_choice == "1":
check_damage()
if Player.damage_points < 20 and Player.cash >= 6:
Player.damage_upgrade(1)
store()
else:
if Player.damage_points > 20:
print("Your damage is already at the maximum level!")
store()
elif Player.cash < 6:
print("You do not have enough money to purchase this!")
store()
elif store_choice == "2":
check_damage()
if Player.damage_points < 18 and Player.cash >= 10:
Player.damage_upgrade(3)
store()
else:
if Player.damage_points > 20:
print("Your damage is already at the maximum level!")
store()
elif Player.cash < 10:
print("You do not have enough money to purchase this!")
store()
elif store_choice == "3":
if Player.health < 17 and Player.cash >= 4:
Player.health += 3
print("Your health has been increased! Your total health is now: " + str(Player.health))
store()
else:
if Player.health > 17:
print("Wait for your health to lower before buying this weapon!")
store()
elif Player.cash < 4:
print("You do not have enough money to purchase that!")
store()
elif store_choice == "4":
if Player.health < 15 and Player.cash >= 6:
Player.health += 5
print("Your health has been increased! Your total health is now: " + str(Player.health))
store()
else:
if Player.health > 15:
print("Wait for your health to lower before buying this weapon!")
store()
elif Player.cash < 6:
print("You do not have enough money to purchase that!")
store()
if store_choice == "5":
print("Sending you back to the Main Menu!")
GameLoop()
else:
print("That is not a valid option! Sending you back to store menu!")
store()
# Main game loop
Player1 = Player()
def GameLoop():
print("\nGame Menu")
print(
"""
1 - Next Move
2 - Go to store
3 - Get player status
4 - Quit game
"""
)
choice = input("Choice: ")
while choice != "4":
if choice == "1":
MoveLoop()
elif choice == "2":
store()
elif choice == "3":
print(Player1)
GameLoop()
if choice == "4":
input("Press the [ENTER] key to exit the program.")
else:
print("That is not a valid option! Sending you back to menu!")
# start the game
GameLoop()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T03:56:44.943",
"Id": "37747",
"Score": "0",
"body": "I think toxotes gave a good explanation and I am agree with him. You should do object oriented programming if you are dealing with classes and all. Ok, I will add just one more point, please try to read this first http://www.python.org/dev/peps/pep-0008/ it will help you to write more readable code. cheers!"
}
] |
[
{
"body": "<p>I would use <code>Player.health</code>, <code>.damage_points</code>, and <code>.cash</code> as instance attributes, rather than class attributes:</p>\n\n<pre><code>class Player(object):\n def __init__(self):\n self.health = 20\n self.damage_points = 8\n self.cash = 0\n</code></pre>\n\n<p>A class attribute describes (and applies to) every possible instance of the class, and although there's only going to be a single <code>Player</code> in a given game, this information really is just describing that one player. For example, what if you wanted to add NPC allies? You might want to use the same <code>Player</code> object, but then they'd all have the same health, the same cash, etc.</p>\n\n<p>You already create <code>Player1</code>, so you can just keep that instance through the game loop and change calls to <code>Player</code> to that. Though I'd rename it to <code>player1</code> -- capitalized names are almost universally expected to refer to class names in Python, not instances of a class. Check out the <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">Python style guide</a> for some general standards.</p>\n\n<p>Doing this, I believe you'd also want to change the staticmethods to just normal methods.</p>\n\n<hr>\n\n<p>I wouldn't have the <code>Player</code> methods do all the message printing. This might just be my preference, but if I were expanding or debugging this code, I wouldn't expect <code>store</code>'s upgrade messages to be relayed to the user through here. What if, for example, you want to add several different stores with different upgrade messages? Or let people find magic assault rifles? And you're already taking that approach with the health upgrades.</p>\n\n<hr>\n\n<p>Don't use <code>Player</code>'s <code>__str__</code> method this way: it's meant to create a human-readable representation of your object. Just call it <code>.stat</code>, and let <code>__str__</code> return the player's name or something.</p>\n\n<hr>\n\n<p>Generally, think very carefully about when something should be a method vs. a function vs. just some inline code. Why is <code>check_damage</code> a function while <code>check_for_death</code> is a <code>Player</code> method? Always ask yourself: In your mental model of the process, what work is being done, and what object is actually doing it? And should it be that way?</p>\n\n<hr>\n\n<p>You should also look at how you name and implement the <code>Aliens</code> class. Do these represent individual mobs the PC is fighting, as the name implies? Or an encounter and series of events, as its coded? It's really important to use intuitive, descriptive names for your objects: it makes a big difference later when you or someone else returns to your code, and has to make assumptions based on them. If you want to think of an encounter as an object, go all the way: don't just say 'here are three attack methods', but define some possible ways each round of fighting could go, and say 'while we still have alien to kill, do another round of fighting'.</p>\n\n<hr>\n\n<p>Backing up a bit, your main game routine isn't doing what you might expect it to. This is getting into stuff that's too complex to really go into here, but look at how control is being passed around: you have a whole lot of nested function calls that never actually terminate, and end up just piling up. Let's say someone starts, checks his stats, goes to the store, then makes a move with a <code>randmove</code> value of 8. That's just three actions and he ends up back at the <code>Gameloop</code> menu, right?</p>\n\n<pre><code>Gameloop() # he starts, checks his stats, which calls a new\n--> Gameloop() # then he goes to the store, which calls a new\n --> store() # exits the store, which calls a new\n --> Gameloop() # makes a move, which calls a new\n --> Moveloop() # and the randmove value ends up calling a new\n --> Gameloop()\n</code></pre>\n\n<p>So at this point, you're nested several frames deep in functions that aren't <em>doing</em> anything. At best this is a waste of memory, but think about what happens when one of those frames is created within a <code>while</code> loop that hasn't reached a defined break condition yet.</p>\n\n<p>What you really need to do is have a single main loop, usually a <code>while</code>, that iterates until the player wins, loses, quits, or whatever, and a way of keeping track of the game state -- where the player is, what he's doing, what's going on. As the player does something, control is passed off to new procedures, but you <em>don't</em> call the main loop to return to it. You just let the procedure terminate and return there automatically, because you never actually left it.</p>\n\n<hr>\n\n<p>A few smaller details, because this is getting long:</p>\n\n<p>Look into <a href=\"http://docs.python.org/3.1/library/string.html#format-string-syntax\" rel=\"nofollow\">string formatting</a> to make your output strings easier to read. Instead of </p>\n\n<pre><code>print(\"Your new balance is $\" + str(Player.cash) + \"!\")\n</code></pre>\n\n<p>you could do</p>\n\n<pre><code>print(\"Your new balance is ${}!\".format(self.cash))\n</code></pre>\n\n<p>(Be sure to read the examples in that link, you'll get some ideas.)</p>\n\n<p>An alternative to the <code>check_health</code> and <code>check_damage</code> functions: take a look at <code>min()</code> and <code>max()</code>.</p>\n\n<p>Instead of <code>if randmove == 12 and ... and ...</code>, Python has a nice, concise syntax you can use:</p>\n\n<pre><code>if 12 <= randmove <= 14:\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T00:21:14.363",
"Id": "37730",
"Score": "0",
"body": "Hey, thanks so much for the great answer. All the things you mentioned are gonna help me on my next project. I'm already looking forward to the extra updates that you're gonna provide for me later. Thanks again, I'm taking notes from all of the answers and these are some good things to keep in mind."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-12T21:43:27.470",
"Id": "121019",
"Score": "1",
"body": "I would go a step further and have both `Player` and `Alien` subclass from an `Entity` class that holds things like health, position, death status, etc."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T00:10:04.717",
"Id": "24451",
"ParentId": "24445",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T22:28:37.413",
"Id": "24445",
"Score": "7",
"Tags": [
"python",
"beginner",
"game"
],
"Title": "Alien battle code"
}
|
24445
|
<p>I was wondering about the best way to return the most common items in a list. So far the best way I could do it was:</p>
<pre><code>//@param string $this->matched_ids_list = 1,11,12,11,12,
$this->matched_ids_list = "," . $this->matched_ids_list;
$this->ids_count = explode(",", $this->matched_ids_list);
$this->ids_count = array_unique($this->ids_count); //See below why this is done
foreach ($this->ids_count as $this->id) {
$this->appearences[$this->id] = substr_count($this->matched_ids_list, ",{$this->id},");
//[1] => 1, [11] => 2, [12] => 2
}
$this->most_appearences = max($this->appearences); //2
foreach ($this->appearences as $this->id => $this->times) {
if ($this->times == $this->most_appearences) {
$this->top_ids .= $this->id . ",";
}
}
$this->top_ids = rtrim($this->top_ids, ",");
echo "tops = " . $this->top_ids;
</code></pre>
<p>It basically just works for <code>1,11,12,11,12,</code> and returns <code>11,12</code>, but it seems a bit overcomplicated. I've been at it for some time now. Am I doing more steps than necessary, missing a built-in function or something?</p>
<p>I might be dealing with hundreds of <code>ids</code>, so performance is important.</p>
<p>Would this step:</p>
<pre><code>foreach ($this->ids_count as $this->id) {
$this->appearences[$this->id] = substr_count($this->matched_ids_list, ",{$this->id},");
//[1] => 1, [11] => 2, [12] => 2
}
</code></pre>
<p>do more looping than necessary if <code>array_unique</code> wasn't used?</p>
<p>For instance, if <code>ids_count</code> was</p>
<pre><code>[0] => 1, [1] => 11, [2] => 12, [3] => 11, [4] => 12
</code></pre>
<p>it would count how many times <code>11</code> and <code>12</code> appear on <code>matched_ids_list</code> twice. Instead, I use <code>array_unique</code> so <code>ids_count</code> is</p>
<pre><code>[0] =>, [1] => 1, [2] => 11, [3] => 12
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T23:46:40.450",
"Id": "96300",
"Score": "1",
"body": "After the explode() call use [array_count_values](http://php.net/manual/en/function.array-count-values.php)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T00:11:26.990",
"Id": "96301",
"Score": "0",
"body": "Thanks, I didn't know about that, still a beginner. That makes things simpler, but I wonder if it makes things any faster. Any ideas on how to do some benchmarking?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T00:41:17.010",
"Id": "96302",
"Score": "0",
"body": "Run the two solution 100000 times and measure time with microtime() (simple substracting will give you the delta T) but i have no doubt that array_count_values will be much more faster (built in C function, no string function used)."
}
] |
[
{
"body": "<h2>Skip to the Dramatic Update for the best solution</h2>\n<p>I was curious how to do this myself, because I could clearly tell there had to be an easier way! I started from scratch and I think I've found exactly what this question is asking for.</p>\n<p>I don't normally just rewrite code, but since the question asks the best way, I believe I'm obligated to share what I believe is the "bets way".</p>\n<pre><code>$input = [1, 10, 11, 12, 11, 12, 18, 18];\n\n$recorded = array_count_values($input);\n\narsort($recorded);\n\n$output = [];\n\nforeach ($recorded as $key => $value) {\n if ($value == max($recorded)) {\n array_push($output, $key);\n }\n}\n\nprint_r($output);\n</code></pre>\n<p>I'll explain what's happening here:</p>\n<ol>\n<li>We receive the input in <code>$input</code></li>\n<li><em><code>array_count_values()</code> returns an array using the values of array as keys and their frequency in array as values.</em> In our case, from <code>$input</code>.</li>\n<li><em><a href=\"http://www.php.net/manual/en/function.arsort.php\" rel=\"nofollow noreferrer\"><code>arsort</code></a> — Sort an array in reverse order and maintain index association</em></li>\n<li>Loop over each pair in the newly sorted array. Create some variables to reference the current pair.</li>\n<li><em>If the current value is equal to the largest value from <code>$recorded</code></em></li>\n<li>Add that key to the output!</li>\n</ol>\n<p>And there we have it!</p>\n<p><strong>Update to increase performance</strong></p>\n<pre><code>$input = [1, 10, 11, 12, 11, 12, 18, 18];\n\n$recorded = array_count_values($input);\n\narsort($recorded);\n\n$output = [];\n\n$maximum = max($recorded);\n\nforeach ($recorded as $key => $value) {\n if ($value == $maximum) {\n $output[] = $key;\n } else if ($value < $maximum) {\n break;\n }\n}\n\nprint_r($output);\n</code></pre>\n<p>We've stored the maximum so we aren't checking every iteration, and we're checking for a value less than the maximum so we can break out of the loop to prevent going through the whole array.</p>\n<h2>Dramatic Update</h2>\n<p>So, I completely missed the <a href=\"http://www.php.net/manual/en/function.array-keys.php\" rel=\"nofollow noreferrer\">array_keys function</a>, as <a href=\"https://codereview.stackexchange.com/questions/24446/return-most-common-items-in-list#comment99055_56282\">pointed out by shudder</a>. The newly improved code would look something like:</p>\n<pre><code>$input = [1, 10, 11, 12, 11, 12, 18, 18];\n\n$recorded = array_count_values($input);\n\n$output = array_keys($recorded, max($recorded));\n\nprint_r($output);\n</code></pre>\n<p>Crazy improvement compared to the OPs original code!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-06T19:26:08.607",
"Id": "99044",
"Score": "0",
"body": "If you're working on sorted array then Your loop is not effective. It should break after first rejected key is found. Add `$max = reset($recorded);` before loop and `if ($value < $max) { break; }` inside before `array_push()` (which is actually slower than `$output[] = $key;`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-06T20:52:39.507",
"Id": "99050",
"Score": "0",
"body": "@shudder I suppose you mean *efficient*? If so, I see what you're saying, however using `reset` has no benefit over `max`. Using `array_push` [could be slower](http://php.net/array_push), thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-06T22:14:04.083",
"Id": "99055",
"Score": "0",
"body": "After closer look it can be shorten to a 3-liner with `$output = array_keys($recorded, max($recorded));` being the 3rd."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-06T18:26:47.440",
"Id": "56282",
"ParentId": "24446",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T22:50:32.880",
"Id": "24446",
"Score": "4",
"Tags": [
"php",
"performance"
],
"Title": "Return most common items in list"
}
|
24446
|
<p>I'm open to any advice to help improve this code for general use. </p>
<pre><code>/**
*
* This code was created by Joshua Getner.
* @license http://opensource.org/licenses/bsd-license.php BSD
*
*
*/
namespace Blacksmith;
class Autoloader
{
// an array that maps classnames to there filepaths
protected static $classes = array();
/**
* register your classnames and class paths to the autoloader.
* keeps the loading quick and accurate.
* @param string $class
* @param string $path
* @return null
*/
public static function setClassPath($className, $path)
{
static::$classes[$className] = str_replace('\\' , '/' , $path);
}
/**
* register an array of classname with paths to the file
* keeps the loading quick and accurate.
* @param array $classes
* @return null
*/
public static function setClassPaths(array $classes)
{
static::$classes = array_merge($classes, static::$classes);
}
/**
* return the path to the classname registered.
* @param string $class
* @return string
*/
public static function getClassPath($className)
{
return((isset(static::$classes[$className]) ?
static::$classes[$className] : false));
}
/**
* return the array of all the classes registered.
* @return array
*/
public static function getClassPaths()
{
return static::$classes;
}
/**
* return a formated file path according to the PSR standard
* @param string $class
* @return string
*/
public static function formatPSRClass($class)
{
return str_replace(array('\\', '_'), '/', strtolower($class)) . '.php';
}
/**
* attempt to load the registered class or interface.
* @param string $class
* @return bool
*/
public static function loadClass($class)
{
$path = "";
// check if the class has been mapped
if(static::getClassPath($class) !== false)
{
// set the path as the mapped path
$path = static::getClassPath($class);
}
// so no class mapped, lets try the PSR way
else
{
// get the path from the class name according to PSR-0
$path = str_replace('\\', '/', dirname(__FILE__)) . '/' . static::formatPSRClass($class);
}
// lets attempt to load the file and check if the class or interface exists
if(file_exists($path))
{
@require $path;
if(class_exists($class, false) || interface_exists($class , false))
{
return true;
}
}
// throw an exception no class was loaded.
else
{
throw new \Exception(sprintf('unable to load the requested class: %s at path %s', $class, $path));
}
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li>I don't see a reason to use static methods here, consider using plain 'ol methods.</li>\n<li>Why throw an exception? PHP will issue a fatal error when a class is used but not defined.</li>\n<li>Since you are not using <code>spl_autoload_register()</code>, I'm not sure yours will play nicely with other autoloaders</li>\n<li>Why not simply use the <a href=\"https://gist.github.com/jwage/221634\" rel=\"nofollow\">PSR-0 sample autoloader</a>?</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T17:01:04.107",
"Id": "24571",
"ParentId": "24453",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T03:19:32.200",
"Id": "24453",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"classes"
],
"Title": "autoloader class fine tune to be usable in every project"
}
|
24453
|
<p>I'm trying to merge counts for items (URLs) in the list:</p>
<pre><code>[['foo',1], ['bar',3],['foo',4]]
</code></pre>
<p>I came up with a function, but it's slow when I run it with 50k entries. I'd appreciate if somebody could please review and suggest improvements.</p>
<pre><code>def dedupe(data):
''' Finds duplicates in data and merges the counts '''
result = []
for row in data:
url, count = row
url_already_in_result = filter(lambda res_row: res_row[0] == url, result)
if url_already_in_result:
url_already_in_result[0][1] += count
else:
result.append(row)
return result
def test_dedupe():
data = [['foo',1], ['bar',3],['foo',4]]
assert dedupe(data) == [['foo',5], ['bar',3]]
</code></pre>
|
[] |
[
{
"body": "<p>It looks like you could use <a href=\"http://docs.python.org/2/library/collections.html#counter-objects\"><code>collections.Counter</code></a>. Although you may want to use it earlier in your code, when you create the list of pairs you pass to <code>dedupe</code>. As is, you could use the following in your code:</p>\n\n<pre><code>from collections import Counter\n\ndef dedupe(data):\n result = Counter()\n for row in data:\n result.update(dict([row]))\n return result.items()\n\n>>> data = [['foo',1], ['bar',3],['foo',4]]\n>>> dedupe(data)\n[('foo', 5), ('bar', 3)]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T06:54:28.910",
"Id": "24460",
"ParentId": "24458",
"Score": "6"
}
},
{
"body": "<p>Let's assume your list of lists is like this : </p>\n\n<pre><code>a = [[1,1], [2,2], [1,4], [2,3], [1,4]]\nimport itertools\n#you can loop through all the lists and count as :\nb = a\nb.sort()\nb = list(b for b,_ in itertools.groupby(b)) #removing duplicates\ntotal = len(b) #counting total unique elements\nfor i in range(total):\n b[i].insert(3, a.count(b[i])) #count repetitions and inserting in list\n</code></pre>\n\n<p>The counts of elements would be inserted in the index 3 of respective lists.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-28T07:00:04.113",
"Id": "136150",
"ParentId": "24458",
"Score": "1"
}
},
{
"body": "<p>Your main problem is lookups in data structure unfit for this case (list).</p>\n\n<p>To find out count for <code>foo</code> you have to do <em>O(n)</em> operations. You are doing this for every entry in <code>data</code> so you'll have a lot of operations going on.</p>\n\n<p>Instead, you should use data structure with faster lookups. In Python, it would be <code>dict</code> or its derivatives.</p>\n\n<p>You could use <code>collections.defaultdict</code> with <code>0</code> as a default value so you don't have to check if your <code>foo</code> is in the dict already or not - you simply increment <code>result['foo']</code>.</p>\n\n<p>In fact, this use case is so common that <code>collections.Counter</code> implements it and some more things, so you should probably get yourself familiar with it.</p>\n\n<p>So, root of your problem is inappropriate data structure. Speaking of Python, you'd better use <code>dict</code> for your <code>result</code> instead of <code>list</code> - that will give you performance you need - and using <code>Counter</code> instead of raw <code>dict</code> will make things more readable and also DRY.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-28T08:23:16.260",
"Id": "136153",
"ParentId": "24458",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T06:10:21.250",
"Id": "24458",
"Score": "5",
"Tags": [
"python",
"performance",
"array"
],
"Title": "Find and process duplicates in list of lists"
}
|
24458
|
<p>I'm (very) new to Scala, and decided I'd try to get a handle on some of the syntax and general language constructs. This currently doesn't implement any backtracking and will only solve things if they can be derived exactly from the values given in the initial board. </p>
<p>That being said, I don't particularly care about adding backtracking at the moment; this was much more a project to simply deal with some of the simpler language constructs (Basic <code>I/O</code> and <code>Collections</code> usage, mainly). I'm far more interested in:</p>
<ul>
<li>How I can improve my code: there are definite blocks of "imperativeness" that are hanging around. Can these be replaced with equivalent code in a more functional style?</li>
<li>Style guidelines: are there any general Scala style guidelines I'm breaking? Names and cases for methods and variables, comments, etc.</li>
<li>Collection and File I/O usage. Any methods from these that I'm not currently using that would simplify the code?</li>
<li>Exception handling: currently there is none. I'm not sure how this is done idiomatically in Scala, minus the fact that exceptions are used judiciously. I've left it out mainly out of language ignorance; any pointers on how this could be included here in a functional style would be great.</li>
</ul>
<p>{Note: I'm aware of the badness of not putting this in a package, but I've left it out here on purpose.}</p>
<pre><code>import scala.collection.mutable.{Map => MMap}
import scala.collection.mutable.HashMap
import scala.collection.mutable.{Set => MSet}
import scala.io.Source
import scala.math.ceil
/** Basic Sudoku Solver.
*
* Currently only supports solving completely "logical" puzzles
* (that is, anything that doesn't need guess-and-check
* style backtracking).
*
*/
object BasicSudokuSolver
{
val rowLength = 9
val columnLength = 9
val allPossible = allPossibleValues()
def main(args: Array[String]) = {
val line = readPuzzleFile(args(0))
val puzzle = linesToMap(line)
var hasChanged = true
//Imperative style code. Each time around, we check if we've solved
//at least one extra value in our puzzle. If we haven't, then we've
//exhausted how much can be filled in by logic alone, and we'd have
//to start guess and check + backtracking to a solution.
while (hasChanged) {
hasChanged = false
//We only want a list indexes of values that haven't been solved yet
val currentUnknown = puzzle.filter(x => x._2 == 0).keys.toIterator
for (index <- currentUnknown) {
val z = filterPossibilities(puzzle, index)
if (z > 0) {
hasChanged = true
puzzle(index) = z
}
}
}
//Create a sorted list from our Map, based on List[Int].
//We want the indexes to come out in the value ordered by row, then column.
val solved = puzzle.toList.sortWith((x, y) => if (x._1(0) == y._1(0)) x._1(1) < y._1(1)
else x._1(0) < y._1(0))
for (v <- solved.zipWithIndex) {
if (v._2 % columnLength == 0) println()
print(v._1._2 + " ")
}
println()
}
/** Reads in a sudoku puzzle. This should conform to the following:
* - Unknown values are 0
* - Known values are their integer value
* - Separator is a simple space (" ")
* - There is a trailing space after the last value, before the newline
* For example, a row of the puzzle may look like:
* 0 0 3 0 2 0 6 0 0 /n
*
* Returns: The puzzle as a single string, separated by spaces.
*/
def readPuzzleFile(name: String): String = {
val source = Source.fromFile(name)
val lines = source.mkString.replace(System.lineSeparator(), "")
source.close
lines
}
/** Given a string containing a sudoku puzzle conforming to spec in the
* comments above readPuzzleFile, will convert this to a Map[List[Int], Int]
* where the List[Int] (Key) contains the row/column index,
* and the Int (Value) contains the puzzle value for that index. Note that
* indexes start at 1, and go through to 9 (inclusive).
*
* Returns: Map containing ((rowIndex, columnIndex), value) pairs
*/
def linesToMap(line: String): MMap[List[Int], Int] = {
val puzzleValues = line.split(" ").map(_.toInt)
val m = new HashMap[List[Int], Int]()
for {
i <- 1 to rowLength
j <- 1 to columnLength
} m += (List(i, j) -> puzzleValues((i - 1) * rowLength + (j - 1)))
m
}
/** Returns: A simple Set[Int] containing all possible values for any
* index prior to removal via constraints. Equivalent to a Set[Int](1 to 9).
*/
def allPossibleValues(): Set[Int] = {
val set = MSet[Int]()
for(i <- 1 to rowLength) set += i
set.toSet
}
/** Filters the set of all possibilities (1 - 9) based on row, column
* and box constraints. Any value which already exists in the same
* column, row, or box is removed from the set of all possibilities.
*
* Returns: the (singular) value that can go into a given index if such a
* singular value exists, otherwise 0.
*/
def filterPossibilities(puzzle: MMap[List[Int], Int], index: List[Int]): Int = {
val columnValues = puzzle.filter(x => x._1(1) == index(1) &&
x._2 != 0).values.toSet
val rowValues = puzzle.filter(x => x._1(0) == index(0) &&
x._2 != 0).values.toSet
val allPoss = allPossible&~(columnValues.union(rowValues).union(getBoxValues(puzzle, index)))
if (allPoss.size == 1) allPoss.toIterator.next else 0
}
/** Returns: All values around an index in its given "box". These are then
* removed from the set of all possibilities in filterPossibilities.
*/
def getBoxValues(puzzle: MMap[List[Int], Int], index: List[Int]):
Set[Int] = {
val boxNumber = List(ceil(index(0) / 3.0).toInt, ceil(index(1) / 3.0).toInt)
val upperBound = List(3 * boxNumber(0), 3 * boxNumber(1))
val lowerBound = List(3 * boxNumber(0) - 2, 3 * boxNumber(1) - 2)
val values = MSet[Int]()
for {
i <- lowerBound(0) to upperBound(0)
j <- lowerBound(1) to upperBound(1)
} values += puzzle(List(i, j))
values.toSet
}
}
</code></pre>
|
[] |
[
{
"body": "<p>There are some things that can improved here. First, try to find the most appropriate data structure that does what you want. Why a <code>List</code> with x and y coordinates instead of a <code>Tuple2</code> or even better a <code>Position</code>?</p>\n\n<hr>\n\n<p>Why does <code>allPossibleValues</code> exists?</p>\n\n<p><code>(1 to 9).toSet</code> or <code>Set(1 to 9: _*)</code> is enough.</p>\n\n<hr>\n\n<p>Never return error values like in <code>filterPossibilities</code>, instead use the <code>Option</code> monad:</p>\n\n<pre><code>if (allPoss.size == 1) allPoss.toIterator.next else 0\n// should be used as\nif (allPoss.size == 1) allPoss.headOption else None\n</code></pre>\n\n<p>Furthermore, try to prefix <code>find</code> before methods returning <code>Option</code>.</p>\n\n<hr>\n\n<p>Don't prefix <code>get</code> before a method name unless you try to interoperate with Java code - in functional languages everything returns a value, thus there is no need to mark this as a property of a method.</p>\n\n<pre><code>getBoxValues -> boxValues\n</code></pre>\n\n<hr>\n\n<p><code>source.mkString.replace(System.lineSeparator(), \"\")</code> is equivalent to <code>source.getLines.mkString</code></p>\n\n<hr>\n\n<p><code>map.filter(f).keys</code> is equivalent to <code>map.collect{case (k,v) if f => k}</code></p>\n\n<hr>\n\n<p>A <code>Map[Position, Int]</code> can easily be sorted with <code>map.toList.sortBy(_._1)</code> when you provide an implicit <code>Ordering[Position]</code> (preferable in the companion object of <code>Position</code> because of automatic import)</p>\n\n<hr>\n\n<p>Instead of your imperative way to print out the Sudoku, you can use something of the form</p>\n\n<pre><code>seqOfDim2 map (_ mkString \" \") mkString \"\\n\"\n</code></pre>\n\n<hr>\n\n<p>In Scala normally one does never create a collection with <code>new</code>, instead the companion objects should be used. These provide factories in order to hide the information which collection is created. Appending to mutable collections can normally be avoided with <code>yield</code> (of the for-comprehension) or with a <code>fold</code>.</p>\n\n<hr>\n\n<p>Instead of accessing values in a <code>Seq</code> by its index or in a tuple by its corresponding <code>_x</code> methods, just use pattern matching:</p>\n\n<pre><code>scala> val List(a, b) = List(1, 2)\na: Int = 1\nb: Int = 2\n\nscala> val (a, b) = (1, 2)\na: Int = 1\nb: Int = 2\n</code></pre>\n\n<hr>\n\n<p>To get rid of ugly side effects monads can be used. But for I/O there is no I/O-monad in Scala. Instead we have to use some method chaining on <code>Iterator</code>:</p>\n\n<pre><code>val value = Iterator.iterate(start)(f).dropWhile(f).next\n</code></pre>\n\n<hr>\n\n<p>Use classes to avoid unnecessary parameters to methods. Methods that operate on the same values can be methods on class</p>\n\n<pre><code>case class Sudoku(puzzle: Map[Position, Int]) {\n def findPossibility(pos: Position): Option[Int] = ???\n def boxValues(pos: Position): Set[Int] = ???\n}\n\n// instead of\ndef findPossibility(puzzle: Map[Position, Int], pos: Position): Option[Int] = ???\ndef boxValues(puzzle: Map[Position, Int], pos: Position): Set[Int] = ???\n</code></pre>\n\n<p>This also brings more OO into your code.</p>\n\n<hr>\n\n<p>You can use <code>util.Try</code> (another monad) to get rid of exceptions.</p>\n\n<hr>\n\n<p>At the end your code can look like this:</p>\n\n<pre><code>import scala.util._\n\n/**\n * Basic Sudoku Solver.\n *\n * Currently only supports solving completely \"logical\" puzzles\n * (that is, anything that doesn't need guess-and-check\n * style backtracking).\n *\n */\nobject BasicSudokuSolver {\n\n def main(args: Array[String]) = {\n// val input = readPuzzleFile(\"sudoku\")\n\n val input =\n \"\"\"0 6 0 8 0 0 2 0 9\n3 2 1 0 6 0 0 7 0\n0 9 0 0 0 0 6 5 3\n0 0 0 0 1 7 0 6 0\n4 0 0 3 0 2 0 0 5\n0 1 0 6 8 0 0 0 7\n1 3 0 0 0 9 0 4 0\n0 5 0 0 4 0 9 3 8\n6 0 9 0 0 8 0 0 0\"\"\" split \"\\n\"\n\n val linesToPuzzle = Try {\n val data = input map (_ split \" \" map (_.toInt))\n val puzzle = for (x <- 1 to 9; y <- 1 to 9) yield Position(x, y) -> data(x - 1)(y - 1)\n puzzle.toMap\n }\n\n linesToPuzzle match {\n case Failure(e) => println(e)\n case Success(startPuzzle) =>\n val field = solveSudoku(startPuzzle).field.toList.sortBy(_._1)\n val actual = field map (_._2) grouped 9 map (_ mkString \" \") mkString \"\\n\"\n\n val expected =\n \"\"\"5 6 4 8 7 3 2 1 9\n3 2 1 9 6 5 8 7 4\n8 9 7 4 2 1 6 5 3\n9 8 3 5 1 7 4 6 2\n4 7 6 3 9 2 1 8 5\n2 1 5 6 8 4 3 9 7\n1 3 8 2 5 9 7 4 6\n7 5 2 1 4 6 9 3 8\n6 4 9 7 3 8 5 2 1\"\"\"\n\n assert(actual == expected)\n println(\"ok\")\n }\n\n }\n\n def solveSudoku(startField: Map[Position, Int]): Sudoku = {\n val iter = Iterator.iterate(Sudoku(startField, solved = false))(_.solveStepByLogic)\n val end = iter dropWhile (!_.solved)\n end.next\n }\n\n /**\n * Reads in a sudoku puzzle. This should conform to the following:\n * - Unknown values are 0\n * - Known values are their integer value\n * - Separator is a simple space (\" \")\n * For example, a row of the puzzle may look like:\n * 0 0 3 0 2 0 6 0 0 \\n\n *\n * Returns: The puzzle as a single string, separated by spaces.\n */\n def readPuzzleFile(name: String): Seq[String] = {\n val source = io.Source.fromFile(name)\n val lines = source.getLines.toList\n source.close\n lines\n }\n}\n\nobject Position {\n implicit val ordering: Ordering[Position] = new Ordering[Position] {\n def compare(p1: Position, p2: Position) = {\n val comp = p1.x - p2.x\n if (comp == 0) p1.y - p2.y else comp\n }\n }\n}\ncase class Position(x: Int, y: Int)\n\nobject Sudoku {\n val possibleValues = (1 to 9).toSet\n}\ncase class Sudoku(field: Map[Position, Int], solved: Boolean) {\n import Sudoku._\n\n def solveStepByLogic: Sudoku = {\n val currentUnknown = field collect { case (p, i) if i == 0 => p }\n val found = for {\n pos <- currentUnknown.toList\n p <- findPossibility(pos).toList\n } yield pos -> p\n\n Sudoku(field ++ found, found.isEmpty)\n }\n\n /**\n * Filters the set of all possibilities (1 - 9) based on row, column\n * and box constraints. Any value which already exists in the same\n * column, row, or box is removed from the set of all possibilities.\n *\n * Returns: the (singular) value that can go into a given index if such a\n * singular value exists, otherwise 0.\n */\n def findPossibility(pos: Position): Option[Int] = {\n val columnValues = field.collect { case (p, i) if p.y == pos.y && i != 0 => i }.toSet\n val rowValues = field.collect { case (p, i) if p.x == pos.x && i != 0 => i }.toSet\n val allPoss = possibleValues &~ (columnValues | rowValues | boxValues(pos))\n\n if (allPoss.size == 1) allPoss.headOption else None\n }\n\n /**\n * Returns: All values around an index in its given \"box\". These are then\n * removed from the set of all possibilities in filterPossibilities.\n */\n private def boxValues(pos: Position): Set[Int] = {\n import math.ceil\n val (xb, yb) = (ceil(pos.x / 3.0).toInt, ceil(pos.y / 3.0).toInt)\n val (xub, yub) = (3 * xb, 3 * yb)\n val (xlb, ylb) = (3 * xb - 2, 3 * yb - 2)\n\n val values = for {\n x <- xlb to xub\n y <- ylb to yub\n } yield field(Position(x, y))\n\n values.toSet\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T01:15:24.637",
"Id": "37809",
"Score": "0",
"body": "Thanks for the feedback. Generally, the answer to all your questions of \"why ...\" or \"why not ...\" are purely me being ignorant of the language and associated constructs. There's a lot here to go over, especially case classes, pattern matching and yield. I -knew- there must be a better way to create a set of 9 consecutive values, so thanks for that too."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T20:31:39.640",
"Id": "24486",
"ParentId": "24461",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "24486",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T07:11:00.193",
"Id": "24461",
"Score": "8",
"Tags": [
"scala",
"sudoku"
],
"Title": "Basic (Logical Only) Sudoku Solver"
}
|
24461
|
<p>The following piece of code executes 20 million times each time the program is called, so I need a way to make this code as optimized as possible.</p>
<pre><code>int WilcoxinRST::work(GeneSet originalGeneSet, vector<string> randomGenes) {
vector<string> geneIDs;
vector<bool> isOriginal;
vector<int> rank;
vector<double> value;
vector<int> score;
int genesPerSet = originalGeneSet.geneCount();
unsigned int totalGenes, tempScore;
/**
* Fill the first half of the vectors with original gene set data
*/
totalGenes = genesPerSet * 2;
for (int i = 0; i < genesPerSet; i++) {
geneIDs.push_back(originalGeneSet.getMemberGeneAt(i));
isOriginal.push_back(true);
value.push_back(fabs(expressionLevels.getValue(geneIDs[i], statType)));
}
/**
* Fill the second half with random data
*/
for (unsigned int i = genesPerSet; i < totalGenes; i++) {
geneIDs.push_back(randomGenes.at(i - genesPerSet));
isOriginal.push_back(false);
value.push_back(fabs(expressionLevels.getValue(geneIDs[i], statType)));
}
totalGenes = geneIDs.size();
/**
* calculate the scores
*/
if (statType == Fold_Change || statType == T_Statistic
|| statType == Z_Statistic) {
// Higher value is a winner
for (unsigned int i = 0; i < totalGenes; i++) {
tempScore = 0;
if (!isOriginal[i]) {
for (int j = 0; j < genesPerSet; j++) {
if (value.at(i) > value.at(j)) {
tempScore++;
}
}
} else {
for (unsigned int j = genesPerSet; j < totalGenes; j++) {
if (value.at(i) > value.at(j)) {
tempScore++;
}
}
}
score.push_back(tempScore);
}
} else if (statType == FDR_PValue || statType == PValue) {
// Lower value is a winner
for (unsigned int i = 0; i < totalGenes; i++) {
tempScore = 0;
if (!isOriginal[i]) {
for (int j = 0; j < genesPerSet; j++) {
if (value.at(i) < value.at(j)) {
tempScore++;
}
}
} else {
for (unsigned int j = genesPerSet; j < totalGenes; j++) {
if (value.at(i) < value.at(j)) {
tempScore++;
}
}
}
score.push_back(tempScore);
}
} else {
cout << endl << "ERROR. Statistic type not defined." << endl;
}
/**
* calculate Ua, Ub and U
*/
int U_Original = 0, U_Random = 0, U_Final;
for (int j = 0; j < genesPerSet; j++) {
U_Original += score[j];
}
for (unsigned int j = genesPerSet; j < totalGenes; j++) {
U_Random += score[j];
}
U_Final = (U_Original < U_Random) ? U_Original : U_Random;
/**
* calculate z
*/
double Zn, Zd, Z;
Zn = U_Final - ((genesPerSet * genesPerSet) / 2);
Zd = sqrt(
(double) (((genesPerSet * genesPerSet
* (genesPerSet + genesPerSet + 1)))) / 12.0);
Z = Zn / Zd;
/**
* Return 0/1/2
* 2: p value < 0.01
* 1: 0.01 < p value < 0.05
* 0: p value > 0.05
*/
if (fabs(Z) > 2.303)
return 2;
else if (fabs(Z) > 1.605)
return 1;
else
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T08:43:55.200",
"Id": "37740",
"Score": "2",
"body": "Your best course of action is to use a profiler. Other classes e.g. GeneSet need looking at too."
}
] |
[
{
"body": "<p>It's somewhat difficult without more context, but there are definitely a few things I can see:</p>\n\n<pre><code>int WilcoxinRST::work(GeneSet originalGeneSet, vector<string> randomGenes) \n</code></pre>\n\n<p>This copies <code>randomGenes</code> every time it is called. You should pass by <code>const &</code>:</p>\n\n<pre><code>int WilcoxinRST::work(GeneSet originalGeneSet, const vector<string>& randomGenes)\n</code></pre>\n\n<p>With some of your <code>vectors</code>, you already know how much space they will need up front - so initialize it - this will save reallocations later.</p>\n\n<pre><code>vector<string> geneIDs(genesPerSet);\nvector<double> value(totalGenes);\n</code></pre>\n\n<p>Don't use <code>vector<bool></code>. It's not a <code>vector</code>, and it doesn't hold <code>bool</code>s (to paraphrase from Scott Myers). Use a <code>std::bitset</code> instead. This is also stack allocated, and so may be (slightly) faster, although be careful if it gets too large - you may run out of stack space:</p>\n\n<pre><code>std::bitset<genesPerSet * 2> isOriginal;\n</code></pre>\n\n<p><code>rank</code> seems to be unused, get rid of it.</p>\n\n<p><code>at</code> is range checked and will throw an exception if it is out of bounds. Utilize <code>operator[]</code> if you're really worried about speed (although this will likely be a tiny speed-up).</p>\n\n<p>These are probably the most obvious things. There's not really enough context for any other suggestions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T14:44:23.960",
"Id": "37755",
"Score": "2",
"body": "A template's argument has to be a compile time constant. Your declaration for `isOriginal` will not compile."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T08:46:14.967",
"Id": "24466",
"ParentId": "24462",
"Score": "2"
}
},
{
"body": "<p>Your code have a complexity of O(N*N) [<code>genesPerSet</code>=N]. But using the fact that the order of the values is irrelevant for you we can order it in O(N•log(N)) and compute the “scores” in O(N). (With potentially can be thousands time faster).</p>\n\n<p>Also, we have a total of N*N comparisons. Then <code>U_Original + U_Random</code> = N*N, meaning we don’t need to compute U_Random. \nAlso your statistic Zn= Umin-N*N/2;[<code>Umix=min(U_Original,U_Random)],</code> when you only abs(Zn/Zd) is symmetric around N*N/2. We need only one algorithm. </p>\n\n<p>1.- A first thing can be to take arguments by (const) reference :</p>\n\n<pre><code>int WilcoxinRST::work(const GeneSet &originalGeneSet, const vector<string> &randomGenes)\n</code></pre>\n\n<p>2.- You fill into vector geneIDs; but dont use it ? Why?</p>\n\n<p>3.- You can iterate only 2 times.</p>\n\n<p>4.- You keep the signal values (probe intensitat?) together in one vector and use another vector to signal what is each item – simple keep in two vector.</p>\n\n<p>5.- You don’t need the score vector, only the summa.</p>\n\n<p>6.- Why 20 millions times? I gess your are computing some “statistic” stability or BStrap. Probably you use the same originalGeneSet many time. I think you can in another question post the code that call this function to spare in making each time the vector of values and sorting. </p>\n\n<p>7.- If you aproximatly know the espected size of the vectors you can reserve() it, add new item with push_back(), and access with .at() (somewhere write a try/catsh). But here we know exactly the numer of item, and we can set it in the cinstructor and then use [] with is the faster way.</p>\n\n<p>Here is first the new O(N•log(N)) code. </p>\n\n<p>What follows is a cleanup of your code but still O(N*N), fast but only by a constant factor. </p>\n\n<p>Then the same code but mixed with yours original code and with more comments.</p>\n\n<p>Please, debugg this and tell me how was.</p>\n\n<pre><code>#include<vector>\n#include<algorithm>\n\nint WilcoxinRST::work(const GeneSet &originalGeneSet , const vector<string>& randomGenes) \n{\n size_t genesPerSet = originalGeneSet.geneCount();\n std::vector<double> valueOri(genesPerSet), valueRnd(genesPerSet);\n /**\n * Fill the valueOri vector with original gene set data, and valueRnd with random data\n */\n for (size_t i = 0; i < genesPerSet; i++) \n {\n valueOri[i] = std::fabs(expressionLevels.getValue( originalGeneSet.getMemberGeneAt(i) , statType ));\n valueRnd[i] = std::fabs(expressionLevels.getValue( randomGenes.at(i) , statType ));\n }\n std::sort(valueOri.begin(),valueOri.end());\n std::sort(valueRnd.begin(),valueRnd.end());\n\n /**\n * calculate the scores Ua, Ub and U\n */\n long U_Original=0 ;\n\n if (statType == Fold_Change || statType == T_Statistic || statType == Z_Statistic \n statType == FDR_PValue || statType == PValue ) \n {\n // Higher value is a winner\n size_t j=0;\n for (size_t i = 0; i < genesPerSet /*totalGenes*/; i++) // i - 2x\n { \n while(valueOri[i] > valueRnd[j]) ++j ;\n U_Original += j;\n }\n } else { cout << endl << \"ERROR. Statistic type not defined.\" << endl; }\n\n /**\n * calculate z\n */\n double Zn, Zd, Z;\n Zn = U_Original - ((genesPerSet * genesPerSet) / 2);\n Zd = std::sqrt( (double) (((genesPerSet * genesPerSet* (genesPerSet + genesPerSet + 1)))) / 12.0);\n Z = Zn / Zd;\n\n /**\n * Return 0/1/2\n * 2: p value < 0.01\n * 1: 0.01 < p value < 0.05\n * 0: p value > 0.05\n */\n if (std::fabs(Z) > 2.303) return 2;\n else if (std::fabs(Z) > 1.605) return 1;\n else return 0;\n}\n</code></pre>\n\n<p>What follows is a cleanup of your code but still O(N*N), fast but only by a constant factor. </p>\n\n<pre><code>#include<vector>\nusing namespace std;\nclass GeneSet ;\nclass WilcoxinRST;\n\nint WilcoxinRST::work(const GeneSet &originalGeneSet , const vector<string>& randomGenes) \n{\n size_t genesPerSet = originalGeneSet.geneCount();\n vector<double> valueOri(genesPerSet), valueRnd(genesPerSet);\n /**\n * Fill the valueOri vector with original gene set data, and valueRnd with random data\n */\n for (size_t i = 0; i < genesPerSet; i++) \n {\n valueOri[i] = fabs(expressionLevels.getValue( originalGeneSet.getMemberGeneAt(i) , statType ));\n valueRnd[i] = fabs(expressionLevels.getValue( randomGenes.at(i) , statType ));\n }\n /**\n * calculate the scores Ua, Ub and U\n */\n long U_Original = 0, U_Random = 0, U_Final;\n\n if (statType == Fold_Change || statType == T_Statistic || statType == Z_Statistic) \n {\n // Higher value is a winner\n for (size_t i = 0; i < genesPerSet /*totalGenes*/; i++) // i - 2x\n { for (size_t j = 0; j < genesPerSet; j++) \n { U_Random += (valueRnd[i] > valueOri[j]);// i en 2 set=Rnd, j in 1 set=Ori. count how many Ori are less than this Rnd \n U_Original+= (valueOri[i] > valueRnd[j]);// i in 1 set=Ori, j in 2 set=Rnd, count how many Rnd are less than this Ori \n }\n }\n } else \n if (statType == FDR_PValue || statType == PValue) \n {\n // Lower value is a winner\n for (size_t i = 0; i < genesPerSet; i++) \n { \n for (size_t j = 0; j < genesPerSet; j++) \n { U_Random += (valueRnd[i] < valueOri[j]);// i en 2 set=Rnd, j in 1 set=Ori. count how many Ori are > than this Rnd \n U_Original+= (valueOri[i] < valueRnd[j]);// i in 1 set=Ori, j in 2 set=Rnd, count how many Rnd are > than this Ori \n }\n }\n } else { cout << endl << \"ERROR. Statistic type not defined.\" << endl; }\n\n\n U_Final = (U_Original < U_Random) ? U_Original : U_Random;\n\n /**\n * calculate z\n */\n double Zn, Zd, Z;\n Zn = U_Final - ((genesPerSet * genesPerSet) / 2);\n Zd = sqrt(\n (double) (((genesPerSet * genesPerSet\n * (genesPerSet + genesPerSet + 1)))) / 12.0);\n Z = Zn / Zd;\n\n /**\n * Return 0/1/2\n * 2: p value < 0.01\n * 1: 0.01 < p value < 0.05\n * 0: p value > 0.05\n */\n if (fabs(Z) > 2.303) return 2;\n else if (fabs(Z) > 1.605) return 1;\n else return 0;\n}\n</code></pre>\n\n<p>the same code but mixed with yours original code and with more comments.</p>\n\n<pre><code>int WilcoxinRST::work(const GeneSet &originalGeneSet , const vector<string>& randomGenes) \n{\n size_t genesPerSet = originalGeneSet.geneCount();\n unsigned int totalGenes, tempScore;\n totalGenes = genesPerSet * 2;\n\n //vector<string> geneIDs;\n //vector<bool> isOriginal;\n //vector<int> rank;\n vector<double> valueOri(genesPerSet), valueRnd(genesPerSet);\n //vector<int> score;\n /**\n * Fill the first half of the vectors with original gene set data\n */\n\n for (size_t i = 0; i < genesPerSet; i++) \n {\n //geneIDs.push_back( originalGeneSet.getMemberGeneAt(i) );\n //isOriginal.push_back(true);\n\n valueOri[i] = fabs(expressionLevels.getValue( originalGeneSet.getMemberGeneAt(i) , statType ));\n valueRnd[i] = fabs(expressionLevels.getValue( randomGenes.at(i) , statType ));\n }\n /**\n * Fill the second half with random data\n */\n //for (unsigned int i = genesPerSet; i < totalGenes; i++) {\n // geneIDs.push_back(randomGenes.at(i - genesPerSet));\n // isOriginal.push_back(false);\n // value.push_back(fabs(expressionLevels.getValue(geneIDs[i], statType)));\n //}\n //totalGenes = geneIDs.size();\n /**\n * calculate the scores\n */\n /**\n * calculate Ua, Ub and U\n */\n long U_Original = 0, U_Random = 0, U_Final;\n //for (int j = 0; j < genesPerSet; j++) // j in 1 set=Ori. count how many Ori are less than this Rnd\n //{\n // U_Original += score[j];\n //}\n //for (unsigned int j = genesPerSet; j < totalGenes; j++) // j in 2 set=Rnd, count how many Rnd are less than this Ori \n //{\n // U_Random += score[j];\n //}\n\n if (statType == Fold_Change || statType == T_Statistic || statType == Z_Statistic) \n {\n // Higher value is a winner\n for (size_t i = 0; i < genesPerSet /*totalGenes*/; i++) // i - 2x\n { //tempScore = 0;\n //if (!isOriginal[i]) // i en 2 set=Rnd, j in 1 set=Ori. count how many Ori are less than this Rnd \n for (size_t j = 0; j < genesPerSet; j++) \n { U_Random += (valueRnd[i] > valueOri[j]);// i en 2 set=Rnd, j in 1 set=Ori. count how many Ori are less than this Rnd \n U_Original+= (valueOri[i] > valueRnd[j]);// i in 1 set=Ori, j in 2 set=Rnd, count how many Rnd are less than this Ori \n }\n //} else \n //{\n // for (unsigned int j = genesPerSet; j < totalGenes; j++) // i in 1 set=Ori, j in 2 set=Rnd, count how many Rnd are less than this Ori \n // { if (value.at(i) > value.at(j)) { tempScore++; }\n // }\n\n //}\n //score.push_back(tempScore);\n }\n\n } else \n if (statType == FDR_PValue || statType == PValue) \n {\n // Lower value is a winner\n for (size_t i = 0; i < genesPerSet; i++) \n { \n for (size_t j = 0; j < genesPerSet; j++) \n { U_Random += (valueRnd[i] < valueOri[j]);// i en 2 set=Rnd, j in 1 set=Ori. count how many Ori are > than this Rnd \n U_Original+= (valueOri[i] < valueRnd[j]);// i in 1 set=Ori, j in 2 set=Rnd, count how many Rnd are > than this Ori \n }\n //} else \n //{\n // for (unsigned int j = genesPerSet; j < totalGenes; j++) // i in 1 set=Ori, j in 2 set=Rnd, count how many Rnd are less than this Ori \n // { if (value.at(i) > value.at(j)) { tempScore++; }\n // }\n\n //}\n //score.push_back(tempScore);\n }\n\n //for (unsigned int i = 0; i < totalGenes; i++) \n //{ tempScore = 0;\n // if (!isOriginal[i]) \n // { for (int j = 0; j < genesPerSet; j++) {\n // if (value.at(i) < value.at(j)) { // Rnd i < Ori j increm U_Random\n // tempScore++;\n // }\n // }\n\n // } else {\n // for (unsigned int j = genesPerSet; j < totalGenes; j++) { // Ori i < Rnd j. Increm U_Original\n // if (value.at(i) < value.at(j)) {\n // tempScore++;\n // }\n // }\n\n // }\n\n // score.push_back(tempScore);\n //}\n\n } else { cout << endl << \"ERROR. Statistic type not defined.\" << endl; }\n\n\n U_Final = (U_Original < U_Random) ? U_Original : U_Random;\n\n /**\n * calculate z\n */\n double Zn, Zd, Z;\n Zn = U_Final - ((genesPerSet * genesPerSet) / 2);\n Zd = sqrt(\n (double) (((genesPerSet * genesPerSet\n * (genesPerSet + genesPerSet + 1)))) / 12.0);\n Z = Zn / Zd;\n\n /**\n * Return 0/1/2\n * 2: p value < 0.01\n * 1: 0.01 < p value < 0.05\n * 0: p value > 0.05\n */\n if (fabs(Z) > 2.303)\n return 2;\n else if (fabs(Z) > 1.605)\n return 1;\n else\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T16:18:37.627",
"Id": "37817",
"Score": "2",
"body": "stop using `using namespace std;` http://stackoverflow.com/a/1453605/14065"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T19:05:01.543",
"Id": "37826",
"Score": "0",
"body": "@LokiAstari OK. Actualized. More suggestion, please!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T20:03:13.577",
"Id": "38139",
"Score": "0",
"body": "@Pranjal. I forget one initialization. Now edited."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T10:30:54.550",
"Id": "24467",
"ParentId": "24462",
"Score": "10"
}
},
{
"body": "<p>I took many Ideas from your posts and finally the code runs in 40 seconds from 3 hours before all this. Here is the code that I am using now</p>\n\n<pre><code>/*\n * WilcoxinRST.cpp\n *\n * Created on: 2013-04-07\n * Author: Pranjal\n */\n\n#include \"WilcoxinRST.h\"\n#include <iostream>\n#include <math.h>\n#include <stdio.h>\n#include \"data/ExpressionLevels.h\"\n#include \"data/GeneSetDB.h\"\n#include <string.h>\n#include <vector>\n#include <algorithm>\n\nstd::WilcoxinRST::WilcoxinRST(ExpressionLevels* exp, GeneSetDB* gsdb,\n StatType stat, int maxGenesPerGeneSet) {\n this->expressionLevels = *exp;\n this->maxGenesPerGeneSet = maxGenesPerGeneSet;\n this->geneSetDB = *gsdb;\n this->statType = stat;\n this->opFile.open(\"results.txt\");\n this->opFile << \"Gene Set ID\\t#Genes\\tp<0.01\\tp<0.05\\tp>0.05\" << endl;\n srand(time(NULL));\n go();\n this->opFile.close();\n}\n\nvoid std::WilcoxinRST::go() {\n int x = 0, p005 = 0, p001 = 0, pRem = 0, geneCount = 0, genesWithoutValues;\n GeneSet originalGeneSet;\n vector<string> randomGenes;\n vector<string> originalGenes;\n vector<string> originalGenesRefined;\n unsigned int totalGeneSets = geneSetDB.totalGeneSets();\n\n // Runs for each gene set\n for (unsigned int i = 0; i < totalGeneSets; i++) {\n p001 = 0;\n p005 = 0;\n pRem = 0;\n genesWithoutValues = 0;\n // get the original gene set\n originalGeneSet = geneSetDB.getGeneSetNumber(i);\n originalGenes = originalGeneSet.getMemberGenes();\n\n // refine original gene set based on the availability of expression values.\n for (unsigned int k = 0; k < originalGenes.size(); ++k) {\n if (expressionLevels.getValue(originalGenes[k], statType)\n != -999.999) {\n // cout << expressionLevels.getValue(originalGenes[i], statType);\n originalGenesRefined.push_back(originalGenes[k]);\n } else\n genesWithoutValues++;\n }\n\n originalGeneSet.setMemberGenes(originalGenesRefined);\n originalGenesRefined.clear();\n geneCount = originalGeneSet.geneCount();\n // check if geneCount > max limit;\n if (geneCount == 4/*>= this->maxGenesPerGeneSet*/) {\n //geneCount = originalGeneSet.geneCount();\n vector<double> valueOriginal(geneCount);\n vector<double> valueRandom(geneCount);\n vector<string> originalGenes = originalGeneSet.getMemberGenes();\n\n cout << endl << originalGeneSet.getGeneSetName() << endl;\n // Fill the valueOriginal vector with expression values\n for (int j = 0; j < geneCount; j++) {\n valueOriginal[j] = fabs(\n expressionLevels.getValue(originalGenes[j], statType));\n }\n\n // Sort the valueOriginal vector.\n std::sort(valueOriginal.begin(), valueOriginal.end());\n\n // iterate for 1000 random gene sets.\n for (int j = 0; j < 1000; j++) {\n //randomGenes = expressionLevels.getRandomGenes(geneCount);\n // x = work3(originalGeneSet, randomGenes);\n valueRandom = expressionLevels.getRandomValues(geneCount,\n statType, true);\n\n std::sort(valueRandom.begin(), valueRandom.end());\n x = work3(valueOriginal, valueRandom);\n switch (x) {\n case 1: {\n p005++;\n break;\n }\n case 2: {\n p001++;\n break;\n }\n case 0: {\n pRem++;\n break;\n }\n }\n }\n\n this->opFile << originalGeneSet.getGeneSetId() << \"\\t\"\n << originalGeneSet.geneCount() << \"\\t\" << p001 << \"\\t\"\n << p005 << \"\\t\" << pRem << \"\\t\" << endl;\n cout << endl << i + 1 << \"\\t\" << expressionLevels.printTime();\n cout.flush();\n break;\n }\n this->opFile.flush();\n }\n}\n\nint std::WilcoxinRST::work3(vector<double> originalGenes,\n vector<double> randomGenes) {\n\n /*\n * @param geneSetSize contains the size of the original gene set\n * @param uOriginal stores the final U for the original gene set\n * @param uRandom stores the final U for the random gene set\n * @param originalTemp will be set such that\n */\n int geneSetSize = originalGenes.size();\n int uOriginal = 0;\n int uRandom = 0;\n int originalTemp = 0;\n int randomTemp = 0;\n\n for (int i = 0; i < geneSetSize; ++i) {\n originalTemp = 0;\n while ((originalGenes[i] > randomGenes[randomTemp])\n && randomTemp < geneSetSize) {\n randomTemp++;\n }\n while ((randomGenes[i] > originalGenes[originalTemp])\n && originalTemp < geneSetSize) {\n originalTemp++;\n }\n uOriginal += randomTemp;\n uRandom += originalTemp;\n }\n\n int uFinal = (uOriginal < uRandom) ? uOriginal : uRandom;\n\n /**\n * calculate z\n */\n double Zn, Zd, Z;\n Zn = (double) uFinal\n - (((double) geneSetSize * (double) geneSetSize) / 2.0);\n Zd = sqrt(\n (double) (((geneSetSize * geneSetSize\n * (geneSetSize + geneSetSize + 1)))) / 12.0);\n Z = Zn / Zd;\n\n// cout << endl << \"U Original:\\t\" << uOriginal << \"\\tU Random:\\t\" << uRandom\n// << \"\\tSum = \" << uOriginal + uRandom << \"\\t Z = \" << Z << endl;\n /**\n * Return 0/1/2\n * 2: p value < 0.01\n * 1: 0.01 < p value < 0.05\n * 0: p value > 0.05\n */\n\n cout << Z << \"\\t\";\n cout.flush();\n if (fabs(Z) > 2.303)\n return 2;\n else if (fabs(Z) > 1.605)\n return 1;\n else\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-25T16:48:30.367",
"Id": "307016",
"Score": "0",
"body": "You're still copying the vector arguments every time `work3` is called. Change the argument types to `std::vector<double> const &` instead. Also, I'm not sure how this code can compile, since `vector` is not a type, it's `std::vector`. Maybe one of your includes does a `using namespace std`? In which case, as mentioned by Loki in another comment: http://stackoverflow.com/a/1453605/14065."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T01:29:11.943",
"Id": "24929",
"ParentId": "24462",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T08:03:49.830",
"Id": "24462",
"Score": "8",
"Tags": [
"c++",
"performance",
"statistics",
"bioinformatics"
],
"Title": "Statistical calculations with sets of genes"
}
|
24462
|
<p>I have a requirement to implement a generic UniqueIdentifier which can cover identifiers like OrderId, TrackingID, scannableId and other Ids. The ids, as they are now, are either <code>Long</code> or <code>String</code>.<br>
Below is my implementation of the UniqueIdentifier class --<br></p>
<pre><code>public class UniqueIdentifier {
String stringValue;
Long longValue;
boolean isLong;
boolean isString;
public UniqueIdentifier(String value) {
setStringValue(value);
try
{
setLongValue(Long.parseLong(value));
}
catch(NumberFormatException nex)
{
setLong(false);
}
}
public UniqueIdentifier(Long value) {
setLongValue(value);
setStringValue(Long.toString(value));
}
public String getStringValue() {
return stringValue;
}
private void setStringValue(String stringValue) {
this.stringValue = stringValue;
}
public Long getLongValue() {
return longValue;
}
private void setLongValue(Long longValue) {
this.longValue = longValue;
}
public boolean isLong() {
return isLong;
}
private void setLong(boolean isLong) {
this.isLong = isLong;
}
public boolean isString() {
return isString;
}
private void setString(boolean isString) {
this.isString = isString;
}
}
</code></pre>
<p>Is there anything that i can do better here <br></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T11:28:04.030",
"Id": "37746",
"Score": "0",
"body": "Are you using an ORM, hibernate/JPA or anyhing else?\n\nGive examples of how you would use this class. As it is, it's not very usable.\n\nMost important of all, where and how did this requirement for a generic unique identifier came?"
}
] |
[
{
"body": "<p>Although your requirements are not clear, namely, why unwrapped <code>Long</code> and <code>String</code> objects are not enough or if an identifier can be both simultaneously, I'd say that this would be better served by the following:</p>\n\n<pre><code>public abstract class UniqueIdentifier { /* no data */ }\n\npublic class LongIdentifier extends UniqueIdentifier { ... }\npublic class StringIdentifier extends UniqueIdentifier { ... }\n</code></pre>\n\n<p>In addition:</p>\n\n<ul>\n<li><p>make sure you define <code>equals</code> and <code>hashCode</code>, and maybe, implement <code>Comparable</code>, as identifiers tend to be used as map keys</p></li>\n<li><p>omit setters, making your identifiers immutable, again, for using them as map keys</p></li>\n</ul>\n\n<p>You can check for the class of each object with <code>instanceof</code>, but you should worry if you need to use it a lot. Would such functionality be better server by additional methods in the base class?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T11:24:20.830",
"Id": "24469",
"ParentId": "24468",
"Score": "1"
}
},
{
"body": "<p>You can get rid of the <code>isLong</code> and <code>isString</code> fields, because they will <strong>always</strong> be false! They're initialised to false on construction of a <code>UniqueIdentifier</code> and you never set them to true.</p>\n\n<p>This points to a deeper problem: the <code>isLong</code> and <code>longValue</code> have more to do with each other than your code makes clear (similarly for <code>isString</code> and <code>stringValue</code>). I think your intent is that <code>longValue</code> either contains a number (in which case <code>isLong</code> should be true), or <code>longValue</code> is <code>null</code> and <code>isLong</code> is <code>false</code>. If that's the case, you should get rid of the <code>isLong</code> field and setter, and replace the getter by </p>\n\n<pre><code>public boolean getLong() {\n return longValue == null;\n}\n</code></pre>\n\n<p>There's a problem if you want to be able to use <code>UniqueIdentifier((Long) null)</code> as something that contains an 'absent' <code>Long</code> value, but I think you should rethink your design if you need that.</p>\n\n<p>You could also look into using <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Optional.html\" rel=\"nofollow\">the <code>Optional<T></code> type from Guava</a> or one of it's (many) variants.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T03:37:10.153",
"Id": "37860",
"Score": "0",
"body": "I can not follow this: \"will always be false\". If he calls `setString(true)`, then it is true, not false. - I think you mistyped the method name in your code example, it should be `isLong()`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T04:23:47.113",
"Id": "37861",
"Score": "0",
"body": "`setString(boolean)` is a private method, and is never called from the code, so `isString` can't change from its initial value of `false`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T11:32:48.150",
"Id": "24470",
"ParentId": "24468",
"Score": "0"
}
},
{
"body": "<p>I think this one screams for usage of generics.</p>\n\n<p>ie. </p>\n\n<pre><code>public class UniqueIdentifier<T> {\n T theValue;\n public UniqueIdentifier( T t ) {\n theValue = t;\n }\n public T getValue() {\n return theValue;\n }\n}\n</code></pre>\n\n<p>Can even be extened with a nice factory method.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T14:07:51.420",
"Id": "37749",
"Score": "0",
"body": "Of course they might actually be needing just an `Entity<T>` where `T` is the type of the id, either `Long` or `String`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T12:34:35.140",
"Id": "24474",
"ParentId": "24468",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T10:59:27.047",
"Id": "24468",
"Score": "1",
"Tags": [
"java"
],
"Title": "Implementation of an UniqueIdentifier class"
}
|
24468
|
<p>I am trying to crank up my javascript knowledge by diving into the MVC/MV* design patterns in order to create more reusable and extendable apps.</p>
<p>I am currently sketching out a webapp that involves real time updating of various data feeds.(Facebook and Twitter in the example code) </p>
<p>The app uses jQuery, underscore and native code. I would love to get some feedback on my current implementation with regards to MV*/MVC. Am i doing it wrong/good etc.</p>
<p>Config code:</p>
<pre><code><script type="text/template" id="fb-list-template">
<li>Entry: <%- app.title %></li>
</script>
<script type="text/template" id="tw-list-template">
<li>Entry: <%- app.title %></li>
</script>
<script type="text/template" id="tw-stats-template">
Total tweets: <%- app.tweets %>
<br />
Total lists: <%- app.lists %>
<br />
Total followers: <%- app.followers %>
</script>
<script>
;var AppApi = (function appConfig (AppApi, $, _, undefined) {
'use strict';
_.templateSettings.variable = 'app';
AppApi.config = {
baseurl : window.location.protocol + '//' + window.location.host,
baseuri : window.location.pathname
};
AppApi.config.feeds = [{
type : 'list',
namespace : '_facebook_list_',
api_url : AppApi.config.baseurl + '/assets/script/facebook_list_test.php',
el : $('#fb-list'),
template : $('#fb-list-template').html()
}, {
type : 'list',
namespace : '_twitter_list_',
api_url : AppApi.config.baseurl + '/assets/script/twitter_list_test.php',
el : $('#tw-list'),
template : $('#tw-list-template').html()
}, {
type : 'stats',
namespace : '_twitter_stats_',
api_url : AppApi.config.baseurl + '/assets/script/twitter_stats_test.php',
el : $('#tw-stats'),
template : $('#tw-stats-template').html()
}];
return AppApi;
}(AppApi || {}, jQuery, _));
</script>
</code></pre>
<p>App code:</p>
<pre><code><script>
;var AppApi = (function appInit (AppApi, $, _, window, document, undefined) {
'use strict';
var ListModel = function (opts) {
this.namespace = opts.namespace;
this.api_url = opts.api_url;
this.items = [];
};
ListModel.prototype = {
getItems : function () {
return [].concat(this.items);
},
addItem : function (item) {
this.items.push(item);
Observer.publish(this.namespace + 'item_added', item);
},
openConnection : function () {
var _this = this;
$.ajax({
url : this.api_url,
type : 'GET',
dataType : 'json',
success : function (response) {
_this.addItem(response);
},
complete : function ($xhr, status) {
_this.openConnection();
},
timeout : 50000
});
}
};
var StatsModel = function (opts) {
this.namespace = opts.namespace;
this.api_url = opts.api_url;
this.stats = {};
};
StatsModel.prototype = {
getStats : function () {
return this.stats;
},
updateStats : function (stats) {
this.stats = stats;
Observer.publish(this.namespace + 'stats_updated', stats);
},
openConnection : function () {
var _this = this;
$.ajax({
url : this.api_url,
type : 'GET',
dataType : 'json',
success : function (response) {
_this.updateStats(response);
},
complete : function ($xhr, status) {
_this.openConnection();
},
timeout : 50000
});
}
};
var ListView = function (model, opts) {
this.model = model;
this.el = opts.el;
this.template = _.template(opts.template);
Observer.subscribe(this.model.namespace + 'item_added', this.addItem, this);
};
ListView.prototype = {
addItem : function (item) {
this.el.prepend(this.template(item));
}
};
var StatsView = function (model, opts) {
this.model = model;
this.el = opts.el;
this.template = _.template(opts.template);
Observer.subscribe(this.model.namespace + 'stats_updated', this.updateStats, this);
};
StatsView.prototype = {
updateStats : function (stats) {
this.el.html(this.template(stats));
}
};
var Observer = {
subscribers : {
all : []
},
subscribe : function (type, fn, context) {
type = type || 'all';
fn = typeof fn === 'function' ? fn : context[fn];
if (typeof this.subscribers[type] === 'undefined') {
this.subscribers[type] = [];
}
this.subscribers[type].push({
fn : fn,
context : context || this
});
},
unsubscribe : function (type, fn, context) {
this.updateSubscriptions('unsubscribe', type, fn, context);
},
publish : function (type, publication) {
this.updateSubscriptions('publish', type, publication);
},
updateSubscriptions : function (action, type, arg, context) {
var i,
type = type || 'all',
subscribers = this.subscribers[type],
nrofsubscribers = subscribers ? subscribers.length : 0,
subscriber;
for (i = 0; i < nrofsubscribers; i += 1) {
subscriber = subscribers[i];
if (action === 'publish') {
subscriber.fn.call(subscriber.context, arg);
} else {
if (subscriber.fn === arg && subscriber.context === context) {
subscribers.splice(i, 1);
}
}
}
}
};
if (!AppApi.config || !AppApi.config.feeds) {
throw new Error('Please configure the feeds properly. Aborting...');
return;
} else {
var i,
nroffeeds = AppApi.config.feeds.length,
config;
for (i = 0; i < nroffeeds; i+=1) {
config = AppApi.config.feeds[i];
if (config.type === 'list') {
var model = new ListModel({
api_url : config.api_url,
namespace : config.namespace
}),
view = new ListView(model, {
el : config.el,
template : config.template
});
model.openConnection();
} else if (config.type === 'stats') {
var model = new StatsModel({
api_url : config.api_url,
namespace : config.namespace
}),
view = new StatsView(model, {
el : config.el,
template : config.template
});
model.openConnection();
} else {
throw new Error('Error. Aborting...');
}
}
}
return AppApi;
}(AppApi || {}, jQuery, _, this, this.document));
</script>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T14:38:10.273",
"Id": "37754",
"Score": "0",
"body": "The source can be found at this url. http://001-030.nick.mdcdev.nl/app.php right click and view source. Below at the end of the body tag there is a script tag wich holds the config, the app is located in http://001-030.nick.mdcdev.nl/assets/js/app.js"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T15:00:24.063",
"Id": "37756",
"Score": "0",
"body": "Please paste the code here with the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T15:40:02.637",
"Id": "37778",
"Score": "0",
"body": "Code has been added. Merci folks!"
}
] |
[
{
"body": "<p>I think this code will require more than one review and more than one rewrite.\nPlease consider the following:\n* If you are planning for more feeds, you could consider a helper function to start each one.</p>\n\n<pre><code> for (i = 0; i < nroffeeds; i+=1) {\n\n config = AppApi.config.feeds[i];\n\n if (config.type === 'list') {\n\n var model = new ListModel({\n api_url : config.api_url,\n namespace : config.namespace\n }),\n\n view = new ListView(model, {\n el : config.el,\n template : config.template\n });\n\n model.openConnection();\n\n } else if (config.type === 'stats') {\n\n var model = new StatsModel({\n api_url : config.api_url,\n namespace : config.namespace\n }),\n\n view = new StatsView(model, {\n el : config.el,\n template : config.template\n });\n\n model.openConnection();\n\n } else {\n throw new Error('Error. Aborting...');\n }\n}\n</code></pre>\n\n<p>Could become then</p>\n\n<pre><code>feedTypes =\n{\n 'list' : { model : ListModel , view : ListView },\n 'stats' : { model : StatsModel , view : StatsView }\n};\nfor (i = 0; i < nroffeeds; i+=1)\n{\n config = AppApi.config.feeds[i];\n feedType = feedTypes[config.type];\n if( feedType )\n {\n var model = new feedType.mode( config ); //Not sure this is future proof\n var view = new feedType.view( model , config ); //Not sure this is future proof\n model.openConnection();\n }\n else\n { \n throw new Error('Error. Aborting...');\n }\n}\n</code></pre>\n\n<ul>\n<li><p>Also, openConnection() violates DRY. I would consider having a Model class with an openConnection function. And then use that function.</p></li>\n<li><p>In general, consider having a parent class for Model and View. There is so much duplicated code</p></li>\n<li><p>nrofsubscribers looks not nice, subscriberCount looks better</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T23:33:02.353",
"Id": "37913",
"Score": "0",
"body": "Thanks for your input! It brought me on some better ideas. Reviews and rewrites is how to learn writing better code, this way of writing js is new to me so any feedback is much appreciated. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T13:33:42.023",
"Id": "24535",
"ParentId": "24475",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T13:35:09.770",
"Id": "24475",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Learning MV* based javascript, would appreciate a review of my current app"
}
|
24475
|
<p>I have a class with a method that will be called multiple times over an object's lifetime to perform some processing steps. This method operates on a mixture of immutable (does not change over the lifetime of the process) data and data that is passed as an argument. The immutable data is comparatively expensive to calculate, so I would like to cache it.</p>
<pre><code>class Sample
{
public function process($data)
{
$immutable = $this->getImmutable();
$this->processImplementation($immutable, $data); // not interesting
}
}
</code></pre>
<p><strong>How should <code>getImmutable</code> be implemented?</strong></p>
<p>Option #1 would be</p>
<pre><code>public function getImmutable()
{
static $cache;
if ($cache === null) {
$cache = "not interesting";
}
return $cache;
}
</code></pre>
<p>Option #2 would be</p>
<pre><code>private $_cache;
public function getImmutable()
{
if ($this->_cache === null) {
$this->_cache = "not interesting";
}
return $this->_cache;
}
</code></pre>
<p>Option #2 is of course better OOP, but what I like about option #1 is that the "implementation detail" <code>$cache</code> is physically close to the only place where it is used. This means that it doesn't increase the mental load of someone reading the code unless that someone decides to read the body of <code>getImmutable</code>, in which case the implementation detail has become important.</p>
<p>In my mind, this purely practical argument is stronger than theoretical purisms.</p>
<p>I am also aware that the <code>static</code> version shares the cache across all instances of the class, which option #2 does not (and that's a good thing). However this is not an issue because</p>
<ul>
<li>no more than one instance of the class will be created per process</li>
<li>PHP is not multithreaded so the shared cache will not be a problem even when unit testing</li>
</ul>
<p>Is there some other argument for option #2 that could tip the scales?</p>
|
[] |
[
{
"body": "<p>I'd go with Option #3: extract <code>$cache</code> and <code>getImmutable</code> to a new class whose sole responsibility is providing the expensive data. Whether it caches it and how should be up to the new class. This new class will look just like Option #2 but be separated from the existing class that needs the data.</p>\n\n<p>This provides encapsulation and increases testability.</p>\n\n<p><strong>Update</strong></p>\n\n<p>The ideal design that allows maximal flexibility must always be weighed against the current needs. If the former may give you 4 degrees of awesomeness but you only need 1 in the current application, you are probably better off going with a design that satisfies the latter until you <em>need</em> those extra features.</p>\n\n<p>Encapsulation doesn't need to be applied at the class level in every instance. You can apply it at the method level until you need something more complex.</p>\n\n<p>What would be more complex? One controller needs the data as a PHP model while another needs the JSON, but both may be required multiple times. In this case you'll get gains by caching each form separately. Now you'll want to separate the code to produce and transform the various data representations where the JSON producer can reuse the data-model producer.</p>\n\n<p>By making the JSON controller depend on the JSON producer alone, that producer is free to reuse the data-model producer, hit the database directly, or use test data provided in a fixture for unit tests. Now you're ready to separate all these concerns.</p>\n\n<p>Until then, however, a static variable hidden inside a controller method is sufficient for your needs while providing a basic level of encapsulation.</p>\n\n<p><em>In other words, go with Option #1 and call it a day.</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T23:06:55.313",
"Id": "37803",
"Score": "0",
"body": "First of all thanks for you input. Unfortunately I don't feel that #3 is a good approach in this particular case because calculating the immutable data is 5 LOC; writing a new class for that feels like bringing in the worst parts of Java. In addition, `Sample` is in reality a controller and `$data` is a collection of models; the final result goes into a view. Inserting a new actor in the play is not something I would prefer to do. I should perhaps have mentioned all this because in the general case your recommendation is good, and for that you have my +1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T23:37:31.350",
"Id": "37805",
"Score": "0",
"body": "In that case, given that `$cache` is used in that single method, I would encapsulate it as a static local variable (#1) in the same spirit as #3."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T23:59:14.730",
"Id": "37806",
"Score": "0",
"body": "Yes, `$cache` is never going to be used from anywhere else. One specific controller method transforms models into one particular JSON representation (rendered by the view); the immutable data is a blueprint of what goes into the JSON, which I calculate on the fly by poking the model to see what it has to offer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T03:43:58.893",
"Id": "37810",
"Score": "0",
"body": "@Jon - Does my update satisfy your original query?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T08:16:15.770",
"Id": "37960",
"Score": "0",
"body": "In the end I believe it would be best for a data-agnostic caching component to be utilized here, but since one does not exist ATM I went with localized caching as above. Thanks for your time!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T17:52:41.233",
"Id": "24482",
"ParentId": "24480",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "24482",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T15:48:26.940",
"Id": "24480",
"Score": "7",
"Tags": [
"php",
"object-oriented",
"static"
],
"Title": "Static variable in method vs private class property"
}
|
24480
|
<p>I'm trying to calculate a total value with an array of six numbers and all the basic operators (+-*/).</p>
<p>Suppose you have: 1, 2, 3, 4, 5, 6 and you want to have a total of 10.</p>
<p>Here is my function call a part of my result:</p>
<blockquote>
<p>10 = 4 - ((2 - (5 + 6)) + (3 * 1))
10 = (((6 - 4) - 1) - (2 - 3)) * 5
10 = (2 * 3) - ((1 + (5 - 4)) - 6)<br>
:<br>
:<br>
:<br>
10 = 3 - (5 - (6 * 2))
10 = (3 - 2) * ((1 * 5) * (6 - 4))<br>
10 = (4 + (6 + 3)) - ((5 + 1) / 2)</p>
<p>Number of solutions = 252676</p>
<p>3/28/2013 12:28:25 PM 3/28/2013 12:28:44 PM 00:00:19.7425257</p>
</blockquote>
<p>It took 19 secs for my old quad CPU Q8200 2.33Ghz to process the 105164223 possible expression. I put all the possible expression in a Hashtable. And at the end, I print all the valid expressions. There should be a way to speed up this process.</p>
<p>I have tried to put all the results in a file like: (C - B) * ((A * E) * (F - D))</p>
<p>After that, I process the file and change the letter for the right number. But this file has a size of about 2GB, and it takes 35 secs just to read the file without any progress.</p>
<p>I'd like to have your comments about the code. Can I speed up this code? How can we speed up the process, may be :( parallel, task, async/wait, etc.. ) I'm not used of all this things.</p>
<p>Do you have an other idea for the calculation like put all the equation in a table (like: (C - B) * ((A * E) * (F - D))) and process the table.</p>
<p><a href="https://skydrive.live.com/?cid=cc3999c91405e1b6&id=CC3999C91405E1B6!107&Bsrc=Share&Bpub=SDX.SkyDrive&sc=Documents&authkey=!AqWEqxt1AAYXKeM" rel="nofollow">Sky drive</a></p>
<pre><code>using System;
using System.Collections;
/// <summary>
/// Class to Find all the possible value to reach a number
///from an number array with the basic operators
/// </summary>
class PossibleExpression
{
public DateTime mStartDateTime;
public DateTime mEndDateTime;
public TimeSpan mTimeSpan;
// all the solutions are stored in an Hachtable
public Hashtable mSolutionHashtable = new Hashtable();
// NbEvaluate
public int mNbEvaluate = 0;
// calculate the AbsValue, if we are not able to reach the total, we kept the nearest total
public int mAbsValue = int.MaxValue;
public PossibleExpression()
{
}
/// <summary>
/// Evaluate all the possibility to reach the total with this numbers
/// </summary>
/// <param name="Numbers"></param>
/// <param name="total"></param>
private void Evaluate(Number[] Numbers, int total)
{
mNbEvaluate++;
if (Numbers.Length == 1)
{
int absValue = Math.Abs(Numbers[0].Value - total);
// if the abolute value is less then the one before
if (absValue < mAbsValue)
{
mAbsValue = absValue;
}
// if it was the right absolute value store the ValueString and the Value in the SolutionHashtable
if (mAbsValue == absValue)
{
string valueString = Numbers[0].ValueString.ToString();
if (mSolutionHashtable.ContainsKey(valueString) == false)
{
mSolutionHashtable.Add(valueString, Numbers[0].Value);
}
}
}
else
{
{
// we prepare to call back the function with a smaller array size
Number[] NextNumbers = new Number[Numbers.Length - 1];
{
// allocate Number for this new array
int i = 0;
while (i < NextNumbers.Length)
{
NextNumbers[i] = new Number();
i++;
}
}
// get the right Mix Array
int[][] Mix = AllMix[Numbers.Length];
// for all the possible Mix
int indexMixOperand = 0;
while (indexMixOperand < Mix.Length)
{
// copy all the numbers that was not in the Mix index
if ((Numbers.Length - 1 > 1))
{
int indexNextNumbers = 1; // we kept the index 0 for the Mix result
int i = 0;
while (i < Numbers.Length)
{
if ((i != Mix[indexMixOperand][0])
&& (i != Mix[indexMixOperand][1]))
{
NextNumbers[indexNextNumbers++] = Numbers[i];
}
i++;
}
}
// for all the operators
for (int indexOperator = 0; indexOperator < 4; indexOperator++)
{
// set the number 0 to the total of the expression composed of this two number and operator
if (NextNumbers[0].Set(Numbers[Mix[indexMixOperand][0]], Numbers[Mix[indexMixOperand][1]], indexOperator) == true)
{
// call to evaluate
Evaluate(NextNumbers, total);
}
//next operator
}
// next MixPermutation
indexMixOperand++;
}
}
}
}
public bool Find(int[] numbers, int total)
{
if( numbers.Length == 6)
{
mStartDateTime = DateTime.Now;
mSolutionHashtable = new Hashtable();
mNbEvaluate = 0;
mAbsValue = int.MaxValue;
Number[] Numbers = new Number[6];
Numbers[0] = new Number();
Numbers[1] = new Number();
Numbers[2] = new Number();
Numbers[3] = new Number();
Numbers[4] = new Number();
Numbers[5] = new Number();
Numbers[0].Set(numbers[0]);
Numbers[1].Set(numbers[1]);
Numbers[2].Set(numbers[2]);
Numbers[3].Set(numbers[3]);
Numbers[4].Set(numbers[4]);
Numbers[5].Set(numbers[5]);
foreach (int[] index in m_Index)
{
Number[] CurrentNumbers = new Number[index.Length];
for (int i = 0; i < index.Length; i++)
{
CurrentNumbers[i] = Numbers[index[i]];
}
Evaluate(CurrentNumbers, total);
}
mEndDateTime = DateTime.Now;
mTimeSpan = mEndDateTime - mStartDateTime;
}
return (numbers.Length == 6);
}
// possible index for indirection table
static private int[][] m_Index = new int[][]
{
// with one number
new int[] {0},
new int[] {1},
new int[] {2},
new int[] {3},
new int[] {4},
new int[] {5},
// with two numbers
new int[] {0,1},
new int[] {0,2},
new int[] {0,3},
new int[] {0,4},
new int[] {0,5},
new int[] {1,2},
new int[] {1,3},
new int[] {1,4},
new int[] {1,5},
new int[] {2,3},
new int[] {2,4},
new int[] {2,5},
new int[] {3,4},
new int[] {3,5},
new int[] {4,5},
// with three numbers
new int[] {0,1,2},
new int[] {0,1,3},
new int[] {0,1,4},
new int[] {0,1,5},
new int[] {0,2,3},
new int[] {0,2,4},
new int[] {0,2,5},
new int[] {0,3,4},
new int[] {0,3,5},
new int[] {0,4,5},
new int[] {1,2,3},
new int[] {1,2,4},
new int[] {1,2,5},
new int[] {1,3,4},
new int[] {1,3,5},
new int[] {1,4,5},
new int[] {2,3,4},
new int[] {2,3,5},
new int[] {2,4,5},
new int[] {3,4,5},
// with four numbers
new int[] {0,1,2,3},
new int[] {0,1,2,4},
new int[] {0,1,2,5},
new int[] {0,1,3,4},
new int[] {0,1,3,5},
new int[] {0,1,4,5},
new int[] {0,2,3,4},
new int[] {0,2,3,5},
new int[] {0,2,4,5},
new int[] {0,3,4,5},
new int[] {1,2,3,4},
new int[] {1,2,3,5},
new int[] {1,2,4,5},
new int[] {1,3,4,5},
new int[] {2,3,4,5},
// with five numbers
new int[] {0,1,2,3,4},
new int[] {0,1,2,3,5},
new int[] {0,1,2,4,5},
new int[] {0,1,3,4,5},
new int[] {0,2,3,4,5},
new int[] {1,2,3,4,5},
// with six numbers
new int[] {0,1,2,3,4,5},
};
static private int[][] Mix0 = new int[][]
{
};
static private int[][] Mix1 = new int[][]
{
};
static private int[][] Mix2 = new int[][]
{
new int[] {0,1},
new int[] {1,0}
};
static private int[][] Mix3 = new int[][]
{
new int[] {0,1},
new int[] {0,2},
new int[] {1,0},
new int[] {1,2},
new int[] {2,0},
new int[] {2,1}
};
static private int[][] Mix4 = new int[][]
{
new int[] {0,1},
new int[] {0,2},
new int[] {0,3},
new int[] {1,0},
new int[] {1,2},
new int[] {1,3},
new int[] {2,0},
new int[] {2,1},
new int[] {2,3},
new int[] {3,0},
new int[] {3,1},
new int[] {3,2}
};
static private int[][] Mix5 = new int[][]
{
new int[] {0,1},
new int[] {0,2},
new int[] {0,3},
new int[] {0,4},
new int[] {1,0},
new int[] {1,2},
new int[] {1,3},
new int[] {1,4},
new int[] {2,0},
new int[] {2,1},
new int[] {2,3},
new int[] {2,4},
new int[] {3,0},
new int[] {3,1},
new int[] {3,2},
new int[] {3,4},
new int[] {4,0},
new int[] {4,1},
new int[] {4,2},
new int[] {4,3}
};
static private int[][] Mix6 = new int[][]
{
new int[] {0,1},
new int[] {0,2},
new int[] {0,3},
new int[] {0,4},
new int[] {0,5},
new int[] {1,0},
new int[] {1,2},
new int[] {1,3},
new int[] {1,4},
new int[] {1,5},
new int[] {2,0},
new int[] {2,1},
new int[] {2,3},
new int[] {2,4},
new int[] {2,5},
new int[] {3,0},
new int[] {3,1},
new int[] {3,2},
new int[] {3,4},
new int[] {3,5},
new int[] {4,0},
new int[] {4,1},
new int[] {4,2},
new int[] {4,3},
new int[] {4,5},
new int[] {5,0},
new int[] {5,1},
new int[] {5,2},
new int[] {5,3},
new int[] {5,4}
};
static private int[][][] AllMix = { Mix0, Mix1, Mix2, Mix3, Mix4, Mix5, Mix6 };
using System.Text;
/// <summary>
/// allways have the value and the Value in String format
/// </summary>
public class Number
{
// the int value
public int Value = 0;
// the string value
public StringBuilder ValueString = new StringBuilder(40);
// the operator
public int m_Operator = -1;
/// <summary>
/// Set the value
/// </summary>
/// <param name="value"></param>
public void Set(int value)
{
Value = value;
ValueString.Clear();
ValueString.Append(value);
}
/// <summary>
/// Build the Value String depending on the operand and the operator
/// </summary>
/// <param name="Operande1"></param>
/// <param name="Operande2"></param>
/// <param name="Operator"></param>
private void BuildValueString(Number Operande1, Number Operande2, int Operator)
{
ValueString.Clear();
// int Operande1OperatorFamily = Operande1.m_Operator / 2;
// int Operande2OperatorFamily = Operande2.m_Operator / 2;
// int OperatorFamily = Operator / 2;
if ((Operande1.m_Operator != -1)
// && ( (Operande1OperatorFamily != OperatorFamily)
// || (Operator == 1)
// || (Operator == 2)
// || (Operator == 3)
// )
)
{
ValueString.Append("(");
}
ValueString.Append(Operande1.ValueString);
if ((Operande1.m_Operator != -1)
// && ((Operande1OperatorFamily != OperatorFamily)
// || (Operator == 1)
// || (Operator == 2)
// || (Operator == 3)
// )
)
{
ValueString.Append(")");
}
switch (Operator)
{
case 0:
ValueString.Append(" + ");
break;
case 1:
ValueString.Append(" - ");
break;
case 2:
ValueString.Append(" * ");
break;
case 3:
ValueString.Append(" / ");
break;
}
if ((Operande2.m_Operator != -1)
// && ( (Operande2OperatorFamily != OperatorFamily)
// || (Operator == 1)
// || (Operator == 2)
// || (Operator == 3)
// )
)
{
ValueString.Append("(");
}
ValueString.Append(Operande2.ValueString);
if ((Operande2.m_Operator != -1)
// && ((Operande2OperatorFamily != OperatorFamily)
// || (Operator == 1)
// || (Operator == 2)
// || (Operator == 3)
// )
)
{
ValueString.Append(")");
}
}
/// <summary>
/// Set the number for these operands and operator
/// </summary>
/// <param name="Operande1"></param>
/// <param name="Operande2"></param>
/// <param name="Operator"></param>
/// <returns></returns>
public bool Set(Number Operande1, Number Operande2, int Operator)
{
bool returnValue = true;
m_Operator = Operator;
Value = Operande1.Value;
switch (Operator)
{
case 0:
Value += Operande2.Value;
BuildValueString(Operande1, Operande2, Operator);
break;
case 1:
Value -= Operande2.Value;
BuildValueString(Operande1, Operande2, Operator);
break;
case 2:
Value *= Operande2.Value;
BuildValueString(Operande1, Operande2, Operator);
break;
case 3:
if ((Operande2.Value != 0)
&& (Value % Operande2.Value) == 0)
{
Value /= Operande2.Value;
BuildValueString(Operande1, Operande2, Operator);
}
else
{
returnValue = false;
}
break;
}
return returnValue;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T20:29:54.310",
"Id": "37790",
"Score": "0",
"body": "I believe you wrote too much code. Are you using http://en.wikipedia.org/wiki/Reverse_Polish_notation to compute the values or are you doing something more complex? It is hard to tell by reading all that code. You could also create a dictionary that maps a char operand such as '*' to a lambda that computes the result. I coded something similar in Python ages ago and the hardest part was setting up reverse postfix and some combinatorial tricks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T20:34:44.710",
"Id": "37791",
"Score": "1",
"body": "What does `6 * (1 / 3)` equal? Does `1/3` evaluate to `0` thus making the whole thing `0` or is it operating on floats? If all arithmetic is integer, then you could cull non-integer fractions to speed things up. I would simplify the algorithm before polishing the C# look and feel, as your code could look quite different when you are done."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T20:42:09.997",
"Id": "37792",
"Score": "0",
"body": "Looks like you are doing some memoization with a Hashtable, which is a good idea, I am just not sure yet what it is that you are memoizing. You should using a generic `Dictionary<TKey, TValue>` instead of Hashtable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T20:45:51.653",
"Id": "37793",
"Score": "0",
"body": "1/3 is not a valid sub expression, all arithmetic are integers"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T20:52:09.233",
"Id": "37794",
"Score": "1",
"body": "There should be at most (4^5) * 6! = 737280 permutations: `n1 op n2 op n3 op n4 op n5 op n6` - you have `6!` ways to rearrange the numbers and `4*4*4*4*4 = 1024` ways to pick 5 different operators. With reverse postfix notation the sequence will not necessarily be `num op num op ...` but it is true that you need one less operator than you have numbers."
}
] |
[
{
"body": "<p>I'll comment on the C#ness of the code, then we can worry about the logic.</p>\n\n<p>Overall, not bad. I like the casing and white space.</p>\n\n<p>I see a few things to improve though:</p>\n\n<ol>\n<li>In C#, the general standard for class level members is to prefix with a _. i.e. <code>_solutionHasTable</code>, or if you prefer <code>m_solutionHasTable</code>. There is discussions all over as to which is better, I'll let you decide.</li>\n<li>No need to include an empty default constructor. C# will add it if it is not declared.</li>\n<li>Use var when declaring obvious variables. var is strongly typed, using it just removes unneeded clutter from the code. i.e. <code>var absValue = Math.Abs(Numbers[0].Value - total);</code></li>\n<li>Overall, I think your methods are too long, and trying to do too much. Optimally, the whole method should fit onto one screen. If it doesn't, refactor it into smaller functions. This will also help with #5</li>\n<li>I think the code is over commented. comments like <code>// for all the operators</code> or <code>// call to evaluate</code> are just reiterating what I can read in the code. Comments should be saved to describe why you did something, or to enhance the code, not explain what it is doing. Good code explains what its doing</li>\n<li>Too many magic numbers. use <code>private const int MeaningOfNumber = 1</code> instead.</li>\n<li><code>foreach</code> is a much easier loop structure than <code>for (var i=0;i<4;i++)</code> to use. You should look into it</li>\n<li>m_Index is not correct naming convention for C#. I think a better name can be found.</li>\n<li>On the same note, the operations in m_Index could be done with loops, and constant (or a value in the app.confg file). This way if in the future the number changes, you change it in one place, and the program continues running.</li>\n<li>Use enums when you can. Your operators should be an enum, that will make the switch statement much easier to read:</li>\n</ol>\n\n<hr>\n\n<pre><code>switch (Operator)\n{\n case Operator.Add:\n Value += Operande2.Value;\n BuildValueString(Operande1, Operande2, Operator);\n break;\n case Operator.Subtract:\n Value -= Operande2.Value;\n BuildValueString(Operande1, Operande2, Operator);\n break;\n case Operator.Multiple:\n Value *= Operande2.Value;\n BuildValueString(Operande1, Operande2, Operator);\n break;\n case Operator.Divide:\n if ((Operande2.Value != 0)\n && (Value % Operande2.Value) == 0)\n {\n Value /= Operande2.Value;\n BuildValueString(Operande1, Operande2, Operator);\n }\n else\n {\n returnValue = false;\n }\n break;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T20:58:14.030",
"Id": "37795",
"Score": "1",
"body": "I believe there is actually no standard for fields. Some use the `m_` prefix, others no prefix."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T21:00:20.693",
"Id": "37796",
"Score": "0",
"body": "true, but generally there is something there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T21:01:06.747",
"Id": "37797",
"Score": "0",
"body": "If you count StyleCop as standard, then it would prescrive using `this.` instead of `m_`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T21:02:27.937",
"Id": "37798",
"Score": "0",
"body": "Reshaper likes `_` Tomato Tomato I guess..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T13:44:09.787",
"Id": "38313",
"Score": "0",
"body": "1- I have uses { get; set; } to acces variable member.\n2- The constructor are now, not empty.\n3-\n4- most of the methods are shorter.\n5- I have remove some comment\n6- No more magics numbers.\n7- Now I use a foreach to loop for the operator array.\n8- m_Index is now IndexArray\n9-\n10- I used enum for operators\nThe use of the Dictionary is in general faster than the HachTable.\nIt took about 10 sec to find all the possible equations.\nIf you want to check a look or try it I can put the code\nThank's\nMarc"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T13:45:08.980",
"Id": "38314",
"Score": "0",
"body": "I have not used the \"var\" type for declaration! \nIs-it faster ?\nOr we just used it when the compiler is able to find the proper type ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T15:28:50.820",
"Id": "38316",
"Score": "1",
"body": "[var](http://msdn.microsoft.com/en-us/library/bb383973.aspx) is strongly typed. There aren't any speed enhancements, most people find that it cleans up the code nicely as declarations are all lined up, and it removes unneeded clutter from the code."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T20:49:17.443",
"Id": "24487",
"ParentId": "24485",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-28T20:06:30.663",
"Id": "24485",
"Score": "2",
"Tags": [
"c#",
"performance"
],
"Title": "Optimization expression evaluation challenge"
}
|
24485
|
<p>I need to pull things from lazy source till timeout is reached in this fashion:</p>
<pre><code>var results = lazySource.SelectMany(item =>
{
//processing goes here
}).Pull(timeout: TimeSpan.FromSeconds(5), times: maxNumberOfIterations);
</code></pre>
<p>and I have this solution: </p>
<pre><code>public static class IEnumerableExtensions
{
public static IEnumerable<T> Pull<T>(this IEnumerable<T> enumerable, int? times = null)
{
if (times == null)
return enumerable.ToArray();
else
return enumerable.Take(times.Value).ToArray();
}
public static IEnumerable<T> Pull<T>(this IEnumerable<T> enumerable, TimeSpan timeout, int? times = null)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
if (times != null) enumerable = enumerable.Take(times.Value);
using (var iterator = enumerable.GetEnumerator())
{
while (stopwatch.Elapsed < timeout && iterator.MoveNext())
yield return iterator.Current;
}
}
}
</code></pre>
<p>Am I just reinvented the wheel and it can be done using some external libs? like Rx/Ix maybe ...</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T00:17:11.090",
"Id": "37807",
"Score": "0",
"body": "Use Stopwatch (Elapsed property) instead of DateTime especially DateTime.Now which is slow as hell."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T22:15:54.373",
"Id": "37834",
"Score": "0",
"body": "Is `lazySource` under your control? Can you use .Net 4.5?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T00:40:57.507",
"Id": "37853",
"Score": "0",
"body": "@svick yes, it is, but it should be lazily evaluated, because data amount could be huge"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T00:57:19.910",
"Id": "37854",
"Score": "0",
"body": "What about my second question? Can you use .Net 4.5?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T17:11:05.917",
"Id": "37896",
"Score": "0",
"body": "yes, i can use it"
}
] |
[
{
"body": "<ol>\n<li>A better name for <code>times</code> would be <code>count</code>.</li>\n<li><p>Your two <code>Pull</code> methods are inconsistent:</p>\n\n<ul>\n<li>The first one actually returns a copy of the entire input sequence (<code>ToArray()</code>) while the second one doesn't.</li>\n<li>To keep it consistent with the standard LINQ methods the first method should also just enumerate the input sequence rather than making a copy.</li>\n</ul>\n\n<p>The first method can then be rewritten as:</p>\n\n<pre><code>public static IEnumerable<T> Pull<T>(this IEnumerable<T> enumerable, int? count = null)\n{\n return (times == null) ? enumerable : enumerable.Take(count.Value);\n}\n</code></pre>\n\n<p>Or if you prefer to create a new enumerator:</p>\n\n<pre><code>public static IEnumerable<T> Pull<T>(this IEnumerable<T> enumerable, int? count = null)\n{\n var items = (times == null) ? enumerable : enumerable.Take(count);\n foreach (var item in items)\n {\n yield return item;\n }\n}\n</code></pre></li>\n<li><p>When i first read this question I assumed the intend was to only wait a maximum time for an item to arrive (i.e. input sequence is possibly blocking). Reading the code however seems that you just want to consume as many items as you can in a given time span (specifically it doesn't deal with blocking input sequences). Assuming the latter is what you wanted then I'd change the code to not use the enumerator interface but stick on a slightly higher level:</p>\n\n<pre><code>public static IEnumerable<T> Pull<T>(this IEnumerable<T> enumerable, TimeSpan timeout, int? count = null)\n{\n var stopwatch = new Stopwatch();\n stopwatch.Start();\n\n var items = (times == null) ? enumerable : enumerable.Take(count.Value);\n\n foreach (var item in items)\n {\n if (stopwatch.Elapsed >= timeout) { yield break; }\n yield return item;\n }\n}\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T08:51:07.823",
"Id": "36041",
"ParentId": "24492",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T00:05:56.317",
"Id": "24492",
"Score": "3",
"Tags": [
"c#",
".net",
"system.reactive"
],
"Title": "pull things from lazy source till timeout is reached"
}
|
24492
|
<p>I'm trying to get in the habit of writing better looking code and more efficient code blocks. I wrote this Twitch TV Application which allows you to add and edit channels and it lets you know when a channel is live. Is there anything I can work on to make my code work / look better? </p>
<p><strong>HTML</strong></p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Streaming</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="streamer.js"></script>
<script type="text/javascript" src="dynamic.js"></script>
</head>
<body>
<div id="container">
<div id="nav">
<ul id="mainNav">
<li id="streamInfo"></li>
</ul>
<ul id="chatAnchor">
<li>
<a onclick="$(this).addClass('activeChat');$('#streamChat').removeClass('activeChat')" href="http://twitch.tv/chat/embed?popout_chat=true&amp;channel=mxgdichello" target="chatFrame" id="mainChat" class="activeChat">
Main Chat
</a>
</li>
<li>
<a href="javascript: void(0)" class="tab" id="streamChat" onclick="changeChat()">
Stream Chat
</a>
</li>
</ul>
</div>
<div style="clear:both"></div>
<div id="player">
<object type="application/x-shockwave-flash" id="twitchTV" width="780px"
height="500px"></object>
</div>
<div id="chat">
<iframe name="chatFrame" frameborder="0" scrolling="no" id="chatFrame" src="http://twitch.tv/chat/embed?popout_chat=true&amp;channel=mxgdichello"></iframe>
</div>
<div id="chanControls">
<div id="add">
<a href="javascript:void(0)">
<img src="add.jpg" />
</a>
<form id="addChan" onSubmit="return addChannel()">
Streamer Name:
<input type="text" name="title" />
Streamer Channel:
<span style="color:#383838; font-style:italic">
http://www.twitch.tv/
</span>
<input type="text" name="url" />
<input type="submit" id="submit" value="Verify Channel" />
<span class="successMsg"></span>
</form>
</div>
<div id="edit">
<a href="javascript:void(0)">
<img src="edit.jpg" />
</a>
</div>
</div>
<div id="list">
<ul></ul>
</div>
</div>
</body>
</html>
</code></pre>
<p><strong>Jquery</strong></p>
<pre><code>var streams = new Array();
var current = -1; // For viewers update
var twitch = false;
var youtube = false;
var timer = 60000; // Miliseconds
var toggleEdit = [editList, addList];
var toggleCounter = 0;
var youtubePlayer = '<iframe width="765" height="500" frameborder="0" allowfullscreen id="youtubePlayer"></iframe>';
var twitchPlayer = '<object type="application/x-shockwave-flash" id="twitchTV" width="780px" height="500px"></object>';
var tubes = ["zn7-fVtT16k", "IVJVCoHDAXs", "1_hKLfTKU5Y", "l3w2MTXBebg", "UcTLJ692F70", "zj2Zf9tlg2Y", "mgVwv0ZuPhM",
"7ZsKqbt3gQ0", "YHRxv-40WMU", "ZIMoQHpvFQQ", "TAaE7sJahiw", "xBzoBgfm55w", "AeNYDwbm9qw", "mhTd4_Ids80",
"AFA-rOls8YA", "CeLrlmV9A-s", "7rE0-ek6MZA", "WA4tLCGcTG4", "0M0RbaPxq2k", "vICX-6dMOuA", "njos57IJf-0",
"K5a_v0MP_Fk", "dX_1B0w7Hzc", "xDj7gvc_dsA", "17CLlZuiBkQ", "0kRAKXFrYQ4", "gJ1Mz7kGVf0", "-6G6CZT7h4",
"liLU2tEz7KY", "eHCyaJS4Cbs", "uEIPCOwY4DE", "V2XGp5ix8HE", "DrQRS40OKNE", "BBcYG_J3O2Q", "upxzaVMhw8k",
"0XcN12uVHeQ", "itvJybdcYbI", "l7iVsdRbhnc", "51V1VMkuyx0", "aQQeg3jYgOA", "XGK84Poeynk", "MaCZN2N6Q_I",
"9q5pZ49r9aU", "DFM140rju4k", "qHBVnMf2t7w", "YtO-6Xg3g2M"];
var updateTimer = setInterval(getList, timer); // Update the streams list every minute
$(window).load(function(){
if(localStorage.length == 0)
{
var streamer1 = new Streamer("Gaurdsman Bob", "guardsmanbob", null, null);
var streamer2 = new Streamer("Siv HD", "sivhd", null, null);
var streamer3 = new Streamer("Day9 TV", "day9tv", null, null);
localStorage.setItem(streamer1.url, JSON.stringify(streamer1));
localStorage.setItem(streamer2.url, JSON.stringify(streamer2));
localStorage.setItem(streamer3.url, JSON.stringify(streamer3));
}
getStorage();
getList();
});
$(document).ready(function(){
$('#add a').click(function() {
var lefty = $(this).next();
lefty.animate({
left: parseInt(lefty.css('left'),10) == 150 ?
-lefty.width() : 150
});
});
$('#addChan input[name=title]').click(function(){
var title = $('#addChan input[name=title]');
if(title.val() == "Enter Streamer Name")
{
title.val('');
title.css("border-color", "");
}
});
$('#addChan input[name=url]').click(function(){
var url = $('#addChan input[name=url]');
if(url.val() == "Enter Streamer URL")
{
url.val('');
url.css("border-color", "");
}
});
$('#edit a').click(function(){
if(toggleCounter % 2 == 1)
{
$(document).off('click', '#list li img');
$(document).off('focusout', '#list input.editTitle');
}
toggleEdit[toggleCounter++%2]();
});
});
function getList(){
$.post(
"streams.php",
{streams : JSON.stringify(streams)},
function(data)
{
streams = $.parseJSON(data);
$.each(streams, function(index, obj){
$.each(obj, function(key, value){
if(current == -1 && value == 'online')
{
current = index;
return false;
}
});
});
if(current != -1 && !twitch)
build(current);
else if(current == -1 && !youtube)
randomTube();
if(twitch)
updateViewers();
addList();
}
);
}
function build(index){
var data = 'http://www.twitch.tv/widgets/live_embed_player.swf?channel='; // Object Data
var src = 'hostname=www.twitch.tv&auto_play=false&start_volume=25&channel='; // Flashvars Param
var changeVars = '<param name="flashvars" \
value="hostname=www.twitch.tv&auto_play=false&start_volume=100&channel='+streams[index].url+'"/>';
var params = '<param name="allowFullScreen" value="true" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowNetworking" value="all" />' +
'<param name="movie" value="http://www.twitch.tv/widgets/live_embed_player.swf" />' +
changeVars;
$("#player").html(twitchPlayer);
$("#twitchTV").html(params);
$("#twitchTV").attr("data", data);
if(streams[index].status == 'online')
$('#streamInfo').html("<span id=\"streamTitle\">Streamer: " + streams[index].title +
"</span> - <span id=\"viewers\">" + streams[index].viewers + "</span> Viewers");
else
$('#streamInfo').text("Streamer: " + streams[index].title + " - Offline");
current = index;
twitch = true;
}
function addList(){
var numOffline = 0;
var online = '';
var offline = '';
var curr = '';
for(var i = 0; i < streams.length; i++)
{
if(i == current && streams[i].status == 'online')
{
curr = '<li class="item"><div class="online"></div><a style="color:green" href="javascript: void(0)" \
title="'+streams[i].title+' Stream" \
onClick="changeStream($(this).text())">'+streams[i].title+'</a></li>';
}
else if(streams[i].status == 'online' && i != current)
{
online += '<li class="item"><div class="online"></div><a style="color:green" href="javascript: void(0)" \
title="'+streams[i].title+' Stream" \
onClick="changeStream($(this).text())">'+streams[i].title+'</a></li>';
}
else
{
offline += '<li class="item"><div class="offline"></div><a href="javascript: void(0)" \
title="'+streams[i].title+' Stream - Offline" \
onClick="changeStream($(this).text())">'+streams[i].title+'</a></li>';
numOffline++;
}
}
if(numOffline == streams.length)
{
online += '<li class="item"><div class="online"></div><a style="color:green" href="javascript: void(0)" \
title="Random Youtube" onClick="randomTube()">Random Youtube</a></li>';
}
$('#list ul').html(curr + online + offline);
}
function editList(){
clearInterval(updateTimer);
var online = '';
var offline = '';
var curr = '';
var previousText;
for(var i = 0; i < streams.length; i++)
{
if(i == current && streams[i].status == 'online')
{
curr = '<li class="item"><div><img src="greenDelete.png" /></div> \
<input type="text" value="'+streams[i].title+'" class="editTitle" /></li>';
}
else if(streams[i].status == 'online' && i != curr)
{
online += '<li class="item"><div><img src="greenDelete.png" /></div>\
<input type="text" value="'+streams[i].title+'" class="editTitle" /></li>';
}
else
{
offline += '<li class="item"><div><img src="redDelete.png" /></div>\
<input type="text" value="'+streams[i].title+'" class="editTitle" /></li>';
}
}
$('#list ul').html(curr + online + offline);
$(document).on('click', '#list li div img', function(){
var find = $(this).parent().next("input").val();
alert(find);
var index = findObjByTitle(streams, find);
var obj = streams.splice(index, 1);
removeFromStorage(obj[0]);
$(this).parent().parent().remove();
});
$(document).on('focus', '#list input.editTitle', function(){
previousText = this.value;
});
$(document).off('focus', '#list input.editTitle', function(){});
$(document).on('focusout', '#list input.editTitle', function(){
var index = findObjByTitle(streams, previousText);
streams[index].title = this.value;
updateStorage(streams[index]);
});
}
function updateViewers(){
if(typeof(streams[current]) != 'undefined')
$('#viewers').text(streams[current].viewers);
}
function changeChat(){
var chatSrc = $('#chatFrame').attr('src');
var chat = chatSrc.split('channel=');
$('#chatFrame').attr('src', chat[0]+'channel='+streams[current].url);
$('#mainChat').removeClass('activeChat');
$('#streamChat').addClass('activeChat');
}
function changeStream(find){
var found = false
$.each(streams, function(index, obj){
$.each(obj, function(key, value){
if(!found && streams[index].title == find)
{
build(index);
current = index;
found = true;
return false;
}
});
});
if($('#streamChat').hasClass('activeChat'))
changeChat();
}
function randomTube(){
var video = tubes[Math.floor(Math.random()*tubes.length)];
$('#player').html(youtubePlayer);
$('#player iframe').attr("src", "http://www.youtube.com/embed/"+ video);
$.ajax({
url: "http://gdata.youtube.com/feeds/api/videos/"+video+"?v=2&alt=json",
dataType: "jsonp",
success: function (data){
$('#streamInfo').html('<a href="javascript: void(0)" style="color:#ae0000" title="Random Video" onClick="randomTube()">\
Random Video</a> -- ' + data.entry.title.$t);
}
});
youtube = true;
}
function addChannel(){
var tempStreamer;
var title = $('#addChan input[name=title]');
var url = $('#addChan input[name=url]');
if(title.val() == '' && url.val() == '')
{
title.css("border-color", "red");
title.val("Enter Streamer Name");
url.css("border-color", "red");
url.val("Enter Streamer URL");
return false;
}
else if(title.val() == '')
{
title.css("border-color", "red");
title.val("Enter Streamer Name");
return false;
}
else if(url.val() == '')
{
url.css("border-color", "red");
url.val("Enter Streamer URL");
return false;
}
else
{
title = title.val();
url = (url.serialize()).split('=');
}
tempStreamer = new Streamer(title, url[1], null, null);
$.post(
"chanExists.php",
{streams : tempStreamer},
function(data){
tempStreamer = $.parseJSON(data);
if(!(tempStreamer.status))
{
$('#addChan .successMsg').text("Channel Does Not Exist!");
$('#addChan .successMsg').css('color', 'red');
}
else
{
var objIndex = objExists(streams, tempStreamer);
if(objIndex == -1)
{
$('#addChan .successMsg').text("Channel Added!");
$('#addChan .successMsg').css('color', 'green');
localStorage.setItem(tempStreamer.url, JSON.stringify(tempStreamer));
streams.push(tempStreamer);
clearInterval(updateTimer);
getList();
}
else
{
$('#addChan .successMsg').text("Channel " + streams[objIndex].title + " Already Added");
$('#addChan .successMsg').css('color', 'red');
}
}
});
updateTimer = setInterval(getList, timer);
return false;
}
/*******************************
/* The Following are Storage
/* Manipulation Functions
*******************************/
function getStorage(){
var tempStream;
for(var i = 0; i < localStorage.length; i++)
{
tempStream = $.parseJSON(localStorage.getItem(localStorage.key(i)));
streams.push(tempStream);
}
}
function removeFromStorage(obj){
var found = false;
for(var i = 0; (i < localStorage.length && !found); i++)
{
tempStream = $.parseJSON(localStorage.getItem(localStorage.key(i)));
if(tempStream.url = obj.url)
{
localStorage.removeItem(obj.url);
found = true;
}
}
}
function updateStorage(obj){
var found = false;
for(var i = 0; (i < localStorage.length && !found); i++)
{
tempStream = $.parseJSON(localStorage.getItem(localStorage.key(i)));
if(tempStream.url = obj.url)
{
localStorage.removeItem(obj.url);
localStorage.setItem(obj.url, JSON.stringify(obj));
found = true;
}
}
}
/*******************
/* Streamer Object
/* And Member Functions
*******************/
function Streamer(title, url, status, viewers)
{
this.title=title;
this.url=url;
this.status=status;
this.viewers=viewers;
}
function objExists(arr, obj)
{
var i = arr.length;
while(i--)
{
if(arr[i].url == obj.url)
return i;
}
return -1;
}
function findObjByTitle(arr, title)
{
var found = false;
var i = 0;
while(!found)
{
if(arr[i].title == title)
{
return i;
}
i++;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li>You are mixing single double quote and double quote strings, you should stick to 1</li>\n<li>It is considered better style to have a single comma separated <code>var</code> statement</li>\n<li><p>For</p>\n\n<pre><code>$('#addChan input[name=title]').click(function(){\n var title = $('#addChan input[name=title]');\n if(title.val() == \"Enter Streamer Name\")\n {\n title.val('');\n title.css(\"border-color\", \"\");\n }\n});\n</code></pre>\n\n<ul>\n<li>You could do `var $this = $(this)</li>\n<li>You could chain <code>.val</code> and <code>.css</code> to <code>title.val('').css(\"border-color\", \"\");</code></li>\n<li>You might be able to unify <code>$('#addChan input[name=title]').click(function(){</code> and <code>$('#addChan input[name=url]').click(function(){</code> they are pretty much the same</li>\n</ul></li>\n<li>Your <code>$.post</code> calls have no error handling at all, you should look at that</li>\n<li><code>current</code> is a terrible name, current what ?</li>\n<li><code>$.each(streams, function(index, obj){</code> -> <code>obj</code> should have been <code>stream</code></li>\n<li>HTML building in general: consider a template function, either find a good library or build your own</li>\n<li>Your declaration of variables is not consistent, I can understand why you want to declare <code>twitchPlayer</code> on top, because it could get modified and you could consider the top part a 'config section'. But then you declare <code>changeVars</code> inside <code>build()</code>.. I think you need to re-think where to put which variables</li>\n<li><code>addList</code> has total copy pastage, please consider using a helper function, or perhaps even a temporary variable to hold the <code><li></li></code> and then concatenate into the right string</li>\n<li>The same goes for <code>editList</code></li>\n<li>In <code>addChannel</code> you re-purpose <code>title</code> and <code>url</code> from a jQuery object to a value, not good practice</li>\n<li>In <code>addChannel</code> you should not check for <code>if(title.val() == '' && url.val() == '')</code> as you are basically combining what you already coded for <code>else if(title.val() == '')</code> and <code>else if(url.val() == '')</code></li>\n<li><code>function getStorage(){</code> is funny and shows a general problem with the code. Instead of return what is in storage, as the name would let you believe, a global variable gets set. On the whole, your code is too reliant on globals</li>\n<li>In <code>updateStorage</code>, I dont believe you need to call <code>removeItem</code> first</li>\n<li>I would expect <code>objExists</code> to return a boolean, perhaps call it <code>objIndex</code> ?</li>\n<li><code>findObjByTitle</code>\n<ul>\n<li>You never use <code>found</code></li>\n<li>You never return a boolean</li>\n<li>It seems you could go infinite loop if the title is not at all in the array</li>\n</ul></li>\n</ul>\n\n<p>I hope my feedback does not sound too harsh, it is still an impressive piece of code. You have extracted a lot of constants into well named variables, your functionality is well split over functions. I think you could just use a few more rounds of polishing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:31:58.950",
"Id": "77438",
"Score": "0",
"body": "Thanks for your feedback - Year too late xD - it was a nice stepping stone project and you're right, much of it is redundant and how I handled the ajax call was always sloppy. Not sure what exactly classifies as a answer here but none-the-less I appreciate the input :D !"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T20:17:40.213",
"Id": "44610",
"ParentId": "24493",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "44610",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T04:06:11.323",
"Id": "24493",
"Score": "0",
"Tags": [
"javascript",
"jquery",
"optimization"
],
"Title": "Optimizing Jquery Twitch TV Application"
}
|
24493
|
<p>I am wondering what would be an efficient way to simplify this very simple PHP method and I really lack inspiration:</p>
<pre><code>public function formatToFullDate($countryCode, $hideTime = false)
{
$format = '';
if($hideTime === true)
{
switch($countryCode)
{
case 'us':
case 'ca':
$format = '%A %e %B %Y';
break;
case 'de':
$format = '%A, den %e. %B %Y';
break;
default:
$format = '%A %e %B %Y';
}
}
else
{
switch($countryCode)
{
case 'us':
case 'ca':
$format = '%A %e %B %Y - %I:%M %P';
break;
case 'de':
$format = '%A, den %e. %B %Y - %H:%M';
break;
default:
$format = '%A %e %B %Y - %H:%M';
}
}
return gmstrftime($format, $this->getTimestamp());
}
</code></pre>
|
[] |
[
{
"body": "<p>There is still some redundant code in there(' - %H:%M' and '%A %e %B %Y'). You could put these in variabels, but i like it so more. Sory for my bad English.</p>\n\n<pre><code>public function formatToFullDate($countryCode, $hideTime = false)\n{\n $format = '';\n $time_format = '';\n switch($countryCode)\n {\n case 'us':\n case 'ca':\n $time_format = ' - %I:%M %P';\n $date_format = '%A %e %B %Y';\n break;\n case 'de':\n $time_format = ' - %H:%M';\n $date_format = '%A, den %e. %B %Y';\n break;\n default:\n $date_format = '%A %e %B %Y';\n $time_format = ' - %H:%M';\n }\n if($hideTime)$time_format = '';\n\n return gmstrftime($date_format.$time_format, $this->getTimestamp());\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T12:45:00.783",
"Id": "37812",
"Score": "0",
"body": "Thanks for your suggestion, it is indeed more clean this way."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T11:48:14.770",
"Id": "24498",
"ParentId": "24495",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "24498",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T09:27:58.567",
"Id": "24495",
"Score": "5",
"Tags": [
"php"
],
"Title": "Avoid redundant code in this simple method"
}
|
24495
|
<p>I'm using Raphael.js to generate objects which are unique but do basically the same thing. I'm also using Fancybox to display a unique image after a click on a generated object.</p>
<p>Is there a way to write this more concise?</p>
<pre><code>//OBJECT 101
var p1_101 = p1.path("M361,146.773 366.25,192.94 365.917,196.606 366.583,199.69 387,197.773 392.417,179.023 387.75,178.273 395.833,146.106 397.583,145.94 398,143.023 374,145.273z").attr({"fill":"#d3ae6b", "stroke-width": 0, "fill-opacity": .5, "stroke": "transparent","cursor": "pointer", "title": "101"}).click(function () {
$.fancybox.open([
{
href : 'img/rzuty/p1/101.jpg',
openEffect : 'elastic',
openSpeed : 150,
closeEffect : 'elastic',
closeSpeed : 150,
padding: 2,
}
], {
beforeShow : function() {
$('<a class="pdf" href="img/rzuty/p1/101.pdf" target="_blank"></a>').appendTo(".fancybox-inner");
}
});
}).mouseover(
function () {
this.animate({"fill-opacity": .8}, 200);
}).mouseout(function () {
this.animate({"fill-opacity": .5}, 200);
});
//SETTING CLASS AND ID
p1_101.node.setAttribute('class','reserved'); // CLASS 'reserved' OR 'sold'
p1_101.node.id = 'p1_101';
//OBJECT 102
var p1_102 = p1.path("M337.583,149.023 342.667,196.69 342.333,197.023 342.833,202.107 365.667,199.857 365.167,194.523 364.667,194.357 359.917,150.357 356,150.773 355.75,147.19z").attr({"fill":"#d3ae6b", "stroke-width": 0, "fill-opacity": .5, "stroke": "transparent","cursor": "pointer", "title": "102"}).click(function () {
$.fancybox.open([
{
href : 'img/rzuty/p1/102.jpg',
openEffect : 'elastic',
openSpeed : 150,
closeEffect : 'elastic',
closeSpeed : 150,
padding: 2,
}
], {
beforeShow : function() {
$('<a class="pdf" href="img/rzuty/p1/102.pdf" target="_blank"></a>').appendTo(".fancybox-inner");
}
});
}).mouseover(
function () {
this.animate({"fill-opacity": .8}, 200);
}).mouseout(function () {
this.animate({"fill-opacity": .5}, 200);
});
//SETTING CLASS AND ID
p1_102.node.setAttribute('class','sold'); // CLASS 'reserved' OR 'sold'
p1_102.node.id = 'p1_102';
//OBJECT 103
var p1_103 = p1.path("M314.5,155.107 319.167,197.607 319.167,199.19 318.667,199.44 319.25,204.357 342,202.273 341.583,197.023 340.833,196.607 340.833,195.357 335.917,149.357 331.833,149.607 316.5,151.107 316.75,154.607z").attr({"fill":"#d3ae6b", "stroke-width": 0, "fill-opacity": .5, "stroke": "transparent","cursor": "pointer", "title": "103"}).click(function () {
$.fancybox.open([
{
href : 'img/rzuty/p1/103.jpg',
openEffect : 'elastic',
openSpeed : 150,
closeEffect : 'elastic',
closeSpeed : 150,
padding: 2,
}
], {
beforeShow : function() {
$('<a class="pdf" href="img/rzuty/p1/103.pdf" target="_blank"></a>').appendTo(".fancybox-inner");
}
});
}).mouseover(
function () {
this.animate({"fill-opacity": .8}, 200);
}).mouseout(function () {
this.animate({"fill-opacity": .5}, 200);
});
//SETTING CLASS AND ID
p1_103.node.setAttribute('class','reserved'); // CLASS 'reserved' OR 'sold'
p1_103.node.id = 'p1_103';
</code></pre>
|
[] |
[
{
"body": "<p>Well you could author a jQuery plugin. That would have default settings, with the option of passing some parameters and override settings.</p>\n\n<p>General ideas behind this are :</p>\n\n<ul>\n<li>Making reusable code. Another project with similar stuff? You include the lib and re-use it.</li>\n<li>Making the code as dry as possible. Writing the same thing again and again is annoying and hard to refactor. In a plugin everything is wrote once.</li>\n<li>Even though you want everything to look the same, you have to build it a way you can override default setting, because there's always one object that need to be different.</li>\n</ul>\n\n<hr>\n\n<p>I haven't debug the whole plugin as I had no idea what did a paper object looked lik. But it seemed like it was a jQuery built object as you called <code>.attr</code>, <code>.mouseover</code> and <code>.mouseout</code> which are jQuery function. Though I have debugged the rest of the plugin without calling <code>.path</code> and it was working.</p>\n\n<p>To call the plugin just do something like :</p>\n\n<pre><code>var basePath = 'img/rzuty/p1/';\npaperObject.animatePath('M36.146...', 101, basePath);\npaperObject.animatePath('M337.583...', 102, basePath); \n//...\n</code></pre>\n\n<p>So the plugin code looks like that :</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>(function ($) {\n /**\n *\n * @param path the paper path\n * @param imageNumber the image number which is used in href and pdf and for the id\n * @param basePath the base path for the image\n * @param options option to override defaults settings\n */\n $.fn.animatePath = function (path, imageNumber, basePath, options) {\n\n //Default settings\n var defaults = {\n htmlAttr: {\n 'class': 'reserved',\n 'id': 'ap_' + imageNumber\n },\n cssOptions: {\n fill: '#d3ae6b',\n 'stroke-width': 0,\n 'fill-opacity': 0.5,\n stroke: 'transparent',\n cursor: 'pointer',\n title: imageNumber\n },\n fancyboxOptions: {\n href: basePath + imageNumber + '.jpg ',\n openEffect: 'elastic',\n openSpeed: 150,\n closeEffect: 'elastic',\n closeSpeed: 150,\n padding: 2\n },\n fancyboxAnimations: {\n beforeShow: function () {\n $('<a class =\"pdf\" href=\"' + basePath + imageNumber + '.pdf' + '\"target=\"_blank\" ></a>')\n .appendTo(\".fancybox-inner\");\n }\n },\n mouseOver: function () {\n $(this).animate({\n 'fill-opacity': 0.8\n }, 200);\n },\n mouseOut: function () {\n $(this).animate({\n 'fill-opacity': 0.5\n }, 200);\n }\n\n };\n\n //Merge settings\n var settings = $.extend(true, defaults, options || {});\n\n //Add the fancybox and stuff\n this.path(path)\n .attr(settings.htmlAttr)\n .css(settings.cssOptions);\n this.click(function () {\n $.fancybox.open([settings.fancyboxOptions], settings.fancyboxAnimations);\n });\n this.mouseover(settings.mouseOver);\n this.mouseout(settings.mouseOut);\n\n return this;\n };\n})(jQuery);\n</code></pre>\n\n<p>As you can see every default settings is defined in an object and you can override it by passing it in the options object (which is then merge recursively with the defaults object). The nice thing is that it is now easily reusable. Also, using <code>function($){}(jQuery);</code> enclose the function scope so that it doesn't clash with any other library using <code>$</code>.</p>\n\n<p>Here is a <a href=\"http://jsfiddle.net/dozoisch/9Qczz/\" rel=\"nofollow\">link to a fiddle</a>, be free to update it with the paperObject, because I couldn't do it not knowing what it was.</p>\n\n<hr>\n\n<p>To learn more about <a href=\"http://docs.jquery.com/Plugins/Authoring\" rel=\"nofollow\">jQuery Authoring</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T08:02:55.253",
"Id": "38021",
"Score": "0",
"body": "i will check this and let u know, thx for your answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T09:17:40.573",
"Id": "38027",
"Score": "0",
"body": "in the meantime i can show u a website http://dev.fama.net.pl/nosalowy/apartamenty.html select the first floor of an image in the background and u will see the floor plan"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T19:59:57.867",
"Id": "24575",
"ParentId": "24496",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T10:27:47.973",
"Id": "24496",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"raphael.js",
"fancybox"
],
"Title": "Displaying unique objects generated by Raphael.js in FancyBox"
}
|
24496
|
<p>I've got this code that I found in a project and I'm wondering how can it be done better:</p>
<pre><code>- (void) setAlpha:(float)alpha {
if (self.superview.tag == noDisableVerticalScrollTag) {
if (alpha == 0 && self.autoresizingMask == UIViewAutoresizingFlexibleLeftMargin) {
if (self.frame.size.width < 10 && self.frame.size.height > self.frame.size.width) {
UIScrollView *sc = (UIScrollView*)self.superview;
if (sc.frame.size.height < sc.contentSize.height) {
return;
}
}
}
}
if (self.superview.tag == noDisableHorizontalScrollTag) {
if (alpha == 0 && self.autoresizingMask == UIViewAutoresizingFlexibleTopMargin) {
if (self.frame.size.height < 10 && self.frame.size.height < self.frame.size.width) {
UIScrollView *sc = (UIScrollView*)self.superview;
if (sc.frame.size.width < sc.contentSize.width) {
return;
}
}
}
}
[super setAlpha:alpha];
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T18:10:47.727",
"Id": "37823",
"Score": "1",
"body": "Woah there. That's a big set of conditions. It would be more helpful to know context: what do these do, why are they here, and what do they apply to? It may be possible to break this up into different components by using more OOP functionality, but without that, it's hard to help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-23T08:13:03.917",
"Id": "218942",
"Score": "0",
"body": "This code appears to have been taken from [here](http://stackoverflow.com/a/8607393/1157100) without attribution — which also makes this question off-topic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-27T10:59:10.543",
"Id": "219661",
"Score": "0",
"body": "@200_success, this code was taken from an actual project I was working on at that time and that made me\" wtf\" when I saw it. But I'm glad you're taking interest in a question asked 3 years ago. Hope you get your points. Cheers!"
}
] |
[
{
"body": "<p>That’s almost unreadable. Or, more precisely, it’s plain what the code does, but it’s almost impossible to guess the purpose. Generally, there are two conditions that prevent the view from taking a new alpha setting, right? Some general remarks:</p>\n\n<ul>\n<li><p>The <code>noDisableHorizontalScrollTag</code> constant deserves a better name. It’s a good idea to mark constants with uppercase initial letter (think <code>UIViewAutoresizingFlexibleHeight</code>, <code>CGRectZero</code> and similar), but more importantly the double negation (<em>no disable</em>) is needlessly hard to parse. Why not <code>EnableHorizontalScrollingTag</code>? Or something similar, better fitting your use case.</p></li>\n<li><p>If possible, it’s good to avoid changing view behaviour according to its superview. Especially when you assume here that the superview is always a <code>UIScrollView</code>. Maybe you could introduce some “delegate” or “data source” style pointer to the view to read the constraints from? That would also express the type constraint in the type system, making it possible for the compiler to check the code for you. Again, hard to say more without understanding your use case.</p></li>\n</ul>\n\n<p>But above all, you should introduce some higher-level concept to make the code readable. Like wrap the frame-checking logic into a named method, where the name would be some meaningful concept (<code>isVerticalScrollingEnabled</code>, for example). Otherwise it’s very hard to find the connection between alpha, autoresizing mask, superview’s frame and its content size.</p>\n\n<p>But maybe we’re just missing context here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T11:47:21.367",
"Id": "24794",
"ParentId": "24497",
"Score": "0"
}
},
{
"body": "<p>First of all, using the <code>tag</code> to distinguish between views is almost everytime (there are exceptions) a bad idea. It's much cleaner to use your own variable (pointers to view, <code>BOOL</code> flags).</p>\n\n<p><code>10</code> is a magic number. What does it mean? Use a constant.</p>\n\n<p>Use methods. Four levels of <code>if</code> are terrible. Extract the code into methods.</p>\n\n<pre><code>if ([self isVerticalScrollingDisabled] || [self isHorizontalScrollingDisabled]) {\n return;\n}\n\n[super setAlpha:alpha];\n</code></pre>\n\n<p>By the way, changing the behavior of a method in a subclass (the method sets alpha only if some conditions are valid) is smelly from architecture point of view. Declaring a special method, e.g. <code>setAlphaIfScrollingEnabled:</code> would be better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T10:20:43.300",
"Id": "39631",
"Score": "1",
"body": "Exactly, it violates LSP"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T20:56:42.260",
"Id": "41195",
"Score": "0",
"body": "+1. For example, they could use KVO to listen for alpha changes, and perform the *side effects* then, instead of overriding `setAlpha:`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T12:12:20.170",
"Id": "24796",
"ParentId": "24497",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "24796",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T10:56:24.767",
"Id": "24497",
"Score": "0",
"Tags": [
"objective-c",
"ios"
],
"Title": "iOS/Objective-C \"if\" best practice"
}
|
24497
|
<p>What is the best way to tidy up JavaScript code I have written? It seems very long winded, any suggestions to shorten it?</p>
<p>Note: I'm running it on Wordpress which runs jQuery in nonconflict mode, hence the insane amounts of <code>jQuery.()</code>.</p>
<pre><code>jQuery("document").ready(function (jQuery) {
if (jQuery(window).width() < 960) {
jQuery(".main").animate({
"top": "22%"
});
jQuery('#tblcontents').toggle(function () {
jQuery(".main").fadeOut(1000);
}, function () {
jQuery(".main").fadeIn(1000);
jQuery(".main").animate({
"top": "22%"
});
});
} else {}
jQuery('.menu-button').click(function () {
jQuery("#sb-container div").css("transform", "rotate(0deg)");
jQuery("#sb-container div").css("-webkit-transform", "rotate(0deg)");
jQuery("#sb-container div").css("-ms-transform", "rotate(0deg)");
jQuery("#sb-container div").css("-moz-transform", "rotate(0deg)");
jQuery("#sb-container div").css("-o-transform", "rotate(0deg)");
jQuery(".main").animate({
"right": "1%"
}, "slow");
});
jQuery(function () {
jQuery('.toggle_div').toggle(function () {
jQuery(".main").animate({
"right": "50%"
}, "slow");
}, function () {
jQuery(".main").animate({
"right": "1%"
}, "slow");
});
});
jQuery(".pulse").effect("pulsate", {
times: 100
}, 2000).click(function () {
jQuery(".pulse").effect().stop(true, true);
jQuery(".pulse").animate({
"opacity": "1"
}, "fast");
});
jQuery('.thumb').click(function () {
jQuery("#sb-container div").css("transform", "rotate(0deg)");
jQuery("#sb-container div").css("-webkit-transform", "rotate(0deg)");
jQuery("#sb-container div").css("-ms-transform", "rotate(0deg)");
jQuery("#sb-container div").css("-moz-transform", "rotate(0deg)");
jQuery("#sb-container div").css("-o-transform", "rotate(0deg)");
jQuery("#sb-container").animate({
"left": "0px"
}, "slow");
jQuery(".main").animate({
"right": "1%"
}, "slow");
});
jQuery(window).scroll(function () {
if (jQuery(this).scrollTop() > 20) {
jQuery("#sb-container div").css("transform", "rotate(0deg)");
jQuery("#sb-container div").css("-webkit-transform", "rotate(0deg)");
jQuery("#sb-container div").css("-ms-transform", "rotate(0deg)");
jQuery("#sb-container div").css("-moz-transform", "rotate(0deg)");
jQuery("#sb-container div").css("-o-transform", "rotate(0deg)");
jQuery(".main").animate({
"right": "1%"
}, "slow");
} else {
jQuery("#sb-container").draggable()
}
});
});
jQuery(function () {
jQuery("#sb-container").draggable()
});
</code></pre>
<p>How do I go about reducing the amount of code shown here? What are the best practices and what am I missing? Also, do I need the else statements querying the window width since they don't have any functions in them for the most part?</p>
|
[] |
[
{
"body": "<p>One simple thing you could do is to use <code>jQuery</code> as <code>$</code> inside your <code>ready</code> function.</p>\n\n<p>Since the <code>ready</code> function takes a parameter to <code>jQuery</code>, you could capture that as <code>$</code> for the duration of the <code>ready</code> function:</p>\n\n<pre><code>jQuery(document).ready(function($){\n\n if ( $(window).width() < 960) {\n ...\n</code></pre>\n\n<p>That would likely help improve the readability of the code.</p>\n\n<p>For more info on this capability, you can reference jQuery docs on the <a href=\"http://api.jquery.com/ready/\" rel=\"nofollow\">ready</a> function, which call this nice feature out in the \"Aliasing the jQuery Namespace\" section - specifically intended for use in <code>$.noConflict()</code> mode.</p>\n\n<p>Also, I think you want to switch the <code>ready</code> call to reference <code>document</code> directly, instead of the string <code>\"document\"</code>:</p>\n\n<pre><code>jQuery(document).ready(...\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>jQuery(\"document\").ready(...\n</code></pre>\n\n<p>You might also consider creating this CSS rule:</p>\n\n<pre><code>#sb-container div.clicked {\n transform: rotate(0deg);\n -webkit-transform: rotate(0deg);\n -ms-transform: rotate(0deg);\n -moz-transform: rotate(0deg);\n -o-transform: rotate(0deg);\n}\n</code></pre>\n\n<p>You can then just apply (or remove) the <code>clicked</code> class to that <code>div</code> instead of applying all the CSS directly in javascript. (Separates out the styling to the CSS file from the behaviour in the JS file.)</p>\n\n<pre><code>$('.menu-button').click(function(){\n $('#sb-container div').addClass('clicked');\n $('.main').animate({'right': '1%'}, 'slow');\n});\n</code></pre>\n\n<p>You could also consider using <code>fadeToggle</code> instead of <code>toggle</code> with two <code>fade</code> functions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T15:19:14.583",
"Id": "37813",
"Score": "0",
"body": "all implemented thank you for your time and patiance, I was running jQuery in no conflict I just didn't know you could initilize the $ again in the document ready function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T18:07:10.257",
"Id": "37822",
"Score": "0",
"body": "@vimes1984 would you mind up-voting this answer since you implemented it? Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T19:46:01.223",
"Id": "37831",
"Score": "0",
"body": "I tried but i can't I have to have at least 15 rep to upvote answers srry..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T15:00:16.980",
"Id": "24501",
"ParentId": "24499",
"Score": "4"
}
},
{
"body": "<p>I'm going to go through a few main points here about your code and at the bottom I'll have a \"what I would change\" section with inline comments. Do not be overwhelmed by the size of this book, I prefer to be on the side of too much information than too little.</p>\n\n<p><strong>- Cache your selectors:</strong> Probably the most important thing you can do for your code now. As a rule of thumb, if you use a selection more than once, you should cache it. What happens when you use <code>$(\"someElem\")</code> is jQuery queries the DOM to try and find elements that match. So imagine that every time you do that it runs a search. Would it be better if you could save the search results? This way you can look and play with them whenever you want. Ex.:</p>\n\n<pre><code>$(\"#sb-container div\").css(\"transform\", \"rotate(0deg)\" );\n$(\"#sb-container div\").css(\"-webkit-transform\", \"rotate(0deg)\" );\n\n//Should be like this:\nvar sbContainer = $(\"#sb-container div\"); //Saved my search to a variable, which I use later.\nsbContainer.css(\"transform\", \"rotate(0deg)\" );\nsbContainer.css(\"-webkit-transform\", \"rotate(0deg)\" );\n</code></pre>\n\n<p><strong>- You can use $ in Wordpress:</strong> If you have your code in the footer (which you should be doing) what you'll want to do is wrap it in a IIFE. \"What the hell is that?\" you may ask. A basic syntax looks like this:</p>\n\n<pre><code>(function () {\n //Code goes in here.\n})();\n</code></pre>\n\n<p>You'll see several variations of this all over the internet as you read to find out more. The one I recommend you use in this case is like this:</p>\n\n<pre><code>;(function ($, window, document) {\n //Code goes here and the $ belongs to jQuery\n})(jQuery, window, document);\n</code></pre>\n\n<p>So lets break this down. The <code>;</code> in the front is a safety net against unclosed scripts, which can be common if you use plugins in Wordpress, or if you concat and minify your files it will protect you from your function becoming an argument.</p>\n\n<p>Then we pass in <code>$</code>, <code>window</code>, and <code>document</code>. We pass in <code>$</code> and at the bottom assign it to jQuery. So now in this function, no matter what value the <code>$</code> carried outside, in here it's jQuery. Then we pass in <code>window</code> and <code>document</code>. These are optional in your case, but a good idea since you do use references to <code>window</code> in your code. It saves <code>window</code> as a local variable, and also will be good when you minify your code as the <code>window</code> reference can be changed to something like <code>a</code> or <code>foo</code> automatically.</p>\n\n<p>Now keep in mind there might be times where you have to put your script in the header. Modernizr is an example of this. Then you'll probably end up using the <code>document.ready</code>. Don't sweat because all you have to do is this:</p>\n\n<pre><code>jQuery(document).ready(function( $ ) {\n //Code goes here and $ will belong to jQuery.\n});\n</code></pre>\n\n<p>I wouldn't rely on $.noConflict</p>\n\n<p><strong>- Chaining:</strong> As pointed out in your question, you should be using something like that. jQuery is particularly good at this and you should make the most of it. Ex.:</p>\n\n<pre><code>$(\"#someElem\").css(\"background-color\", \"#fff\").animate({\"right\":\"1%\"}, \"slow\").draggable();\n</code></pre>\n\n<p>I apply all this stuff to this selector, one after the other. If I want to continue chaining but change my selectors, I can use stuff like <code>.find()</code> and continue with my methods.</p>\n\n<p><strong>- Save function calls:</strong> If you read the jQuery source code you'll see that shortcut methods like <code>.click()</code>, <code>.scroll()</code>, and etc. all reference the <code>.on()</code> method. All they do is basically call the <code>.on()</code> method with some variances. Well why not just go straight to the meat and potatoes? Check this out:</p>\n\n<pre><code>$(\"#foo\").click(function() {\n //Do your awesomeness\n});\n\n//That does the same thing as this:\n$(\"foo\").on(\"click\", function() {\n //Do your awesomeness even awesomener.\n});\n</code></pre>\n\n<p>I highly recommend, if you're going to use jQuery on a regular basis, that you take some time and read through the source code of the methods you're using. To find them quickly just use <code>CTRL+F</code> and type <code>method:</code>. That should jump you straight to what you want to know. This way you can understand what and how you are doing things, and even find better ways to do them on your own.</p>\n\n<p><strong>-Playing with visible elements:</strong> You're if statements from what I can tell are trying to detect scroll position and etc. I highly recommend you check out <a href=\"https://github.com/teamdf/jquery-visible/\" rel=\"nofollow\">this tiny plugin</a>. It basically detects if an element is visible or not at any given time. This may or may not help you out but I just thought I'd throw that out there.</p>\n\n<p><strong>-Things I'd write differently:</strong> Here's an example of all of this summed up into your actual code. I've included comments so you can relate to the reading part.</p>\n\n<pre><code>;(function ($, window) { //Here's our IIFE giving us full $ power\n //Right here at the top we declare our selection variables to be used throught the code.\n //Don't forget to replace your selectors with the appropriate variable name.\n var main = $(\".main\"),\n sbContainer = $(\"#sb-container\"),\n sbContainerDiv = sbContainer.find(\"div\");\n\n function animate() { //Write your code only once, and call it when you need it.\n sbContainerDiv.css({ //You should apply a class instead of doing all of this in here like this.\n \"transform\": \"rotate(0deg)\",\n \"-webkit-transform\": \"rotate(0deg)\",\n \"-ms-transform\": \"rotate(0deg)\",\n \"-moz-transform\": \"rotate(0deg)\",\n \"-o-transform\": \"rotate(0deg)\"\n });\n\n main.animate({\"right\":\"1%\"}, \"slow\");\n }\n\n if ( window.width() < 960) {\n main.animate({\"top\":\"22%\"});\n\n //This use of .toggle() was deprecated in jQuery 1.8 and removed in 1.9\n //Consider doing this differently\n //If you provide me with more details on this I can help you come up with a different solution\n $('#tblcontents').toggle(function() {\n main.fadeOut(1000);\n }, function() { \n main.fadeIn(1000);\n main.animate({\"top\":\"22%\"});\n });\n } else {\n $('.menu-button').on('click', function() {\n animate(); //Here we call our previously set animate function\n });\n }\n\n //Refer to the previous toggle comment.\n $('.toggle_div').toggle(function() {\n main.animate({\"right\":\"50%\"}, \"slow\");\n }, function(){ \n main.animate({\"right\":\"1%\"}, \"slow\");\n });\n\n $(\".pulse\").effect(\"pulsate\", { times:100 }, 2000).on('click', function() {\n $(this).effect().stop(true, true); //In a callback function, 'this' refers to the element in question.\n $(this).animate({\"opacity\":\"1\"}, \"fast\");\n });\n\n $('.thumb').on('click', function() {\n animate();\n });\n\n window.on('scroll', function() {\n if ($(this).scrollTop() > 20) {\n animate();\n } else{\n sbContainer.draggable();\n }\n });\n //You only need to make this draggable once, either here or in your else statement.\n //Remove one depending on what you need.\n sbContainer.draggable()\n\n})(jQuery, window); //Here we set our awesome stuff in the function\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>I've looked at your .js file and there's quite a bit I would change. But focus on the resize event for now. The way you have it now, the code runs hundreds of times since it is called each time the window size changes, even if the user isn't done resizing.</p>\n\n<p>Now we don't want to do that since it can really slow down the browser, if not crash it all together. So what you want to do is only run when the user stops or is done resizing, then run the code. Here's an example of how I'd probably do it:</p>\n\n<pre><code>var $window = $(window); //Remember, if you use a selection more than once, you should cache it.\n$window.resize(function() {\n //Check if there has been a call already\n //If the check is true that means the code was already called\n //So we cancel any previous calls, this way the code is only called once\n if(this.resizeTO) clearTimeout(this.resizeTO);\n\n this.resizeTO = setTimeout(function() {\n $(this).trigger('resizeEnd'); //Call the actual code with a 500ms delay\n }, 500);\n});\n\n$window.on('resizeEnd', function() {\n//This is a custom event that is triggered in the timeout\n//This will only run on the last time the resize method was called\n var winWidth = $window.width();\n\n if( winWidth < 960 ) {\n toggletwo();\n animate();\n } else {\n toggleone();\n }\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T15:29:47.693",
"Id": "37814",
"Score": "0",
"body": "you are my new best friend thank you for the detailed instructions I will be reading them with determination! You have taken time out of your day to help someone and I thank you... :D \nNow to be extremely cheeky: \nAny ideas as to how I can stop the fadeIn and fadeOut that is called on the window width < 960 when the user expands the window???"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T15:31:43.250",
"Id": "37815",
"Score": "0",
"body": "Check out that plugin I put in there. That should solve your problems. Just read the docs and see the examples. If you have questions I can help answer them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T19:53:27.757",
"Id": "37832",
"Score": "0",
"body": "thanks @Jonny I have implemented your fixes and learnt a lot :D I do have one question: \nThe .toggle i am using is due to an element fading out when one div expands and the screen width is beneath 960px's\nyou can see a copy of the script hear: \n[link](http://buildawebdoctor.com/wp-content/themes/twentytwelve/js/custom.js)\nand a copy of the working script on the root of that server.\nbascialy I want to unbind the fadin fadeout once the screen returns to over 960px's I posed the question here [link](http://stackoverflow.com/questions/15705990/jquery-unbind-or-remove-fadein-fadeout)\nthanks :D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T02:50:43.300",
"Id": "37859",
"Score": "0",
"body": "What do you mean by \"stop\". Do you want it to freeze in the middle of the animation, or to become completely visible or invisible?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T11:07:19.640",
"Id": "37870",
"Score": "0",
"body": "I wanted it to remove the toggle event so the #tblcontents only fades in and out when the screen is below a certain width.: \nHere's a step by step of what currently happens: \nA) user opens window @ 1024px ( #tblcontents does NOT fadeIN/Out) \nB) user resizes window to 700px ( #tblcontents starts fadeIN /OUT) \nC) user resizes window back to 1024px's ( #tblcontents now has fadeIN/OUT applied to it when I would like it to return to step one)\nHere's the exact code I'm using for this:"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T11:14:49.083",
"Id": "37871",
"Score": "0",
"body": "`$(window).resize(function() {\nif ( $(window).width() < 960) {\n main.animate({\"top\":\"22%\"});\n tblcontents.toggle(function(){\n main.fadeOut(1000);\n }, function(){ \n main.fadeIn(1000);\n main.animate({\"top\":\"22%\"});\n\n });\n\n}else {\n\n }\n\n});`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T11:52:38.983",
"Id": "37873",
"Score": "0",
"body": "looking for a toggle replacement I have a feeling this will anwser my question..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T15:13:59.927",
"Id": "38101",
"Score": "0",
"body": "I've updated my answer to fit what you asked for in the comments. Remember to remove old code from your JS file before putting the update in."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T16:26:47.443",
"Id": "38106",
"Score": "0",
"body": "just updated and run the new code it's a lot smoother."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T16:32:29.637",
"Id": "38108",
"Score": "0",
"body": "Right I'm a little unsure as to why or how `$window.resize(function() { ` checks to see if the window has been resized?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T16:33:34.813",
"Id": "38109",
"Score": "0",
"body": "stupid question I read the rest of it and understood.:D thanks again @jonny Sooter"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T18:32:13.867",
"Id": "38113",
"Score": "2",
"body": "When in doubt about any method, just read the jQuery documentation. For resize it's this: http://api.jquery.com/resize/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T18:35:20.273",
"Id": "38114",
"Score": "0",
"body": "thank you again @jonny sooter I appreciated your patience. it's working better and better.. \nAny other suggestion please feel free to suggest away :D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T21:15:15.277",
"Id": "38150",
"Score": "0",
"body": "I suggest you open a new question now with the new code you have now since it's quite different from the original. You could link back here in that question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T23:37:39.453",
"Id": "38213",
"Score": "0",
"body": "I will do just that."
}
],
"meta_data": {
"CommentCount": "15",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T15:24:25.403",
"Id": "24503",
"ParentId": "24499",
"Score": "8"
}
},
{
"body": "<p>For some reason i can't find the comment button, hence a answer. </p>\n\n<p>Jonny Sooter's advice covers most, a extra i would add is to namespace your events.</p>\n\n<pre><code>$('selector').on('click.namespace', handler);\n</code></pre>\n\n<p>This kinda acts like a identifier, maybe you want to disable your events in a certain app state. By using your namespace you can target these specific events and only remove these specific events instead of removing all click events from that element.</p>\n\n<pre><code>$('your-selector').off('click.namespace');\n</code></pre>\n\n<p>By using a 'anomonous self invoking function' as Jonny covered earlier you can do what's called global import. What this basicly means is that you import variables into your closure and map/alias it to whatever you want. </p>\n\n<pre><code>;(function (Alias) {\n// Now within this closure jQuery is mapped/aliased to the variable Alias. Another benefit of this is that this can enhance scope chain lookups, and create a private state for your local variables.\n}(jQuery));\n\n// Difference in scope chain lookups.\nvar a = 'something';\n;(function (window, document) {\n document.location.href = a;\n}(this, this.document));\n\nvar a = 'something';\n;(function (importedVar, window, document) {\n document.location.href = importedVar;\n}(a, this, this.document));\n</code></pre>\n\n<p>In the scope chain example the first part is slower then the last part, this is because how javascript works, it will check it's local scope first to see if it has a variable a, if it can't find it it goes up a context(nested functions) to see if its there, this will go on all the way up to the global window object, if it cant find it it will throw. Thats why you should avoid using global variables as much as possible, eg: window.something or using somthing without a var keyword before it.</p>\n\n<p>In the second example we import that variable into our closure, so basicly it has a local reference. This goes alot deeper though but i'll keep it simple. :)</p>\n\n<p>A very good read can be found here <a href=\"http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html\" rel=\"nofollow\">http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html</a> this is a pattern i use heavily.</p>\n\n<p>And another very good vid from Paul Irish wit a few tips and tricks. <a href=\"http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/\" rel=\"nofollow\">http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T22:36:19.053",
"Id": "24515",
"ParentId": "24499",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "24503",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T13:46:40.100",
"Id": "24499",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"animation",
"wordpress"
],
"Title": "jQuery animation and rotation effects for a WordPress site"
}
|
24499
|
<p>I have a fitness function, where inputs <code>x1</code> to <code>x14</code> have values between 1:4. Is there a way to make this more efficient? Any suggestions are useful. I need to get the computation time down. A smaller scale pseudocode is below:</p>
<pre><code>%Help improve computation time
function y = Reduce(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14)
P= [ 0.3 0.2 0.01 0;
0.4 0.1 0.02 0;
0.7 0.5 0.2 0;
0.5 0.3 0.17 0;
0.3 0.2 0.09 0;
0.4 0.3 0.17 0;
0.4 0.1 0.11 0;
0.3 0.1 0.11 0;
0.23 0.14 0.04 0;
0.25 0.13 0.02 0;
0.625 0.589 0.29 0;
0.6 0.38 0.2 0;
0.23 0.15 0.05 0;
0.3 0.01 0.001 0];
Q= [ 0 0 0 0;
0 0 0 0;
0 0 0 0;
0 .11 .11 .11;
0 0 0 0;
0 0 0 0;
0 0 0 0;
0 0 0 0;
0 0 0 0;
0 0 0 0;
0.178 0.1 0.01 0;
0.43 0.32 0.07 0;
0 0.13 0.08 0;
0 0 0 0];
N=1-P-Q;
P= [P, Q];
%Make grid for all the pets
web={0:1,0:1,0:2,0:1,0:1,0:1,0:1,0:1,0:1,0:2,0:2,0:2,0:1,0:1};
[aa bb cc dd ee ff gg hh ii jj kk ll mm nn ] = ndgrid(web{:});
RaNk = [aa(:) bb(:) cc(:) dd(:) ee(:) ff(:) gg(:) hh(:) ii(:) jj(:) kk(:) ll(:) mm(:) nn(:)];
%function to get weight proportion
function result = gailv(a,b,c,d,e)
result = d;
result(c==4 & b>0) = 0;
result(c==4 & b==0) = 1;
result(c<4 & b==1) = a;
result(c<4 & b==2) = e;
end
%% Loop over all weight proportion possibilities
y = 0;
for j=1:size(RaNk,1)
Proportion=gailv(P(1,x1),RaNk(j,1),x1,N(1,x1),Q(1,x1))*gailv(P(2,x2),RaNk(j,2),x2,N(2,x2),Q(2,x2))*gailv(P(3,x3),RaNk(j,3),x3,N(3,x3),Q(3,x4))*gailv(P(4,x4),RaNk(j,4),x4,N(4,x4),Q(4,x4))*gailv(P(5,x5),RaNk(j,5),x5,N(5,x5),Q(5,x5))*gailv(P(6,x6),RaNk(j,6),x6,N(6,x6),Q(6,x6))*gailv(P(7,x7),RaNk(j,7),x7,N(7,x7),Q(7,x7))*gailv(P(8,x8),RaNk(j,8),x8,N(8,x8),Q(8,x8))*gailv(P(9,x9),RaNk(j,9),x9,N(9,x9),Q(9,x9))*gailv(P(10,x10),RaNk(j,10),x10,N(10,x10),Q(10,x10))*gailv(P(11,x11),RaNk(j,11),x11,N(11,x11),Q(11,x11))*gailv(P(12,x12),RaNk(j,12),x12,N(12,x12),Q(12,x12))*gailv(P(13,x13),RaNk(j,13),x13,N(13,x13),Q(13,x13))*gailv(P(14,x14),RaNk(j,14),x14,N(14,x14),Q(14,x14));
weightCATS(aa(j)==0 & bb(j)==0)=0;
weightCATS(bb(j)==1)=2;
weightCATS(aa(j)==1 & bb(j)==0)=1;
weightCOWS(cc(j)==0 & dd(j)==0 & ee(j)==0 & ff(j)==0 & gg(j)==0 & hh(j)==0)=0;
weightCOWS(ff(j)==1)=7;
weightCOWS(ff(j)~=1 & gg(j)==1)=6;
weightCOWS(ff(j)~=1 & gg(j)==0 & hh(j)==1)=5;
weightCOWS(cc(j)==1 & ff(j)~=1 & gg(j)==0 & hh(j)==0)=4;
weightCOWS(cc(j)==0 & ff(j)==2 & gg(j)==0 & hh(j)==0)=3;
weightCOWS(cc(j)==0 & ee(j)==1 & ff(j)==0 & gg(j)==0 & hh(j)==0)=2;
weightCOWS(cc(j)==0 & dd(j)==1 & ee(j)==0 & ff(j)==0 & gg(j)==0 & hh(j)==0)=1;
weightDOGS(ii(j)==0 & jj(j)==0 & kk(j)==0)=0;
weightDOGS(jj(j)==1)=3;
weightDOGS(ii(j)==1 & jj(j)==0)=2;
weightDOGS(ii(j)==0 & jj(j)==0 & kk(j)==1)=1;
weightDUCKS(ll(j)==0 & mm(j)==0 & nn(j)==0)=0;
weightDUCKS(ll(j)==1 | mm(j)==1 | nn(j)==1)=2;
weightDUCKS(ll(j)==0 & ((mm(j)==2 & nn(j)==2) | (mm(j)==2 & nn(j)==0) | (mm(j)==0 & nn(j)==2)))=1;
weight=[weightCATS(:) weightCOWS(:) weightDOGS(:) weightDUCKS(:) ];
weight=sscanf(sprintf('%d',weight),'%d');
% get weight from search function
weight_get= [00000 10000 20000 00001 30000 10001 40000 20001 00002 30001 50000 00003 ;
0 1.636626462 2.277517454 2.767758977 2.86906291 4.415328506 4.667984412 5.062564392 5.476217888 5.651094723 5.743576203 6.659943334];
WEI = weight_get(2,weight_get(1,:)==weight);
y=y-Proportion*WEI;
end
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-26T12:33:50.490",
"Id": "48055",
"Score": "0",
"body": "Please try to [profile](http://www.mathworks.nl/help/matlab/ref/profile.html) your code. That gives you and others a starting point for improvements."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T15:54:08.903",
"Id": "24505",
"Score": "3",
"Tags": [
"performance",
"matlab"
],
"Title": "Fitness function"
}
|
24505
|
<p>How could I possibly shorten / clean this up? I suppose mainly clean up the loop at the start asking whether they would like to scramble the code.</p>
<pre><code>def userAnswer(letters):
print("Can you make a word from these letters? "+str(letters)+" :")
x = input("Would you like to scrample the letters? Enter 1 to scramble or enter to guess :")
while x == '1':
print(''.join(random.sample(letters,len(letters))))
x = input("Would you like to scrample the letters? Enter 1 to scramble or enter to guess :")
word = input("What is your guess? :")
word = word.lower()
if checkSubset(word, letters) == True and checkWord(word) == True:
print("Yes! You can make a word from those letters!")
else:
print("Sorry, you cannot make that word from those letters")
userAnswer("agrsuteod")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T18:21:56.353",
"Id": "37824",
"Score": "0",
"body": "What version of python are you using?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-26T17:58:57.653",
"Id": "89467",
"Score": "0",
"body": "Some of your print statements have typos: \"scrample\" should be \"scramble\"."
}
] |
[
{
"body": "<p>For one thing, if <code>checkSubset()</code> and <code>checkWord()</code> return bools, you can leave out the <code>== True</code>. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T18:22:20.603",
"Id": "24509",
"ParentId": "24508",
"Score": "3"
}
},
{
"body": "<p>Don't repeat yourself, like I have assigned the message to a variable <code>msg</code> so that if you need to change the message in future then, you don't have to edit at more than one place. Also, you don't need to compare for boolean values as <code>if</code> statement takes care of that.</p>\n\n<pre><code>def userAnswer(letters):\n print(\"Can you make a word from these letters? \"+str(letters)+\" :\")\n msg = \"Would you like to scrample the letters? Enter 1 to scramble or enter to guess :\"\n x = input(msg)\n while x == '1':\n print(''.join(random.sample(letters,len(letters))))\n x = input(msg)\n word = input(\"What is your guess? :\").lower()\n if checkSubset(word, letters) and checkWord(word):\n print(\"Yes! You can make a word from those letters!\")\n else:\n print(\"Sorry, you cannot make that word from those letters\")\n\nuserAnswer(\"agrsuteod\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T18:54:23.957",
"Id": "24511",
"ParentId": "24508",
"Score": "2"
}
},
{
"body": "<p>Before presenting my version, I would like to make a couple of comments:</p>\n\n<ul>\n<li>Use descriptive names. The name <code>userAnswer</code> gives me an impression of just getting the user's answer, nothing else. I like to suggest using names such as <code>startScrambleGame</code>, <code>runScrambleGame</code> or the like. </li>\n<li>Avoid 1-letter names such as <code>x</code> -- it does not tell you much.</li>\n<li>I don't know which version of Python you are using, but mine is 2.7 and <code>input()</code> gave me troubles: it thinks my answer is the name of a Python variable or command. I suggest using <code>raw_input()</code> instead.</li>\n<li>Your code calls <code>input()</code> 3 times. I suggest calling <code>raw_input()</code> only once in a loop. See code below.</li>\n<li>The <code>if checkSubset()...</code> logic should be the same, even if you drop <code>== True</code>.</li>\n</ul>\n\n<p>Here is my version of <code>userAnswer</code>, which I call <code>startScrambleGame</code>:</p>\n\n<pre><code>def startScrambleGame(letters):\n print(\"Can you make a word from these letters: {}?\".format(letters))\n while True:\n answer = raw_input('Enter 1 to scramble, or type a word to guess: ')\n if answer != '1':\n break\n print(''.join(random.sample(letters, len(letters))))\n\n word = answer.lower() \n if checkSubset(word, letters) and checkWord(word):\n print(\"Yes! You can make a word from those letters!\")\n else:\n print(\"Sorry, you cannot make that word from those letters\")\n\nstartScrambleGame(\"agrsuteod\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T23:11:53.973",
"Id": "37840",
"Score": "3",
"body": "In Python 3, `raw_input()` has been replaced with `input()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T23:17:07.003",
"Id": "37841",
"Score": "2",
"body": "OK. Sorry for living in stone age :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-26T18:09:07.693",
"Id": "89468",
"Score": "1",
"body": "and the code uses `print()` as a function; the OP is almost certainly using Python 3."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T23:02:30.590",
"Id": "24518",
"ParentId": "24508",
"Score": "6"
}
},
{
"body": "<p>In Python there is an agreed-upon standard on how the code should look: <a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8 -- Style Guide for Python Code</a>. The standard is to use lowercase names with underscores.</p>\n\n<p>For shuffling a list, there is a function in <code>random</code> aptly called <code>random.shuffle</code>. Use <code>.format</code> to interpolate values in string. Do not repeat yourself and just ask the thing once; one can combine these inputs together.</p>\n\n<p>Do not needlessly compare against <code>True</code> using <code>==</code>; just use the implied boolean value of the expression (and if you need to be explicit then use <code>is</code> instead of <code>==</code>). Store the letters in a list for easier modification. Also there is no need to write <code>check_subset</code> as a function, if you really want a set operation (that is, the same letter can occur multiple times in the word, even if only once in the original).</p>\n\n<p>Thus we get:</p>\n\n<pre><code>def ask_user(letter_word):\n letters = list(letter_word)\n while True:\n print(\"Can you make a word from these letters: {}?\"\n .format(''.join(letters)))\n\n choice = input(\"Enter your guess or 1 to scramble: \")\n\n if choice == '1':\n random.shuffle(letters)\n else:\n break # break out of the while loop, a guess was entered\n\n word = choice.lower() \n if set(word).issubset(letters) and check_word(word):\n print(\"Yes! You can make a word from those letters!\")\n else:\n print(\"Sorry, you cannot make that word from those letters\")\n\nask_user(\"agrsuteod\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-26T18:26:10.827",
"Id": "89474",
"Score": "0",
"body": "The `Can you make a word ...` introduction is displayed only once in the OP."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-26T18:27:53.383",
"Id": "89475",
"Score": "0",
"body": "Yes, I did coalesce them together here, also I did change the input handling."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-26T18:08:36.740",
"Id": "51774",
"ParentId": "24508",
"Score": "6"
}
},
{
"body": "<p>One minor thing of note is that</p>\n<pre><code>word = word.lower()\n</code></pre>\n<p>would be better served with</p>\n<pre><code>word = word.casefold()\n</code></pre>\n<p><a href=\"https://docs.python.org/3.5/library/stdtypes.html#str.casefold\" rel=\"noreferrer\">Here are the docs.</a></p>\n<blockquote>\n<p>Return a casefolded copy of the string. Casefolded strings may be used for caseless matching.</p>\n<p>Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-26T18:32:09.317",
"Id": "89476",
"Score": "0",
"body": "+1 for mentioning `casefold` here, but again *would be better* is debatable."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-26T18:10:07.337",
"Id": "51775",
"ParentId": "24508",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "24518",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T18:17:16.813",
"Id": "24508",
"Score": "5",
"Tags": [
"python",
"beginner",
"game",
"python-3.x"
],
"Title": "Guessing words from scrambled letters"
}
|
24508
|
<p>I am developing a WEB based GPS system and one of its functionalities is to be able to send messages and routes to GARMIN devices.</p>
<p>I have never been using sockets before, and for some (obvious) reason, I don't feel ready to submit my code before being reviewed by more experienced users.</p>
<p>If some of you have the time to check it, here it is:</p>
<pre><code>//This is an inner class - that is why it is private
private class MessageReceiver implements Runnable
{
private Thread clientSocketListener = null;
private Socket clientSocket = null;
private Socket currentSocket = null;
private ServerSocket mReceiverSocket = null;
private DataInputStream in = null;
boolean shutDownServer = false;
boolean stopLoop = false;
public MessageReceiver()
{
try
{
if(mReceiverSocket == null) { mReceiverSocket = new ServerSocket(12346); }
System.out.println("mReceiverSocket initialized");
}
catch (IOException ex) {ex.printStackTrace();}
}
/**
* Listens for clients...
*/
private void initConnection()
{
clientSocketListener = new Thread(new Runnable()
{
private boolean loopStatus = true;
@Override
public void run()
{
while(loopStatus)
{
try {Thread.sleep(200);}
catch (InterruptedException ex) {ex.printStackTrace();}
try
{
clientSocket = mReceiverSocket.accept();
if(currentSocket != null) { currentSocket.close(); }
currentSocket = clientSocket;
System.out.println("new clientSocket accepted");
}
catch(SocketException e)
{
System.out.println("SocketException initConnection() ");
e.printStackTrace();
}
catch(IOException e)
{
System.out.println("Exception initConnection()");
e.printStackTrace();
}
finally
{
if(shutDownServer)
{
System.out.println("Breaking while looop for client listening");
loopStatus = false;
}
}
}
}
});
clientSocketListener.setPriority(3);
clientSocketListener.start();
}
@Override
public void run()
{
this.initConnection();
System.out.println("After calling initConncetion()");
byte currentByte = 0;
byte previousByte = 0;
boolean firstRun = true;
LinkedList<Byte> inputDataArray = new LinkedList<Byte>();
while(stopLoop == false)
{
try
{
if(currentSocket != null)
{
in = new DataInputStream(currentSocket.getInputStream());
System.out.println("After checking if currentSocket is null");
int nextByte;
while((nextByte = this.in.read()) != -1)
{
if(firstRun)
{
firstRun = false;
previousByte = (byte) nextByte; //in.readByte();
if(previousByte == (byte) 0xa5) inputDataArray.add(previousByte);
}
else
{
currentByte = (byte) nextByte; //in.readByte();
if(previousByte == 21 && currentByte == 22)
{
inputDataArray.clear();
System.out.println("Na4alo...");
}
else if(previousByte == 23 && currentByte == 24)
{
//Do something here...
if(type.equals(GarminMessage.MESSAGE_TYPE_GARMIN_TEXT))
{
//Do what is supposed to do...
}
else if(type.equals(GarminMessage.MESSAGE_TYPE_GARMIN_ACKNOWLEDGEMENT))
{
//Do what is supposed to do...
}
else if(type.equals(GarminMessage.MESSAGE_TYPE_SYNCHRONIZE_POINT_ACCNOWELDGEMENT))
{
//Do what is supposed to do...
}
else if(type.equals(GarminMessage.MESSAGE_TYPE_ETA_ACCNOWELDGEMENT))
{
//Do what is supposed to do...
}
inputDataArray.clear();
firstRun = true;
System.out.println("Krai!");
}
else
{
inputDataArray.add(currentByte);
previousByte = currentByte;
if(inputDataArray.size() == 5)
{
boolean flag = true;
for(int i=0; i<inputDataArray.size(); i++)
{
byte a = inputDataArray.get(i); //System.out.println("data: " + a);
if(a != (byte) 0xa5)
{
flag = false;
break;
}
}
if(flag == true)
{
//System.out.println("Handshake message received");
inputDataArray.clear();
firstRun = true;
byte handShakeMessage[] = new byte[]{(byte) 0xa6,(byte) 0xa6,(byte) 0xa6,(byte) 0xa6,(byte) 0xa6};
try
{
MessageService.this.messageSender.out.write(handShakeMessage);
MessageService.this.messageSender.out.flush();
}
catch (IOException ex)
{
System.out.println("IOException: Connection has been lost and the handshake message was not sent!");
if(MessageService.this.messageSender.out != null)
{
try {MessageService.this.messageSender.out.close();}
catch (IOException e) {}
finally{MessageService.this.messageSender.out = null;}
}
if(MessageService.this.messageSender.mSenderSocket != null)
{
try {MessageService.this.messageSender.mSenderSocket.close();}
catch (IOException e) {}
finally{MessageService.this.messageSender.mSenderSocket = null;}
}
MessageService.this.messageSender.initConnection();
}
catch(Exception ex)
{
System.out.println("Exception: Connection has been lost and the handshake message was not sent!");
if(MessageService.this.messageSender.out != null)
{
try {MessageService.this.messageSender.out.close();}
catch (IOException e) {}
finally{MessageService.this.messageSender.out = null;}
}
if(MessageService.this.messageSender.mSenderSocket != null)
{
try {MessageService.this.messageSender.mSenderSocket.close();}
catch (IOException e) {}
finally{MessageService.this.messageSender.mSenderSocket = null;}
}
MessageService.this.messageSender.initConnection();
}
}
}
}
}
}
}
}
catch (IOException ex)
{
ex.printStackTrace();
System.out.println("IOException inside while loop of run method of thread message receiver");
inputDataArray.clear();
this.closeInputStream();
this.closeSocket();
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("Exception");
inputDataArray.clear();
this.closeInputStream();
this.closeSocket();
}
finally
{
try {Thread.sleep(200);}
catch (InterruptedException ex)
{
Thread.currentThread().interrupt();
break;
}
}
} //end of while(true)
System.out.println("Outside while loop");
//shutDownServer = true;
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><blockquote>\n<pre><code>private ServerSocket mReceiverSocket = null;\n...\npublic MessageReceiver()\n{\n try \n {\n if(mReceiverSocket == null) { mReceiverSocket = new ServerSocket(12346); }\n System.out.println(\"mReceiverSocket initialized\");\n } \n catch (IOException ex) {ex.printStackTrace();}\n}\n</code></pre>\n</blockquote>\n\n<p>The if condition inside the constructor is never <code>false</code>. It could be simply the following:</p>\n\n<blockquote>\n<pre><code>private ServerSocket mReceiverSocket;\n...\npublic MessageReceiver() {\n try {\n mReceiverSocket = new ServerSocket(12346);\n System.out.println(\"mReceiverSocket initialized\");\n } catch (IOException ex) {\n ex.printStackTrace();\n }\n}\n</code></pre>\n</blockquote></li>\n<li><p>Allowing to create an object with an invalid state (when <code>receiverSocket</code> is <code>null</code>) does not look a good idea. You'll get a <code>NullPointerException</code> later, usually when it runs on another thread. It's harder to debug since the stacktrace will not contain any clue where was the <code>MessageReceiver</code> created. So, instead of <code>printStackTrace</code> throw an exception immediately. (<em>The Pragmatic Programmer: From Journeyman to Master</em> by <em>Andrew Hunt</em> and <em>David Thomas</em>: <em>Dead Programs Tell No Lies</em>.)</p></li>\n<li><blockquote>\n<pre><code>boolean shutDownServer = false;\nboolean stopLoop = false;\n</code></pre>\n</blockquote>\n\n<p>I guess it's not thread-safe. Access to the fields above should be synchronized, otherwise not all thread will see that their values are changed.</p>\n\n<blockquote>\n <p>[...] synchronization has no effect unless both read and write operations are synchronized.</p>\n</blockquote>\n\n<p>Source: <em>Effective Java, 2nd Edition, Item 66: Synchronize access to shared mutable data</em></p>\n\n<blockquote>\n <p>Unless synchronization is used every time a variable is accessed,\n it is possible to see a stale value for that variable. Worse, \n staleness is not all-or-nothing: a thread can see an up-to-date\n value of one variable but a stale value of another variable that\n was written first.</p>\n</blockquote>\n\n<p>Source: <em>Java Concurrency in Practice</em>, <em>3.1.1. Stale Data</em></p>\n\n<p>Consider using <code>AtomicBoolean</code>s.</p></li>\n<li><p>Fourteen level of indentation is hard to read (you need to scroll horizontally), you should extract out some methods and classes to fulfil the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">single responsibility principle</a>. Having small classes and methods means that you don't have to understand the whole program when maintaining it later to modify just a small part of it which is easier and requires less work.</p>\n\n<blockquote>\n <p>The first rule of functions is that they should be small. \n The second rule of functions is that\n they should be smaller than that.</p>\n</blockquote>\n\n<p>Source: <em>Clean Code</em> by <em>Robert C. Martin</em>, <em>Chapter 3: Functions</em></p></li>\n<li><p>In the <code>run</code> method a simple <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">guard clause</a> could save you an indentation level.</p>\n\n<blockquote>\n<pre><code>while(stopLoop == false)\n{\n try \n { \n if(currentSocket != null)\n {\n ...\n }\n }\n ...\n}\n</code></pre>\n</blockquote>\n\n<p>would become</p>\n\n<pre><code>while (stopLoop == false) {\n try {\n if (currentSocket == null) {\n continue;\n }\n ...\n }\n ...\n}\n</code></pre></li>\n<li><p>The following try-catch (with every catch blocks) could have a separate method too:</p>\n\n<blockquote>\n<pre><code>byte handShakeMessage[] = new byte[] { (byte) 0xa6, (byte) 0xa6, (byte) 0xa6, (byte) 0xa6, (byte) 0xa6 };\n\ntry {\n MessageService.this.messageSender.out.write(handShakeMessage);\n MessageService.this.messageSender.out.flush();\n} catch (IOException ex) {\n ...\n}\n</code></pre>\n</blockquote></li>\n<li><p>The content of the two <code>catch</code> blocks above is exactly the same, you can move that logic to a separate method too:</p>\n\n<pre><code>private void closeAndReconnect() {\n if (MessageService.this.messageSender.out != null) {\n try {\n MessageService.this.messageSender.out.close();\n } finally {\n MessageService.this.messageSender.out = null;\n }\n }\n\n if (MessageService.this.messageSender.mSenderSocket != null) {\n try {\n MessageService.this.messageSender.mSenderSocket.close();\n } catch (IOException e) {\n } finally {\n MessageService.this.messageSender.mSenderSocket = null;\n }\n }\n\n MessageService.this.messageSender.initConnection();\n}\n</code></pre>\n\n<p>Then it gets being readable, although a good name is still missing:</p>\n\n<pre><code>private void extracted() {\n byte handShakeMessage[] = new byte[] { (byte) 0xa6, (byte) 0xa6, (byte) 0xa6, (byte) 0xa6, (byte) 0xa6 };\n\n try {\n MessageService.this.messageSender.out.write(handShakeMessage);\n MessageService.this.messageSender.out.flush();\n } catch (IOException ex) {\n System.out.println(\"IOException: Connection has been lost and the handshake message was not sent!\");\n closeAndReconnect();\n } catch (Exception ex) {\n System.out.println(\"Exception: Connection has been lost and the handshake message was not sent!\");\n closeAndReconnect();\n }\n}\n</code></pre></li>\n<li><p>If both <code>messageSender.out</code> and <code>messageSender.mSenderSocket</code> implements <code>Closeable</code> you could create a <code>closeQuietly</code> method for them:</p>\n\n<pre><code>private void closeQuietly(final Closeable closeable) {\n if (closeable == null) {\n return;\n }\n try {\n closeable.close();\n } catch (IOException e) {\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code> private void closeAndReconnect() {\n try {\n closeQuietly(MessageService.this.messageSender.out);\n closeQuietly(MessageService.this.messageSender.mSenderSocket);\n } finally {\n MessageService.this.messageSender.out = null;\n MessageService.this.messageSender.mSenderSocket = null;\n }\n\n MessageService.this.messageSender.initConnection();\n}\n</code></pre>\n\n<p>Anyway, it's usually not a good idea to swallow exceptions. You should at least log them, it could help with \"doesn't work\" bugs where there is no other clue what has happened.</p></li>\n<li><p>Numbers like, <code>0xa5</code>, <code>21</code>, <code>24</code> are magic numbers. Using a named constants would help readers/maintainers because named constants could express the purpose of value, they would reveal the intent, what the original author wanted to achieve with the number.</p></li>\n<li><blockquote>\n<pre><code>boolean shutDownServer = false;\n</code></pre>\n</blockquote>\n\n<p><code>shutdown</code> is one word, I'd write it with lowercase <code>d</code>.</p></li>\n<li><blockquote>\n<pre><code>private ServerSocket mReceiverSocket = null; \n</code></pre>\n</blockquote>\n\n<p>The <code>m</code> prefix is rather unnecessary.</p></li>\n<li><blockquote>\n<pre><code>LinkedList<Byte> inputDataArray = new LinkedList<Byte>();\n</code></pre>\n</blockquote>\n\n<p><code>LinkedList<...></code> reference types should be simply <code>List<...></code>. See: <em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em></p></li>\n<li><blockquote>\n<pre><code>boolean flag = true;\n</code></pre>\n</blockquote>\n\n<p>I more descriptive name would help readers, since every <code>boolean</code> is a flag it doesn't say too much.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T15:32:05.007",
"Id": "76039",
"Score": "1",
"body": "10x. It's just amazing how well you explain stuff. I have to post questions more often here"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-08T09:17:48.610",
"Id": "43781",
"ParentId": "24510",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "43781",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T18:46:58.000",
"Id": "24510",
"Score": "3",
"Tags": [
"java",
"multithreading",
"networking",
"socket",
"location-services"
],
"Title": "Communication with GARMIN through WEB"
}
|
24510
|
<p>I'm using PDO, but I want to create my own class for more convenient work with the database.</p>
<p>My main idea in example with comments:</p>
<pre><code><?php
/**
* User entity. I want to save it into database.
* @Table(name="my_table")
*/
class User {
/**
* Special phpDoc values indicates that this variable should be stored into database.
* @Column(type="integer", autoincrement=true)
*/
private $id;
/**
* @Column(type="string", length=32)
*/
private $name;
/**
* @Column(type="string", length=64)
*/
private $password;
/**
* @Column(type="string", length=256)
*/
private $email;
public function __construct($id = NULL) {
if($id) {
// Load user data from DB
}
// If `id` not provided — we are creating new empty user, no need to load something
}
public function __set($var, $value) {
return (isset($this->$var)) ? $this->$var = $value : FALSE;
}
public function __get($var) {
return (isset($this->$var)) ? $this->$var : NULL;
}
}
// --------------------------------------------------
// Somewhere...
// --------------------------------------------------
$dataMgr = new DataManager(); // My class that will read object properties and store them in MySQL
// --------------------------------------------------
// Create new user
// --------------------------------------------------
$user = new User(); // Empty user
/*
* Set user data
*/
//$user->id = 1; // Autoincrement value
$user->name = 'TestUser';
$user->password = 'verystrongpassword';
$user->email = 'google@hotmail.com';
/*
* Read $user object properties and perform MySQL query if phpdoc block with special values found.
* INSERT query will be performed, because `id` field == NULL
*/
$dataMgr->save($user);
// --------------------------------------------------
// Update existing user
// --------------------------------------------------
$user = new User(50);
$user->password = 'newstrongpassword';
$dataMgr->save($user); // `id` in object != NULL, so perform UPDATE query
</code></pre>
<p>I know that there are good ORM frameworks, but they're very powerful and I don't need to use all their functions. Also I want to use my own mechanism in my own system.</p>
<p>What are the disadvantages? Perhaps I missed something, and my idea is not optimal, is it good practice? And what about Reflection performance? </p>
|
[] |
[
{
"body": "<p><strong>Code critique</strong></p>\n\n<p>You indicate that the constructor will be responsible for fetching and hydrating the Entity's values. I know this is tempting. Don't do it. You already have something named <code>DataManager</code>. Shouldn't it handle fetching and hydrating the Entity?</p>\n\n<p>In your magic get/set, you should add some code to handle the cases where a concrete getter/setter exists. Inevitably, you will end up needing special logic or transformations done to data going in our out of the object. Allowing getters and setters to be added later without having to change calling code will make life easier.</p>\n\n<p>Your __set method does not need to return a value.</p>\n\n<p>One example where I think you already need a setter is for the password property. I posted an example about this <a href=\"https://codereview.stackexchange.com/a/19983/11197\">previously</a>.</p>\n\n<pre><code>/*\n * @param string $clearPassword\n */\npublic function setPassword($clearPassword)\n{\n $this->salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);\n $this->password = crypt($clearPassword, $this->salt);\n}\n</code></pre>\n\n<p><strong>Me trying to talk you out of writing your own ORM</strong></p>\n\n<p>\"<em>I want to create my own class for more convenient work with the database...I don't need to use all their functions</em>\"</p>\n\n<p>This indicates that you may not fully understand how to use other ORM tools. Implementing your own ORM is a massive undertaking. What are you ultimately trying to achieve? Write an application? Write an ORM library? Go down this path if you feel you must but, your time is probably better spent learning how to use of the existing tools. </p>\n\n<p>You think you don't need all their (other ORM tools) functions but you eventually will as your application grows and matures. Here is a small list of things that you will eventually need but don't yet realize it:</p>\n\n<ul>\n<li>Associations - How will you map Entity associations?</li>\n<li>Transactions - How will you deal with transactions?</li>\n<li>Custom SQL - Where would you keep any custom sql?</li>\n<li>Database Migrations - After your app is in production, how will you manage schema changes?</li>\n</ul>\n\n<p>Your Entity class annotations look similar to that of <a href=\"http://www.doctrine-project.org/\" rel=\"nofollow noreferrer\">Doctrine's</a>. It uses proxies and cached code to get around the performance issues related to reflection.</p>\n\n<p>Since you seem to favor the <a href=\"http://martinfowler.com/eaaCatalog/repository.html\" rel=\"nofollow noreferrer\">Repository Pattern</a>, why not simply use <a href=\"http://www.doctrine-project.org/\" rel=\"nofollow noreferrer\">Doctrine</a>?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T16:37:48.507",
"Id": "24570",
"ParentId": "24512",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T19:41:14.740",
"Id": "24512",
"Score": "2",
"Tags": [
"php",
"mysql",
"reflection"
],
"Title": "PHP ORM like system"
}
|
24512
|
<p>I've been working on a lightweight cookiemanager and version 1 has been completed and works perfectly as intended. I would love to get a review to see where we can improve it.</p>
<p>Where should I throw logical errors? For now I only log. </p>
<p>Its usage is as follows:</p>
<p>Getting cookies can be done by calling <code>Cookiemanger.get()</code>. You can supply a name argument to get a specific cookie, if no name is supplied it will return all cookies currently in the document. An additional flag can be set as a second argument whether to use strict matching on the cookies name.</p>
<pre><code>Cookiemanager.get(); // returns all cookies currently defined in the document as a name/value object.
Cookiemanager.get('your_cookie_name'); // returns cookie(s) as a name/value object, using loose matching. so 'your_cookie_name_123' will get returned also.
Cookiemanager.get('your_cookie_name', true); // Same as above only now it will do strict name matching.
</code></pre>
<p>Setting cookies can be done by calling <code>Cookiemanger.set()</code>. It requires a settings object with at least a name key/value supplied.</p>
<pre><code>// Simple setting
Cookiemanger.set({
name : 'your_cookie_name',
value : 'your value'
});
// Extended setting
Cookiemanger.set({
name : 'your_cookie_name',
value : 'your value',
expires : 'a expiry date in as a UTC string'
path : '/',
domain : document.location.host,
secure : false
});
</code></pre>
<p>Removing cookies can be done by calling <code>Cookiemager.remove()</code>. It accepts 3 arguments: <code>name</code>, <code>domain</code> and <code>path</code> as a string. <code>domain</code> and <code>path</code> are optional. If none are supplied, it will remove all cookies from the domain including all sub paths.</p>
<pre><code>// Removes the cookie at the current domain, including all sub paths.
Cookiemanger.remove({
name : 'your_cookie_name',
domain : document.location.host
});
// Removes the cookie at the supplied path, excluding sub paths.
Cookiemanger.remove({
name : 'your_cookie_name',
path: '/'
});
</code></pre>
<p>Testing a cookie against a certain value can be done by calling <code>Cookiemanger.test()</code>. It accepts a settings object as below with at least a name supplied. You can add custom values if a value matches with the value in the current cookie and it will call the function if supplied. If no cookies are found with the name supplied you can pass a undefined, as seen below.</p>
<pre><code>Cookiemanger.test({
name : 'testcookie',
'an_expected_value' : function () {
},
'undefined' : function () {
}
});
</code></pre>
<hr>
<pre><code>;var Cookiemanager = (function (Cookiemanager, window, document, undefined) {
'use strict';
function isObject (arg) {
return Object.prototype.toString.call(arg) === '[object Object]';
};
function isArray (arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
function isString (arg) {
return Object.prototype.toString.call(arg) === '[object String]';
};
function isEmptyObj (argument){
for( var key in argument ) return false;
return true;
};
function returnCookieString (sName, sValue, sExpires, sPath, sDomain, bSecure) {
var sCookie = (sName + '=' + escape(typeof sValue !== 'undefined' ? sValue : '')) +
(isString(sExpires) && sExpires.indexOf('GMT') !== -1 ? ';expires=' + sExpires : '') +
(isString(sPath) ? ';path=' + sPath : ';path=') +
(isString(sDomain) ? ';domain=' + sDomain : '') +
(bSecure ? ';secure' : '');
return sCookie;
};
function returnURIPaths () {
var i,
sURIPath,
aURIPaths = [],
aURISegments = document.location.pathname.replace(/\/$/, '').split('/'),
iNrOfURISegments = aURISegments.length;
for (i = iNrOfURISegments; i--;) {
sURIPath = aURISegments.slice(0, i + 1).join('/');
aURIPaths.push(sURIPath);
aURIPaths.push(sURIPath + '/');
}
return aURIPaths;
};
function error (msg) {
throw new Error(msg);
};
function log (msg) {
try {
console.log(msg);
} catch (e) {}
};
Cookiemanager.get = function (arg, strict) {
var sCookies = document.cookie;
if (sCookies.length) {
var i,
oResult = {},
aCookies = sCookies.split(';'),
iNrOfCookies = aCookies.length,
sCookie,
aCookieValues,
sCookieName,
sCookieValue;
for (i = iNrOfCookies; i--;) {
sCookie = aCookies[i];
if (sCookie.charAt(0) === ' ') {
sCookie = sCookie.substring(1, sCookie.length);
}
aCookieValues = sCookie.split('=');
sCookieName = aCookieValues[0];
sCookieValue = unescape(aCookieValues[1]);
if (arg && isString(arg)) {
if (strict) {
if (sCookieName === arg) {
oResult[sCookieName] = sCookieValue;
}
} else {
if (sCookieName.indexOf(arg) !== -1) {
oResult[sCookieName] = sCookieValue;
}
}
} else {
oResult[sCookieName] = sCookieValue;
}
}
if (! isEmptyObj(oResult)) {
return oResult;
} else {
log('Cookiemanager.get(): Could not find cookie with supplied name.');
}
} else {
log('Cookiemanager.get(): No cookies defined in the current document.');
}
};
Cookiemanager.set = function (arg) {
if (arg && isObject(arg)) {
if (isString(arg.name)) {
document.cookie = returnCookieString(arg.name, arg.value, arg.expires, arg.path, arg.domain, arg.secure);
} else {
log('Cookiemanager.set(): Cookie not set, please provide a valid name.');
}
} else {
log('Cookiemanager.set(): Cookie not set, please provide a valid settings object.');
}
};
Cookiemanager.remove = function (sName, sPath, sDomain) {
if (isString(sName)) {
var expires = new Date();
expires.setFullYear(expires.getFullYear() - 1);
if (isString(sPath)) {
this.set({
name : sName,
expires : expires.toUTCString(),
path : sPath,
domain : typeof sDomain !== 'undefined' ? sDomain : document.location.host
});
} else {
var i,
aURIPaths = returnURIPaths(),
iNrOfURIPaths = aURIPaths.length;
for (i = iNrOfURIPaths; i--;) {
this.set({
name : sName,
expires : expires.toUTCString(),
path : aURIPaths[i],
domain : typeof sDomain !== 'undefined' ? sDomain : document.location.host
});
}
}
} else {
log('Cookiemanager.remove(): No cookies removed, please provide a valid name.');
}
};
Cookiemanager.test = function (arg, strict) {
if (arg && isObject(arg)) {
var sName = arg.name;
if (isString(sName)) {
var oCookie = this.get(sName, strict || false);
if (isEmptyObj(oCookie)) {
arg['undefined'].call(this);
} else {
for(var key in arg) {
if (key === oCookie[sName]) {
arg[key].call(this);
}
}
}
} else {
log('Cookiemanager.test(): Could not test, please provide a valid name.');
}
} else {
log('Cookiemanager.test(): Could not test, please provide a valid settings object.');
}
};
return Cookiemanager;
}(Cookiemanager || {}, this, this.document));
</code></pre>
|
[] |
[
{
"body": "<p>For a \"lightweight\" cookie manager, there seems to be rather a lot going on in my opinion. And I'd call the object <code>CookieManager</code> since it's two words, but that's not structurally/syntactically important.</p>\n\n<p>I am however a bit suspicious of the <code>get()</code> usage. If I give it a string, and nothing else, I'd expect <em>that</em> to do strict name-matching. I.e. given a name, I expect zero or 1 cookie in return, not a list. Maybe break out the \"fuzzy matching\" into a <code>find()</code> method, or have <code>get()</code> accept a regular expression instead.</p>\n\n<p>Speaking of regular expressions, that's probably the easiest way to parse the <code>document.cookie</code> string:</p>\n\n<pre><code>function all() {\n var cookies = {};\n // using replace, as it accepts a function\n document.cookie.replace(/([^=]+)=([^;]*)[;\\s]*/g, function(match, name, value) {\n cookies[name] = value;\n });\n return cookies;\n}\n</code></pre>\n\n<p>That'll get you an object (or hash or map if you prefer) of all the cookies. You might also expose that as <code>CookieManager.all()</code> instead of overloading the <code>get()</code> method with yet another usage.</p>\n\n<p>Internally, <code>get()</code> can use <code>all()</code> to get the individual cookies, and basically become a very simply shortcut</p>\n\n<pre><code>function get(name) {\n return all()[name];\n}\n</code></pre>\n\n<p>I wouldn't bother logging errors within the cookie manager, as you'll still have to check the return value elsewhere. In this case, <code>get()</code> will simply return a string value or undefined. GIGO: Garbage in, garbage out.</p>\n\n<p>Now, for fuzzy name-matching, I'd add a <code>find()</code> function to have something distinct from the stricter <code>get()</code> function. Something like</p>\n\n<pre><code>function find(pattern) {\n var name,\n found = {},\n cookies = all();\n if( pattern instanceof RegExp ) {\n for( name in cookies ) {\n if( pattern.test(name) ) {\n found[name] = cookies[name];\n }\n }\n } else {\n for( name in cookies ) {\n if( name.indexOf(pattern) !== -1 ) {\n found[name] = cookies[name];\n }\n }\n }\n return found;\n}\n</code></pre>\n\n<p>Once again, GIGO. Not necessarily your responsibility to check the arguments.</p>\n\n<p>Lastly, I'd probably have <code>set()</code> accept specific arguments, rather than an object simply because it makes its usage more obvious. If I just have to pass an object, I still have to know what that object should contain.<br>\nAnother reason would be to keep it consistent with the <code>remove()</code> function, which takes specific arguments already.</p>\n\n<p><code>set()</code> and <code>remove()</code> are the two functions that should probably do some input-checking and maybe throw an exception. This is mostly as they can't really follow the GIGO approach, because they don't return something. So it's more like \"garbage in, throw exception\"<br>\nAgain, not much reason to attempt to log, just to risk throwing an exception there; probably easier to just throw if the input is spurious.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T17:54:23.710",
"Id": "37897",
"Score": "0",
"body": "Thanks for the response, very constructive! I haven't thought of the regular expression approach, but looking at it i'll definitely incorporate it, although regex ain't my strongest point it will be a good learn. What would you define as 'lightweight'? I'll be throwing this script on github soon so everyone can contribute if willing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T20:24:54.347",
"Id": "37906",
"Score": "0",
"body": "@ngr Well, in terms of functionality (get, set, remove) your code is pretty \"lightweight\". I was mostly looking at it and felt like there was too much code for those 3 simple operations. A lot of it has to do with the (in my opinion unnecessary) error logging and type checking. Type checking is sometimes useful of course, but again: GIGO for the most part."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T21:12:32.503",
"Id": "37908",
"Score": "0",
"body": "I am currently refactoring with your above suggestions and it cleans the methods up really nice, also it follows the single responsibility principle more then before. The regular expression i find still hard to grasp, but then again i think that's an art on its own. :) Merci!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T21:45:10.720",
"Id": "37909",
"Score": "0",
"body": "With regard to the domain flag, isn't it useful for cookies on a specific subdomain? For example setting and removing cookies on sub.domain.com"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T22:41:38.450",
"Id": "37910",
"Score": "0",
"body": "@ngr Sorry, yes, you're right about the domain part. I don't know what I was thinking. By the way, if you think the answer helped, click the checkmark next to it. Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T22:45:37.860",
"Id": "37912",
"Score": "0",
"body": "@ngr By the way, check out [this page over on MDN](https://developer.mozilla.org/en-US/docs/DOM/document.cookie) which has a full implementation ready-to-use. I'm not saying you should use that instead of yours, but you may get some ideas. Their function names (`getItem`, `setItem`, etc.) are intended to be identical to the `window.localStorage` API, which is quite clever"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T17:23:40.943",
"Id": "24544",
"ParentId": "24513",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "24544",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T21:31:57.357",
"Id": "24513",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Lightweight Cookiemanager"
}
|
24513
|
<p>Basically I have created a function which takes two lists of dicts, for example: </p>
<pre><code>oldList = [{'a':2}, {'v':2}]
newList = [{'a':4},{'c':4},{'e':5}]
</code></pre>
<p>My aim is to check for each dictionary key in the oldList and if it has the same dictionary key as in the newList update the dictionary, else append to the oldList.
So in this case the key 'a' from oldList will get updated with the value 4, also since the keys b and e from the newList don't exist in the oldList append the dictionary to the oldList. Therefore you get <code>[{'a': 4}, {'v': 2}, {'b': 4}, {'e': 5}]</code>. </p>
<p>Is there a better way to do this?</p>
<pre><code>def sortList(oldList, newList):
for new in newList: #{'a':4},{'c':4},{'e':5}
isAdd = True
for old in oldList: #{'a':2}, {'v':2}
if new.keys()[0] == old.keys()[0]: #a == a
isAdd = False
old.update(new) # update dict
if isAdd:
oldList.append(new) #if value not in oldList append to it
return oldList
sortedDict = sortList([{'a':2}, {'v':2}],[{'a':4},{'b':4},{'e':5}])
print sortedDict
[{'a': 4}, {'v': 2}, {'b': 4}, {'e': 5}]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T22:34:04.337",
"Id": "37835",
"Score": "4",
"body": "Why in the world do you have a list of single element dictionaries?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T23:33:20.897",
"Id": "37844",
"Score": "0",
"body": "Please make an effort to name and structure questions appropriately. Because your code has nothing to do with sorting, I tried to find a better title—feel free to improve it further."
}
] |
[
{
"body": "<p>You don't need the <code>isAdd</code> flag, instead you can structure your for loops like this:</p>\n\n<pre><code>for new, old in newList, oldList:\n if new.keys()[0] == old.keys()[0]:\n old.update(new)\n else:\n oldList.append(new)\nreturn oldList\n</code></pre>\n\n<p>As well, you might want to look at <a href=\"http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html\" rel=\"nofollow\">PEP</a> documents for coding style</p>\n\n<p>For reference, here is the rest of your code with those standards in place:</p>\n\n<pre><code> def sort_list(old_list, new_list):\n for new, old in new_list, old_list: \n if new.keys()[0] == old.keys()[0]:\n old.update(new)\n else:\n old_list.append(new)\n return old_list \n\nsorted_dict = sort_list([{'a':2}, {'v':2}],[{'a':4},{'b':4},{'e':5}])\nprint sorted_dict\n\n[{'a': 4}, {'v': 2}, {'b': 4}, {'e': 5}]\n</code></pre>\n\n<p>Oh, and I'm assuming you are doing this for practice/homework, but the <a href=\"http://docs.python.org/2/library/stdtypes.html#dict.update\" rel=\"nofollow\">dict.update(iterable)</a> method does this exact thing far, far faster than you ever could.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T22:56:46.497",
"Id": "37837",
"Score": "1",
"body": "Yeah, I'm pretty sure that code doesn't do the same thing. His code only adds to the list if none of the keys match, yours will it for every non-matching key. Furthermore, `for new, old in new_list, old_list`? I'm pretty sure that's not what you meant."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T22:59:59.183",
"Id": "37838",
"Score": "0",
"body": "Using his check (and multiple others) I got the code to produce the same output."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T23:03:30.483",
"Id": "37839",
"Score": "1",
"body": "Really? I get `ValueError: too many values to unpack` if I copy and paste your code from above. (After correcting a spacing error)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T22:50:51.687",
"Id": "24516",
"ParentId": "24514",
"Score": "0"
}
},
{
"body": "<pre><code>def sortList(oldList, newList):\n</code></pre>\n\n<p>Python convention is to lowercase_with_underscores for pretty much everything besides class names</p>\n\n<pre><code> for new in newList: #{'a':4},{'c':4},{'e':5}\n isAdd = True \n</code></pre>\n\n<p>Avoid boolean flags. They are delayed gotos and make it harder to follow your code. In this case, I'd suggest using an else: block on the for loop.</p>\n\n<pre><code> for old in oldList: #{'a':2}, {'v':2} \n if new.keys()[0] == old.keys()[0]: #a == a\n isAdd = False\n old.update(new) # update dict\n if isAdd:\n oldList.append(new) #if value not in oldList append to it\n return oldList \n\nsortedDict = sortList([{'a':2}, {'v':2}],[{'a':4},{'b':4},{'e':5}])\nprint sortedDict\n</code></pre>\n\n<p>Why are you calling it sortList? You are merging lists, not sorting anything...</p>\n\n<p>Your whole piece of code would be quicker if implemented using dicts:</p>\n\n<pre><code># convert the lists into dictionaries\nold_list = dict(item.items()[0] for item in oldList)\nnew_list = dict(item.items()[0] for item in newList)\n# actually do the work (python already has a function that does it)\nold_list.update(new_list)\n# covert back to the list format\nreturn [{key:value} for key, value in old_list.items()]\n</code></pre>\n\n<p>All of which raises the question: why aren't these dicts already? What are you trying to do with this list of dicts stuff?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T23:24:31.817",
"Id": "37842",
"Score": "0",
"body": "1) Your right about the lowercase_with_underscores and the name of the function.\n2) Your code snippet doesn't take order into account and will return `[{'a': 4}, {'b': 4}, {'e': 5}, {'v': 2}]` instead of `[{'a': 4}, {'v': 2}, {'b': 4}, {'e': 5}]`. I guess ordereddict should be used instead"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T23:28:14.920",
"Id": "37843",
"Score": "0",
"body": "@user1741339, or you could sort the result, if what you really want is for the keys to be in sorted order. Regardless, its still bizarre to have a list of single-element dicts like this."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T23:01:29.710",
"Id": "24517",
"ParentId": "24514",
"Score": "1"
}
},
{
"body": "<p>A list of 1-pair dictionaries makes no sense as data structure. You should join them to create a single dictionary. This way all your code reduces to:</p>\n\n<pre><code>d1 = {'a': 2, 'b': 2}\nd2 = {'a': 4, 'c': 4, 'e': 5}\nd3 = dict(d1, **d2)\n# {'a': 4, 'b': 2, 'c': 4, 'e': 5}\n</code></pre>\n\n<p>If you are going to union/merge dicts a lot, you can create a handy abstraction, more general than <code>dict(d1, **d2)</code>:</p>\n\n<pre><code>def merge_dicts(d1, d2):\n return dict(itertools.chain(d1.items(), d2.items()))\n</code></pre>\n\n<p>To convert list of dictionaries to a dictionary is simple:</p>\n\n<pre><code>d2 = dict(list(d.items())[0] for d in new_list)\n# {'a': 4, 'c': 4, 'e': 5}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-05-10T18:31:01.260",
"Id": "373423",
"Score": "0",
"body": "`d3 = dict(d1, **d2)`\n I didn't know about this behaviour; super useful. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T23:39:24.300",
"Id": "24519",
"ParentId": "24514",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T22:08:41.477",
"Id": "24514",
"Score": "1",
"Tags": [
"python",
"hash-map"
],
"Title": "Updating list of Dictionaries from other such list"
}
|
24514
|
<p>Here is a problem I am trying to solve: trying to find missing photographs from a sequence of filenames. The problem boils down to: given an unsorted list of integers, return a sorted list of missing numbers. Below is my code.</p>
<p>What I am looking for are:</p>
<ul>
<li>Are there more efficient algorithms?</li>
<li>Is there any performance problem if the list is large (tens of thousands)</li>
<li><p>Corner cases which does not work?</p>
<pre><code>def find_missing_items(int_list):
'''
Finds missing integer within an unsorted list and return a list of
missing items
>>> find_missing_items([1, 2, 5, 6, 7, 10])
[3, 4, 8, 9]
>>> find_missing_items([3, 1, 2])
[]
'''
# Put the list in a set, find smallest and largest items
original_set = set(int_list)
smallest_item = min(original_set)
largest_item = max(original_set)
# Create a super set of all items from smallest to largest
full_set = set(xrange(smallest_item, largest_item + 1))
# Missing items are the ones that are in the full_set, but not in
# the original_set
return sorted(list(full_set - original_set))
if __name__ == '__main__':
import doctest
doctest.testmod()
</code></pre></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T23:56:18.607",
"Id": "37847",
"Score": "0",
"body": "Looks fine to me. `find_missing_items([-20000,0,20000])` returned correctly all 39998 items in less than 2s running on a old dual-core."
}
] |
[
{
"body": "<p>For this</p>\n\n<pre><code>full_set = set(xrange(smallest_item, largest_item + 1))\n</code></pre>\n\n<p>I'd suggest inlining the min and max:</p>\n\n<pre><code>full_set = set(xrange(min(original), max(original) + 1))\n</code></pre>\n\n<p>You don't need to convert to a list before using sorted so:</p>\n\n<pre><code>sorted(list(full_set - original_set))\n</code></pre>\n\n<p>Can be written as:</p>\n\n<pre><code>sorted(full_set - original_set)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T00:00:30.003",
"Id": "37849",
"Score": "0",
"body": "Beautiful. I especially like the last one: sorted() without list()."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T23:57:36.223",
"Id": "24523",
"ParentId": "24520",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "24523",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T23:39:45.547",
"Id": "24520",
"Score": "5",
"Tags": [
"python",
"algorithm",
"performance"
],
"Title": "Finding missing items in an int list"
}
|
24520
|
<p>Number can be very big.Script is taking number as a "number" list and crossing from 10-decimal based system to n-based system until list equals "5".I don't use letters like in 16-base system(hex).Example if result will be AB5 in hex list will be [10,11,5]. Some ideas how to optimize or/and change this to recursion?Any other hints/ideas for optimizing this code?</p>
<pre><code>r=-1
number = [9,7,1,3,3,6,4,6,5,8,5,3,1]
l=len(number)
p=11
while (number[-1]!=5):
i=1
while(i<=l):
#for x in reversed(xrange(1,i)):
for x in xrange(i-1,0,-1):
number[x]+=(number[x-1]*r)
while(number[x]<0):
number[x]+=p
number[x-1]-=1
if number[0]==0:
#number.pop(0)
del number[0]
i-=1
l-=1
i+=1
#print p
p+=2
r=-2
print p-2
</code></pre>
<p>Algorithm in theory:
From start we have some decimal number: 2507 . Base of decimal as everyone know is 10. list=[2, 5, 0, 7] :</p>
<pre><code> [2, 5, 0, 7] # 2507 decimal(base 10)
1.
l[1]=l[1]+(diff_between_earlier_and_current_base*l[1-1]
2.
1.l[2]=l[2]+(diff_between_earlier_and_current_base*l[2-1]
1.l[1]=l[1]+(diff_between_earlier_and_current_base*l[1-1]
3.
1.l[3]=l[3]+(diff_between_earlier_and_current_base*l[3-1]
1.l[2]=l[2]+(diff_between_earlier_and_current_base*l[2-1]
1.l[1]=l[1]+(diff_between_earlier_and_current_base*l[1-1]
</code></pre>
<p><strong>if some element (while doing this) will be <0 we need to borrow from l[curent-1] until element<0</strong>
(if we doing subtraction below the line we are borrowing 10 but when we converting to 11 base we are borrowing 11 so when we have [2,-2] >> [1,9])</p>
<pre><code> Result in 11 base:
[1, 9, 7, 10]
</code></pre>
<p><strong>I think any way to optimize this is to write my code as recurrent function but i don't know how to do this.Anyone?</strong></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T23:48:17.783",
"Id": "37845",
"Score": "2",
"body": "Welcome to Code Review! Please add an explanation of what the purpose of this code is."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T23:49:51.663",
"Id": "37846",
"Score": "1",
"body": "What does it matter?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T23:57:08.863",
"Id": "37848",
"Score": "2",
"body": "Because it is hard to write good answers without this information. Take a look at the [about page](http://codereview.stackexchange.com/about): *\"Focus on questions about an actual problem you have faced. Include details about what you have tried and exactly what you are trying to do.\"* I strongly recommend you follow these guidelines."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T08:44:57.590",
"Id": "37862",
"Score": "3",
"body": "Can you please update your question to add a precise description of what you are trying to achieve because I'm not quite sure this is very clear now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T18:03:51.013",
"Id": "37898",
"Score": "1",
"body": "`p` seems the base of the numbers. But the base then changes? That's just odd... Can you give us an idea of the motivation here? Right now it just seems a bunch of pointless calculation and its hard to see how to convey its intent better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T18:22:29.300",
"Id": "37901",
"Score": "0",
"body": "This site is for help optimizing code or just asking what is the code for? Yes p=11 because on start we have decimal number.Next will be in 11-base.The question is how to write this more optimal rather than what it is for."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T00:34:26.940",
"Id": "37916",
"Score": "4",
"body": "Here's your optimised version of the code : `print 17`.\nPlease keep in mind that people who have commented here are people who would have been willing to help you if they could understand what you are trying to achieve."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T16:57:25.283",
"Id": "37941",
"Score": "0",
"body": "Very funny.Number can be different."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T14:29:30.550",
"Id": "38044",
"Score": "3",
"body": "Actually the site is for improving your code both with performance and style. The biggest problem with your code as it stands is that its inscrutable. It would help us suggest way to make it faster and easier to follow if you'd let us know what the fried monkey it's trying to accomplish. You don't have to tell us what the code is for, but you are much more likely to get help if you do."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T14:36:33.210",
"Id": "38045",
"Score": "2",
"body": "The operations that you do are strange and difficult to optimize. This suggests that either you are attempting to optimize silly code (which isn't likely to get much help) or you've taken a strange tact to solve a bigger problem and if we knew that bigger problem we could provide better help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T22:07:29.980",
"Id": "38062",
"Score": "0",
"body": "Assuming my understanding is ok, I've answered your solution. Had you accepted to give more information in the first place, you'd probably had a better solution in a smaller time."
}
] |
[
{
"body": "<p>I can't do much to help optimize this code as I don't know what its trying to do.</p>\n\n<pre><code>r=-1\nnumber = [9,7,1,3,3,6,4,6,5,8,5,3,1]\n</code></pre>\n\n<p>I suggest presenting this as a function which takes number as a parameter. Code also runs faster in functions.</p>\n\n<pre><code>l=len(number)\np=11\n</code></pre>\n\n<p>Use names that mean things. Single letter variables names make your code hard to read</p>\n\n<pre><code>while (number[-1]!=5):\n</code></pre>\n\n<p>You don't need the parens.</p>\n\n<pre><code> i=1\n while(i<=l):\n #for x in reversed(xrange(1,i)):\n</code></pre>\n\n<p>Delete dead code, don't comment it out</p>\n\n<pre><code> for x in xrange(i-1,0,-1):\n number[x]+=(number[x-1]*r)\n</code></pre>\n\n<p>No need for parens, let your binary operates breath with some spaces</p>\n\n<pre><code> while(number[x]<0):\n number[x]+=p\n number[x-1]-=1\n\n\n\n if number[0]==0:\n #number.pop(0)\n del number[0]\n i-=1\n l-=1\n</code></pre>\n\n<p>You don't actually gain much by deleting the empty places in the number. Your code will operate just the same if leave them with zeros. It'll simplify your code if you do that.</p>\n\n<pre><code> i+=1\n#print p\n p+=2\n r=-2\n</code></pre>\n\n<p>Rather then this, add a line</p>\n\n<pre><code> r = 1 if p == 11 else 2\n</code></pre>\n\n<p>to the beginning of the loop. That way r is set in only one place</p>\n\n<pre><code>print p-2\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T21:12:07.917",
"Id": "38061",
"Score": "0",
"body": "Thanks for suggestions.but my script is slower with they."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T14:42:12.600",
"Id": "24636",
"ParentId": "24521",
"Score": "2"
}
},
{
"body": "<p>From the explanation you provided, I think this does what you want to do :</p>\n\n<pre><code>def listToNumber(l,b):\n n=0\n for i in l:\n n = i+b*n\n return n\n\ndef numberToList(n,b):\n l=[]\n while n>0:\n l.append(n%b)\n n/=b\n return l[::-1]\n\nl=[9,7,1,3,3,6,4,6,5,8,5,3,1]\nbase=10\nn=listToNumber(l,base)\nwhile numberToList(n,base)[-1] != 5:\n base+=1\nprint base\n</code></pre>\n\n<p>Tested on both <code>[9,7,1,3,3,6,4,6,5,8,5,3,1]</code> and <code>[9,7,1,3,3,6,4,6,5,8,5,3,1]*10</code> , it seems like it returns the same thing but my implementation is much faster and much easier to understand.</p>\n\n<p>A possible improvement would be :</p>\n\n<pre><code>def lastDigitInBase(n,b):\n return n%b\n\nl=[9,7,1,3,3,6,4,6,5,8,5,3,1]*10\nbase=10\nn=listToNumber(l,base)\nwhile lastDigitInBase(n,base) != 5:\n base+=1\nprint base\n</code></pre>\n\n<p>On that final version and working with <code>[9,7,1,3,3,6,4,6,5,8,5,3,1]*30</code>, my code returns 13259 in 0.2 seconds while your implementation return the same result in more than 3 minutes and 16 seconds which is roughly 1000 times slower.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T22:15:21.117",
"Id": "38063",
"Score": "0",
"body": "Ok, but what happened to the stuff he was doing with `r`? That's the part that still confuses me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T22:25:29.270",
"Id": "38064",
"Score": "0",
"body": "I have no idea. My feeling is that the code was way too complicated for what it was trying to achieve. Once I understood the problem, I wrote this simple solution and it seems like it returns the same thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T00:40:45.763",
"Id": "38067",
"Score": "0",
"body": "Nice.For different number with pypy: my: Initial run time: 1.15500020981 ,\nyours: Initial run time: 0.999000072479 ,but can you write as recursive function without using \">>\" , \"/\" or \"%\" ? That's the point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T07:31:50.673",
"Id": "38072",
"Score": "0",
"body": "r = previous_base - current_base. The initial step is base-10 -> base-11, hence -1; then base-11 to base-13 (11+2), hence -2. Why he's jumping by 2, I don't know."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T11:06:46.383",
"Id": "38087",
"Score": "0",
"body": "Do not think about it, it is intentionally.Base 10 > 11 > 13 > 15 > 17 > 19 > 21.Only odd."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T15:02:30.600",
"Id": "38100",
"Score": "0",
"body": "@prosze_wyjsc_z_kosmosu, why do you want recursion? Why do you want to avoid \">>\", \"/\", and \"%\"? That's rather like trying to build a house with using wood."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T17:07:31.783",
"Id": "38111",
"Score": "0",
"body": "I want to check something,that can't be checked if I will use(sorry for grammar) \">>\" , \"/\" or \"%\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T17:19:35.033",
"Id": "38317",
"Score": "0",
"body": "@prosze_wyjsc_z_kosmosu, what do you want to check?"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T22:04:46.063",
"Id": "24653",
"ParentId": "24521",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T23:42:34.243",
"Id": "24521",
"Score": "-3",
"Tags": [
"python",
"optimization"
],
"Title": "Any way to change optimize this or/and change to recursion?"
}
|
24521
|
<p>In such an array:</p>
<pre><code>$arr = Array (
[key0] => Array (
[subkey0] => Array (
[0] => "value0"
[1] => "value1"
)
[subkey1] => Array (
[0] => "value0"
[1] => "value1"
)
)
[key1] => Array (
[subkey0] => Array (
[0] => "value0"
[1] => "value1"
)
[subkey1] => Array (
[0] => "value0"
[1] => "value1"
)
)
)
</code></pre>
<p>In order to add $varX to the end of $arr[keyX][subkeyX] as [X] => $varX, I use, inside a loop, the following:</p>
<pre><code>$arr[$key] = array(
"subkey0" => array_merge((array)$arr[$key]["subkey0"], (array)$var1),
"subkey1" => array_merge((array)$arr[$key]["subkey1"], (array)$var2)
...
)
</code></pre>
<p>And I might be working with even more nested arrays, so I was wondering if there was a way for <code>subkey0</code> to refer to itself, or if I could do something like:</p>
<pre><code>"subkeyX" =>+ (array)$varX
</code></pre>
<p>Or use <code>array_merge()</code> in a different way to add <code>$varX</code> to the end of <code>subkeyX</code> as <code>[X] => $varX</code>.</p>
|
[] |
[
{
"body": "<p>I don't know if I understand the question right. But this should work.</p>\n\n<pre><code>foreach ($keys as $key) {\n $arr2[$key]['subkey0'][] = $var1;\n $arr2[$key]['subkey1'][] = $var2;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T01:11:17.220",
"Id": "37855",
"Score": "0",
"body": "Thanks but it does not seem to work. For instance, check [this phpfiddle](http://phpfiddle.org/main/code/e95-3tr) -- click on run to see the results."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T01:54:09.173",
"Id": "37857",
"Score": "0",
"body": "Sorry, my answer was not clear enough. I edited it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T00:14:29.460",
"Id": "24524",
"ParentId": "24522",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "24524",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-29T23:43:11.220",
"Id": "24522",
"Score": "1",
"Tags": [
"php",
"array",
"php5"
],
"Title": "Referring to nested arrays and array_merge (php)"
}
|
24522
|
<p>I have an http library in Ruby with a Response class, I have broken it down into smaller methods to avoid having a big intialize method, but then I end up with this:</p>
<pre><code> def initialize(res)
@res = res
@headers = Hash.new
if res.empty?
raise InvalidHttpResponse
end
split_data
parse_headers
set_size
check_encoding
set_code
end
</code></pre>
<p>I don't feel well about calling function after function like that, any suggestions on how to improve this? Full code is at <a href="https://github.com/matugm/dirfuzz/blob/multi-host/lib/http.rb" rel="nofollow">github</a>.</p>
|
[] |
[
{
"body": "<p>Looking through your whole module it's apparent you've only had experience with imperative programming (it's full of side-effects, variable re-bounds, in-place updates, ...). I've already written on the topic (see <a href=\"https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming\" rel=\"nofollow\">this</a> and <a href=\"http://public.arnau-sanchez.com/ruby-functional/\" rel=\"nofollow\">this</a>) so I won't expand here about the goodness of functional programming. </p>\n\n<p>I'd write:</p>\n\n<pre><code>def initialize(response_string)\n @code = parse_code(response_string)\n raw_headers, @body = parse_data(response_string)\n @headers = parse_headers(raw_headers)\nend\n</code></pre>\n\n<p>You get the idea, create parsing methods (or class methods, actually they won't need instance variables, they are pure functions) with inputs (arguments) and outputs that get assigned/bound to instance variables just once (not incidentally, that makes those methods easier to test).</p>\n\n<p>On the other hand, there are already good network libraries for Ruby, what's the point of re-implementing them?</p>\n\n<p>[EDIT] You asked for further advice. Ok, let's get a couple of methods of <code>Response</code> and refactor them:</p>\n\n<pre><code>def parse_data(raw_data)\n all_headers, body = raw_data.split(\"\\r\\n\\r\\n\", 2)\n raise InvalidHttpResponse unless body && raw_data.start_with?(\"HTTP\")\n raw_headers = all_headers.split(\"\\r\").drop(1)\n [raw_headers, body]\nend\n\ndef decode_data(body)\n # You can use condition ? value1 : value2 for compactness\n data = if headers[\"Transfer-Encoding\"] == \"chunked\"\n decode_chunked(body)\n else\n body\n end\n\n if headers[\"Content-Encoding\"] == \"gzip\" && body.length > 0\n Zlib::GzipReader.new(StringIO.new(data)).read\n else\n data\n end\nend\n</code></pre>\n\n<p>Ideas behind the refactor:</p>\n\n<ul>\n<li>Put a space after a comma (more on <a href=\"https://code.google.com/p/tokland/wiki/RubyIdioms\" rel=\"nofollow\">style</a>).</li>\n<li>Don't reuse variables names (different values must have different names).</li>\n<li>Don't update variables in-place.</li>\n<li>Don't write explicit <code>return</code>.</li>\n<li>Use <code>if</code> conditionals as expressions.</li>\n<li>Use <code>||</code> <code>&&</code> for boolean logic.</li>\n<li>Put parentheses on calls (except on DSL code).</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T02:59:48.737",
"Id": "37926",
"Score": "0",
"body": "Thank you, I just pushed the changes if you want to check, any further advice?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T09:51:48.940",
"Id": "37930",
"Score": "0",
"body": "@matugm: more on the answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T11:43:14.270",
"Id": "24533",
"ParentId": "24525",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "24533",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T02:39:38.797",
"Id": "24525",
"Score": "4",
"Tags": [
"ruby"
],
"Title": "Refactor a sequence of functions"
}
|
24525
|
<p>I was using <code>foo(bar)</code> as it's adopted for functional programming.</p>
<pre><code>console.log(
join(
map(function(row){ return row.join(" "); },
tablify(
map(function(text){return align(text},
view),
20))),
"\n");
</code></pre>
<p>Now, with dot operator:</p>
<pre><code>view.map(function(text){return align(text)})
.tablify(20)
.map(function(row){return row.join(" ");})
.join("\n")
.log();
</code></pre>
<p>I guess everyone will agree this reads too much better, and the only cost is that you have to modify the native types prototype. So, which? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T06:50:37.970",
"Id": "37868",
"Score": "0",
"body": "This will help you find the right thing... just go to http://jsperf.com/ and paste your code there and compare the speed..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T16:33:22.590",
"Id": "37892",
"Score": "0",
"body": "Who says the OOP approach has to modify native prototypes? jQuery, for instance, doesn't modify native prototypes, but still gives you array-like objects with chainable methods. As for the functional approach, it requires (the way it's written now) a lot of functions to be in the current scope - perhaps even in the global scope. That seems more suspect to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T18:08:46.420",
"Id": "37900",
"Score": "0",
"body": "@Flambino how else would you do it? If you had it all inside an object your whole code would gain a substantial noise (if you're using them too much, which you should)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T20:18:17.583",
"Id": "37905",
"Score": "0",
"body": "@Dokkat Sorry, not sure which approach you're referring to there"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T00:50:04.327",
"Id": "37917",
"Score": "0",
"body": "@Flambino you suggested I shouldn't have so many globals, so what instead? myLib.map?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T01:00:11.097",
"Id": "37918",
"Score": "0",
"body": "@Dokkat Ah, for the functional approach. Yes, I'd namespace stuff where I can to avoid global namespace conflicts. Like, e.g. underscore.js does by using `_` for its namespace, or how jQuery uses `$`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T01:03:54.157",
"Id": "37919",
"Score": "0",
"body": "@Flambino but then again, your source is pretty much calls to chose functions so you are adding a huge noise to it! What's wrong in opening it to global scope for your app?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T15:16:41.133",
"Id": "37933",
"Score": "1",
"body": "@Dokkat Nothing, if you can control it. But in JS, that's sort of impossible. There's no telling what other libraries might define, what certain browsers might define, what users' own extensions and little helper scripts might define. Maybe someone missed a `var` keyword in function, and made an implicit global that overwrites your stuff - or vice-versa. Maybe a new browser version will overwrite something with new native functions. The global scope is already crowded; namespacing your stuff limits your exposure to those issues. Which is why it's considered best practice to do so."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T15:20:00.467",
"Id": "37934",
"Score": "0",
"body": "@Flambino good points, but aren't all those problems solved by simply loading your lib last?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T15:28:28.843",
"Id": "37935",
"Score": "0",
"body": "@Dokkat Not if you're in conflict with built-in, native functions/properties that are protected and can't be overwritten. Then your code just gets ignored. Also, if you use a library and overwrite something that it depends on, then that library breaks. If all the code's run sequentially it's OK, but if it's event-driven it's no longer sequential, so event handlers that worked fine when they were defined, might break when they're triggered if they rely on stuff you've since overwritten."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T16:42:24.383",
"Id": "37938",
"Score": "0",
"body": "@mikrowelt Faster is not always better. (And in fact, usually isn't.)"
}
] |
[
{
"body": "<p>I think that the first variant can look nice, too, if you change the way you format the code and you always use the function as the last argument:</p>\n\n<pre><code>log(map(tablify(map(view, function(text) {\n return align(text)\n}), 20), function(row) {\n return row.join(\" \")\n}).join(\"\\n\"))\n</code></pre>\n\n<p>Edit: Or if you really like indent:</p>\n\n<pre><code>log(map(tablify(map(view,\n function(text) { return align(text) }\n ),\n 20\n ),\n function(row) { return row.join(\" \") }\n ).join(\"\\n\")\n)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T14:27:28.280",
"Id": "24567",
"ParentId": "24526",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T06:29:54.290",
"Id": "24526",
"Score": "3",
"Tags": [
"javascript",
"object-oriented",
"functional-programming"
],
"Title": "The eternal dilemma: bar.foo() or foo(bar)?"
}
|
24526
|
<p>I am using PHP to build a REST API. I want to receive requests from the URL in the following format:</p>
<p>http://mydomain.com/api/format/method?app_id=value&call=encrypted_request</p>
<p>So, I have modified my .htaccess as:</p>
<pre><code>Options +FollowSymLinks
IndexIgnore */*
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
</code></pre>
<p>Now, I receive the request URI and extract the name of the method and the parameters from it:</p>
<pre><code>$params = explode('/',$_SERVER['REQUEST_URI']);
$format = $params[count($params)-2];
$method = substr($params[count($params)-1],0,strpos($params[count($params)-1],'?'));
$app_id = $_REQUEST['app_id'];
$enc_request = $_REQUEST['call'];
</code></pre>
<p>My question here is, whether it is ok to use substr and strpos on the array value, simultaneously ? Also, whether this approach of forming the URL and extracting the paramters from it is correct ?</p>
<p>Reference :
<a href="http://php.net/manual/fr/function.substr.php" rel="nofollow">substr</a> <a href="http://www.php.net/manual/fr/function.strpos.php" rel="nofollow">strpos</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T08:57:56.257",
"Id": "37864",
"Score": "0",
"body": "If you want to fetch the `GET` variables, they are stored in `$_GET` array."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T08:59:48.443",
"Id": "37865",
"Score": "0",
"body": "If I were you, I'd store `$params[count($params)-1]` in a variable to make things easier to read.\n\nThen, I'd consider the situation where what you are looking for does not exist : what is no '?' can be found ? At the moment, I think your `substr` would return the empty string but you might prefer the whole string."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T09:17:07.977",
"Id": "37866",
"Score": "0",
"body": "@Josay: Valid point. If I add some checks for various possible case or use a try...catch block, will this approach and code be ok then ?"
}
] |
[
{
"body": "<p>Instead of raw string manipulation, I would use <a href=\"http://php.net/parse_url\" rel=\"nofollow\">parse_url</a> and <a href=\"http://php.net/parse_str\" rel=\"nofollow\">parse_str</a>:</p>\n\n<pre><code><?php\n\n// Note: parse_url is not intended for relative URLs\n// (in other words, bare $_SERVER['REQUEST_URI'] will not work -- you'll have to build a full URL)\n$url = 'http://mydomain.com/api/format/method?app_id=value&call=encrypted_request';\n\n$path = explode('/', ltrim(parse_url($url, PHP_URL_PATH), '/'));\nparse_str(parse_url($url, PHP_URL_QUERY), $query);\n\n$api = array_shift($path);\n$format = array_shift($path);\n$method = array_shift($path);\n\n$app_id = (isset($query['app_id'])) ? $query['app_id'] : null;\n$enc_request = (isset($query['call'])) ? $query['call'] : null;\n</code></pre>\n\n<p>Yes, this code is a bit longer, but it's more readable to me. Also, raw string manipulation is hazard to failing border cases. If you use a well tested parser, problems less likely.</p>\n\n<p>And, as an added bonus, this routing isn't tied to any globals. Off the top of my head I can't think of a reason, but at some point, it might be useful to be able to route a fake request. It definitely makes unit testing easier.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T20:46:19.290",
"Id": "24553",
"ParentId": "24528",
"Score": "1"
}
},
{
"body": "<blockquote>\n <p>Is it ok to use substr and strpos on the array value, simultaneously?</p>\n</blockquote>\n\n<p>Well to answer this question we can just look up the manual and see what each returned and passed value means. As for the types we are perfectly fine because the <code>substr</code> function will accept an int (or something that can be valued as one) and we are returning an int from <code>strpos</code>.</p>\n\n<p>As per the logical meaning, assuming <code>$params[count($params)-1]</code> actually exists, we are getting a position of the first occurrence of <code>?</code> in the string.</p>\n\n<p>But we have to notice that <code>strpos</code> might return false if no occurrence of the symbol is found, therefore leading to a problem in your script.</p>\n\n<p>I suggest you to check for that option:</p>\n\n<pre><code>$e = strpos($params[count($params)-1],'?');\nif ($e === false) $e = 0;\n</code></pre>\n\n<p>And then call:</p>\n\n<pre><code>$method = substr($params[count($params)-1],0,$e);\n</code></pre>\n\n<blockquote>\n <p>Is this approach of forming the URL and extracting the paramters from it correct?</p>\n</blockquote>\n\n<p>Well it has few bugs we should discuss.</p>\n\n<p>First, every occurrence in the form of <code>$params[count($params)-x]</code> may trigger an undefined index error if the count of <code>$params</code> is actually 0 (or 1). Therefore I suggest you to check for the option where the string is way shorter than you expect:</p>\n\n<pre><code>if (count($params) < 2) // what do we do?\n</code></pre>\n\n<p>On a side note, you probably want to store the value of <code>count($params)</code> instead of calling it every time (it's not likely gonna change). (<code>$i = count($params)</code>).</p>\n\n<p>Second, assuming we are expecting a <em>well formed string</em> in the form of (<code>[x]</code> means x is optional):</p>\n\n<blockquote>\n <p>a[/b[/c[/...]]][?x=x1[&y=y1[&z=z1[&...]]]]</p>\n</blockquote>\n\n<p>You might want to take a look at <code>$_SERVER['PATH_INFO']</code> which will remove the query string for you:</p>\n\n<blockquote>\n <p>Contains any client-provided pathname information trailing the actual script filename but preceding the query string, if available. For instance, if the current script was accessed via the URL <a href=\"http://www.example.com/php/path_info.php/some/stuff?foo=bar\" rel=\"nofollow\">http://www.example.com/php/path_info.php/some/stuff?foo=bar</a>, then $_SERVER['PATH_INFO'] would contain /some/stuff.</p>\n</blockquote>\n\n<p><em>Notice: it will work also with URL rewriting because the actual filename will be inserted anyway into the request.</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T23:26:29.137",
"Id": "24555",
"ParentId": "24528",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24555",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T08:44:35.950",
"Id": "24528",
"Score": "2",
"Tags": [
"php",
"api",
".htaccess"
],
"Title": "Is it ok to use PHP's strpos and substr altogether in one statement?"
}
|
24528
|
<p>I've recently picked up PHP, for the first assignment in my IT-security class I decided to code it in PHP.
The algorithm is an alternation of the Caesar cipher, instead of using a fixed number to push the letters a keyword is applied to rearrange a couple of letters and then move the rest of the letters accordingly.</p>
<p>I am pretty sure there can be improvements in string usage and probably also in the algorithm?
Any ideas and notes on programming style and such are very welcome.</p>
<p>Code:
<a href="https://github.com/TheLML/encrypt/blob/master/encrypt.php" rel="nofollow">https://github.com/TheLML/encrypt/blob/master/encrypt.php</a></p>
<p>or:</p>
<pre><code><?php
class encrypt
{
private $key;
private $uword;
private $eword;
private $letters;
/**
* Constructor.
*
* Creates the $letters array.
*/
function __construct()
{
for($i=0;$i<26;$i++)
{
$this->letters[$i][0] = chr(65+$i);
$this->letters[$i][1] = 0;
}
for($i=26;$i<52;$i++)
{
$this->letters[$i][0] = chr(97+$i-26);
$this->letters[$i][1] = 0;
}
for($i=52;$i<62;$i++)
{
$this->letters[$i][0] = $i-52;
$this->letters[$i][1] = 0;
}
$this->letters[62][0] = ' ';
$this->letters[62][1] = 0;
}
/**
* Encrypts the key using an alternation of the caesar cipher.
* The key is used to set a different alternation for the letters, instead
* of having it moved by a constant number.
*
* @throws Exception - if there is no key
* @return string - returns the encrypted alphabet as array
*/
private function _encrypt()
{
if(empty($this->key))
{
throw new Exception("Empty key: cannot create encryption without a key.");
}
$key = $this->key;
$letters = $this->letters;
$encryption = array_fill(0, 63, '');
$pos = 0;
//add key to encoding. each letter only once, though
for($i=0;$i<strlen($key);$i++)
{
$c = substr($key, $i, 1);
$do = true;
//only add letter if it hasn't been used yet
for($j=0;$j<count($encryption);$j++)
{
if(!strcmp($encryption[$j], $c)) $do=false;
}
if($do) $encryption[$pos] = $c;
//find letters that have already been used
for($j=0;$j<63;$j++)
{
if(!strcmp($letters[$j][0], $encryption[$pos]))
{
$letters[$j][1] = 1;
}
}
if($do) $pos++;
}
//add all the unused letters to the encoding array
$k=63;
for($i=$pos;$i<63;$i++)
{
$continue=true;
for($j=63-$k;$j<63 && $continue;$j++)
{
if($letters[$j][1]==0)
{
$encryption[$i] = $letters[$j][0];
$letters[$j][1] = 1;
$continue = false;
--$k;
}
}
}
//reset letter's usage
for($i=0;$i<63;$i++)
{
$this->letters[$i][1] = 0;
}
return $encryption;
}
/**
* Encrypts the given word.
*
* @throws Exception - if there is no unencrypted word
* @return string - Encrypted word
*/
public function encrypt()
{
if(empty($this->uword))
{
throw new Exception("Empty word: cannot encrypt a non-existend word.");
}
$encryption = $this->_encrypt();
$uword = $this->uword;
$eword = '';
$letters = $this->letters;
for($i=0;$i<strlen($uword);$i++)
{
$c = substr($uword, $i, 1);
for($j=0;$j<63;$j++)
{
if(!strcmp($letters[$j][0], $c))
{
$eword .= $encryption[$j];
}
}
}
$this->eword = $eword;
return $eword;
}
/**
* Decrypts the given encryption.
*
* @throws Exception - if there is no encrypted word
* @return string - Encrypted word
*/
public function decrypt()
{
if(empty($this->eword))
{
throw new Exception("Empty encryption: cannot decrypt a non-existend word.");
}
$encryption = $this->_encrypt();
$eword = $this->eword;
$uword = '';
$letters = $this->letters;
for($i=0;$i<strlen($eword);$i++)
{
$c = substr($eword, $i, 1);
for($j=0;$j<63;$j++)
{
if(!strcmp($encryption[$j], $c))
{
$uword .= $letters[$j][0];
}
}
}
$this->uword = $uword;
return $uword;
}
/**
*
* @param unknown_type $key - keyword for encryption
*/
public function setKey($key)
{
$this->key = $key;
}
/**
*
* @param unknown_type $uword - unencrypted word
*/
public function setUword($uword)
{
$this->uword = $uword;
}
/**
*
* @param unknown_type $eword - encrypted word
*/
public function setEword($eword)
{
$this->eword = $eword;
}
/**
*
* @return - $key
*/
public function getKey()
{
return $this->key;
}
/**
*
* @return - $uword
*/
public function getUword()
{
return $this->uword;
}
/**
*
* @return - $eword
*/
public function getEword()
{
return $this->eword;
}
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T10:10:48.030",
"Id": "37867",
"Score": "3",
"body": "Welcome to CodeReview.SE. Please have a look at the http://codereview.stackexchange.com/faq . Among other things, please make sure you include your code in the question. Enjoy!"
}
] |
[
{
"body": "<p>Give the class a better name... a noun makes more sense than a verb.</p>\n\n<p>Consider simply removing the <code>$uword</code> and <code>$eword</code> properties and applicable setter methods. Instead, your encrypt method signature could be:</p>\n\n<pre><code>/**\n * @param string $uword word to encrypt\n * @return string encrypted word\n */\npublic function encrypt($uword)\n...\n</code></pre>\n\n<p>Do the same with decrypt:</p>\n\n<pre><code>/**\n * @param string $eword word to decrypt\n * @return string decrypted word\n */\npublic function decrypt($eword)\n...\n</code></pre>\n\n<p>Put a $key argument in the constructor:</p>\n\n<pre><code>public function __construct($key)\n{\n $this->key = $key;\n ...\n</code></pre>\n\n<p>With the $key invariant satisfied, no need to throw an exception if not set. Remove the setKey/getKey methods (unless you really need them).</p>\n\n<p>Cleaner calling code example:</p>\n\n<pre><code>$cipher = new CeaserCipher('my key, get this from where ever');\n$encryptedValue = $cipher->encrypt('foo');\n\n$decryptedValue = $cipher->decrypt($encryptedValue);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T20:01:36.403",
"Id": "40661",
"Score": "0",
"body": "thanks for your input, I will consider all of this in future projects.\nFunnily enough, when I eventually implemented it into Qt C++ using QByteArrays and its methods the code shrunk from this massive size to just a couple of lines."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T17:22:03.370",
"Id": "24573",
"ParentId": "24529",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T09:33:47.110",
"Id": "24529",
"Score": "4",
"Tags": [
"php",
"algorithm",
"php5",
"caesar-cipher"
],
"Title": "Alternated Caesar Cipher"
}
|
24529
|
<p>Basically I have a 2d list containing movies. Movies are specified by name, version and description. For example</p>
<p><code>['Jaws', 1, 'Movie about sharks']</code> - where <code>Jaws</code> = name, <code>1</code> = version and <code>Movie about sharks</code> = description.</p>
<p>My result is a dictionary which contains a map between name and description. But name should be updated to contain the version for e.g </p>
<p><code>['Jaws', 2, 'Movie about more sharks']</code> - should now be : </p>
<p><code>{'JawsV2': 'Movie about more sharks'}</code></p>
<p>Is there a more pythonic way to do this?</p>
<pre><code>def movie_version_map():
movies = [['Jaws', 1, 'Movie about sharks'],
['Jaws', 2, 'Movie about more sharks'],
['HarryPotter', 1, 'Movie about magic'],
['HarryPotter', 4, 'Movie about more magic']]
for movie in movies:
if movie[1] != 1:
movie[0] = ''.join([movie[0], 'V',str(movie[1])])
newversion = dict([(movie[0],movie[2]) for movie in movies])
return newversion
</code></pre>
<p>Output</p>
<pre><code>{'Jaws': 'Movie about sharks', 'HarryPotter': 'Movie about magic', 'HarryPotterV4': 'Movie about more magic', 'JawsV2': 'Movie about more sharks'}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T13:33:52.420",
"Id": "37876",
"Score": "1",
"body": "What if a movie was to be called 'somethingV1' ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T13:53:57.153",
"Id": "37880",
"Score": "0",
"body": "this is a case where if version is 1 leave the name as it is"
}
] |
[
{
"body": "<p>A simple <a href=\"http://www.youtube.com/watch?v=pShL9DCSIUw\">dict comprehension</a> and use of <a href=\"http://docs.python.org/3.3/library/stdtypes.html#str.format\"><code>str.format()</code></a> will do the job here:</p>\n\n<pre><code>>>> {\"{}V{}\".format(name, version): description \n for name, version, description in movies}\n{'HarryPotterV1': 'Movie about magic', \n 'HarryPotterV4': 'Movie about more magic', \n 'JawsV1': 'Movie about sharks', \n 'JawsV2': 'Movie about more sharks'}\n</code></pre>\n\n<p>Or, in very old versions of Python where dict comprehensions don't exist, simple replace with <code>dict()</code> and a generator expression - e.g: <code>dict(... for ... in moves)</code>.</p>\n\n<p>Note that if this is just because you want to have the data as keys, you don't need to turn them into a string, a tuple can be a key too:</p>\n\n<pre><code>>>> {(name, version): description \n for name, version, description in movies}\n{('Jaws', 1): 'Movie about sharks', \n ('HarryPotter', 4): 'Movie about more magic', \n ('Jaws', 2): 'Movie about more sharks', \n ('HarryPotter', 1): 'Movie about magic'}\n</code></pre>\n\n<p>This would be more appropriate where you don't need the strings, as it means you don't have to parse stuff out or create strings for keys, and makes the data easier to manipulate.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T13:42:31.103",
"Id": "24537",
"ParentId": "24534",
"Score": "8"
}
},
{
"body": "<p>I included the case in which version is 1</p>\n\n<pre><code>{'{}{}'.format(name, version > 1 and 'V'+str(version) or ''):\\ \ndescription for name,version,description in movies}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T16:54:10.317",
"Id": "24543",
"ParentId": "24534",
"Score": "1"
}
},
{
"body": "<p>I suggest to use list comprehension as others did. However, to simplify <em>reading</em>, I am creating a separate function called <em>make_title</em> to deal with combining title and version.</p>\n\n<pre><code>def make_title(title, version):\n if version != 1:\n title = '{}V{}'.format(title, version)\n return title\n\ndef movie_version_map():\n movies = [['Jaws', 1, 'Movie about sharks'], \n ['Jaws', 2, 'Movie about more sharks'], \n ['HarryPotter', 1, 'Movie about magic'], \n ['HarryPotter', 4, 'Movie about more magic']]\n\n new_version = dict((make_title(title, version), description) for title, version, description in movies)\n return new_version\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T17:59:42.570",
"Id": "24545",
"ParentId": "24534",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24543",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T12:45:29.473",
"Id": "24534",
"Score": "1",
"Tags": [
"python",
"hash-map"
],
"Title": "update list based on other values"
}
|
24534
|
<p>There have been many posts here about enums in python, but none seem to be both type safe and simple. Here is my attempt at it. Please let me know if you see anything obviously wrong with it. </p>
<pre><code>def typeSafeEnum(enumName, *sequential):
topLevel = type(enumName, (object,), dict(zip(sequential, [None] * len(sequential))))
vals = map(lambda x: type(x,(topLevel,),{}), sequential)
for k, v in zip(sequential, vals):
setattr(topLevel, k, v())
return topLevel
</code></pre>
<p>Then to test it:</p>
<pre><code>Colors = typeSafeEnum('Colors', 'RED', 'GREEN', 'BLUE')
if __name__ == '__main__':
x = Colors.RED
assert isinstance(x, Colors)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T11:46:54.223",
"Id": "37877",
"Score": "1",
"body": "What do you mean by \"type safe\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T11:51:10.883",
"Id": "37878",
"Score": "0",
"body": "Good point. It should not be comparable to other types. E.g., you should not be able to accidentally use an int instead of Colors.RED"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-16T19:57:36.567",
"Id": "177725",
"Score": "0",
"body": "Note for posterity: as of Python 3.4, there is a standard [`enum`](https://docs.python.org/3/library/enum.html) module and it's available via `pip install enum34` for older versions."
}
] |
[
{
"body": "<pre><code>def typeSafeEnum(enumName, *sequential):\n</code></pre>\n\n<p>Python convention is <code>lowercase_with_underscores</code> for functions and parameters. Although since this is a type factory its not totally clear what convention should appply. I also wonder if passing the enum values as a list might be better.</p>\n\n<pre><code> topLevel = type(enumName, (object,), dict(zip(sequential, [None] * len(sequential))))\n</code></pre>\n\n<p>There is no point in the dict you are passing since you just setattr all the enums in place already. Here you set all the enum values up with None initially and then fill them in. Why? I can also see why you call this topLevel but its not an immeadiately obvious name</p>\n\n<pre><code> vals = map(lambda x: type(x,(topLevel,),{}), sequential)\n</code></pre>\n\n<p>List comprehensions are generally preffered to calling map with a lambda. But also, why? Just do this in the for loop. You don't gain anything by having it done in a map and then zipping over it.</p>\n\n<pre><code> for k, v in zip(sequential, vals):\n</code></pre>\n\n<p>I suggest longer less abbreviated names</p>\n\n<pre><code> setattr(topLevel, k, v())\n return topLevel\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T15:14:36.633",
"Id": "37977",
"Score": "0",
"body": "Thanks, Winston! I will do some revisions and post a new version. Besides the style and code cleanliness, does the approach seem correct to you?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T15:30:47.353",
"Id": "37978",
"Score": "0",
"body": "@user1094206, I avoid enums generally in favor of actually defining classes for what would be an enum value. That way I can take advantage of polymorphism and such. So stylistically, I wouldn't use this approach at all."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T15:17:27.880",
"Id": "24541",
"ParentId": "24536",
"Score": "3"
}
},
{
"body": "<p>I'm not sure why you would want to use a Java idiom in Python. The problems TypeSafe Enums fix in Java are not really issues in Python as far as I can tell.</p>\n\n<p>If you can use a regular enumeration you can use <a href=\"http://docs.python.org/2/library/collections.html#collections.namedtuple\" rel=\"nofollow\"><code>collections.namedtuple</code></a>.</p>\n\n<pre><code>from collections import namedtuple\nColors = namedtuple('Colors', ['RED', 'GREEN', 'BLUE'])._make(xrange(3))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T02:13:13.613",
"Id": "24838",
"ParentId": "24536",
"Score": "1"
}
},
{
"body": "<p>This seems like a problem to me:</p>\n\n<pre><code>>>> type(Colors.RED) is type(Colors.GREEN)\nFalse\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T19:31:17.880",
"Id": "24920",
"ParentId": "24536",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "24541",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T11:38:52.837",
"Id": "24536",
"Score": "3",
"Tags": [
"python",
"enum",
"type-safety"
],
"Title": "An attempt at a simple type safe python enum"
}
|
24536
|
<p>Is there any way I can simplify this inefficient piece of JavaScript?</p>
<pre><code>$(function () {
var $carousel = $('#carousel');
var $switch = $('#switch');
var $header = $('#header');
var $submit = $('#submit');
$carousel.bind('slid', function() {
var index = $('#carousel .item').index($('#carousel .carousel-inner .active'));
if (index == 0) {
$header.text('Sign In');
$switch.text('Sign Up');
$submit.text('Sign In');
$submit.attr('form', 'sign_in');
} else {
$header.text('Sign Up');
$switch.text('Sign In');
$submit.text('Sign Up');
$submit.attr('form', 'sign_up');
}
});
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T14:32:11.570",
"Id": "37882",
"Score": "0",
"body": "I'm assuming `$` stands for `jQuery`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T16:00:02.053",
"Id": "37885",
"Score": "0",
"body": "@JanDvorak yea it is"
}
] |
[
{
"body": "<p>You could do this:</p>\n\n<pre><code>$(function () {\n var $carousel = $('#carousel');\n var $switch = $('#switch');\n var $headerSubmit = $('#header, #submit');\n var $submit = $('#submit');\n var text_strings = [ 'Sign In', 'Sign Up' ];\n var form_strings = [ 'sign_in', 'sign_up' ];\n\n $carousel.bind('slid', function() {\n var index = $('#carousel .item').index($('#carousel .carousel-inner .active'));\n var sign_in = (index == 0);\n $headerSubmit.text(text_strings[sign_in ? 1 : 0]);\n $switch.text(text_strings[sign_in ? 0 : 1]);\n $submit.attr('form', form_strings[sign_in ? 1 : 0]);\n });\n});\n</code></pre>\n\n<p>If you want to reduce the lines of code (with a slight <em>negative</em> impact to performance if this function gets called a lot), you could do this:</p>\n\n<pre><code>$(function () {\n var text_strings = [ 'Sign In', 'Sign Up' ];\n var form_strings = [ 'sign_in', 'sign_up' ];\n\n $('#carousel').bind('slid', function() {\n var index = $('#carousel .item').index($('#carousel .carousel-inner .active'));\n var sign_in = (index == 0);\n $('#header, #submit').text(text_strings[sign_in ? 1 : 0]);\n $('#switch').text(text_strings[sign_in ? 0 : 1]);\n $('#submit').attr('form', form_strings[sign_in ? 1 : 0]);\n });\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T15:52:23.480",
"Id": "37884",
"Score": "0",
"body": "Hm, i never thought about doing it like the last example you wrote, you said this will make the performance better?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T16:02:22.263",
"Id": "37886",
"Score": "0",
"body": "I would use `+sign_in` instead of `sign_in?1:0` and `+!sign_in` instead of `sign_in?0:1`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T16:19:42.507",
"Id": "37888",
"Score": "0",
"body": "@CristianRivera Sorry, I should've been more clear. It makes performance slightly worse since you call `$` every time the event executes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T16:21:32.123",
"Id": "37889",
"Score": "1",
"body": "@JanDvorak good point. Personally I don't like that trick; I feel it harms readability."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T16:22:35.893",
"Id": "37890",
"Score": "0",
"body": "In the code above to counteract the calling of $ every time, can you load them into a var such as var $switch = $('#switch'); then call $switch so you dont have to query the object every time? In regards to Jan Dvorak, are there any performance differences?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T16:35:21.167",
"Id": "37893",
"Score": "0",
"body": "@CristianRivera yes, that's exactly how the first example is written. There is no practical performance difference between `sign_in?0:1` and `+sign_in` AFAIK, but it's probably going to differ depending on the precise js engine that's running the code."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T14:51:30.507",
"Id": "24539",
"ParentId": "24538",
"Score": "5"
}
},
{
"body": "<p>It seems like you're using Bootstrap's Carousel? I've moved the two texts of the buttons to variables so that if you're using a minification tool (UglifyJs, Google's Closure Compiler etc), it'll help with minification. </p>\n\n<p>I find using the index really reduces the readability of the code, so I've declared a variable <code>isSignUp</code>. This way, you reduce the cognitive load of the user reading the code. You don't have to remember which index is which after this declaration. </p>\n\n<p>Since the <code>.item</code>s are already on the page, you can cache their lookup with <code>$carouselItems</code> and then find the <code>.active</code> one with <code>.index()</code>. A better approach could be to check for a specific class rather than index. </p>\n\n<p>Shorter code isn't always the best approach. I find that the current answer is difficult to read.</p>\n\n<pre><code>$(function () {\n var $carousel = $('#carousel');\n var $carouselItems = $carousel.find('.carousel-inner .item');\n var $switch = $('#switch');\n var $header = $('#header');\n var $submit = $('#submit');\n\n var SIGN_IN = 'Sign In';\n var SIGN_UP = 'Sign Up';\n\n $carousel.on('slid', function() {\n var isSignIn = $carouselItems.index('.active') === 0;\n\n if (isSignIn) {\n $header.text(SIGN_IN);\n $switch.text(SIGN_UP);\n $submit.text(SIGN_IN).attr('form', 'sign_in');\n }\n else {\n $header.text(SIGN_UP);\n $switch.text(SIGN_IN);\n $submit.text(SIGN_UP).attr('form', 'sign_up');\n }\n });\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T16:25:14.320",
"Id": "38187",
"Score": "0",
"body": "Thanks for this i am using your code for the index specifically with the other code from above"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T18:19:28.337",
"Id": "24547",
"ParentId": "24538",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "24539",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T14:18:22.803",
"Id": "24538",
"Score": "8",
"Tags": [
"javascript",
"jquery",
"dom"
],
"Title": "Switching some text labels when the first image of a carousel is active"
}
|
24538
|
<p>I'm working on an ASP.NET project using VB.NET that uses <a href="https://github.com/SamSaffron/dapper-dot-net" rel="nofollow">Dapper</a> and the code as implemented so far runs fine with just me testing. In the example below, Dapper calls a stored proc. </p>
<p>But I am wondering primarily right now if the method of generating an open connection (see <code>dbConnFactory</code> below) implemented in the Domain project is not good practice.</p>
<p>Also, can there be pitfalls to calling a <code>Shared</code> function from .NET's WebAPI, whether it the function is for GET, PUT, POST, or Delete?</p>
<p><strong>AutomoblieDomain project</strong></p>
<pre class="lang-vb prettyprint-override"><code>Imports System.Data.Common
Imports Dapper
Namespace DAL
Public Class DomainSettings
Public Shared Property CustomConnectionString As String
End Class
Public Class dbConnFactory
Public Shared Function GetOpenConnection() As DbConnection
Dim connection = New SqlClient.SqlConnection(CustomConnectionString)
connection.Open()
Return connection
End Function
End Class
Public Class CarTypes
Public Property CarTypeID As Integer
Public Property CarTypeText As String
Public Shared Function GetList() As IEnumerable(Of CarTypes)
Using conn = dbConnFactory.GetOpenConnection()
Dim _list = conn.Query(Of CarTypes)("dbo.CarTypes_GetList", CommandType.StoredProcedure).ToList()
Return _list
End Using
End Function
End Class
End Namespace
</code></pre>
<p><strong>Web UI Project</strong></p>
<pre class="lang-vb prettyprint-override"><code>Imports System.Net
Imports System.Web.Http
Imports AutomobileDomain
Public Class CarTypesController
Inherits ApiController
<HttpGet()>
Public Function GetList() As IEnumerable(Of DAL.CarTypes)
Return DAL.CarTypes.GetList()
End Function
End Class
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T08:38:58.990",
"Id": "38022",
"Score": "0",
"body": "Just an opinion but if your GetList() method is returning a list then perhaps you should specify an IList instead of an IEnumerable. That way it's explict to the caller that there is no delayed execution occuring once they have the data back"
}
] |
[
{
"body": "<p>According to MSDN:</p>\n\n<blockquote>\n <p>\"We recommend that you always close the connection when you are finished using it in order for the connection to be returned to the pool. You can do this using either the <strong>Close</strong> or <strong>Dispose</strong> methods of the Connection object, <em>or by opening all connections inside of a <strong>using</strong> statement in C#, or a <strong>Using</strong> statement in Visual Basic</em>.\"\n <a href=\"http://msdn.microsoft.com/en-us/library/8xx3tyca(v=VS.80).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/8xx3tyca(v=VS.80).aspx</a> - Section: \"Adding Connections\"</p>\n</blockquote>\n\n<p>The way your code is written, (connection being delivered via a factory method) does look a little risky. However, the way MSDN describes it, at the end of the <strong>Using</strong> block, the connection object will be automatically closed and disposed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T01:09:13.967",
"Id": "38012",
"Score": "0",
"body": "Thanks; I saw the msdn documentation, and was looking for confirmation as to whether or not it was completely foolish to use the factory method. It does seem like over optimization and I'll stay away from that implementation, but now I'm wondering about calling the `Shared` function from the web api controller..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T16:10:26.140",
"Id": "38051",
"Score": "0",
"body": "Using a factory method to return an open connection is a risky endeavor because you have to trust that anyone using it will _always_ remember to close/dispose it. It is a violation of atomicity (an object is not self-dependent any more). Make sure you are vigilant with your code-reviews! One approach that might help would be to move GetOpenConnection() to a private method in a base class and have your CarTypes class (and others) inherit from it. Then you would limit the use of that factory method. Otherwise, you have to search all of your code for calls to GetOpenConnection()"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T03:05:00.110",
"Id": "39380",
"Score": "0",
"body": "@mg1075 I agree with TGolisch completely. Do not expose a method that returns an Open connection. I don't see anything wrong with just returning a connection object."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T23:46:54.803",
"Id": "24615",
"ParentId": "24542",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T15:52:17.557",
"Id": "24542",
"Score": "4",
"Tags": [
"asp.net",
"database",
"vb.net"
],
"Title": "Handling of open database connection and calling shared function from WebAPI"
}
|
24542
|
<p>I have a function that I need to optimize:</p>
<pre><code>def search(graph, node, maxdepth = 10, depth = 0):
nodes = []
for neighbor in graph.neighbors_iter(node):
if graph.node[neighbor].get('station', False):
return neighbor
nodes.append(neighbor)
for i in nodes:
if depth+1 > maxdepth:
return False
if search(graph, i, maxdepth, depth+1):
return i
return False
</code></pre>
<p><code>graph</code> should be a networkx graph object. How can I optimize this? This should find the closest node in the network with <code>'station'</code> attribute to <code>True</code>.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T01:17:28.670",
"Id": "37924",
"Score": "0",
"body": "You might have a bug: `if search(graph, i, ...): return i` ==> the search() function might return something other than i, yet you are returning i."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T01:18:19.243",
"Id": "37925",
"Score": "0",
"body": "Not a bug, this should return the first step to the station."
}
] |
[
{
"body": "<pre><code>def search(graph, node, maxdepth = 10, depth = 0):\n nodes = []\n for neighbor in graph.neighbors_iter(node):\n if graph.node[neighbor].get('station', False):\n return neighbor\n nodes.append(neighbor)\n</code></pre>\n\n<p>Why store the neighbor in the list? Instead of putting it in a list, just combine your two loops.</p>\n\n<pre><code>for i in nodes:\n</code></pre>\n\n<p><code>i</code> typically stands for index. I suggest using neighbor to make your code easier to follow</p>\n\n<pre><code> if depth+1 > maxdepth:\n return False\n</code></pre>\n\n<p>This doesn't relate to this individual node. What is it doing inside this loop?</p>\n\n<pre><code> if search(graph, i, maxdepth, depth+1):\n return i\n return False\n</code></pre>\n\n<p>Failure to find is better reported using <code>None</code> rather than <code>False</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T19:01:46.470",
"Id": "37903",
"Score": "0",
"body": "The first loop needs to be run on all litems and if none are station, it should search recursively"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T19:32:01.407",
"Id": "37904",
"Score": "2",
"body": "@fread2281, my bad... I didn't think of that. Actually, I think that makes your code wrong. Its implementing a DFS, so it wasn't neccesairlly find the closest \"station\""
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T18:56:45.480",
"Id": "24549",
"ParentId": "24546",
"Score": "4"
}
},
{
"body": "<p>Is there any reason that you are shy from using networkx's functions such as breadth-first search <code>bfs_tree()</code> or depth-first search <code>dfs_tree()</code>? Here is an example of breadth-first search:</p>\n\n<pre><code>import networkx as nx\n...\nfor visiting_node in nx.bfs_tree(graph, node):\n if graph.node[visiting_node].get('station', False):\n print 'Found it' # Do something with visiting_node\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T01:06:00.263",
"Id": "37920",
"Score": "0",
"body": "Good point, although it seems he couldn't do the max_depth with it..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T01:12:48.663",
"Id": "37921",
"Score": "0",
"body": "I think max_depth is to prevent circular links in a graph. the `bfs_tree()` function ensures no circular references."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T01:14:35.230",
"Id": "37922",
"Score": "0",
"body": "Ah, you may well be right."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T01:17:05.533",
"Id": "37923",
"Score": "0",
"body": "`max_depth` is to limit time. I need speed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T16:54:00.280",
"Id": "37940",
"Score": "0",
"body": "I reimplemented it using a custom BFS and thanks for the indirect pointer!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T00:58:41.020",
"Id": "24557",
"ParentId": "24546",
"Score": "4"
}
},
{
"body": "<p>Are you implementing some routing protocol? Can you give me more details? </p>\n\n<p>If your networking is based on equal weight (length) of each edges (let's say wired network or wireless network with backbone base station), than you can use breadth first search (fastest searching algorithm which takes \\$O(|V|+|E|)\\$ times). If you want to find closest nodes base on geometry distance(it could be wireless networks or MANET ad-hoc network), than you need a greedy algorithm.</p>\n\n<p>There are two ways to optimize your func:</p>\n\n<ul>\n<li><p>Searching algorithm: If you are looking for the\nshortest path or closest node in geometry distance, than you'd better to use greedy\napproach, BFS return shortest path only when edges have equal\nweight (cost, length, etc..). You probably know Dijkstra algorithm\nbecause it's widely used in network routings. So use a greedy\nalgorithm would make your network links more stable and robust.\nYou can choose <a href=\"http://en.wikipedia.org/wiki/Best_first_search\" rel=\"nofollow\">Best first search</a>, <a href=\"http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm\" rel=\"nofollow\">Dijkstra algorithm</a>, <a href=\"http://en.wikipedia.org/wiki/A%2a_algorithm\" rel=\"nofollow\">A* algorithm</a>(if\nyou have information of target nodes). </p>\n\n<p>Although Breadth first search and depth first search are available to\nuse in python, but they have some limitations: BFS tree is based on\nthe entry of your neighbor list, it's won't guarantee to find\nshortest path (it's not a greedy algorithm). Same to DFS and your\nalgorithm.</p></li>\n<li><p>choose a proper data structure to build your graph: A good data structure is always the easiest way to make your program faster. If you have more\nedges then vertexes (\\$E > V^2\\$) than use a neighbor matrix. Because\nin this scenario, if you are using a neighbor list, it will take a\nconsiderable time to find out each edge whether belong to your\ngraph or not.</p>\n\n<p>As a side effect, the memory overhead is huge for neighbor matrix.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-10T05:08:36.760",
"Id": "86834",
"Score": "0",
"body": "My code should be a simple breadth first search."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-10T05:12:02.410",
"Id": "86835",
"Score": "0",
"body": "average edges per vertex? are you using this for wired or wireless?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-09T03:33:48.187",
"Id": "49289",
"ParentId": "24546",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "24549",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T18:18:15.363",
"Id": "24546",
"Score": "3",
"Tags": [
"python",
"performance",
"recursion",
"graph"
],
"Title": "Finding the closest node"
}
|
24546
|
<p>I've implemented selection sort, heap sort, insertion sort, and iterative quicksort using C++11. Am I using the correct STL data structures/algorithms? Am I using move semantics correctly in my code?</p>
<pre><code>#include <algorithm>
#include <vector>
#include <queue>
#include <functional>
#include <iterator>
#include <utility>
#include <stack>
namespace detail
{
template <typename It, typename Comp>
void heapSort(It begin, It end, Comp compFunc, std::random_access_iterator_tag)
{
std::make_heap(begin, end, compFunc);
std::sort_heap(begin, end, compFunc);
}
template <typename It, typename Comp, typename IterCat>
void heapSort(It begin, It end, Comp compFunc, IterCat)
{
typedef typename It::value_type value_type;
std::vector<value_type> randomAccessContainer(std::make_move_iterator(begin), std::make_move_iterator(end));
heapSort(std::begin(randomAccessContainer), std::end(randomAccessContainer), compFunc, std::random_access_iterator_tag());
std::move(std::begin(randomAccessContainer), std::end(randomAccessContainer), begin);
}
template <typename It>
class QuicksortStack
{
private:
typedef std::pair<It, It> IterRange;
std::stack<IterRange> m_stack;
public:
void push(IterRange&& range)
{
if (std::distance(range.first, range.second) >= 2)
{
m_stack.push(std::move(range));
}
}
void push(const IterRange& range)
{
if (std::distance(range.first, range.second) >= 2)
{
m_stack.push(range);
}
}
void pop()
{
m_stack.pop();
}
IterRange top() const
{
return m_stack.top();
}
bool empty() const
{
return m_stack.empty();
}
};
}
template <typename It, typename Comp>
void selectionSort(It begin, It end, Comp compFunc)
{
for (; begin != end; ++begin)
{
const It minElem(std::min_element(begin, end, compFunc));
if (begin != minElem)
{
std::iter_swap(begin, minElem);
}
}
}
template <typename It>
void selectionSort(It begin, It end)
{
selectionSort(begin, end, std::less<typename It::value_type>());
}
template <typename It, typename Comp>
void heapSort(It begin, It end, Comp compFunc)
{
detail::heapSort(begin, end, compFunc, typename std::iterator_traits<It>::iterator_category());
}
template <typename It>
void heapSort(It begin, It end)
{
heapSort(begin, end, std::less<typename It::value_type>());
}
template <typename It, typename Comp>
void insertionSort(It begin, It end, Comp compFunc)
{
if (std::distance(begin, end) < 2)
{
return;
}
It elem(std::next(begin));
It nextElem(std::next(elem));
for (; nextElem != end; ++nextElem)
{
std::inplace_merge(begin, elem, nextElem, compFunc);
elem = nextElem;
}
std::inplace_merge(begin, elem, nextElem, compFunc);
}
template <typename It>
void insertionSort(It begin, It end)
{
insertionSort(begin, end, std::less<typename It::value_type>());
}
template <typename It, typename Comp>
void quickSort(It begin, It end, Comp compFunc)
{
detail::QuicksortStack<It> ranges;
ranges.push(std::make_pair(begin, end));
while (!ranges.empty())
{
const auto current(ranges.top());
ranges.pop();
const It last(std::prev(current.second));
const It pivot(std::partition(current.first, last, [=](const typename It::value_type& val){ return compFunc(val, *last); }));
std::iter_swap(pivot, last);
ranges.push(std::make_pair(current.first, pivot));
if (pivot != current.second)
{
ranges.push(std::make_pair(std::next(pivot), current.second));
}
}
}
template <typename It>
void quickSort(It begin, It end)
{
quickSort(begin, end, std::less<typename It::value_type>());
}
</code></pre>
<p><strong>Edit:</strong> Updated to reflect Dave's answer, below.</p>
<pre><code>#include <algorithm>
#include <vector>
#include <queue>
#include <functional>
#include <iterator>
#include <utility>
#include <stack>
#include <iostream>
namespace detail
{
template <typename RandIt, typename Comparer>
void heapSort(RandIt begin, RandIt end, Comparer compFunc, std::random_access_iterator_tag)
{
std::make_heap(begin, end, compFunc);
std::sort_heap(begin, end, compFunc);
}
template <typename FwdIt, typename Comparer, typename IterCat>
void heapSort(FwdIt begin, FwdIt end, Comparer compFunc, IterCat)
{
typedef typename std::iterator_traits<FwdIt>::value_type value_type;
std::vector<value_type> randomAccessContainer(std::make_move_iterator(begin), std::make_move_iterator(end));
heapSort(std::begin(randomAccessContainer), std::end(randomAccessContainer), compFunc, std::random_access_iterator_tag());
std::move(std::begin(randomAccessContainer), std::end(randomAccessContainer), begin);
}
template <typename InIt>
class QuicksortStack
{
private:
typedef std::pair<InIt, InIt> IterRange;
std::stack<IterRange> m_stack;
public:
void push(IterRange&& range)
{
if (std::distance(range.first, range.second) >= 2)
{
m_stack.push(std::move(range));
}
}
void push(const IterRange& range)
{
if (std::distance(range.first, range.second) >= 2)
{
m_stack.push(range);
}
}
void pop()
{
m_stack.pop();
}
IterRange top() const
{
return m_stack.top();
}
bool empty() const
{
return m_stack.empty();
}
};
}
template <typename FwdIt, typename Comparer>
void selectionSort(FwdIt begin, FwdIt end, Comparer compFunc)
{
for (; begin != end; ++begin)
{
const auto minElem(std::min_element(begin, end, compFunc));
if (begin != minElem)
{
std::iter_swap(begin, minElem);
}
}
}
template <typename FwdIt>
void selectionSort(FwdIt begin, FwdIt end)
{
selectionSort(begin, end, std::less<typename std::iterator_traits<FwdIt>::value_type>());
}
template <typename FwdIt, typename Comparer>
void heapSort(FwdIt begin, FwdIt end, Comparer compFunc)
{
detail::heapSort(begin, end, compFunc, typename std::iterator_traits<FwdIt>::iterator_category());
}
template <typename FwdIt>
void heapSort(FwdIt begin, FwdIt end)
{
heapSort(begin, end, std::less<typename std::iterator_traits<FwdIt>::value_type>());
}
template <typename FwdIt, typename Comparer>
void insertionSort(FwdIt begin, FwdIt end, Comparer compFunc)
{
for (auto elem = begin; elem != end; ++elem)
{
const auto current(std::move(*elem));
const auto sortPosition(std::upper_bound(begin, elem, current, compFunc));
std::move_backward(sortPosition, elem, std::next(elem));
*sortPosition = std::move(current);
}
}
template <typename FwdIt>
void insertionSort(FwdIt begin, FwdIt end)
{
insertionSort(begin, end, std::less<typename std::iterator_traits<FwdIt>::value_type>());
}
template <typename BiDirIt, typename Comparer>
void quickSort(BiDirIt begin, BiDirIt end, Comparer compFunc)
{
detail::QuicksortStack<BiDirIt> ranges;
ranges.push(std::make_pair(begin, end));
while (!ranges.empty())
{
const auto current(ranges.top());
ranges.pop();
const auto last(std::prev(current.second));
const auto pivot(std::partition(current.first, last, [=](const typename std::iterator_traits<BiDirIt>::value_type& val){ return compFunc(val, *last); }));
std::iter_swap(pivot, last);
ranges.push(std::make_pair(current.first, pivot));
if (pivot != current.second)
{
ranges.push(std::make_pair(std::next(pivot), current.second));
}
}
}
template <typename BiDirIt>
void quickSort(BiDirIt begin, BiDirIt end)
{
quickSort(begin, end, std::less<typename std::iterator_traits<BiDirIt>::value_type>());
}
</code></pre>
|
[] |
[
{
"body": "<p>Your code looks good, I don't see any major problems.</p>\n<p>Here's what I would consider changing:</p>\n<ul>\n<li>Name your iterator template arguments by the <a href=\"https://en.cppreference.com/w/cpp/named_req\" rel=\"nofollow noreferrer\">iterator concept they are required to meet</a>. For example: <code>template<typename ForwardIt></code></li>\n<li>I would prefer not to see early <code>return</code>s from functions if possible. I think it's clearer to do <code>if(blah){ do stuff }</code> then to do <code>if(!blah){ return; } do stuff</code></li>\n<li>I didn't look closely at all of them, but you can use STL to make a much prettier insertion sort:</li>\n</ul>\n<p>....</p>\n<pre><code>template<typename ForwardIt, typename Compare>\nvoid InsertionSort(ForwardIt first, ForwardIt last, Compare comp)\n{\n for(auto i = first; i != last; ++i)\n {\n std::rotate(std::upper_bound(first, i, *i, comp), i, std::next(i));\n }\n}\n</code></pre>\n<p><strong>Edit:</strong>\nIn hindsight, that insertion sort is sub optimal. Yours will be quite bad too. Here's a <em>much</em> faster one, with different STL use:</p>\n<pre><code>template<typename BiDirIt, typename Compare>\nvoid InsertionSort(BiDirIt first, BiDirIt last, Compare comp)\n{\n for(auto i = first; i != last; ++i)\n {\n auto current = std::move(*i);\n auto start = std::upper_bound(first, i, current, comp);\n std::move_backward(start, i, std::next(i));\n *start = std::move(current);\n }\n}\n</code></pre>\n<p><strong>Edit2:</strong>\nYour forwarding functions (the functions that fill in a default compare function) don't allow for raw pointer iterators. The STL algorithms do. The problem is that you're using <code>typename FwdIt::value_type</code>. Obviously a raw pointer doesn't have a member typedef called <code>value_type</code>. The way to solve this is to use <code>iterator_traits</code>:</p>\n<pre><code>template <typename FwdIt>\nvoid selectionSort(FwdIt begin, FwdIt end)\n{\n selectionSort(begin, end, std::less<typename std::iterator_traits<FwdIt>::value_type>());\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-27T03:51:59.350",
"Id": "494415",
"Score": "0",
"body": "`if(!blah){ return; } do stuff` why not?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-04-01T18:03:00.873",
"Id": "24600",
"ParentId": "24548",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "24600",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T18:51:42.670",
"Id": "24548",
"Score": "3",
"Tags": [
"c++",
"c++11",
"sorting",
"stl"
],
"Title": "Am I using C++11 features like STL and move semantics correctly?"
}
|
24548
|
<p>I am learning ORM using Hibernate by creating a movie rental application. Currently, I have the following three entities for persistence:</p>
<ul>
<li>User</li>
<li>Movie</li>
<li>Rental (composite element for many-to-many mapping between above two)</li>
</ul>
<p>Now, to handle the cart updates, I have the following code in a session scoped bean:</p>
<pre><code>@ManagedBean
@SessionScoped
public class UserManager extends BaseBean implements Serializable
{
....
private Map<Integer, Movie> cart;
....
public void updateCart(Movie selectedMovie)
{
if (!isLoggedIn()) {
return;
}
int id = selectedMovie.getMovieID();
if (cart.containsKey(id)) {
cart.remove(id);
}
else {
cart.put(id, selectedMovie);
}
}
}
</code></pre>
<p>Now for user's purchase scenario, I need to keep track of the number of rentals per movie. So, I thought of adding that property to the <code>Rental</code> entity and use it as a value for the map. But, this class itself contains <code>Movie</code> as a property for the mapping as below:</p>
<pre><code><set name="rentals" cascade="all" lazy="true" table="USER_MOVIES">
<key column="userRegistrationID" not-null="true"/>
<composite-element class="Rental">
<property name="bookingDate" column="bookingDate" type="date"/>
<many-to-one name="movie" column="bookedMovieID" class="Movie" not-null="true"/>
</composite-element>
</set>
</code></pre>
<p>So, while adding to / removing from cart, I will have to create / destroy an instance of the <code>Rental</code> class, which would be a bad idea. So I am thinking that I should restructure my entities.</p>
<p>Am I right in assuming the above? Is there a better approach for the above?</p>
<p>I am using the following:</p>
<ul>
<li>JSF 2.1 + PrimeFaces</li>
<li>Hibernate 4.3</li>
<li>MySQL</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T06:47:00.047",
"Id": "38018",
"Score": "1",
"body": "\"I need to keep track of the number of rentals per movie.\" And why is that? How you should store that number depends wholly on why you need it. E.g. if you need it for some monthly report you may not need to store it at all."
}
] |
[
{
"body": "<p>You are not correct in assuming the above... If you want to count the number of rentals for one Movie you can do the following (given you are not removing records from your database):</p>\n\n<pre><code>@NamedQueries{\n @NamedQuery(name=\"Movie.getRentalCount\", \n query=\"SELECT COUNT FROM Rentals r WHERE r.bookMovieId = :movieId\")\n}\n@Entity\nclass Movie{\n\n @Transient\n public static final String getRentalCount = \"uniqueQueryNameForMovie\";\n\n // ... \n}\n</code></pre>\n\n<hr>\n\n<p>This allows you to do the following in your purchase process:</p>\n\n<pre><code>@Inject\nEntityManager entityManager;\n\npublic Long getRentalCountForMovieId(long movieId){\n TypedQuery<Long> q = entityManager.createNamedQuery(Movie.getRentalCount, Long);\n q.setParameter(\"movieId\", movieId);\n return q.getSingleResult();\n}\n</code></pre>\n\n<p>You'd need to use the wrapper class, as TypedQuery only accepts Objects as type.</p>\n\n<p>Also it should be unneccesary to create Rental instances while changing the contents of your <code>cart</code>. They should only be created when you check the cart out in the end, because before that there is no need for a Rental instance...</p>\n\n<p>If you decided to destroy the instances of Rental on return of the Movie: You should keep a record of older Rentals for historization and usability reasons.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T18:44:38.923",
"Id": "43236",
"ParentId": "24552",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-30T20:21:59.753",
"Id": "24552",
"Score": "2",
"Tags": [
"java"
],
"Title": "How do I structure my entities for easier persistence?"
}
|
24552
|
<p>The scripts below, I've obtained through tutorials and edited the best I know how. It all works - but I'd like to place them in one, external script. If at all possible, I'd appreciate some help in cleaning up the code too. I've a feeling some of it is redundant.</p>
<p>With the client-side validation script, I have "Name," "Email," "Phone," and "Message" set as input text values in the HTML. If they submit the form with those default values still in place, it gives an error. Also gives one when email is not valid or if phone is not actually a phone number. BUT the phone number is not required. So, the default value of "Phone" could pass through if nothing at all is entered there.</p>
<pre><code><script type="text/javascript">
$(document).ready(function() {
$('nav a[href^="#"]').bind('click.smoothscroll',function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
$('a[href=#top]').click(function(){
$('html, body').animate({scrollTop:0}, 'slow');
return false;
});
$(function() {
$("nav select").change(function() {
window.location = $(this).find("option:selected").val();
});
});
</script>
<script>
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["name", "email", "message"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
phone = $("#tel");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Required field.";
emailerror = "Invalid email.";
nameerror = "Name";
phoneerror = "Phone";
messageerror = "Message";
onlynumber = "Invalid phone.";
$("#contact").submit(function(){
//Validate required fields
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror) || (input.val() == nameerror) || (input.val() == messageerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
if(phone.val() != phoneerror) {
if (!/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/.test(phone.val())) {
phone.addClass("needsfilled");
phone.val(onlynumber);
}
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
return true;
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});
</script>
<script>
$(function(){
$('input, textarea').each(function(){
var txtval = $(this).val();
$(this).focus(function(){
$(this).val('')
});
$(this).blur(function(){
if($(this).val() == ""){
$(this).val(txtval);
}
});
});
});
</script>
</code></pre>
|
[] |
[
{
"body": "<p>basically just cleaned up some redundant brackets, tags, added a comment and modified existing comments, fixed indentations etc. Then i ran it through JSLint(<a href=\"http://www.jslint.com/\" rel=\"nofollow\">http://www.jslint.com/</a>), enjoy :)!</p>\n\n<pre><code>$(document).ready(function() {\n $('nav a[href^=\"#\"]').bind('click.smoothscroll',function (e) {\n e.preventDefault();\n var target = this.hash,\n $target = $(target);\n $('html, body').stop().animate({\n 'scrollTop': $target.offset().top\n }, 900, 'swing', function () {\n window.location.hash = target;\n });\n });\n $('a[href=#top]').click(function(){\n $('html, body').animate({scrollTop:0}, 'slow');\n return false;\n });\n $(function() {\n $(\"nav select\").change(function() {\n window.location = $(this).find(\"option:selected\").val();\n });\n });\n\n //place ID's of all required fields here.\n required = [\"name\", \"email\", \"message\"];\n //if using an ID other than #email or #error then replace it here\n email = $(\"#email\");\n phone = $(\"#tel\");\n errornotice = $(\"#error\");\n //the text to show up within a field when it is incorrect\n emptyerror = \"Required field.\";\n emailerror = \"Invalid email.\";\n nameerror = \"Name\";\n phoneerror = \"Phone\";\n messageerror = \"Message\";\n onlynumber = \"Invalid phone.\";\n\n $(\"#contact\").submit(function(){ \n //validate required fields\n for (i = 0; i < required.length; i++) {\n var input = $('#' + required[i]);\n if (input.val() == \"\" || input.val() == emptyerror || input.val() == nameerror || input.val() == messageerror) {\n input.addClass(\"needsfilled\");\n input.val(emptyerror);\n errornotice.fadeIn(750);\n } else {\n input.removeClass(\"needsfilled\");\n }\n }\n //validate the e-mail.\n if (!/^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {\n email.addClass(\"needsfilled\");\n email.val(emailerror);\n }\n\n //validate phone\n if(phone.val() != phoneerror) {\n if (!/\\(?([0-9]{3})\\)?([ .-]?)([0-9]{3})\\2([0-9]{4})/.test(phone.val())) {\n phone.addClass(\"needsfilled\");\n phone.val(onlynumber);\n }\n }\n\n //if any inputs on the page have the class 'needsfilled' the form will not submit\n if ($(\":input\").hasClass(\"needsfilled\")) {\n return false;\n } else {\n errornotice.hide();\n return true;\n }\n });\n\n //clears any fields in the form when the user clicks on them\n $(\":input\").focus(function(){ \n if ($(this).hasClass(\"needsfilled\") ) {\n $(this).val(\"\");\n $(this).removeClass(\"needsfilled\");\n }\n });\n\n\n $(function(){\n $('input, textarea').each(function(){\n var txtval = $(this).val();\n $(this).focus(function(){\n $(this).val('')\n });\n $(this).blur(function(){\n if($(this).val() == \"\"){\n $(this).val(txtval);\n }\n });\n });\n });\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T06:00:10.317",
"Id": "24563",
"ParentId": "24562",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24563",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T05:54:04.693",
"Id": "24562",
"Score": "3",
"Tags": [
"javascript",
"beginner",
"jquery",
"validation"
],
"Title": "Contact information validation"
}
|
24562
|
<p>Looking at knockout for the first time, would like to know if I'm approaching it correctly.</p>
<p>Here's a live example:
<a href="http://jsfiddle.net/fergal_doyle/xhAe8/1/" rel="nofollow">http://jsfiddle.net/fergal_doyle/xhAe8/1/</a></p>
<p>I have a "car" select, and an "other" input to allow values not present in the select box. When "other" is populated, it over-rides "car" by disabling it and a computed observable is set to the actual chosen car. Only when "other" is emptied, will "car" become enabled again.</p>
<p>HTML:</p>
<pre><code><label for="car">Car</label>
<select id="car" data-bind="options: cars, value: selectedCar, enable: checkCar"></select>
<label for="other">Other</label>
<input id="other" type="text" data-bind="value: other, valueUpdate:'afterkeydown'"/>
<p>Chosen value: <span data-bind="text: chosenCar"></span></p>
</code></pre>
<p>JS:</p>
<pre><code>function viewModel(){
var self = this;
self.cars = ko.observableArray(["Chrysler", "Chevrolet", "Ford", "Lincoln"]);
self.other = ko.observable("");
self.selectedCar = ko.observable("");
self.chosenCar = ko.computed(function() {
return self.other() || self.selectedCar();
});
self.checkCar = ko.computed(function(){
if(self.other())
return false;
else
return true;
});
}
ko.applyBindings(new viewModel());
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T14:15:25.123",
"Id": "37932",
"Score": "3",
"body": "`if(self.other()) return false; else return true;` is a bit verbose, I'd just write `return !self.other();`"
}
] |
[
{
"body": "<p>It looks fine to me. My only real criticism is your <code>checkCar</code> implementation. It ought to be written out as:</p>\n\n<pre><code>self.checkCar = ko.computed(function(){\n return !self.other();\n});\n</code></pre>\n\n<p>On a minor note, you should case your view model name in PascalCase. By making constructors like that, they stand out better. Everything else should be in camelCase.</p>\n\n<hr>\n\n<p>Other than that, you've made great use of the computed observables. A big mistake I see a lot on Stack Overflow IMHO is when I see people putting all that logic in the view.</p>\n\n<p>I might change the name of the properties however to be more descriptive of what they represent. In particular, change <code>checkCar</code> to <code>isSelectedCarOverridden</code>.</p>\n\n<p>Personally, I'd change it around a bit. I'd add an \"Other\" option in the cars list and make the <code>Other</code> car input enabled/visible based on that value.</p>\n\n<p>Also, consider making <code>cars</code> <em>not</em> observable. If this is going to be a fixed list and you won't be dynamically adding to it, making it observable may be unnecessary. In fact, I'd pull that array out of the view model as it appears to be a constant value. That way if you have multiple view models instantiated in the future, they all can share the same instance.</p>\n\n<pre><code>var constants = {\n cars: [\"Chrysler\", \"Chevrolet\", \"Ford\", \"Lincoln\"]\n};\n\nfunction ViewModel() {\n var self = this;\n self.cars = constants.cars;\n // ...\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T13:26:28.593",
"Id": "37972",
"Score": "0",
"body": "What if I removed the checkCar function and did this: `<select id=\"car\" data-bind=\"options: cars, value: selectedCar, enable: !other()\"></select>` Is that considered putting logic in the view?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T13:33:35.250",
"Id": "37973",
"Score": "1",
"body": "I would say so. Any time your bindings doesn't look like `binding: propertyName` or `binding: { 'prop': propertyName }` and has some more complicated expression, I'd consider that putting logic into the view. All of that should be in a computed observable. It's better to keep the bindings in the view as simple as possible so it's easier to debug and you know where all the logic is (in the view model)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T14:11:37.167",
"Id": "38040",
"Score": "0",
"body": "Maybe I'm just reading it wrong but isn't it: camelCase and PascalCase? I.e. in camel casing the first word doesn't start with a capital but it does in Pascal casing (also called upper camel casing)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T14:13:14.353",
"Id": "38041",
"Score": "0",
"body": "@RobH: Ah, you're right, I got it backwards."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T14:19:40.913",
"Id": "38042",
"Score": "0",
"body": "And while we're correcting things, in my comment above, \"I'd consider putting that logic into the view _model_.\""
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T16:18:31.323",
"Id": "24569",
"ParentId": "24565",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "24569",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T13:01:58.353",
"Id": "24565",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Knockout first-timer"
}
|
24565
|
<p>I'm creating a MUD and am running into some design issues regarding Items.</p>
<p>Items are stored in an <code>ItemDatabase</code> after being read from a JSON file. </p>
<pre><code>template <typename ItemType>
static void load(std::string const& filename)
{
PropertyTree propertyTree;
boost::property_tree::read_json(filename, propertyTree);
for (auto& jsonItem : propertyTree)
{
Item *item = new ItemType();
item->fromJson(jsonItem);
database_[item->id()] = item;
}
}
</code></pre>
<p>At first, every Database::find() returned a shallow copy of the item, however, this quickly becomes dangerous and erroneous when items have a finite usage, e.g. a life potion that is consumed after one charge.</p>
<p>Therefore, I want to start returning deep copies as <code>std::unique_ptr</code>s because each Item is unique and is possessed by only one entity. This avoids dangerous dangling pointers, if the Item is not maintained or destroyed by the caller:</p>
<pre><code>template <typename DataType>
std::unique_ptr<DataType> EntityDatabase<DataType>::find(EntityId const& entityId)
{
auto found = std::find_if(std::begin(database_), std::end(database_),
[&entityId](Container::value_type const& candidate)
{
return (candidate.second->id() == entityId);
});
if (found != std::end(database_))
return std::unique_ptr<DataType>(new DataType(*found->second));
else
return nullptr;
}
</code></pre>
<p>However, the resulting code is worse than hideous. Consider turning an <code>Item</code> into a <code>Weapon</code>:</p>
<pre><code>void Inventory::fromJson(PropertyTree::value_type const& properties)
{
auto jsonInventory = *properties.second.find("Inventory");
auto weaponId = getValue<EntityId>(jsonInventory, "Weapon");
weapon_.reset(static_cast<Weapon*>(ItemDatabase::find(weaponId).release()));
auto armorId = getValue<EntityId>(jsonInventory, "Armor");
armor_.reset(static_cast<Armor*>(ItemDatabase::find(armorId).release()));
money_ = getValue<Money>(jsonInventory, "Money");
for (auto& item : jsonInventory.second.get_child("Items"))
{
auto itemId = boost::lexical_cast<EntityId, std::string>(item.second.data());
inventory_.push_back(std::move(ItemDatabase::find(itemId)));
}
}
</code></pre>
<p>How can I improve the code or the design?</p>
|
[] |
[
{
"body": "<p>Let me restate the problem, because it wasn't 100% clear to me from what you've written. I personally think you've left out a bit too much code. I'll state my assumptions of what is going on, but ideally this should be clear from what is posted. Firstly, I assume <code>EntityDatabase</code> is a class, not a namespace. Secondly, I assume <code>ItemDatabase</code> is declared as something like:</p>\n\n<pre><code>EntityDatabase<Item> ItemDatabase;\n</code></pre>\n\n<p>Further, I assume you have some kind of inheritance hierarchy that looks something like:</p>\n\n<pre><code>class Item\n{\n Item();\n virtual ~Item();\n //....\n}\n\nclass Weapon : public Item\n{ \n //...\n}\n\nclass Armor : public Item\n{\n //...\n}\n</code></pre>\n\n<p>The problem then is that <code>ItemDatabase.find(...)</code> (I assume it's meant to be <code>.</code>, not <code>::</code>) will return a <code>std::unique_ptr<Item></code> when you want a <code>std::unique_ptr<Weapon></code> or some other derived class of <code>Item</code>.</p>\n\n<p>This seems less a problem of <code>unique_ptr</code> and more the fact that you're kind of abusing polymorphism. Let's assume you didn't return a <code>unique_ptr</code>, just a normal <code>Item*</code>:</p>\n\n<pre><code>template <typename DataType>\nDataType* EntityDatabase<DataType>::find(EntityId const& entityId)\n</code></pre>\n\n<p>The only thing that would change then is that <code>armor_</code> would be declared as <code>Armor*</code> instead of <code>std::unique_ptr<Armor></code>, so it would become:</p>\n\n<pre><code> armor_ = static_cast<Armor*>(ItemDatabase::find(armorId));\n</code></pre>\n\n<p>Hence, the only things that really change are the calls to <code>release</code> and <code>reset</code>. This is not significantly less ugly than what is already there. If <code>armour_</code> were declared as <code>std::unique_ptr<Item></code> then you could of course do the following:</p>\n\n<pre><code>armor_ = std::move(ItemDatabase::find(armorId));\n</code></pre>\n\n<p>Again, this is all built on a lot of assumptions since there is quite a bit of context missing.</p>\n\n<p>For fixes, I suppose the options are:</p>\n\n<ul>\n<li><p>Leave it as is. It's fairly ugly, but not that much uglier than the code you'd have for raw pointers.</p></li>\n<li><p>Fix your inheritance hierarchy. The fact that you're having to cast things back and forth suggests that perhaps polymorphism isn't the correct solution here. Does each item need to know its specific type? Is there a <code>virtual</code> function you can add to <code>Item</code> that will fix this? I don't know, there's not enough context from the code you've posted.</p></li>\n<li><p>Finally, make a function to limit the uglyness to one spot:</p>\n\n<pre><code>template <typename T, typename U>\nvoid recast(std::unique_ptr<T>& ptr1, std::unique_ptr<U>&& ptr2)\n{\n static_assert(std::is_base_of<U, T>::value, \"U is not a base type of T\");\n ptr1.reset(static_cast<T*>(ptr2.release()));\n}\n\n....\nauto armorId = getValue<EntityId>(jsonInventory, \"Armor\");\nrecast(armor_, ItemDatabase::find(armorId));\n</code></pre></li>\n</ul>\n\n<p>This is still pretty ugly, but if used often, might be slightly less offensive.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T09:31:57.123",
"Id": "37963",
"Score": "0",
"body": "Thank you for your input! You are correct with almost all assumptions, except that EntityDatabase and, by extension, ItemDatabase are static. My first approach was exactly to declare `armor_` as `Armor*`. I did this because I wanted to constrain the types of items that could act as armor or weapons, even though they are items. I'm inclined to agree that this is an abuse of polymorphism, but aside from declaring `Weapon` and `Armor` not a derivative of `Item`, I didn't and don't know how to otherwise solve it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T09:44:43.963",
"Id": "37964",
"Score": "0",
"body": "I added some more information based on the assumptions you made and further snippets I thought to be illuminating."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T01:58:47.213",
"Id": "38068",
"Score": "0",
"body": "I think in this case there isn't all that much you can do. Unfortunately, C++ syntax is not concise at the best of times. The code is ugly, true, but it's not too hard to understand what is going on."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T07:40:10.230",
"Id": "24588",
"ParentId": "24566",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "24588",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T14:13:24.163",
"Id": "24566",
"Score": "6",
"Tags": [
"c++",
"c++11",
"pointers"
],
"Title": "unique_ptr usage too unwieldy"
}
|
24566
|
<p>This is my first real program, though it has gone through a few major revisions. Anyhow, I am sure that there is a lot I could have done better, cleaner or safer.</p>
<p>Can anyone see anything I really need to work on or fix?</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <getopt.h>
#include <allegro.h>
struct cards
{
int card_value[10];
char card_name[10];
char card_suit[10];
int card_tally;
BITMAP *card_pic[10];
};
struct cards hand[2];
short decks=1;
short cards_used[14]= {0};
int player_cash = 500;
void endgame()
{
if (player_cash < 1)
alert("You lost it all big guy! Better luck next time!", NULL, NULL, "&Ok", NULL, 'o', 'k');
else if (player_cash < 501)
alert("Game Over: Not enough cards to continue",
"In the end, you didn't win a dime but at least",
"you still have the shirt on your back",
"&Ok", NULL, 'o', 'k');
else
{
char cash[100];
snprintf(cash, sizeof(cash), "You are leaving with $%d", player_cash);
alert("Amazing! You beat the house!", cash, NULL, "&Ok", NULL, 'o', 'k');
}
exit(EXIT_SUCCESS);
}
void tally (int a)
{
int x=0, y=0;
for (x=0; x<10; x++)
{
y = y + hand[a].card_value[x];
}
hand[a].card_tally = y;
}
void check_for_ace (int a)
{
int x;
for (x=0; x<10; x++)
{ if (hand[a].card_name[x] =='A')
{
int y;
int z = 10;
for (y=0; y<10; y++)
z = z + hand[a].card_value[y];
if (z < 22)
hand[a].card_value[x]=11;
else
hand[a].card_value[x]=1;
}
}
}
void draw_card (int a)
{
short z = 1 + rand () % 13;
short x=0;
short safe_guard=0;
short y= 1 + rand () % 4;
char card_suit = 'd';
while (hand[a].card_value[x] != 0)
x++;
while ((cards_used[z] > (decks * 4)) && (safe_guard < 50))
{
z = 1 + rand () % 13;
safe_guard++;
}
if (safe_guard > 49)
endgame();
cards_used[z] = cards_used[z] + 1;
safe_guard=0;
/*Now Assign Values and Names to the Cards*/
if ((z > 1) && (z < 10))
{
hand[a].card_value[x]=z;
hand[a].card_name[x]=((char) '0' + z);
}
else if (z == 10)
{
hand[a].card_value[x]=z;
hand[a].card_name[x]='T';
}
else if (z == 11)
{
hand[a].card_value[x]=10;
hand[a].card_name[x]='J';
}
else if (z == 12)
{
hand[a].card_value[x]=10;
hand[a].card_name[x]='Q';
}
else if (z == 13)
{
hand[a].card_value[x]=10;
hand[a].card_name[x]='K';
}
else if (z == 1)
{
/*Function 'check_for_ace' deals with this more properly*/
hand[a].card_value[x]=1;
hand[a].card_name[x]='A';
}
/*Assign Suits Randomly*/
if (y == 1)
card_suit='c';
if (y == 2)
card_suit='d';
if (y == 3)
card_suit='h';
if (y == 4)
card_suit='s';
check_for_ace(a);
/*Link the Picture*/
char pic[20];
snprintf(pic, sizeof(pic), "card/%c%c.bmp", hand[a].card_name[x], card_suit);
hand[a].card_pic[x]=load_bmp(pic, NULL);
tally(a);
}
void display_hands ()
{
int x;
int y=10;
clear_bitmap(screen);
/*Dealer hand*/
for (x=0; hand[0].card_name[x]!=0; x++)
{
blit(hand[0].card_pic[x], screen, 0,0,y,10,73,97);
y=y+75;
}
/*Player Hand, displayed on bottom of screen*/
y=10;
for (x=0; hand[1].card_name[x]!=0; x++)
{
blit(hand[1].card_pic[x], screen, 0,0,y,300,73,97);
y=y+75;
}
textprintf_ex(screen, font, 335, 2, makecol(0, 0, 0), makecol(248, 248, 230), " ");
textprintf_ex(screen, font, 335, 10, makecol(0, 0, 0), makecol(248, 248, 230), " Cash ");
textprintf_ex(screen, font, 335, 18, makecol(0, 0, 0), makecol(248, 248, 230), " %d ", player_cash);
textprintf_ex(screen, font, 335, 26, makecol(0, 0, 0), makecol(248, 248, 230), " ");
}
void dealer_turn()
{
while (hand[0].card_tally < 17)
{
draw_card(0);
display_hands();
}
if (hand[0].card_tally > 21)
{
hand[0].card_tally = 0;
alert("Dealer Busts!", NULL, NULL, "&Ok", NULL, 'o', 'k');
}
}
void player_turn()
{
int action=1;
while (action != 2 && hand[1].card_tally < 21)
{
action=alert("What will you do?", NULL, NULL, "&Hit", "&Stand", 'h', 's');
if (action == 1)
draw_card(1);
display_hands();
tally(1);
}
if (hand[1].card_tally > 21)
alert("Player Busts!", NULL, NULL, "&Ok", NULL, 'o', 'k');
}
int main(int argc, char **argv)
{
allegro_init();
install_keyboard();
install_mouse();
set_color_depth(16);
set_gfx_mode(GFX_AUTODETECT_WINDOWED, 400,400,0,0);
argc -= optind;
argv += optind;
if (argv[0])
decks = atoi (argv[0]);
srand(time(NULL));
int x=0;
while (x != -1)
{
display_hands();
int bet = 50;
int alert_val = alert3("Please place your bet", NULL, NULL, "&50", "&100", "15&0", '5', '1', '0');
bet = alert_val * 50;
player_cash=player_cash - bet;
display_hands();
draw_card(0);
draw_card(1);
draw_card(1);
display_hands();
player_turn();
if (hand[1].card_tally < 22)
{
dealer_turn();
display_hands();
}
if ((hand[0].card_tally > hand[1].card_tally) || (hand[0].card_tally == hand[1].card_tally
|| hand[1].card_tally > 21))
{
alert("Dealer wins!", NULL, NULL, "&Ok", NULL, 'o', 'k');
}
else
{
alert("Player wins!", NULL, NULL, "&Ok", NULL, 'o', 'k');
player_cash = player_cash + (bet * 2);
display_hands();
}
if (player_cash < 1)
endgame();
int i;
for (i=0; i < 2; i++)
{
for (x=0; x < 10; x++)
{
hand[i].card_name[x] = 0;
hand[i].card_suit[x] = 0;
hand[i].card_value[x] = 0;
}
hand[i].card_tally = 0;
}
if (alert("Continue or Quit?", NULL, NULL, "&Continue", "&Quit", 'c', 'q') == 2)
exit(EXIT_SUCCESS);
}
int loop=0;
for (loop=0; loop < 11; loop++)
{
destroy_bitmap(hand[0].card_pic[loop]);
destroy_bitmap(hand[1].card_pic[loop]);
}
return 0;
}
END_OF_MAIN();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T16:33:08.847",
"Id": "37936",
"Score": "1",
"body": "Hello, and welcome to Code Review. Questions without code in them are considered off topic, so you'll need to inline the link. If you're having trouble indenting so it's formatted as code, just paste in the code, select it all, and hit Control + K."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T16:42:28.570",
"Id": "37939",
"Score": "0",
"body": "Wow, I did not realize that would work. I always thought I had to indent it line by line."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T18:10:07.323",
"Id": "37947",
"Score": "0",
"body": "Small thing that I see as of right now, all your vars and functions are_like_that BUT endgame! You should put it as end_game to keep up consistency!"
}
] |
[
{
"body": "<p>Here are a few things I notice from skimming through your code:</p>\n\n<p>Pros:</p>\n\n<ul>\n<li>Nice and clean style, lines are short enough to ease reading</li>\n<li>Picked good names for functions</li>\n</ul>\n\n<p>Cons:</p>\n\n<ul>\n<li>The use of one-letter variable. They are not descriptive. For example, <code>void tally (int a)\n</code> does not say what a is</li>\n</ul>\n\n<p>Suggestions:</p>\n\n<ul>\n<li>Use named constants such as HEART, CLUB, ... to help code readability and maintainability.</li>\n<li>Code consistency: I see places where you surround equal sign with space (e.g. <code>x = 0</code>) and places where you don't (e.g. <code>x=0</code>). You should be more consistent.</li>\n<li>Refactor of <code>display_hands()</code>: in this function, you have the same code repeated twice, once for the dealer and once for the player. There is opportunity to refactor the code by pulling the common block into a separate function.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T21:35:39.840",
"Id": "24577",
"ParentId": "24568",
"Score": "7"
}
},
{
"body": "<p>I have some comments, some of which are quite pedantic.</p>\n\n<ul>\n<li>Avoid hard-coded constants (eg 10, 'c, 'd', 'A' etc) - use defines or const </li>\n<li>Inconsistent spacing around <code>=</code> etc</li>\n<li><p>Use of globals is undesirable unless necessary - here it is mostly not, really. And if you must use globals in a file, make them static unless they really <strong>must</strong> be shared between files. And that is rare.</p></li>\n<li><p>Make local functions static wherever possible</p></li>\n<li>Add an explicit <code>void</code> in empty function parameter lists</li>\n<li><p>Add braces on single statement:</p>\n\n<pre><code>if (condition) {\n statement;\n}\n</code></pre></li>\n<li><p>Variable names x,y,z etc are undescriptive and unhelpful. Use of very short\nnames is not necessarily bad, but you should only use such names where it is\nobvious what they relate to. In this code it hinders understanding (mine anyway)</p></li>\n<li><p>use of <code>short</code> rather than <code>int</code> is generally pointless</p></li>\n<li><p>I would prefer to see the 'hand' passed around as a pointer to struct (const if possible) rather than a hand number <code>a</code></p></li>\n<li><p><code>tally</code> is more useful if it just sums the content of the <code>card_value</code> array\nand returns the sum without writing to <code>card_tally</code>. Note that <code>check_for_ace</code> contains a loop that is much the same as (and therefore could use) <code>tally</code></p></li>\n</ul>\n\n<h2>In <code>draw_card</code>:</h2>\n\n<ul>\n<li><p>This loop should be a function. Also there is no error check</p>\n\n<pre><code>while (hand[a].card_value[x] != 0)\n x++;\n</code></pre></li>\n<li><p>The subsequent loop generates a random card that hasn't already been \nused up but there should be a <code>cards_used</code> array for each suit. I\nknow your deck*4 is supposed to handle that, but does it prevent the same card (4 of hearts, say) being used 4 times (with one deck)? You might perhaps use\none array of 52 entries covering all suits. I'd put the loop in a<br>\nfunction too.</p></li>\n<li>a switch might be better than many if/else</li>\n</ul>\n\n<h2>In <code>display_hands</code></h2>\n\n<ul>\n<li>there are two almost identical loops - extract them into a function</li>\n</ul>\n\n<h2>In <code>main</code></h2>\n\n<ul>\n<li><code>main</code> is too big</li>\n<li>Did you chop out some argument handling in <code>main</code>? What you have looks odd.</li>\n<li>The reset loop in <code>main</code> should also be extracted into a separate function</li>\n<li>Variable <code>loop</code> in the bitmap-destroy loop is badly named</li>\n<li><code>END_OF_MAIN</code> - what is this? - remove it anyway.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T05:17:20.340",
"Id": "37958",
"Score": "0",
"body": "Thanks! Yes, I did remove some argument handling code from the main. I originally had an option to set a starting value to the player_cash variable. END_OF_MAIN is required by the Allegro 4 library according to some of what I've read."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T06:56:11.983",
"Id": "38071",
"Score": "0",
"body": "In addition to the above, another thing to consider is to declare loop iterators inside the loop, that's more common practice. That is: `for (int i=0; i < 2; i++)`. (Since you already have a C compiler that allows declaration of variables anywhere, it will also allow this.)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T02:59:39.860",
"Id": "24582",
"ParentId": "24568",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T15:55:53.750",
"Id": "24568",
"Score": "8",
"Tags": [
"c",
"beginner",
"game",
"playing-cards"
],
"Title": "First Blackjack game in C"
}
|
24568
|
<p>I have a weighted BFS search in python for networkx that I want to optimize:</p>
<pre><code>def bfs(graph, node, attribute, max = 10000):
# cProfile shows this taking up the most time. Maybe I could use heapq directly? Or maybe I would get more of a benefit making it multithreaded?
queue = Queue.PriorityQueue()
num = 0
done = set()
for neighbor, attrs in graph[node].iteritems():
# The third element is needed because we want to return the ajacent node towards the target, not the target itself.
queue.put((attrs['weight'], neighbor, neighbor))
while num <= max and not queue.empty():
num += 1
item = queue.get()
if graph.node[item[1]].get(attribute, False):
return item[2]
for neighbor, attrs in graph[item[1]].iteritems():
if neighbor not in done:
queue.put((item[0] + attrs['weight'], neighbor, item[2]))
done.add(neighbor)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T17:20:41.260",
"Id": "37942",
"Score": "0",
"body": "Definitely use `heapq` directly when you don't need the thread synchronization that `Queue.PriorityQueue` provides."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T17:32:00.813",
"Id": "37946",
"Score": "0",
"body": "Right, but should I go threading or heapq?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T18:40:54.187",
"Id": "37951",
"Score": "0",
"body": "@fread2281, no reason to use threading here"
}
] |
[
{
"body": "<p>Some things that might improve your code:</p>\n\n<ol>\n<li><p>Use <code>heapq</code> rather than <code>Queue.PriorityQueue</code>. The latter does synchronization stuff that you don't need, so <code>heapq</code> will be faster.</p></li>\n<li><p>Don't add <code>neighbor</code> to <code>done</code> in your inner loop. This will find incorrect routes on any graphs where some subpath A->B->C is shorter than A->C. Instead, you want to be be putting <code>item[1]</code> into <code>done</code> when you pop it off the queue. Since this means you will get some duplicated nodes in your queue, you'll also need to check if the newly popped node was already done before processing it. You might be able to save a little processing time by storing the cost of the path to the node in a dictionary, and only adding a new path if it's less than the previous one (but I don't think the improvement is very large).</p></li>\n<li><p>This is a readability improvement (not a performance or correctness fix), but I suggest unpacking <code>item</code> into several values, rather than indexing it. <code>cost, node, first_step = queue.get()</code>, or something similar.</p></li>\n<li><p>A terminology suggestion: Rather than being a basic breadth-first search, this is <a href=\"http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm\">Dijkstra's Algorithm</a>. If all the edge weights are equal, you'll examine nodes (roughly) the same order as in a BFS, but if you have different weights you'll go in a different order. It might be a good idea to use a function name that reflect what you're actually doing in the code.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T18:22:42.683",
"Id": "24574",
"ParentId": "24572",
"Score": "8"
}
},
{
"body": "<p>I understand the reason for you to implement your own search routine instead of using what is readily available is because you want to return the node that is the <em>first step toward the target</em> instead of the target itself. Before presenting my code, I would like to raise a couple of suggestions:</p>\n\n<h3>Use better descriptive names</h3>\n\n<p>Names like <em>max</em>, <em>num</em> are not meaningful. I suggest to use names such as <em>max_visiting_nodes</em>, <em>visit_count</em> instead.</p>\n\n<p>Similarly, item[1], item[2], ... do not mean much. Instead of <code>item = queue.get()</code>, how about something like <code>weigh, target_node, first_step_node = queue.get()</code></p>\n\n<h3>Correctness.</h3>\n\n<p>If you have a graph like this:</p>\n\n<p><img src=\"https://www.evernote.com/shard/s1/sh/00639fa5-e44f-4066-a92c-8b72ad3ec972/c3ec750738639d87052c8cca7bfc8f2f/res/8ff8459a-3e10-4762-8522-a6183e746cf3/skitch.png\" alt=\"graph1\"></p>\n\n<p>The red colors are the weight. If search starts with node 1 and node 2 has the attribute you want, the <em>first step toward the target</em> would be node 5, since the path 1-5-4-3-2 is shorter (weight = 4), instead of 1-2 (weight = 10). Your algorithm returns 2, not 5.</p>\n\n<h3>Propose solution</h3>\n\n<p>I propose using what <em>networkx</em> offering, meaning <code>bfs_tree()</code> to find a list of nodes, then <code>shortest_path()</code>:</p>\n\n<pre><code>def bfs_find_first_step(graph, node, attribute, max_visiting_nodes = 10000):\n for visit_count, visiting_node in enumerate(nx.bfs_tree(graph, node)):\n if visit_count == max_visiting_nodes: break\n if graph.node[visiting_node].get(attribute):\n shortest_path = nx.shortest_path(graph, node, visiting_node, 'weight')\n if len(shortest_path) == 1:\n return node # Only current node qualifies\n else:\n return shortest_path[1] # First step toward the target\n return None\n</code></pre>\n\n<p>A few notes:</p>\n\n<ul>\n<li>In my solution, I use the visit_count (AKA <code>num</code>) to limit the search time, the same way you would like to.</li>\n<li>the <code>nx.shortest_path()</code> function takes in as the fourth parameter, the string name of the edge attribute which used for calculating the weight. I think this is what you have in mind.</li>\n<li>If you start search from node 1, and only node 1 has the attribute your want, your function returns 5, whereas mine returns 1. I think mine is more correct, but I am not sure--it might not be what you want. This case is when <code>len(shortest_path) == 1</code> in my code.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T04:49:24.737",
"Id": "37956",
"Score": "0",
"body": "Wow. A few things: `bfs_tree` is slow compared to my method for large networks and small `max_visiting_nodes` (and maybe also my optimized version from the other answer for all networks). Also your version iterates at least twice (at least once in `bfs_tree`) and that is unnecessary. When I get some time, I may go into netowrkx and make a version of A* for search. Also `bfs_search` is not what I am doing, highlighted my the other answer, so `bfs_tree` is not correct here. Your answer is BFS and does not really use `shortest_path` for deciding what node to return (it gets first instead)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T04:51:40.683",
"Id": "37957",
"Score": "0",
"body": "Also your solution will give 1 by 1->2 (it does not matter here, but for more complex networks it will)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T16:45:45.473",
"Id": "37983",
"Score": "0",
"body": "I just found out that `bfs_tree()` does not seem to return the correct sequence. I am doing some tests at this moment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T23:47:54.793",
"Id": "38008",
"Score": "0",
"body": "BFS is breadth-first-search, so it returns based on depth, not weight. http://en.wikipedia.org/wiki/Breadth-first_search"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T03:53:29.833",
"Id": "24584",
"ParentId": "24572",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24574",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T17:06:50.900",
"Id": "24572",
"Score": "2",
"Tags": [
"python",
"queue"
],
"Title": "Optimize BFS weighted search in python"
}
|
24572
|
<p>I want to use some constant in both server side and client side.</p>
<p>Currently, I use PHP reflection in order to synchronize PHP constants and Javascript constants. But for the maintainable reason, it's not a best practise.</p>
<p>For example:</p>
<pre><code>interface IType{
//...
const ID_TYPE_TEXT = 1000;
const ID_TYPE_NUMBER = 2000;
const ID_TYPE_IMAGE = 3000;
const ID_TYPE_VIDEO = 4000;
//...
}
</code></pre>
<p>In view</p>
<pre><code>$r = new ReflectionClass('IType');
foreach( $r->getConstants() as $const => $value)
{
echo "var $const = $value;"
}
</code></pre>
<p>How can I avoid doing that?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T11:14:32.463",
"Id": "37966",
"Score": "0",
"body": "Either place your constants somewhere in the DOM, or retrieve the variables from the server using AJAX"
}
] |
[
{
"body": "<p>One way is to keep the constants in a database table and have a script that automatically generates both JS and PHP code by looking through it. The advantages of this are that you can store other bits of information if you want, and the code is all generated beforehand so there is no extra overhead with each page load. The only disadvantage is that you have to run the script every time you change the constants. The simplest table structure you could use would store just the name and the value, but as an example mine looks like this:</p>\n\n<pre><code>mysql> explain codes;\n+-------------+------------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+-------------+------------------+------+-----+---------+----------------+\n| type | char(3) | YES | | NULL | |\n| code | char(3) | YES | | NULL | |\n| parent | char(3) | YES | | NULL | |\n| long_code | char(64) | YES | | NULL | |\n| description | char(64) | YES | | NULL | |\n| id | int(10) unsigned | NO | PRI | NULL | auto_increment |\n+-------------+------------------+------+-----+---------+----------------+\n</code></pre>\n\n<p>The \"type\" field is a reference to another table, which organises the constants according to which part of the program they're relevant to.</p>\n\n<pre><code>mysql> explain codetypes;\n+-------------+------------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+-------------+------------------+------+-----+---------+----------------+\n| code | char(3) | YES | UNI | NULL | |\n| long_code | char(64) | YES | UNI | NULL | |\n| description | char(64) | YES | | NULL | |\n| id | int(10) unsigned | NO | PRI | NULL | auto_increment |\n+-------------+------------------+------+-----+---------+----------------+\n</code></pre>\n\n<p>Here is a sample from the database behind a chess server:</p>\n\n<pre><code>mysql> select * from codetypes where code='GST';\n+------+------------+-------------+----+\n| code | long_code | description | id |\n+------+------------+-------------+----+\n| GST | GAME_STATE | Game state | 1 |\n+------+------------+-------------+----+\n1 row in set (0.00 sec)\n\nmysql> select * from codes where type='GST';\n+------+------+--------+-------------+-------------+----+\n| type | code | parent | long_code | description | id |\n+------+------+--------+-------------+-------------+----+\n| GST | PRE | NULL | PREGAME | Pregame | 1 |\n| GST | IPR | NULL | IN_PROGRESS | In progress | 2 |\n| GST | FIN | NULL | FINISHED | Finished | 3 |\n| GST | CAN | NULL | CANCELED | Cancelled | 4 |\n+------+------+--------+-------------+-------------+----+\n4 rows in set (0.00 sec)\n</code></pre>\n\n<p>Which generates the following PHP code:</p>\n\n<pre><code>define(\"GAME_STATE\", \"GST\");\n\ndefine(\"GAME_STATE_IN_PROGRESS\", \"IPR\");\ndefine(\"GAME_STATE_FINISHED\", \"FIN\");\ndefine(\"GAME_STATE_CANCELED\", \"CAN\");\ndefine(\"GAME_STATE_PREGAME\", \"PRE\");\n</code></pre>\n\n<p>Using the extra information you can generate other useful bits of code, for example Javascript objects for looping through the constants of each type and accessing the descriptions as well as the values:</p>\n\n<pre><code>var DbEnums={};\n\nDbEnums[\"GST\"]={};\n\nDbEnums[\"GST\"][\"IPR\"]={Type: \"GST\", Code: \"IPR\", Parent: null, Description: \"In progress\"};\nDbEnums[\"GST\"][\"FIN\"]={Type: \"GST\", Code: \"FIN\", Parent: null, Description: \"Finished\"};\nDbEnums[\"GST\"][\"CAN\"]={Type: \"GST\", Code: \"CAN\", Parent: null, Description: \"Cancelled\"};\nDbEnums[\"GST\"][\"PRE\"]={Type: \"GST\", Code: \"PRE\", Parent: null, Description: \"Pregame\"};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T14:34:40.490",
"Id": "24635",
"ParentId": "24576",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T20:28:52.913",
"Id": "24576",
"Score": "3",
"Tags": [
"php",
"reflection"
],
"Title": "How to avoid echoing JavaScript from PHP?"
}
|
24576
|
<p>I'm implementing an <code>is_dir()</code> function to determine if a given item is a directory or a file for FTP/FTPS connections. Currently, I have two methods: one using PHP's FTP wrapper for the <code>is_dir()</code> function and another recommended in the help page for the <code>ftp_chdir()</code> function.</p>
<p>Here's the first one (protocol wrapper):</p>
<pre><code>if ($items = ftp_nlist($this->attributes["link"], $path)) {
$output = null;
foreach ($items as $item) {
if (is_dir("ftp://{$this->attributes["user"]}:{$this->attributes["password"]}@{$this->attributes["host"]}/{$item}")) {
$output[] = $item;
}
}
$output[] = sprintf("%5.4fs", (microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"]));
return $output;
}
</code></pre>
<p>Here's the second one (chdir implementation):</p>
<pre><code>if ($items = ftp_nlist($this->attributes["link"], $path)) {
$output = null;
$current = ftp_pwd($this->attributes["link"]);
foreach ($items as $item) {
if (@ftp_chdir($this->attributes["link"], $item)) {
ftp_chdir($this->attributes["link"], $current);
$output[] = $item;
}
}
$output[] = sprintf("%5.4fs", (microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"]));
return $output;
}
</code></pre>
<p>The problem I find with these two implementations is they're quite slow (or, at least, I think they should be faster to be used within AJAX calls). Running these two functions and measuring their execution time with the last element in the returned array, these are their timed values (ran them 50 times to get an accurate enough time reading): 7.2312s for method A and 2.4534s for method B.</p>
<p>Which shows the <code>ftp_chdir()</code> implementation is almost 3x faster than using the FTP wrapper. Still... I have the feeling there may be room for improvement.</p>
<p>My development machine is Windows 7 x64 with Apache 2.4.4 (x86), PHP 5.4.13 (x86, thread-safe version) and MySQL 5.6.10 x64 (irrelevant in this case), always keeping up-to-date packages. The FTP server I ran these tests against is another Windows machine but a full-fledged production server (dedicated) on a data center.</p>
<p>Is there any other method to do the same but in a better (and/or faster) fashion?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T11:17:44.900",
"Id": "37968",
"Score": "0",
"body": "Why do you iterate through all entries of the directory?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T16:31:43.260",
"Id": "37982",
"Score": "0",
"body": "Because it's how the original `ftp_chdir()` implementation is done and, as `ftp_nlist()` gives you a list of all entries belonging to a given path, I thought that's the way to go. Is there a better method?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T06:55:18.713",
"Id": "38019",
"Score": "0",
"body": "So you want to display a directory listing and additional information? Then you might consider using [`ftp_rawlist()`](http://php.net/manual/en/function.ftp-rawlist.php), which basicly returns the output of `ls -al` from the current directory on the server. But note that the output may change depending on which OS or FTP server software the server uses. Someone on PHP.net implemented such a method already: http://www.php.net/manual/en/function.ftp-nlist.php#108501"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T08:56:16.817",
"Id": "38024",
"Score": "0",
"body": "I already implemented a solution using a combination of `mb_substr($item, 0, 1)` for file/directory detection and `$tmp = explode(\" \", $item)` and `end($tmp)` for link retrieval, but your link points to a much more developed and correct implementation. Thanks a lot! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T09:17:05.007",
"Id": "38026",
"Score": "0",
"body": "You might also want to take a look at this comment on php.net: http://www.php.net/manual/en/function.ftp-nlist.php#77007. `ftp_size($ftp_connect, $filename) == -1` is used to check whether it is a directory or a file"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T08:59:52.457",
"Id": "38080",
"Score": "0",
"body": "Thanks for the directions, although the last function seems to be server-dependent and my intention is for any client to be able to provide his/her own FTP server addresses (it's a file/document manager what I'm building), so something working for vsftpd but not for proftpd wouldn't be good :P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-12T23:02:59.867",
"Id": "176770",
"Score": "2",
"body": "Out of curiousity, why build somthing like this yourself instead of using something like [Flysytem](https://github.com/thephpleague/flysystem)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-22T18:59:48.130",
"Id": "178878",
"Score": "0",
"body": "It's been quite some time since I posted this and, to be honest, I ended implementing Flysystem as my file abstraction layer :P"
}
] |
[
{
"body": "<p>In case someone is interested, here's a follow up to MarcDefiant's comment about using <code>ftp_rawlist()</code>. It's fast if you're already using it for getting the file list as well. Here's a snippet from the <code>filebrowser.php</code> in my <a href=\"https://github.com/mircerlancerous/FileBrowser\" rel=\"nofollow\">GitHub filebrowser project</a>. It's certainly not on the same level as <a href=\"https://github.com/thephpleague/flysystem\" rel=\"nofollow\">Flysystem</a> but I enjoyed working on it :).</p>\n\n<pre><code>public function isDir($path,$contents=NULL){\n $name = getPathName($path);\n if($contents === NULL){\n $path = getItemPath($path);\n $contents = $this->scandir($path);\n }\n foreach($contents as $content => $data){\n if($content == $name){\n if($data['type'] == 'directory'){\n return TRUE;\n }\n return FALSE;\n }\n }\n return FALSE;\n}\n\npublic function scandir($path=NULL){\n if($path === NULL){\n $path = $this->Path;\n }\n if(!$path){\n $path = \".\";\n }\n if(is_array($children = @ftp_rawlist($this->conn_id, $path))){\n $items = array();\n\n foreach($children as $name => $child){\n if(!$name){\n continue;\n }\n $chunks = preg_split(\"/\\s+/\", $child);\n list($item['rights'], $item['number'], $item['user'], $item['group'], $item['size'], $item['month'], $item['day'], $item['time']) = $chunks;\n $item['type'] = $chunks[0]{0} === 'd' ? 'directory' : 'file';\n array_splice($chunks, 0, 8);\n $items[implode(\" \", $chunks)] = $item;\n }\n\n return $items;\n }\n return FALSE;\n}\n\nfunction getPathName($path){\n return substr($path,strrpos(\"/\".$path,\"/\"));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-28T10:03:00.557",
"Id": "317632",
"Score": "0",
"body": "Thank you OffTheBricks.\nJust a little improvment in your code : I replace `$chunks = preg_split( '/\\s+/', $child );` by `$chunks = preg_split( '/\\s+/', $child, 9 );` and\n`array_splice($chunks, 0, 8); $items[implode(\" \", $chunks)] = $item;`\nby `$name = array_pop( $chunks ); $items[$name] = $item;` because I have some files with several consecutives spaces that was lost by the use of /s+ and implode( \" \"… )."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-22T19:06:53.657",
"Id": "123573",
"ParentId": "24578",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T22:42:29.873",
"Id": "24578",
"Score": "6",
"Tags": [
"php",
"file-system",
"ftp"
],
"Title": "is_dir function for FTP/FTPS connections"
}
|
24578
|
<p>In Rails 3, I have two models: <code>Nutrient</code> and <code>Recommendation</code>:</p>
<ul>
<li><code>Nutrient</code> has_many <code>Recommendation</code></li>
<li><code>Recommendation</code> belongs_to <code>Nutrient</code></li>
</ul>
<p>I am trying to implement the create method of the recommendation in the controller. Is this the proper way to do it?</p>
<pre><code>def create
nutrient_id = params[:recommendation][:nutrient_id]
if nutrient_id.blank?
#nutrient_id was blank in the submit, get other recommendation params and re-render 'new'
params[:recommendation].delete(:nutrient_id)
@recommendation=Recommendation.new(params[:recommendation])
render 'new'
else
@nutrient = Nutrient.find(nutrient_id)
if @nutrient
#nutrient was found by id, create recommendation
@recommendation = @nutrient.recommendations.build(params[:recommendation])
if @recommendation.save
redirect_to @recommendation
else
render 'new'
end
else
#nutrient was not found by id, get other recommendation params and re-render 'new'
params[:recommendation].delete(:nutrient_id)
@recommendation = Recommendation.new(params[:recommendation])
render 'new'
end
end
end
</code></pre>
|
[] |
[
{
"body": "<p>Your approach is fundamentally flawed, I'm afraid. You're not using Rails' abilities to your advantage at all.</p>\n\n<p>For a simple create operation, your controller method rarely needs to be more than 10 lines or so. There's way too much going on in yours.</p>\n\n<p>Start by nesting your routes:</p>\n\n<pre><code> resources :nutrients do\n resources :recommendations\n end\n</code></pre>\n\n<p>Run <code>rake routes</code> to see how the routes now look. Basically, a recommendation will have a URL like <code>/nutrient/:nutrient_id/recommendation/:id</code>.</p>\n\n<p>This means you'll have to make some changes to links in your views and your redirections. Where you could previously write <code>recommendations_path</code> and so on you'll now have to write <code>nutrient_recommendations_path(@nutrient)</code> and so on. Again, <code>rake routes</code> will show you what helpers you now have.</p>\n\n<p>In your recommendation form, you'll have to do something like:</p>\n\n<pre><code> <%= form_for [@nutrient, @recommendation] %>\n</code></pre>\n\n<p>so the form's action URL will be correct. An get rid of the hidden input that I assume you've added to the form as <code>recommendation[nutrient_id]</code>.</p>\n\n<p>Inside the <code>RecommendationsController</code>, you can always get the \"parent\" nutrient by saying</p>\n\n<pre><code> @nutrient = Nutrient.find(params[:nutrient_id])\n</code></pre>\n\n<p>as that param is given in the URL.</p>\n\n<p>In the end, your <code>create</code> method will look like</p>\n\n<pre><code>def create\n @nutrient = Nutrient.find(params[:nutrient_id])\n @recommendation = @nutrient.recommendations.new(params[:recommendation])\n\n if @recommendation.save\n redirect_to @recommendation, :notice => \"Recommendation created.\"\n else\n render 'new'\n end\nend\n</code></pre>\n\n<p>See something like <a href=\"http://ericlondon.com/posts/243-creating-nested-resources-in-ruby-on-rails-3-and-updating-scaffolding-links-and-redirection\" rel=\"nofollow\">this post</a> for a more thorough <code>diff</code>-like walkthrough of the changes to make.</p>\n\n<p>Note, that if Recommendation has further nested resources, you should use \"shallow\" routes, but that's left as an exercise to the reader.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T21:43:22.350",
"Id": "38152",
"Score": "0",
"body": "Thank you so much flambino, I knew I was on the wrong path I just didn't know how to ask the right question. Thanks for laying it all out, you've saved me a huge headache and probably a lot of future miss-steps."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T22:02:59.027",
"Id": "38154",
"Score": "0",
"body": "@Mike No problem. When your code starts to smell (methods are too long, things are getting complicated, etc), just remember that in 99 out of 100 cases, you're trying to well-known problem. So always check if Rails can do it all already, or look for a gem that might do it. I highly recommend looking at [Railscasts](http://railscasts.com/), [The Ruby Toolbox](https://www.ruby-toolbox.com/), and of course [Rails itself](http://api.rubyonrails.org/)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T20:20:36.770",
"Id": "24609",
"ParentId": "24579",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "24609",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T23:02:03.323",
"Id": "24579",
"Score": "1",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Nutrient and Recommendation models"
}
|
24579
|
<p>I have a number of functions inside class, which serve my scripts to provide functionality such as a login, which is the function I am going to be using as my examples. </p>
<pre><code> public static function GetCredentials ($Argument_1, $Argument_2){
$GetUserInformation = self::$Database->prepare("SELECT Username,Password FROM users WHERE Username=? ");
$GetUserInformation->bind_param('s',$Argument_1);
$GetUserInformation->execute();
$GetUserInformation->bind_result($StoredUsername, $StoredPassword);
$GetUserInformation->fetch();
//Re-use Data
$Search_Count = $GetUserInformation->data_seek(0);
if ($Search_Count == 1){
if ($StoredPassword !== $Argument_2){
echo "Passwords Do Not Match!";
exit;
}
$_SESSION['Username'] = $Argument_1;
header('Location: Loggedin.php');
}else{
echo "User Does Not Exist";
}
}
}
</code></pre>
<p>I am planning to call this function once to perform the login for my user. </p>
<p>Now, do I echo through this function, or is it in best practices to return statements aswell as return false; to provide an error. then on my Login checking page perform:</p>
<pre><code>if ($Foo::GetCredentials($_POST['Username'], $_POST['Password']) == false)
{
echo $Foo:GetCredentials($_POST['Username'], $_POST['Password']);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T09:58:39.477",
"Id": "37965",
"Score": "0",
"body": "I'd suggest you not to store password as text. Use `PASSWORD()` function in MySQL."
}
] |
[
{
"body": "<h2>Multiple problems</h2>\n\n<p>Why is static?\nWhy is the database hardcoded in the class?\nEcho or return? Neither\nExit?\nDirect $_SESSION write (super global)\nHTTP stuff in an Auth class?</p>\n\n<h2>Why is static?</h2>\n\n<p>You are using stuffs in static where you should not have. Handling database through a static proxy? Untestable, unreadable and what happens if some forget initialize it?\nSame thing applies to your class which is handling the authentacation. Why is it static? If you wan't to access it whereever you want then create a static facade class and keep the main logic in a separated non-static class.</p>\n\n<h2>Why is the database hardcoded in the class?</h2>\n\n<p>What happens if you don't want to use anymore a standard SQL database to store your users? You will rewrite the whole class to achive that?\nIf you create a new class as i described above leave out this hardcoding use constructor injection instead:</p>\n\n<pre><code>class Auth {\n\n public function __construct(IUSerStore $store) {\n /* store reference, etc ... */\n }\n\n}\n\ninterface IUSerStore {\n\n function GetUserByName($name);\n\n}\n</code></pre>\n\n<p>In this way you have no string dependency to a SQL database to query user you can have for example an in memory store for users if you want to test the Auth class.</p>\n\n<h2>Echo or return? Neither</h2>\n\n<p>Currently you are echoing text from a business logic layer which is bad really bad. Only in the presentation layer should be print out stuff to the end user.\nThe return would not be the solution for this becouse you can't tell what was the Auth process result (only from the message) so create a result class:</p>\n\n<pre><code>class AuthResult {\n\n public $Success;\n public $Message;\n\n}\n</code></pre>\n\n<p>This is a really simple approach but it can be used to signal what happaned in the authentication process.</p>\n\n<h2>Exit?</h2>\n\n<p>What is the reason of the exists of an exit statement in a business layer class? Why is stopped the whole request process if the passwords not match? What happens if you want to test the password equality check method? If they are not equal the test stops?</p>\n\n<h2>Direct $_SESSION write (super global)</h2>\n\n<p>Of course writing into the $_SESSION array is not bad you can have your own session data handler in the background so everything can be done this way. But again: what happens if you want to test the functionality of writing a session data in your Auth class? You will test the session data saver also (your own or the one built into PHP)?\nI would wrap it into a class and pass an argument to the Auth class as i described above the IUserStore solution.</p>\n\n<h2>HTTP stuff in an Auth class?</h2>\n\n<p>Why is a header() call in your Auth class? Is it really neccessary or the redirection can be done depending on the result of the authentication process in your controller if you are following an MVC approach?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T13:08:18.003",
"Id": "24593",
"ParentId": "24580",
"Score": "4"
}
},
{
"body": "<p>The short answer in my opinion is: <strong>Do not echo, return a <em>meaningful</em> response.</strong></p>\n<p>@Peter Kiss nailed it in so many ways and I would like to map some of his thoughts to well known programming principles and design patterns.</p>\n<blockquote>\n<p>Why is the database hardcoded in the class?</p>\n</blockquote>\n<h3>Single Responsibility Principle:</h3>\n<p>Each class, function, module should have one and only one reason to change. Robert C. Matrin in his book <a href=\"https://rads.stackoverflow.com/amzn/click/com/0132350882\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Clean Code</a> Ch3 explains</p>\n<blockquote>\n<p>FUNCTIONS [classes, modules] SHOULD DO ONE THING. THEY SHOULD DO IT WELL. THEY SHOULD DO IT ONLY.</p>\n</blockquote>\n<p>In your code you have DB queries, auth checks, messages intended to be displayed to the user (presentation layer), and redirection. Avoid this kind of mess by creating classes that specialize by identifying what they are responsible of.</p>\n<blockquote>\n<p>What happens if you don't want to use anymore a standard SQL database to store your users?</p>\n</blockquote>\n<h3><strong>Open/Closed Principle</strong>:</h3>\n<p>your classes, functions, modules, packages, bundles should be open for extension, and closed for modification. What this means is that the behavior of your class can be modified without altering the code. A simple example would be a class Shape. The behavior of Shape could be modified by creating a new class Rectangle that extends from Shape. See other examples of this principle <a href=\"http://joelabrahamsson.com/a-simple-example-of-the-openclosed-principle/\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://www.oodesign.com/open-close-principle.html\" rel=\"nofollow noreferrer\">here</a>. Another example of extending functionality is Constructor Injection as described by @Peter Kiss, this is part of a Design Pattern called Dependency Injection explained below.</p>\n<blockquote>\n<p>If you create a new class as i described above leave out this hardcoding use constructor injection instead</p>\n</blockquote>\n<h3><strong>Dependency Injection (DI)</strong>:</h3>\n<p>Dependency injection means giving components the dependencies they need at run time through their constructor, methods, or directly into fields. See <a href=\"http://net.tutsplus.com/tutorials/php/dependency-injection-huh/\" rel=\"nofollow noreferrer\">this example/tutorial in php</a> for more information and learn how to use Inversion of Control (IoC) to simplify the use of your class. Also take a look at <a href=\"http://pimple.sensiolabs.org/\" rel=\"nofollow noreferrer\">Pimple: a simple Dependency Injection Container</a>.</p>\n<blockquote>\n<p>Echo or return? Neither</p>\n</blockquote>\n<p>While I agree that you shouldn't return an message that mixes the presentation layer with the logic, I believe is important to clarify that returning something meaningful is essential based on what you want to accomplish: get user credentials. This brings us to the next principle.</p>\n<h3><strong>Command Query Separation (CQS)</strong>:</h3>\n<p>it states that your methods should either perform an action or return to the caller the results of a query. In your case you are not performing an action such as authentication, but rather you want to query the user credentials. Return a UserCredentials object, that is responsible to set the appropriate info in a session via a cookie or key-value data store like Redis or Memcached. By using the proper patterns and abstractions you can even allow the UserCredentials class set the session using the desired method!</p>\n<blockquote>\n<p>Exit?</p>\n</blockquote>\n<h3><strong>Prefer Exceptions to returning error codes/messages</strong>:</h3>\n<p>You can address your two error cases ("Passwords Do Not Match" and "User Does Not Exist") cleanly by throwing meaningful exceptions and force the user of the class deal with the error immediately. This way you also avid a sudden termination of the logic in your class. Also avoid using the generic Exception class only, create Exception classes that extend from Exception like:</p>\n<p><code>class AuthenticationException extends Exception{};</code></p>\n<p>Make it meaningful :)</p>\n<h3>Final thoughts</h3>\n<p><strong>Use an MVC framework.</strong> A framework will help you separate the business logic from the presentation they also implement common design patterns, and provide classes to help you deal with common task such authentication and sessions. I think <a href=\"http://ellislab.com/codeigniter\" rel=\"nofollow noreferrer\">CodeIgniter</a> is a great lightweight framework to learn MVC, but I would transition out to a micro framework such as <a href=\"http://silex.sensiolabs.org/\" rel=\"nofollow noreferrer\">Silex</a> other PHP 5.3+ frameworks like <a href=\"http://www.fuelphp.com/\" rel=\"nofollow noreferrer\">FuelPHP</a>, <a href=\"http://four.laravel.com/\" rel=\"nofollow noreferrer\">Laravel4</a>, or enterprise level frameworks like <a href=\"http://symfony.com/\" rel=\"nofollow noreferrer\">Symfony2</a> or <a href=\"http://framework.zend.com/\" rel=\"nofollow noreferrer\">Zend Framework 2</a>. It all depends on the size of your project.</p>\n<p><strong>Stand in the shoulders of other developers.</strong> Use composer to install and load third party libraries that can be easily integrated to almost any project. See <a href=\"https://getcomposer.org/\" rel=\"nofollow noreferrer\">https://getcomposer.org/</a> and <a href=\"https://packagist.org/\" rel=\"nofollow noreferrer\">https://packagist.org/</a> for more info.</p>\n<p>I recommend getting the <a href=\"https://rads.stackoverflow.com/amzn/click/com/0132350882\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">book Clean Code by Robert C. Matrin</a>. While I do not agree with some of his views, he has lots of helpful principles that will point you in the right direction to write great, extensible, readable code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T21:19:38.793",
"Id": "38000",
"Score": "0",
"body": "This is my preferred response. You are nailing my exact questions giving detailed opinions/assistance on the code explained in the example; and now just coming across as having a moan about my current style. He has alot of valid points, but not coming across in the way that I appreciate. Thankyou for your assistance."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T17:19:00.007",
"Id": "24597",
"ParentId": "24580",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "24597",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-31T23:37:30.320",
"Id": "24580",
"Score": "3",
"Tags": [
"php"
],
"Title": "Return over echo?"
}
|
24580
|
<p>I have to write methods for a binary tree that has positive integers as values. These are not full methods. They are supposed to be written in pseudocode.</p>
<p>a) Count number of nodes in a Tree</p>
<pre><code>countNodes(TreeNode root){
if(root == null)
return 0;
else{
TreeNode left = root.getLeftChild();
TreeNode right = root.getRightChild();
return (countNodes(left)+countNodes(right)) + 1;
}
}
</code></pre>
<p>b) Compute the height of a tree</p>
<pre><code>height(TreeNode root){
if(root == null)
return 0;
else{
return Math.max(height(root.getLeftChild()), height(root.getRightChild()) +1;
}
}
</code></pre>
<p>c) Find the maximum element</p>
<pre><code>maxElem(TreeNode root){
if(root == null)
return 0;
else{
int temp = 0;
temp = Math.max(maxElem(root.getLeftChild()), maxElem(root.getRightChild()));
return Math.max(root.getValue, temp);
}
}
</code></pre>
<p>d) Find the sum of the elements</p>
<pre><code>sum(TreeNode root){
if(root == null)
return 0;
else{
return (sum(root.getLeftChild()) + sum(root.getRightChild())) + root.getValue();
}
}
</code></pre>
<p>e) Find the average of the Elements</p>
<pre><code>average(TreeNode root){
double sum = sum(root);
double elems = countNodes(root);
return sum/elems;
}
</code></pre>
<p>f) Find a Specific Item</p>
<pre><code>search(int i, TreeNode root){
if(root == null)
return false;
else if(root.getValue == i)
return true;
else{
return search(i, root.getLeftChild);
return search(i, root.getRightChild);
}
}
</code></pre>
<p>g) Determine whether an item is an ancestor of another</p>
<pre><code>isAncestor(TreeNode p, NodeNode c){
if(p==null)
return false;
else
return (c in p.getLeftChild() || c in p.getRightChild())
}
</code></pre>
<p>h) Determine the highest level that is full</p>
<pre><code>maxFull(TreeNode root)
if(root == null)
return 0;
else{
return(numNodes in level h == 2^h - 1)
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T01:50:38.550",
"Id": "38013",
"Score": "1",
"body": "I'm afraid that psuedocode is off-topic as per the FAQ."
}
] |
[
{
"body": "<p>Even if you have to use pseudocode, you should do some checks. Either in pseudcode (calculcate by hand) or implement it in any language.</p>\n\n<p>Most of them look ok, some comments:</p>\n\n<pre><code> return search(i, root.getLeftChild);\n return search(i, root.getRightChild);\n</code></pre>\n\n<p>This can not work, the second return is unreachable.\nYou could do something like</p>\n\n<pre><code>if (current == null)\n return -1; \n...\nif (left != -1) return left;\nreturn right;\n</code></pre>\n\n<hr>\n\n<p>I do not understand your <code>isAncestor</code>function (it is not clear to me what should be done and which argument is responsible for which part). From the description, it looks a bit ridiculous, because you just have to return <code>a.left == b || a.right == b</code> (the difference to your code is the <code>in</code>. Typically <code>in</code> means is <code>contained in the set</code>, but a node is normally not a set.</p>\n\n<hr>\n\n<p>For <code>maxFull</code>, I think you need to give more details instead of just writing the text and the function is probably wrong (if you have a balanced binary tree, root is level zero. Then we have at level 1 two nodes if full. Your formula would expect one node). You have to do something like <code>return 1 + Math.min(maxfull(left), maxfull(right))</code>, but this depends on your definition for full.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T00:27:24.080",
"Id": "24617",
"ParentId": "24581",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24617",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T01:56:36.003",
"Id": "24581",
"Score": "-2",
"Tags": [
"java"
],
"Title": "Review of the following methods of a binary tree which contains positive integers as it's elements"
}
|
24581
|
<pre><code>private eFileStatus CheckConfigSettings()
{
mFileStatus = mXMLHelper.CheckElement(eElementName.StartLanguage.ToString(), out mContent);
if (eFileStatus.OK != mFileStatus)
{
return mFileStatus;
}
else if (eFileStatus.OK == mFileStatus && mContent.Length == 0)
{
mFileStatus = ShowInputFormForElement(eElementName.StartLanguage);
if (eFileStatus.OK != mFileStatus)
{
return mFileStatus;
}
}
mFileStatus = mXMLHelper.CheckElement(eElementName.ExportPath.ToString(), out mContent);
if (eFileStatus.OK != mFileStatus)
{
return mFileStatus;
}
else if (eFileStatus.OK == mFileStatus && mContent.Length == 0)
{
mFileStatus = ShowInputFormForElement(eElementName.ExportPath);
if (eFileStatus.OK != mFileStatus)
{
return mFileStatus;
}
}
}
</code></pre>
<p><strong>eFileStatus</strong> is an <em>enum</em> and so is <strong>mFileStatus</strong>. Basically, <strong><em>CheckElement()</em></strong> checks if an element in an XML is empty or not. Next, if there is an error (it is not equal to <strong>eFileStatus.OK</strong>) then it will return the value of <strong>mFileStatus</strong>. Otherwise, if there is no error and the element is empty, it will call the <strong>ShowInputFormForElement()</strong> method to enable the user to fill up the value for the element.</p>
<p>There are more than two elements to check and I would like to learn how to do this better.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T14:48:44.650",
"Id": "37976",
"Score": "2",
"body": "This code cannot compile - you don't have a \"fall-through\" return value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T15:14:22.223",
"Id": "38102",
"Score": "0",
"body": "@JesseC.Slicer You mean by fall-through that his 'return' statements are wrapped in if statements, which may or may not be hit?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T15:40:28.437",
"Id": "38103",
"Score": "1",
"body": "@IsaiahNelson that's the reason why, yes. But the code simply won't compile noting that not all paths will return a value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-12T19:51:12.213",
"Id": "44599",
"Score": "2",
"body": "-1 for not posting code (yes, I realize that the question used to have code). Note that if your goal in removing your code was to prevent people from seeing private code, your goal has not been accomplished."
}
] |
[
{
"body": "<p>It would be straightforward to extract the repeated code into a function. However, this would still leave a lot of room for improvement:</p>\n\n<p><strong>Separation of concerns</strong>: Your function does several unrelated things: reading a configuration file, some input validation, and user input. These things should be separated.</p>\n\n<p><strong>User experience</strong>: Your function presents a separate form for each configuration parameter. In the worst case, if the configuration file is empty, the user will be confronted with a series of forms, where each form asks for a single parameter. This is not very user friendly.</p>\n\n<p>Therefore I would suggest to refactor your code as follows:</p>\n\n<ul>\n<li>introduce a <code>Configuration</code> class to hold the configuration</li>\n<li>this class should be able to read and write itself to the configuration file</li>\n<li>it should also be able to validate itself</li>\n<li>have a separate configuration UI, that lets the user enter and edit the configuration in a suitable manner</li>\n<li>finally, tie everything together with a function that uses the pieces above to read the configuration, validate it, and if it fails validation, to show the configuration UI.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T08:54:25.343",
"Id": "24590",
"ParentId": "24587",
"Score": "9"
}
},
{
"body": "<p>Without re-architecting things too much, you might try:</p>\n\n<pre><code>List<T> elementsToCheck = new List<T> { eElementName.StartLanguage, eElementName.ExportPath };\n\nforeach (T ele in elementsToCheck)\n{\n mFileStatus = mXMLHelper.CheckElement(ele.ToString(), out mContent);\n if (eFileStatus.OK != mFileStatus)\n {\n return mFileStatus;\n }\n else if (eFileStatus.OK == mFileStatus && mContent.Length == 0)\n {\n mFileStatus = ShowInputFormForElement(ele.StartLanguage);\n if (eFileStatus.OK != mFileStatus)\n {\n return mFileStatus;\n }\n }\n}\n</code></pre>\n\n<p>This type of iterative structure may be a good start to a configuration management class.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T19:06:43.057",
"Id": "24727",
"ParentId": "24587",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T06:59:56.740",
"Id": "24587",
"Score": "-2",
"Tags": [
"c#"
],
"Title": "How can I refactor this code in order to not repeat code?"
}
|
24587
|
<p>I know that Swing <a href="http://www.oracle.com/technetwork/articles/javase/index-142890.html#3" rel="nofollow">isn't true MVC</a>:</p>
<blockquote>
<p>Using this modified MVC helps to more completely decouple the model
from the view.</p>
</blockquote>
<p>Leaving aside the veracity of the above claim, the problem I run into is that I can't seem to just drop a <code>Page</code> into a <code>JList</code>, but have to first extract a <code>List</code> (data) from the <code>Page</code> object. This just seems like a bad idea. Does this break encapsulation?</p>
<p>What's a better approach to handling the <code>nextPage</code> method, invoked by clicking the <kbd>next</kbd> button?</p>
<pre><code>package net.bounceme.dur.nntp.swing;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.logging.Logger;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import net.bounceme.dur.nntp.gnu.PageMetaData;
import net.bounceme.dur.nntp.gnu.Page;
import net.bounceme.dur.nntp.gnu.Usenet;
public class ArticlesPanel extends JPanel {
private static final Logger LOG = Logger.getLogger(ArticlesPanel.class.getName());
private static final long serialVersionUID = 1L;
private JList<String> jList = new JList<>();
private JScrollPane scrollPane = new JScrollPane();
private DefaultListModel<String> defaultListModel;
private JButton next = new JButton("next");
private Page page;
private Usenet usenetConnection = Usenet.INSTANCE; //ensures correct connection
private PageMetaData pageMetaData = new PageMetaData();
public ArticlesPanel() {
nextPage(null);
nextPage(null); //only because default page starts at zero
initComponents();
}
@SuppressWarnings("unchecked")
private void initComponents() {
setLayout(new java.awt.BorderLayout());
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
nextPage(e);
}
});
jList.setModel(defaultListModel);
jList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jList.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
mouseReleases(evt);
}
});
jList.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
keyReleases(evt);
}
});
scrollPane.setViewportView(jList);
add(scrollPane, BorderLayout.CENTER);
add(next, BorderLayout.SOUTH);
this.setSize(300, 100);
scrollPane.setVisible(true);
this.setVisible(true);
}
private void keyReleases(KeyEvent evt) {
itemSelected();
}
private void mouseReleases(MouseEvent evt) {
itemSelected();
}
private void itemSelected() {
LOG.info("selected\t\t" + jList.getSelectedValue());
}
private void nextPage(ActionEvent e) {
page = usenetConnection.getPage(pageMetaData); //first time, default
pageMetaData = new PageMetaData(page.getPageMetaData(), true); //get next is true
List<Message> messages = page.getMessages(); //breaks MVC?
defaultListModel = new DefaultListModel<>(); //clear or new?
for (Message m : messages) {
try {
defaultListModel.addElement(m.getSubject());
} catch (MessagingException ex) {
LOG.warning("bad message\n" + m.toString() + "\n" + ex);
}
}
jList.setModel(defaultListModel);
LOG.fine(page.toString());
}
}
</code></pre>
<p>While it's messy, that's not problem I'm facing. Rather, it's data encapsulation, I believe. I want <code>Page</code> to hide as much data as possible, yet that seems impossible.</p>
<p><code>Page</code> class:</p>
<pre><code>package net.bounceme.dur.nntp.gnu;
import gnu.mail.providers.nntp.GroupMetaData;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.logging.Logger;
import javax.mail.Header;
import javax.mail.Message;
import javax.mail.MessagingException;
public class Page {
private final static Logger LOG = Logger.getLogger(Page.class.getName());
private List<Message> messages = new ArrayList<>();
private PageMetaData pageMetaData = new PageMetaData();
public Page() throws Exception {
GroupMetaData gmd = new GroupMetaData();
pageMetaData = new PageMetaData(gmd);
}
public Page(GroupMetaData gmd) throws Exception {
pageMetaData = new PageMetaData(gmd);
}
public Page(PageMetaData pmd) throws Exception {
this.pageMetaData = pmd;
}
public Page(PageMetaData pmd, List<Message> messages) throws MessagingException {
this.pageMetaData = pmd;
this.messages = messages;
}
public List<Message> getMessages() {
return Collections.unmodifiableList(messages);
}
private String printXref() throws MessagingException {
LOG.fine("starting xref printing...\t" + messages.size());
StringBuilder sb = new StringBuilder();
String s = null;
String headerString = null;
String subString = null;
sb.append("messages to follow\n");
for (Message message : messages) {
LOG.fine(message.getSubject());
int i = messages.indexOf(message);
Enumeration headers = null;
headers = message.getAllHeaders();
while (headers.hasMoreElements()) {
Object o = headers.nextElement();
Header header = (Header) o;
if ("Xref".equals(header.getName())) {
headerString = header.getValue();
int index = headerString.indexOf(":");
subString = headerString.substring(index + 1);
int xref = Integer.parseInt(subString);
s = "\n" + i + "\t\t" + xref;
sb.append(s);
s = message.getSubject();
sb.append("\t").append(s);
}
}
LOG.fine("\n\n\n**********************\n\n\n");
}
LOG.fine(sb.toString());
return sb.toString();
}
public String toString() {
String s = "\n---new page---\n" + getPageMetaData().toString() + "\n";
try {
s = s + printXref();
} catch (MessagingException ex) {
ex.printStackTrace();
}
return s;
}
public PageMetaData getPageMetaData() {
return pageMetaData;
}
public void setPageMetaData(PageMetaData pageMetaData) {
this.pageMetaData = pageMetaData;
}
}
</code></pre>
<p><a href="https://github.com/THUFIR/gnumail-providers" rel="nofollow">Full project</a></p>
|
[] |
[
{
"body": "<p>Extract the busy-work code of transforming the <code>List<Message></code> to <code>DefaultListModel</code> into another method.</p>\n\n<p>From what I'm seeing I would think about the concepts you want to express in your code vis-a-vis some technical adherence to \"encapsulation\". If you want <code>Page</code> users to have no concept of an imbedded <code>Message</code> in a <code>Page</code> fine, but as it stands I'm not thinking message is inadequately encapsulated. Alternatively if there are some <code>Message</code> public getters that you simply do not want <code>Page</code> users to access, then that's OK rational too. </p>\n\n<p>In this case then the alternative is, in the <code>Page</code> class, a public <code>public List<String> Page.getSubjects()</code> - and likewise for all <code>Message</code> properties you want public. If, as far as Page users are concerned, the message's subject <em>is</em> the message, then rename the methods: <code>Page.getMessages()</code>; but it still returns a <code>List<string></code>.</p>\n\n<p>You can take that one step further by having <code>Page</code> implement iterator methods so the calling code looks like <code>page.nextMessage()</code>, <code>page.hasNextMessage()</code>, etc. and whatever. But again, the caller has to iterate. This doesn't feel like much bang for get buck to me, although it seems to fanatically adhere to <a href=\"http://en.wikipedia.org/wiki/Law_of_Demeter\" rel=\"nofollow\">the law of demeter</a>. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T23:46:52.100",
"Id": "38066",
"Score": "0",
"body": "I agree that page.nextMessage() is probably not the way to go, but it's at least an interesting idea -- thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T02:08:43.677",
"Id": "24620",
"ParentId": "24591",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24620",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T10:04:32.223",
"Id": "24591",
"Score": "1",
"Tags": [
"java",
"design-patterns",
"mvc",
"swing"
],
"Title": "Encapsulating this List<Message> properly"
}
|
24591
|
<p>My implemented regex pattern contains two repeating symbols: <code>\d{2}\.</code> and <code><p>(.*)</p></code>. I want to get rid of this repetition and asked myself if there is a way to loop in Python's regular expression implementation.</p>
<p><strong>Note</strong>: I do <strong>not</strong> ask for help to parse a XML file. There are many great tutorials, howtos and libraries. <strong>I am looking for means to implement repetition in regex patterns.</strong> </p>
<p>My code:</p>
<pre><code>import re
pattern = '''
<menu>
<day>\w{2} (\d{2}\.\d{2})\.</day>
<description>
<p>(.*)</p>
<p>(.*)</p>
<p>(.*)</p>
</description>
'''
my_example_string = '''
<menu>
<day>Mi 03.04.</day>
<description>
<p>Knoblauchcremesuppe</p>
<p>Rindsbraten "Esterhazy" (Gem&uuml;serahmsauce)</p>
<p>mit H&ouml;rnchen und Salat</p>
</description>
</menu>
'''
re.findall(pattern, my_example_string, re.MULTILINE)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T14:30:35.247",
"Id": "37974",
"Score": "1",
"body": "Parsing XML with regex is usually wrong, what are you really trying to accomplish?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T14:37:01.643",
"Id": "37975",
"Score": "0",
"body": "The XML is malformed what prevents a usage of LXML and Xpath. I easily can retrieve the deserved data, but I want to find a way to avoid these repetitions in any regex patterns."
}
] |
[
{
"body": "<p>Firstly, just for anyone who might read this: DO NOT take this as an excuse to parse your XML with regular expressions. It generally a really really bad idea! In this case the XML is malformed, so its the best we can do.</p>\n\n<p>The regular expressions looping constructs are <code>*</code> and <code>{4}</code> which you already using. But this is python, so you can construct your regular expression using python:</p>\n\n<pre><code>expression = \"\"\"\n<menu>\n<day>\\w{2} (\\d{2}\\.\\d{2})\\.</day>\n<description>\n\"\"\"\n\nfor x in xrange(3):\n expression += \"<p>(.*)</p>\"\n\nexpression += \"\"\"\n</description>\n</menu>\n\"\"\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T18:40:05.540",
"Id": "37990",
"Score": "0",
"body": "What about `expression += \"<p>(.*)</p>\\n\" * 3` ?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T17:45:04.230",
"Id": "24599",
"ParentId": "24594",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24599",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T13:38:29.410",
"Id": "24594",
"Score": "1",
"Tags": [
"python",
"regex"
],
"Title": "Improvment of and looping in a regular expression pattern"
}
|
24594
|
<p>Teachers can raise 'dramas' which are when students forget equipment, don't do homework or are flagged for concern. Each drama for each student is stored as a separate record.</p>
<p>I seek a list of all unresolved dramas, <strong>grouped by student & date</strong>. So if on one day a student forgets their homework and doesn't have equipment, they come up as a single record with the properties <code>EquipmentDrama</code> and <code>HomeworkDrama</code> both set to <code>true</code>.</p>
<pre><code>var dramas = ctx.Dramas.Where(o => !o.Resolved).Select(o => new
{
o.Id,
o.StudentUsername,
o.Student.FirstName,
o.Student.LastName,
o.Student.TutorGroup,
o.Student.ClassName,
TeacherName = o.Teacher.FirstName + " " + o.Teacher.LastName,
o.DramaType,
o.DateForDetention,
o.DateHappened
}).ToLookup(o => o.StudentUsername + o.DateHappened.ToString("ddMMyy"), o => o);
var students = dramas.Select(o => o.Key).Distinct().Select(o => dramas[o].ToList()).Select(o => new FollowUpItem
{
Id = String.Join(",", o.Select(d => d.Id)),
FirstName = o[0].FirstName,
LastName = o[0].LastName,
TutorGroup = o[0].TutorGroup,
EquipmentDrama = o.Any(d => d.DramaType == DramaType.Equipment),
HomeworkDrama = o.Any(d => d.DramaType == DramaType.Homework),
IsFlagged = o.Any(d => d.DramaType == DramaType.Flagged),
ClassName = o[0].ClassName,
TeacherName = o[0].TeacherName,
DateForDetention = o[0].DateForDetention,
DateHappened = o[0].DateHappened
}).ToList();
</code></pre>
<p>Note the reason for using an anonymous type in the first LINQ statement is that I want to retrieve the related fields <code>o.Teacher.FirstName</code> and <code>o.Teacher.LastName</code> in the initial (only) database call. There must be a better way of doing this though!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T16:06:23.010",
"Id": "37980",
"Score": "0",
"body": "What LINQ provider are you using? Can't you just retrieve the whole `Drama`, `Student` and `Teacher` objects?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T16:11:06.547",
"Id": "37981",
"Score": "0",
"body": "Linq to SQL. The `Person` table which contains student and teacher info has lots of other fields which I don't need to retrieve."
}
] |
[
{
"body": "<p>It seems like you could do this:</p>\n\n<pre><code>var results = \n (from d in ctx.Dramas\n where !d.Resolved\n group d by new { d.Student, DateHappened = d.DateHappened.ToString(\"ddMMyy\") } into g\n select new\n {\n Student = g.Key.Student,\n DateHappened = g.Key.DateHappened,\n EquipmentDrama = g.Any(d => d.DramaType == DramaType.Equipment),\n HomeworkDrama = o.Any(d => d.DramaType == DramaType.Homework),\n IsFlagged = o.Any(d => d.DramaType == DramaType.Flagged),\n Dramas = g.Select(d => new \n {\n d.Id,\n TeacherName = d.Teacher.FirstName + \" \" + d.Teacher.LastName,\n d.DateForDetention\n })\n });\n</code></pre>\n\n<p><em>NOTE:</em> as far as I can tell, there's nothing limiting <code>Teacher</code> (or <code>DateForDetention</code>) to be the same in all grouped dramas; each drama could have a different <code>Teacher</code>. Here's an alternative that includes the teacher in the grouping:</p>\n\n<pre><code>var results = \n (from d in ctx.Dramas\n where !d.Resolved\n group d by new { d.Student, d.Teacher, DateHappened = d.DateHappened.ToString(\"ddMMyy\") } into g\n select new\n {\n Student = g.Key.Student,\n DateHappened = g.Key.DateHappened,\n EquipmentDrama = g.Any(d => d.DramaType == DramaType.Equipment),\n HomeworkDrama = o.Any(d => d.DramaType == DramaType.Homework),\n IsFlagged = o.Any(d => d.DramaType == DramaType.Flagged),\n TeacherName = d.Key.Teacher.FirstName + \" \" + d.Key.Teacher.LastName,\n Dramas = g.Select(d => new \n {\n d.Id,\n d.DateForDetention\n })\n });\n</code></pre>\n\n<p>Of course, you could do the same for <code>DateForDentention</code> if you wanted.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T22:39:37.430",
"Id": "24614",
"ParentId": "24595",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "24614",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T15:03:53.043",
"Id": "24595",
"Score": "3",
"Tags": [
"c#",
"linq",
"linq-to-sql"
],
"Title": "LINQ statement to aggregate data"
}
|
24595
|
<p>This started simple, as most things do. I just wanted a little structure to hold polar coordinates for a totally minor class. But starting with <a href="https://stackoverflow.com/a/9485264">this answer</a> and borrowing from existing Objective-C concepts like <code>CGPoint</code> and <code>CGSize</code>, the simple struct quickly morphed into a more complete solution.</p>
<p>I have this all in a _polar.h file that I have included in my files and I was wondering what other things should be included and/or other criticism of my technique. Am I approaching this thing correctly?</p>
<p>(Note: <code>startPoint</code> and <code>endPoint</code> are part of the structure to help solve other problems in my class and are not necessarily "normal" parts of a polar structure.)</p>
<pre><code>#ifndef Polar__polar_h
#define Polar__polar_h
struct _Polar {
CGFloat angle;
CGFloat r;
CGPoint startPoint;
CGPoint endPoint;
};
typedef struct _Polar Polar;
static inline Polar
PolarMakeFromPoints(CGPoint startPoint, CGPoint endPoint) {
Polar polar;
polar.startPoint =startPoint;
polar.endPoint =endPoint;
polar.angle =atan2f(endPoint.y -startPoint.y, endPoint.x -startPoint.x);
polar.r =sqrtf(powf(endPoint.x -startPoint.x, 2.0) + pow(endPoint.y -startPoint.y, 2.0));
return polar;
}
static inline Polar
PolarMake(CGFloat angle, CGFloat r) {
Polar polar;
polar.angle =angle;
polar.r =r;
polar.startPoint =CGPointZero;
polar.endPoint =CGPointMake((cos(angle) *r), (sin(angle) *r));
return polar;
}
static inline bool
PolarEqualToPolar(Polar polar1, Polar polar2) {
return polar1.angle ==polar2.angle && polar1.r ==polar2.r;
}
static inline bool
PolarIdenticalToPolar(Polar polar1, Polar polar2) {
return CGPointEqualToPoint(polar1.startPoint, polar2.startPoint)
&& CGPointEqualToPoint(polar1.endPoint, polar2.endPoint);
}
static inline Polar
_PolarZero() {
Polar polar;
polar.angle =0.0;
polar.r =0.0;
polar.startPoint =CGPointZero;
polar.endPoint =CGPointZero;
return polar;
}
#define PolarZero _PolarZero()
static inline NSString
*NSStringFromPolar(Polar polar) {
return [NSString stringWithFormat:@"a=%f r=%f", polar.angle, polar.r];
}
// Extend NSValue to work with Polar
@interface NSValue (Polar)
+(id)valueWithPolar:(Polar)polar;
-(Polar)polarValue;
@end
@implementation NSValue (Polar)
+(id)valueWithPolar:(Polar)polar {
return [NSValue value:&polar withObjCType:@encode(Polar)];
}
-(Polar)polarValue {
Polar polar;
[self getValue:&polar];
return polar;
}
@end
@interface NSString (Polar)
@end
@implementation NSString (Polar)
@end
#endif
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>Why the <code>#ifdef</code> guard? It’s not needed in Objective-C since we have the <code>#import</code> directive instead of <code>#include</code>.</p></li>\n<li><p>Why have the whole thing in the header? The usual solution is to put the function declarations into the header and the implementations into the implementation file.</p></li>\n<li><p>The difference between <code>PolarEqualToPolar</code> and <code>PolarIdenticalToPolar</code> is not clear to me. I mean, I could assert something from the implementation, but that’s not a good API if I have to.</p></li>\n<li><p>Related to the previous point, do you realize you’re skating on thin ice when comparing the <code>float</code> components using plain equality (<code>==</code>)? The same disclaimer applies here as for any floating-point comparison, there are nasty suprises caused by precision issues. (See the classical article about <a href=\"http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html\" rel=\"nofollow\">What Every Computer Scientist Should Know About Floating-Point Arithmetic</a>.) This is not necessarily a fault of your API or code, it’s just good to be aware of.</p></li>\n<li><p>Do you really need the performance gains to write this in C instead of Objective-C? Always use high-level code unless the profiler tells you otherwise. Granted, polar coordinates are somewhat on the performant side, but then the modern hardware is so fast you could write the code in high-level Objective-C and still get very usable performance for many use cases.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-20T10:14:36.227",
"Id": "39172",
"Score": "0",
"body": "+1, but note that this was tagged with `ios`, so unless this person's app is only targeting new iPhones (e.g. 5) and iPads, the *modern* hardware is still a pretty small computer. I've run into performance problems with mapping code before."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-20T11:32:41.560",
"Id": "39182",
"Score": "0",
"body": "I have some experience developing games for the iPhone and I was surprised how fast the machines are; I seldom needed to drop into C for performance reasons. But you’re right, C is a reasonable default in this case."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T12:07:57.563",
"Id": "24795",
"ParentId": "24596",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T16:19:42.053",
"Id": "24596",
"Score": "2",
"Tags": [
"objective-c",
"ios",
"coordinate-system"
],
"Title": "A structure and helper functions for working with polar coordinates"
}
|
24596
|
<p>In the snippet below the three exceptions I declare in the <code>throws</code> clause are all thrown by BeanUtils.setProperty(), which is a third party library.</p>
<p>Is letting these three exceptions "bubble upwards" with a <code>throws</code> declaration bad style? Is it better to wrap them in my own RoleBeanException and throw that?</p>
<pre><code>public BeanRole getRoleBean(Request request)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
{
String[] arrayOfProperties = {"application", "environment", "role"};
BeanRole roleBean = new BeanRole();
for (String strProperty : arrayOfProperties) {
String strValue = BeanUtils.getProperty(request, strProperty);
BeanUtils.setProperty(roleBean, strProperty, strValue);
}
return roleBean;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T17:48:42.157",
"Id": "37984",
"Score": "0",
"body": "Are these errors anything that the calling code would actually want/need to handle?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T17:51:29.403",
"Id": "37985",
"Score": "0",
"body": "@WinstonEwert: No, the caller would only act on the fact that the role bean could not be created. It would not care or be able to make any decision on how to proceed based on the three individual exception types."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T17:55:12.517",
"Id": "37986",
"Score": "0",
"body": "Under what circumstances would this bean fail to be created?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T18:03:12.310",
"Id": "37988",
"Score": "0",
"body": "Programming errors would be the only cause I can think of. For example mis-spelling a property name in the array, or changing the setters/getters without adjusting the array."
}
] |
[
{
"body": "<p>Programming errors should, as much as possible, produce unchecked rather than checked exceptions. Checked exceptions are for circumstances that will occur during the normal operation of the program and thus should be handled. For example, you should handle the IOException raised by attempting to open a file that isn't there. However, there is no reason to handle the exception raised by a misspelled property name. Programming errors in general should produce unchecked exceptions. </p>\n\n<p>In this case, you should catch all those exceptions inside this function and rethrow them wrapped in a RuntimeException. Don't declare any exceptions types, those are only for exceptions that your caller should handle.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T19:15:48.323",
"Id": "37991",
"Score": "1",
"body": "I would like to just add that it would also be good to think about who needs to depend on what? Don't make other people depend on a API call that you made, instead as much as possible handle those yourself and if needed throw an exception that everyone has access too so you don't add to dependency. It would be annoying if you added another exception type and I had to change my code because you added something small. basically make me depend on you and not someone else as well as you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T18:15:58.413",
"Id": "24601",
"ParentId": "24598",
"Score": "5"
}
},
{
"body": "<p>As a general rule of thumb, you catch an exception when you intend to do something with it , or when it matters to you . On the other hand , make the method declare that it throws the exception when you really don't care to bother with what happens when the exception occurs. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-06T19:19:07.030",
"Id": "30891",
"ParentId": "24598",
"Score": "1"
}
},
{
"body": "<p>How you handle exceptions depends on how you want your code's interface to look. It basically comes down to how <a href=\"http://www.codinghorror.com/blog/2009/06/all-abstractions-are-failed-abstractions.html\" rel=\"nofollow\">leaky</a> you want your abstraction to be.</p>\n\n<p>Propagate an exception if the caller could reasonably make sense of the exception.</p>\n\n<p>Catch and throw your own exception (possibly wrapping the original exception) in all other cases.</p>\n\n<p>For example, if you want the code that calls your method to be aware that your method uses reflection, then it may be OK to propagate an <code>InvocationTargetException</code>. If, however, reflection just happens to be the way your method is implemented, you wouldn't want to leak details of your method's inner workings by declaring those exceptions in your method signature. Instead, you should create your own type of exception that makes sense for the interface you are trying to define. (As @WinstonEwert advises, the exception class you create should be a subclass of <code>RuntimeException</code> if the problem is mostly the programmer's fault, and a checked exception if it's probably the user's fault.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-07T10:50:58.873",
"Id": "30911",
"ParentId": "24598",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24601",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T17:37:37.467",
"Id": "24598",
"Score": "1",
"Tags": [
"java",
"exception-handling"
],
"Title": "When to catch/wrap an exception vs declaring that method throws exception"
}
|
24598
|
<p>As an interesting exercise in Python 3.3, I implemented a <a href="http://en.wikipedia.org/wiki/Trie" rel="noreferrer"><strong>Trie</strong></a> (also known as a Prefix Tree).</p>
<h2>Example usages</h2>
<h3>Create from list of key-value-tuples</h3>
<pre><code>mapping = (('she', 1), ('sells', 5), ('sea', 10), ('shells', 19), ('today', 5))
trie = Trie.from_mapping(mapping)
some_prefix = 'sh'
some_key = 'today'
print('Keys:', *trie)
print('Items: ', *trie.items())
print('Keys prefixed "{}":'.format(some_prefix), *trie.keys(prefix=some_prefix))
trie[some_key] = -55
print('Value of "{}":'.format(some_key), trie[some_key])
print(some_key, 'is in' if some_key in trie else 'is not in', 'the Trie')
</code></pre>
<blockquote>
<p><strong>Output</strong></p>
<pre><code>Keys: today sells sea she shells
Items: ('today', 5) ('sells', 5) ('sea', 10) ('she', 1) ('shells', 19)
Keys prefixed "sh": she shells
Value of "today": -55
today is in the Trie
</code></pre>
</blockquote>
<h3>Find out lengths of words in a string</h3>
<pre><code>words = 'She sells sea shells today she sells no shells she sells'.split()
trie = Trie.from_keys(words, value_selector=len)
print(*trie.items())
</code></pre>
<blockquote>
<p><strong>Output</strong></p>
<pre><code>('sells', 5) ('sea', 3) ('she', 3) ('shells', 6) ('today', 5) ('no', 2) ('She', 3)
</code></pre>
</blockquote>
<hr />
<h2>Implementation</h2>
<p>For simplicity, each entry is represented by a <code>dict</code> mapping characters to child entries – if this is problematic, feel free to remark on that.</p>
<pre><code>class _Entry:
def __init__(self, value=None):
self.value = value
self.children = {}
def __iter__(self):
return iter(self.children.items())
</code></pre>
<p>I made it iterable so I don't have to constantly write things like <code>entry.children.items()</code>.</p>
<p>Here's the <code>Trie</code> itself – please feel free to <strong>point out any or all issues you can spot.</strong> I started taking a look at Python two weeks ago, so I'd also appreciate your comments on how Pythonic (or not) this is, as well as any potential issues of performance.</p>
<pre><code>class Trie:
@staticmethod
def from_mapping(mapping):
"""
Constructs a Trie from an iterable of two-item tuples.
:param mapping: An iterable of key value pairs (each key must itself
be an iterable)
:return: A new Trie containing the keys and values in the mapping
"""
trie = Trie()
for key, value in mapping:
if not key:
continue
trie[key] = value
return trie
@staticmethod
def from_keys(keys, value_selector):
"""
Constructs a Trie from an iterable of keys, mapping each key to the
value returned by the value selector function, which is passed each key.
:param keys: an iterable of keys (each key must itself be an iterable)
:return: a new Trie containing the keys in the mapping
"""
trie = Trie()
for key in keys:
if not key:
continue
trie[key] = value_selector(key)
return trie
def __init__(self):
"""
Creates an empty Trie.
"""
self._root = _Entry()
self._length = 0
def __getitem__(self, key):
"""
Gets the value corresponding to the specified key.
:param key: an iterable
:return: the value corresponding to the key if it is in the Trie,
otherwise None
"""
entry = self._find(key)
if entry is not None:
return entry.value
def __setitem__(self, key, value):
"""
Sets or inserts the specified value, mapping the specified key to it
:param key: an iterable to update or insert
:param value: the object to associate with the key
"""
self.update(key, lambda old_value: value)
def __delitem__(self, key):
"""
Removes the value of the specified key without removing it from the Trie
:param key: the iterable whose value is to be removed
"""
self[key] = None
self._length -= 1
def __contains__(self, key):
"""
Determines if the key is in the Trie and has a value associated with it
:param key: the iterable to search for
:return: True if the Trie contains the key, otherwise False
"""
entry = self._find(key)
return entry is not None and entry.value is not None
def __len__(self):
return self._length
def __bool__(self):
return len(self) > 0
def __iter__(self):
return iter(self.keys())
def keys(self, prefix=''):
"""
Searches for keys beginning with the specified prefix
:param prefix: an iterable
:return: A generator yielding the keys one by one, as they are found
"""
yield from (key for key, value in self.items(prefix))
def items(self, prefix=''):
"""
Searches for key value pairs where the keys begin with the specified
prefix
:param prefix: an iterable
:return: A generator yielding tuples of keys and values as they are
found
"""
start = self._find(prefix)
if start is None:
return ()
stack = [(prefix, start)]
while stack:
current_prefix, entry = stack.pop()
if entry.value is not None:
yield current_prefix, entry.value
for char, children in entry:
stack.append((current_prefix + char, children))
def update(self, key, value_selector):
"""
Updates key with the value obtained from the value selector function,
to which the old value corresponding to the key is passed.
:param key: the key whose value is to be updated
:param value_selector: a function that takes the old value as an
argument and returns a new value
"""
entry = self._root
for char in key:
if char not in entry.children:
entry.children[char] = _Entry()
entry = entry.children[char]
new_value = value_selector(entry.value)
if entry.value != new_value:
entry.value = new_value
self._length += 1
def _find(self, key):
entry = self._root
for char in key:
if char not in entry.children:
return None
entry = entry.children[char]
return entry
</code></pre>
|
[] |
[
{
"body": "<p>A note on terminology: a <em>mapping</em> is, according to <a href=\"http://docs.python.org/3/glossary.html#term-mapping\" rel=\"nofollow\">Python glossary</a>,</p>\n\n<blockquote>\n <p>A container object that supports arbitrary key lookups and implements\n the methods specified in the Mapping or MutableMapping abstract base\n classes. Examples include <code>dict</code>, <code>collections.defaultdict</code>,\n <code>collections.OrderedDict</code> and <code>collections.Counter</code>.</p>\n</blockquote>\n\n<p>Your <code>from_mapping</code> assumes a different type of argument.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T20:09:38.580",
"Id": "37996",
"Score": "0",
"body": "Thanks, that's a very good point. In fact, I was confused by [the `dict` constructor documentation](http://docs.python.org/3/library/stdtypes.html#dict) but that's because I didn't read it carefully enough. Any suggestions for a better name? I'm thinking of `key_value_pairs`..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T21:19:31.487",
"Id": "37999",
"Score": "0",
"body": "@codesparkle, I'd go from `from_pairs` myself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T06:01:33.900",
"Id": "38016",
"Score": "0",
"body": "@codesparkle I'd follow Gareth's suggestion and have the constructor call `update`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T20:03:01.777",
"Id": "24608",
"ParentId": "24602",
"Score": "3"
}
},
{
"body": "<p><code>__getitem__</code> returns None if a key cannot be found, to follow python conventions it should raise KeyError.</p>\n\n<p>Simliar with <code>__delitem__</code>, I'd expected a KeyError if deleting a non-existent element.</p>\n\n<p>I wonder if it would be better to have your <code>_Entry</code> object support a .items() method which could then be implemented recursively. </p>\n\n<p>Given that it act a lot like a mapping, I'd expect the <code>update</code> method to act like <code>dict.update</code> but it doesn't.</p>\n\n<pre><code> if entry.value != new_value:\n entry.value = new_value\n self._length += 1\n</code></pre>\n\n<p>Its not clear to me that this is the correct logic for incrementing the length.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T21:22:48.460",
"Id": "38001",
"Score": "0",
"body": "Thank you for your excellent points. You're right about `length`: it is indeed a bug."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T21:19:12.923",
"Id": "24610",
"ParentId": "24602",
"Score": "2"
}
},
{
"body": "<h3>1. Bug</h3>\n\n<ol>\n<li><p>Sometimes the <code>_length</code> attribute is updated wrongly. First, when deleting an item, the length is decremented regardless of whether the item was actually present in the trie:</p>\n\n<pre><code>>>> trie = Trie()\n>>> del trie['key']\n>>> len(trie)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nValueError: __len__() should return >= 0\n</code></pre>\n\n<p>Second, when updating an item, the length is incremented regardless of whether the item was actually new:</p>\n\n<pre><code>>>> trie = Trie()\n>>> trie['key'] = 1\n>>> trie['key'] = 2\n>>> print(*trie)\nkey\n>>> len(trie)\n2\n</code></pre></li>\n</ol>\n\n<h3>2. Other comments</h3>\n\n<ol>\n<li><p>You have docstrings for all your methods: awesome! You might consider adding a docstring for the <code>Trie</code> class (look at the output of <code>help(Trie)</code> and consider what else is needed). This is also a good class to consider adding <a href=\"http://docs.python.org/3/library/doctest.html\">doctests</a>.</p></li>\n<li><p>Since the class <code>_Entry</code> is only used in <code>Trie</code>, you could make it an attribute of <code>Trie</code>.</p></li>\n<li><p>In the <code>_Entry</code> class, you use <code>None</code> as a placeholder to mean that there is no value associated with this entry. This prevents anyone from storing <code>None</code> as a value in a <code>Trie</code>. Instead, you could leave the <code>value</code> attribute unset to indicate no value (this can be detected with the <a href=\"http://docs.python.org/3/library/functions.html#hasattr\"><code>hasattr</code></a> function), and write <code>del entry.value</code> to delete it.</p></li>\n<li><p>You could have <code>_Entry</code> inherit from <code>dict</code> and then you wouldn't need to have an attribute <code>children</code>.</p></li>\n<li><p>By using <a href=\"http://docs.python.org/3/library/functions.html#staticmethod\"><code>@staticmethod</code></a> you prevent anyone from subclassing <code>Trie</code>, because when someone calls <code>SubTrie.from_mapping</code>, the object they get back will be a <code>Trie</code> rather than a <code>SubTrie</code>. You should use <a href=\"http://docs.python.org/3/library/functions.html#classmethod\"><code>@classmethod</code></a> instead:</p>\n\n<pre><code>@classmethod\ndef from_mapping(class_, mapping):\n trie = class_()\n # ...\n</code></pre></li>\n<li><p>It's not clear why you have the lines:</p>\n\n<pre><code>if not key:\n continue\n</code></pre>\n\n<p>in <code>from_mapping</code> and <code>from_keys</code>. Why can't I add the empty string to a <code>Trie</code>? (If you have a good reason, it would be worth mentioning it in the documentation, and also worth raising an error here, instead of silently discarding these keys.)</p></li>\n<li><p>The <code>__getitem__</code> method returns <code>None</code> to indicate failure. In Python it's normal to raise an exception to indicate failure rather than returning an exceptional type. In this case it would be appropriate to raise <code>KeyError</code> (just as the built-in <code>dict.__getitem__</code> does).</p></li>\n<li><p>You might consider whether <code>Trie</code> should inherit from <a href=\"http://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping\"><code>MutableMapping</code></a> in the <a href=\"http://docs.python.org/3/library/stdtypes.html#dict.update\"><code>collections.abc</code></a> module: this would give you <code>values</code>, <code>get</code>, <code>__eq__</code>, <code>__ne__</code>, <code>pop</code>, <code>popitem</code>, <code>clear</code>, <code>update</code> and <code>setdefault</code> methods for free.</p></li>\n<li><p>Since your <code>Trie</code> class presents a mapping-like interface, Python programmers will expect its <code>update</code> method to present a similar interface to the <a href=\"http://docs.python.org/3/library/stdtypes.html#dict.update\"><code>update</code></a> method on ordinary dicationary objects. (This is easy if you inherit from <code>MutableMapping</code> since the <code>update</code> method is defined in that abstract base class.)</p>\n\n<p>(Your original <code>update</code> would then need a new name.)</p></li>\n<li><p>Similarly, since your <code>Trie</code> class presents a mapping-like interface, Python programmers will expect its constructor to present a similar interface to the <a href=\"http://docs.python.org/3/library/stdtypes.html#dict\"><code>dict</code></a> constructor. (Again, this is easy if you inherit from <code>MutableMapping</code> since you can just pass the positional and keyword arguments to the <code>update</code> method.)</p></li>\n<li><p>It seems perverse that the <code>value_selector</code> argument to the <code>update</code> method is different from the <code>value_selector</code> argument to the <code>from_keys</code> method. (The former takes the <em>old value</em> as its argument but the latter takes the <em>key</em> as the argument.) This can only be confusing to users.</p>\n\n<p>Also, if your <code>update</code> method is called, but there's no value in the trie for <code>key</code>, the <code>value_selector</code> function gets called anyway (with the argument <code>None</code>). You might consider whether this method should take a third argument, the value to use in the case where there is no value in the trie. (Or maybe you should raise <code>KeyError</code> in this case.)</p>\n\n<p>I have a feeling that your <code>from_keys</code> and <code>update</code> methods are not very Pythonic. Instead of <code>from_keys</code>, callers would be happy to write:</p>\n\n<pre><code>Trie((key, f(key)) for key in keys)\n</code></pre>\n\n<p>and instead of <code>trie.update(key, lambda old_value: old_value + 1)</code> caller would be happy to write</p>\n\n<pre><code>trie[key] += 1\n</code></pre>\n\n<p>My guess is that your goal in writing the <code>update</code> method is to avoid the double lookup in the above. So it's a reasonable thing to provide, it just needs some thought about the name and interface.</p></li>\n<li><p>You could simplify some of your logic if your <code>_find</code> method was able to create new <code>_Entry</code> objects. See below for how.</p></li>\n<li><p>If your function body consists only of <code>yield from <generator></code>, you might as well write <code>return <generator></code>.</p></li>\n</ol>\n\n<h3>3. Revised code</h3>\n\n<p>This is how I would write the class, addressing all the points above.</p>\n\n<pre><code>from collections.abc import MutableMapping\n\nclass Trie(MutableMapping):\n \"\"\"\n A prefix tree.\n\n >>> mapping = dict(she=1, sells=5, sea=10, shells=19, today=5)\n >>> trie = Trie(mapping)\n >>> some_prefix = 'sh'\n >>> some_key = 'today'\n >>> print(*sorted(trie))\n sea sells she shells today\n >>> print(*sorted(trie.items()))\n ('sea', 10) ('sells', 5) ('she', 1) ('shells', 19) ('today', 5)\n >>> print(*trie.keys(prefix='sh'))\n she shells\n >>> trie['today'] = -55\n >>> trie['today']\n -55\n >>> len(trie)\n 5\n >>> 'shells' in trie, 'shore' in trie\n (True, False)\n >>> del trie['shells']\n >>> len(trie)\n 4\n \"\"\"\n\n # A dictionary with an optional :value: attribute.\n class _Entry(dict):\n def has_value(self):\n return hasattr(self, 'value')\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Return a new True initialized from an optional positional\n argument and a possibly empty set of keyword arguments, as for\n the built-in type :dict:\n \"\"\"\n self._root = self._Entry()\n self._length = 0\n self.update(*args, **kwargs)\n\n def __getitem__(self, key):\n \"\"\"\n Gets the value corresponding to the specified key.\n :param key: an iterable\n :return: the value corresponding to the key if it is in the Trie,\n otherwise raise KeyError.\n \"\"\"\n entry = self._find(key)\n if entry.has_value():\n return entry.value\n else:\n raise KeyError(key)\n\n def __setitem__(self, key, value):\n \"\"\"\n Sets or inserts the specified value, mapping the specified key to it\n :param key: an iterable to update or insert\n :param value: the object to associate with the key\n \"\"\"\n entry = self._find(key, create=True)\n if not entry.has_value():\n self._length += 1\n entry.value = value\n\n def __delitem__(self, key):\n \"\"\"\n Removes the value of the specified key from the Trie\n :param key: the iterable whose value is to be removed\n \"\"\"\n entry = self._find(key)\n if entry.has_value():\n del entry.value\n self._length -= 1\n else:\n raise KeyError(key)\n\n def __len__(self):\n return self._length\n\n def __iter__(self):\n return iter(self.keys())\n\n def keys(self, prefix=''):\n \"\"\"\n Searches for keys beginning with the specified prefix\n :param prefix: an iterable\n :return: A generator yielding the keys one by one, as they are found\n \"\"\"\n return (key for key, value in self.items(prefix))\n\n def items(self, prefix=''):\n \"\"\"\n Searches for key value pairs where the keys begin with the specified\n prefix\n :param prefix: an iterable\n :return: A generator yielding tuples of keys and values as they are\n found\n \"\"\"\n try:\n start = self._find(prefix)\n except KeyError:\n raise StopIteration\n stack = [(prefix, start)]\n while stack:\n current_prefix, entry = stack.pop()\n if entry.has_value():\n yield current_prefix, entry.value\n for char, children in entry.items():\n stack.append((current_prefix + char, children))\n\n def _find(self, key, create=False):\n entry = self._root\n for char in key:\n if char in entry:\n entry = entry[char]\n elif create:\n new_entry = self._Entry()\n entry[char] = new_entry\n entry = new_entry\n else:\n raise KeyError(key)\n return entry\n</code></pre>\n\n<h3>4. Algorithmic concerns</h3>\n\n<ol>\n<li><p>You create <code>_Entry</code> objects for all elements in each key, even if there are no other keys sharing any of those entries. For example, if I create an empty <code>Trie</code> and then add a value for the key <code>supercalifragilisticexpialidocious</code>, 34 <code>_Entry</code> objects will be constructed, and when I look up this key, all 34 of them will have to be traversed. You might consider storing the tail of a key differently when it doesn't need to share space with other keys, and creating <code>_Entry</code> objects dynamically as necessary when you add new keys that share a prefix with existing keys.</p></li>\n<li><p>When you delete keys, you don't remove <code>_Entry</code> objects that have become empty as a result. This means that later lookups may need to descend deeper into the trie before discovering that the key is not present.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T21:24:40.420",
"Id": "38002",
"Score": "1",
"body": "Awesome! My only issue is that I sternly disapprove of the suggesting to subclass `dict` for the `_Entry` class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T21:28:57.157",
"Id": "38003",
"Score": "0",
"body": "@WinstonEwert: Can you explain your concern?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T21:31:07.263",
"Id": "38004",
"Score": "0",
"body": "Gareth, thank you for your outstanding review. I particularly like the way you got rid of the duplicated logic by introducing the `create` parameter in `_find`, though I think I might make it keyword-only."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T21:34:34.483",
"Id": "38005",
"Score": "0",
"body": "It only makes sense to subclass `dict` if you are making some kind of special `dict`. Here you are creating a class which uses a `dict`, and I think thats much more naturally represented using composition rather then inheritance. I'll admit, its a bit a purest thing here."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T21:21:47.537",
"Id": "24611",
"ParentId": "24602",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "24611",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T18:43:37.063",
"Id": "24602",
"Score": "9",
"Tags": [
"python",
"algorithm",
"trie"
],
"Title": "Readability and Performance of my Trie implementation"
}
|
24602
|
<p>Here is my first try at Google's Go language, trying to solve Project Euler Problem 10:</p>
<blockquote>
<p>The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.</p>
<p>Find the sum of all the primes below two million.</p>
</blockquote>
<p>Any suggestions on the style and usage (best practice) of Go?</p>
<pre><code>package main
import "fmt"
var primes = []uint64{2, 3}
func CheckIfIsNewPrime(number uint64) bool {
check_if_number_is_new_prime := false
var remainder uint64 = 0
for i := range primes {
remainder = number % primes[i]
if remainder == 0 {
check_if_number_is_new_prime = false
break
} else {
check_if_number_is_new_prime = true
}
}
return check_if_number_is_new_prime
}
func FindNewPrime() uint64 {
for counter := primes[len(primes)-1]; ; counter += 2 {
if CheckIfIsNewPrime(counter) == true {
return counter
}
}
return 0
}
func main() {
limit := 2000000
var sum uint64
sum = 5
for i := 2; i < limit; i++ {
primes = append(primes, FindNewPrime())
sum += primes[len(primes)-1]
}
fmt.Println("sum: ", sum)
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>Algorithm : really important</strong></p>\n\n<p>What you want to to is to use the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow\">Sieve of Eratosthenes</a> because you already know an upper bound for the biggest number you're going to consider. Getting all the primes smaller than 2 millions is going to be straightforward. This will solve your <em>process took too long</em> issue. </p>\n\n<p><strong>Other things not as important</strong></p>\n\n<ul>\n<li><p>You could probably write the following function :</p>\n\n<pre><code>func CheckIfIsNewPrime(number uint64) bool {\n check_if_number_is_new_prime := false\n var remainder uint64 = 0\n\n for i := range primes {\n remainder = number % primes[i]\n if remainder == 0 {\n check_if_number_is_new_prime = false\n break\n } else {\n check_if_number_is_new_prime = true\n }\n }\n return check_if_number_is_new_prime\n}\n</code></pre>\n\n<p>in a more concise way (no real impact on performance)</p>\n\n<pre><code>func CheckIfIsNewPrime(number uint64) bool {\n for i := range primes {\n if number % primes[i] == 0 {\n return false\n }\n }\n return true\n}\n</code></pre></li>\n<li><p>I don't know anything about Go, but I guess</p>\n\n<pre><code>if CheckIfIsNewPrime(counter) == true {\n</code></pre>\n\n<p>could be written as</p>\n\n<pre><code>if CheckIfIsNewPrime(counter) {\n</code></pre></li>\n</ul>\n\n<p><em>As you go further in Project Euler, you'll see that most of the problem is to find the algorithm you want to use and not really to implement it.</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T12:48:28.360",
"Id": "38037",
"Score": "0",
"body": "Thanks for the hints Josay, I incorporated them (except for the `else` loop falling out). I see the Euler Problems more of a way to learn a new language (and prepare a bit for possible job interviews, where i would have to solve problems out of my head). I would have never come up with the `Sieve` algo, hence the implementation by trial division. I impoved the performace a bit by setting an `upper bound` as I dont have to check against division by all previous primes.\n\nI discovered a major misconception in my code: I tries to sum till the 2 millionth prime instead of all primes below 2 mio."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T14:22:59.540",
"Id": "38043",
"Score": "0",
"body": "You're more than welcome. You'll really need to change the algorithm if you want to get any result (either for that problem or for a one later on). Also it's a classic algorithm which is always good to implement."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T22:10:51.957",
"Id": "24613",
"ParentId": "24612",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "24613",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-01T21:23:46.527",
"Id": "24612",
"Score": "3",
"Tags": [
"programming-challenge",
"primes",
"go"
],
"Title": "Project Euler 10: Summation of primes in Go"
}
|
24612
|
<p>I'm working on a simple superfeedr powered rails app here.</p>
<p>Based on the <a href="https://github.com/superfeedr/rack-superfeedr" rel="nofollow">superfeedr-rack gem documentation</a>, I'm doing this to initialize the middleware (snippet from application.rb config block):</p>
<pre><code>Configuration = YAML.load_file(Rails.root.join('config', 'config.yml'))
config.middleware.use Rack::Superfeedr, { :host => Configuration["general"]["hostname"], :login => Configuration["superfeedr"]["username"], :password => Configuration["superfeedr"]["password"]} do |superfeedr|
Superfeedr = superfeedr
superfeedr.on_notification do |notification|
Article.create_from_raw_notification(notification)
end
end
</code></pre>
<p>I'm looking for a better way to do it - I don't like to load my configuration file there instead of in an initializer and I think the block with the article creation callback smells. Any ideas?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T20:00:44.993",
"Id": "38227",
"Score": "0",
"body": "Try Rails.configuration.middleware"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T11:34:50.717",
"Id": "38228",
"Score": "0",
"body": "@tapajos your answer was converted to a comment because it was too short. If you'd like to expand it with an example and a better description, you're welcome to do so."
}
] |
[
{
"body": "<p>Based on tapajos comment, I was able to to refactor the code using initializers. First I created one to load the configuration file:</p>\n\n<pre><code>APP_CONFIG = YAML.load_file(File.expand_path('../../config.yml', __FILE__))\n</code></pre>\n\n<p>Then I created another initializer, like this:</p>\n\n<pre><code>superfeedr_config = {\n :host => APP_CONFIG[\"general\"][\"hostname\"],\n :login => APP_CONFIG[\"superfeedr\"][\"username\"],\n :password => APP_CONFIG[\"superfeedr\"][\"password\"]\n}\n\nRails.configuration.middleware.use Rack::Superfeedr, superfeedr_config do |superfeedr|\n Superfeedr = superfeedr\n superfeedr.on_notification {|notification| Article.create_from_raw_notification(notification)}\nend\n</code></pre>\n\n<p>I also applied the logic described in this SO question to ensure the load order: <a href=\"https://stackoverflow.com/questions/4779773/how-do-i-change-the-load-order-of-initializers-in-rails-3\">How do I change the load order of initializers in Rails 3?</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T05:05:12.937",
"Id": "24935",
"ParentId": "24618",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "24935",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T01:10:03.693",
"Id": "24618",
"Score": "2",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Rails middleware initialization block"
}
|
24618
|
<p>I have the below program </p>
<pre><code>class Program
{
static void Main(string[] args)
{
List<Assembly> failedAssemblies = LoadAssembly();
string batchFile = "D:\\1" + ".bat";
FileStream fs = File.Create(batchFile);
fs.Close();
using (StreamWriter outFile = new StreamWriter(batchFile))
{
string command = @"echo off";
outFile.WriteLine(command);
Process(outFile, failedAssemblies);
}
}
private static void Process(StreamWriter outFile, List<Assembly> assembliesList)
{
string command = "mstest.exe ";
string testcontainer = " /testcontainer:";
List<string> testContainerAssemblies = new List<string>(4);
outFile.WriteLine("SET Path=%MsTestPath%");
foreach (Assembly assmbly in assembliesList)
{
command = string.Empty;
if (!testContainerAssemblies.Contains(assmbly.AssemblyName))
{
outFile.WriteLine(' ');
testContainerAssemblies.Add(assmbly.AssemblyName);
command = "mstest.exe ";
command += testcontainer + "\\" + assmbly.AssemblyName + " ";
command += "/resultsfile:\"" + "\\Resultfile_" + assmbly.AssemblyName.Replace(".dll", "") + "_" + "1".ToString() + ".trx\"";
command += " /runconfig:";
command += " /detail:owner";
command += " /detail:duration";
command += " /detail:description";
command += " /unique ";
}
command += " /test:" + assmbly.NameSpaceName + "." + assmbly.ClassName + "." + assmbly.FunctionName;
outFile.Write(command);
}
}
private static List<Assembly> LoadAssembly()
{
var assemblyCollection = new List<Assembly>();
assemblyCollection.Add(new Assembly { AssemblyName = "AccountTestBase.dll", NameSpaceName = "ECardTest", ClassName = "ECardTest", FunctionName = "ECardTestDownLoadPKGSuccess" });
assemblyCollection.Add(new Assembly { AssemblyName = "AccountTestBase.dll", NameSpaceName = "AccountTest", ClassName = "IAccountTest", FunctionName = "Somefunc" });
assemblyCollection.Add(new Assembly { AssemblyName = "TestPayment.dll", NameSpaceName = "TestPayment", ClassName = "CreditCardTestCases", FunctionName = "BoletoFunctionalTestCase" });
assemblyCollection.Add(new Assembly { AssemblyName = "TestPayment.dll", NameSpaceName = "TestPayment", ClassName = "CreditCardTestCases", FunctionName = "BoletoEndToEndFunctionalTestCase" });
assemblyCollection.Add(new Assembly { AssemblyName = "TestPayment.dll", NameSpaceName = "TestPayment", ClassName = "CreditCardTestCases", FunctionName = "BoletoPurcahseTestCase" });
assemblyCollection.Add(new Assembly { AssemblyName = "TestPayment.dll", NameSpaceName = "TestPayment", ClassName = "CreditCardTestCases", FunctionName = "CreditCard_ResumeOrder_Success" });
assemblyCollection.Add(new Assembly { AssemblyName = "TestPayment.dll", NameSpaceName = "TestPayment", ClassName = "CreditCardTestCases", FunctionName = "CreditCard_EURCurr_USBilling_ENUS" });
assemblyCollection.Add(new Assembly { AssemblyName = "TestPayment.dll", NameSpaceName = "TestPayment", ClassName = "CreditCardTestCases", FunctionName = "DinersClubPayment" });
return assemblyCollection;
}
}
public class Assembly
{
public string AssemblyName { get; set; }
public string ClassName { get; set; }
public string FunctionName { get; set; }
public string NameSpaceName { get; set; }
}
</code></pre>
<p>It generates the below output</p>
<pre><code>echo off
SET Path=%MsTestPath%
mstest.exe /testcontainer:\AccountTestBase.dll /resultsfile:"\Resultfile_AccountTestBase_1.trx" /runconfig: /detail:owner /detail:duration /detail:description /unique /test:ECardTest.ECardTest.ECardTestDownLoadPKGSuccess /test:AccountTest.IAccountTest.Somefunc
mstest.exe /testcontainer:\TestPayment.dll /resultsfile:"\Resultfile_TestPayment_1.trx" /runconfig: /detail:owner /detail:duration /detail:description /unique /test:TestPayment.CreditCardTestCases.BoletoFunctionalTestCase /test:TestPayment.CreditCardTestCases.BoletoEndToEndFunctionalTestCase /test:TestPayment.CreditCardTestCases.BoletoPurcahseTestCase /test:TestPayment.CreditCardTestCases.CreditCard_ResumeOrder_Success /test:TestPayment.CreditCardTestCases.CreditCard_EURCurr_USBilling_ENUS /test:TestPayment.CreditCardTestCases.DinersClubPayment
</code></pre>
<p>Now a new requirement has come where we need to break the output based on the limits passed.</p>
<p>Say If the Limit is 300, the output will be</p>
<pre><code>echo off
SET Path=%MsTestPath%
mstest.exe /testcontainer:\AccountTestBase.dll /resultsfile:"\Resultfile_AccountTestBase_1.trx" /runconfig: /detail:owner /detail:duration /detail:description /unique /test:ECardTest.ECardTest.ECardTestDownLoadPKGSuccess
mstest.exe /testcontainer:\TestPayment.dll /resultsfile:"\Resultfile_TestPayment_1.trx" /runconfig: /detail:owner /detail:duration /detail:description /unique /test:TestPayment.CreditCardTestCases.BoletoFunctionalTestCase /test:TestPayment.CreditCardTestCases.BoletoEndToEndFunctionalTestCase
mstest.exe /testcontainer:\TestPayment.dll /resultsfile:"\Resultfile_TestPayment_1.trx" /runconfig: /detail:owner /detail:duration /detail:description /unique /test:TestPayment.CreditCardTestCases.BoletoPurcahseTestCase /test:TestPayment.CreditCardTestCases.CreditCard_ResumeOrder_Success /test:TestPayment.CreditCardTestCases.CreditCard_EURCurr_USBilling_ENUS /test:TestPayment.CreditCardTestCases.DinersClubPayment
</code></pre>
<p>i.e. the firstone has a total character limit of 210(approx) and henceforth it remain the same.</p>
<p>The second one has crossed the limit and needs to be split into two parts. The first one is split over two lines (290) because adding one more command to it will cross the limit. That's why we need to split it into two parts.</p>
<p>One more point is that, it cannot just split precisely based on the Limit value provided. Because it is a MSTest command that needs to be run. Henceforth,</p>
<pre><code>`"mstest.exe /testcontainer:\TestPayment.dll /resultsfile:"\Resultfile_TestPayment_1.trx" /runconfig: /detail:owner /detail:duration /detail:description /unique"` will always come and then `"test/..."`
</code></pre>
<p>I have acheived the the final output but needs a better one(i am sure it can be)</p>
<pre><code>private static void Process(StreamWriter outFile, List<Assembly> failedAssemblies)
{
int MAXLIMIT = 2000;
string command = "mstest.exe ";
string testcontainer = " /testcontainer:";
List<string> testContainerAssemblies = new List<string>(4);
int sum = 0;
outFile.WriteLine("SET Path=%MsTestPath%");
var failedAssemblyCollections = (from x in failedAssemblies
group x by x.AssemblyName into g
select new
{
AssemblyNames = g.Key,
FullyQualifiedTestMethods = g.Select(i => " /test:" + i.NameSpaceName + "." + i.ClassName + "." + i.FunctionName),
FullyQualifiedTestMethodsLen = g.Select(i => Convert.ToString(" /test:" + i.NameSpaceName + "." + i.ClassName + "." + i.FunctionName).Length)
});
foreach (var item in failedAssemblyCollections)
{
var assemblyNames = item.AssemblyNames;
var methodsLengths = item.FullyQualifiedTestMethodsLen.ToList();
var flag = true;
int counter = 0;
//write for the very first time
if (flag)
{
Write(outFile, ref command, testcontainer, assemblyNames);
flag = false;
}
for (int i = 0; i < methodsLengths.Count; i++)
{
sum += methodsLengths[i];
if (sum <= MAXLIMIT)
{
command += item.FullyQualifiedTestMethods.ToList()[i];
//this will execute when a long command is splitted and is written in new trx files
if (flag)
{
counter++;
Write(outFile, ref command, testcontainer, assemblyNames);
flag = false;
}
}
//if the value crosses max limit
//write the current output
//then reset variables to original
if (sum >= MAXLIMIT)
{
outFile.Write(command);
sum = 0;
flag = true;
i--;
}
}
outFile.Write(command);
}
}
private static void Write(StreamWriter outFile, ref string command, string testcontainer, string assemblyNames)
{
outFile.WriteLine(' ');
command = "mstest.exe ";
command += testcontainer + "\\" + assemblyNames + " ";
command += " /runconfig:";
command += " /detail:owner";
command += " /detail:duration";
command += " /detail:description";
command += " /unique ";
}
</code></pre>
<p>Thanks in advance</p>
|
[] |
[
{
"body": "<p>First off, you are right, this is much more complicated than it needs to be. I do like most of the naming conventions, casing and white space in your code.</p>\n\n<p>I would start off by making <code>maxLimit</code>, <code>command</code>, and <code>testContainer</code> class level constants.</p>\n\n<p>The dynamic object you create while making the <code>failedAssemblyCollections</code> doesn't need the FullyQualifiedTestMethodsLen. This can be calculated by getting the length of FullyQualifiedTestMethods in the code.</p>\n\n<p>Instead of so many outFile.WriteLines, I would format the strings for each line and write when appropriate. This would eliminate the need for <code>flag</code> and <code>sum</code>, which is a good thing, because these are not well named or used variables,.</p>\n\n<p>I'm not sure what <code>counter</code> does, it is only ever assigned. Get rid of it.</p>\n\n<p>Basically, I've found your code to be overly complex, it took me a 2 hours to figure it out.</p>\n\n<p>The good news is, I think I've simplified it. I'm not going to go through line by line, I hope the code is self explanatory. You might want to pull the processing out into its own class, I just included it in the program class. I've also excluded some of your original code which I think did not need cleaning up.</p>\n\n<pre><code>class Program\n{\n private const int Maxlimit = 300;\n private const string Testcontainer = \"/testcontainer:\";\n private const string Command = \"mstest.exe\";\n private const string EchoOff = @\"echo off\";\n private const string BatchFile = \"D:\\\\1\" + \".bat\";\n private const string SetPath = \"SET Path=%MsTestPath%\";\n\n static void Main()\n {\n var failedAssemblies = LoadAssembly();\n var fs = File.Create(BatchFile);\n fs.Close();\n\n using (var outFile = new StreamWriter(BatchFile))\n {\n outFile.WriteLine(EchoOff);\n\n Process(outFile, failedAssemblies);\n } \n }\n\n private static void Process(TextWriter outFile, IEnumerable<Assembly> failedAssemblies)\n {\n outFile.WriteLine(SetPath);\n\n var failedAssemblyCollections = (from x in failedAssemblies\n group x by x.AssemblyName into g\n select new\n {\n AssemblyName = g.Key,\n FullyQualifiedTestMethods = g.Select(i => \" /test:\" + i.NameSpaceName + \".\" + i.ClassName + \".\" + i.FunctionName)\n });\n\n foreach (var item in failedAssemblyCollections)\n {\n var commandLine = InitializeLine(item.AssemblyName);\n\n foreach(var method in item.FullyQualifiedTestMethods)\n {\n if (commandLine.Length + method.Length > Maxlimit)\n {\n outFile.WriteLine(commandLine.ToString());\n\n commandLine = InitializeLine(item.AssemblyName);\n }\n\n commandLine.Append(\" \");\n commandLine.Append(method);\n }\n\n outFile.WriteLine(commandLine.ToString());\n }\n }\n\n private static StringBuilder InitializeLine(string assemblyName)\n {\n var commandLine = new StringBuilder(Command);\n\n commandLine.Append(Write(assemblyName));\n\n return commandLine;\n }\n\n private static string Write(string assemblyName)\n {\n var command = \" \";\n command += Testcontainer + \"\\\\\" + assemblyName;\n command += \" /runconfig:\";\n command += \" /detail:owner\";\n command += \" /detail:duration\";\n command += \" /detail:description\";\n\n command += \" /unique\";\n\n return command;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T05:27:57.827",
"Id": "24622",
"ParentId": "24619",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T01:59:39.590",
"Id": "24619",
"Score": "2",
"Tags": [
"c#"
],
"Title": "A complex string splitter- How do I make this working code better?"
}
|
24619
|
<p>I get great FPS with this as is, but I'm a performance freak and I don't know <code>AffineTransform</code> or the Java graphics libraries very well. I'm sure there is something I could be doing differently to make this faster, but I can't think of anything, other than it looks like the scale transformation gives me a big performance hit, probably because of the algorithm Graphics2D uses to draw the scaled pixels. I'd be fine with it using a different algorithm that doesn't blend colors if that would make things run faster, but I don't know where to even begin to try to do that.</p>
<p>I dumbed down my code to give you a good idea of what's going on (I hope). I'm only concerned about the render method.</p>
<pre><code>public BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
public Graphics2D graphics = image.createGraphics();
public void render(BufferedImage img, Vector2 center, Vector2 offset, double rotation, Vector2 scale) {
graphics.setTransform((AffineTransform) defaultTransform.clone());
graphics.rotate(rotation, center.x, center.y);
graphics.scale(scale.x, scale.y);
graphics.translate(center.x / scale.x + offset.x, center.y / scale.y + offset.y);
graphics.drawImage(img, null, 0, 0);
}
public class Vector2 {
double x = 0.0, y = 0.0;
}
</code></pre>
|
[] |
[
{
"body": "<p>Sometimes, the correct answer really is \"Nope; it's all good.\" It makes for a boring answer, but there it is. It doesn't look like you can make this much faster, based on what you've provided.</p>\n\n<p>One thing you might consider is checking the variables to see if the image manipulations are actually <em>needed</em> before calling the respective methods. So, for example, something like...</p>\n\n<pre><code>graphics.setTransform((AffineTransform) defaultTransform.clone());\nif(rotation != 0.0) {\n graphics.rotate(rotation, center.x, center.y);\n}\nif(scale.x != img.getWidth() || scale.y != img.getHeight()) {\n graphics.scale(scale.x, scale.y);\n}\n//...\n</code></pre>\n\n<p>This might give you a bit of performance where you don't need to bother going down into the <code>rotate()</code> and <code>scale()</code> methods.</p>\n\n<p>Also, is there any way you can get rid of that <code>(AffineTransform)</code> cast? Probably not, but that would speed you up ever so slightly.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T20:45:07.500",
"Id": "42460",
"ParentId": "24621",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "42460",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T03:59:05.720",
"Id": "24621",
"Score": "6",
"Tags": [
"java",
"algorithm",
"performance"
],
"Title": "Can I make my render method more efficient?"
}
|
24621
|
<p><a href="http://www.wikiupload.com/SJ1VLZZZBZU6TVR" rel="nofollow">Link to a full functional solution.</a></p>
<p>I'm working on a physics based algorithm, and I find myself working a lot with functions of style </p>
<pre><code>double GetSpeed(double acceleration, double angle, double resistance)
</code></pre>
<p>A lot of physical values are passed from function to function as double, and it is a nightmare. I fail a lot at giving the right value at the right parameter, and also at the good units. Sometimes speed is in m/s, sometimes in km/h.</p>
<p>So my idea was to create an abstract class for different physical values, like Speed, Angle, etc...<br>
Since you can add doubles, you can also add speeds or angles, so the abstract class must support adding, soustracting, all basic operations you can do on double.</p>
<p>So here is my abstract class :</p>
<pre><code>public interface ISIQuantity
{
double SIValue { get; }
}
/// <summary>
/// Represent maths or physics quantities like angle, mass, speed
/// http://en.wikipedia.org/wiki/International_System_of_Units
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class SIQuantity<T> : ISIQuantity, IComparable, IComparable<T>, IEquatable<T>
where T : ISIQuantity
{
private readonly double _value;
public double SIValue { get { return _value; } }
public SIQuantity(double value)
{
this._value = value;
}
public int CompareTo(T other) { return this.SIValue.CompareTo(other.SIValue); }
public int CompareTo(object other)
{
if (other is T)
{
return this.CompareTo(((T)other));
}
else
{
return 1;
}
}
public bool Equals(T other) { return this.SIValue.Equals(other.SIValue); }
public override bool Equals(object other)
{
if (other is T)
{
return this.Equals(((T)other));
}
else
{
return false;
}
}
public override int GetHashCode()
{
return this._value.GetHashCode();
}
public static bool operator ==(SIQuantity<T> a, SIQuantity<T> b)
{
// If both are null, or both are same instance, return true.
if (Object.ReferenceEquals(a, b))
{
return true;
}
// If one is null, but not both, return false.
if (((object)a == null) || ((object)b == null))
{
return false;
}
return a.Equals(b);
}
public static bool operator !=(SIQuantity<T> r1, SIQuantity<T> r2)
{
return !(r1 == r2);
}
public static bool operator <(SIQuantity<T> r1, SIQuantity<T> r2)
{
return (r1.SIValue.CompareTo(r2.SIValue) < 0);
}
public static bool operator >(SIQuantity<T> r1, SIQuantity<T> r2)
{
return (r1.SIValue.CompareTo(r2.SIValue) > 0);
}
public static bool operator <=(SIQuantity<T> r1, SIQuantity<T> r2)
{
return (r1.SIValue.CompareTo(r2.SIValue) <= 0);
}
public static bool operator >=(SIQuantity<T> r1, SIQuantity<T> r2)
{
return (r1.SIValue.CompareTo(r2.SIValue) >= 0);
}
protected abstract T CreateFromSI(double siValue);
public static T operator +(SIQuantity<T> r1, SIQuantity<T> r2)
{
return r1.CreateFromSI(r1.SIValue + r2.SIValue);
}
// all kind of operator
}
</code></pre>
<p>Basically, just a wrapper around a double.<br>
The double is called SIValue, like Standard Unit value. The idea is to keep the value in the unit of the standard system. So Kilogram for a mass, or meter per seconds for speed.<br>
Each of the derived class must override the <code>CreateFromSI</code> method for specify how to build a new unit based on a value in SI unit.</p>
<p>Here is how we use it :</p>
<pre><code>public enum SpeedUnit { KilometerPerHour, MeterPerSecond }
public class Speed : SIQuantity<Speed>
{
protected override Speed CreateFromSI(double value)
{
return new Speed(value, SpeedUnit.MeterPerSecond);
}
public Speed(double value, SpeedUnit unit)
: base(unit == SpeedUnit.MeterPerSecond ? value : value / 3.6)
{
}
public static Speed FromKilometerPerHour(double value)
{
return new Speed(value, SpeedUnit.KilometerPerHour);
}
public static Speed FromMeterPerSecond(double value)
{
return new Speed(value, SpeedUnit.MeterPerSecond);
}
public double KilometerPerHour
{
get
{
return this.SIValue * 3.6;
}
}
public double MeterPerSecond
{
get
{
return this.SIValue;
}
}
}
</code></pre>
<p>A little extension to make life easier</p>
<pre><code>public static Speed KilometersPerHour(this int speed)
{
return Speed.FromKilometerPerHour(speed);
}
</code></pre>
<p>The tests</p>
<pre><code>[TestMethod]
public void Test_lt()
{
var speed1 = 36.KilometersPerHour();
var speed2 = 37.KilometersPerHour();
Assert.IsTrue(speed1 < speed2);
}
[TestMethod]
public void Test_lte()
{
var speed1 = 36.KilometersPerHour();
var speed2 = 37.KilometersPerHour();
Assert.IsTrue(speed1 <= speed2);
}
[TestMethod]
public void Test_lte_e()
{
var speed1 = 36.KilometersPerHour();
var speed2 = 36.KilometersPerHour();
Assert.IsTrue(speed1 <= speed2);
}
[TestMethod]
public void Test_gt()
{
var speed1 = 37.KilometersPerHour();
var speed2 = 36.KilometersPerHour();
Assert.IsTrue(speed1 > speed2);
}
[TestMethod]
public void Test_gte()
{
var speed1 = 37.KilometersPerHour();
var speed2 = 36.KilometersPerHour();
Assert.IsTrue(speed1 >= speed2);
}
[TestMethod]
public void Test_Add()
{
Assert.AreEqual(5.KilometersPerHour(), 3.KilometersPerHour() + 2.KilometersPerHour());
}
</code></pre>
<p>I have do the sames with the physicals value angle, force, acceleration, etc...
So I can call my safe typed method like that :</p>
<pre><code>Speed GetSpeed(Acceleration acceleration, Angle angle, Force resistance)
{
// foo algorihtm for prouving the point
var speed = Speed.FromMeterPerSeconds(acceleration.MeterPerSecondsMinus2 * angle.Degrees + resistance.Newton);
return speed;
}
</code></pre>
<p>Now, the questions :</p>
<p><strong>First Point :</strong> </p>
<p>I have defined the SIQuantity as a generic type, so my abstract class contains all the logic for adding, substracting, compare the value, and return the good type. This way, it looks like a hack, since I have to define my generic type to extend an interface I have called ISIQuantity to access the SIValue. This looks weird.</p>
<p><strong>Second Point :</strong>
The mechanism to add two values is typically 'take two, unwrap, add, wrap, return'.</p>
<pre><code>public static T operator +(SIQuantity<T> r1, SIQuantity<T> r2)
{
var v1 = r1.SIValue; // unwrap
var v2 = r2.SIValue;
var sum = v1 + v2; // add
var wrap = r1.CreateFromSI(sum); // wrap
return wrap; // return
}
</code></pre>
<p>I find it ugly.<br>
The first thing is that each of the based class must define the method CreateFromSI. I tried to find a way to do it all in the abstract class, but since I can't define a constructor or something like that in the abstract class, I have used the kind of factory pattern to build the object.<br>
Can I do it in a better way? </p>
<p>In a more general way, have I reinvented the wheel? I search a lot on something similar already existing, but I find nothing.<br>
I use this code a lot, lot, and lot. It makes my life sooooo much easier. I don't fight anymore, all my algorithm is type safe, I'm confident on the unit of the physical values I use, I unwrap the values when it's time to really use them, like this little method :</p>
<pre><code>public static Power operator *(Force force, Speed speed)
{
return Power.FromWatt(force.Newton * speed.MeterPerSecond);
}
[TestMethod]
public void TestMethod1()
{
// 10000W = 1000N * 10m/s
Assert.AreEqual(Power.FromKilowatt(10), Force.FromDecanewton(100) * 36.KilometersPerHour());
}
</code></pre>
<p>I use it so often that I must be sure it is perfect. So I definitely need a code review!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T16:09:22.730",
"Id": "38050",
"Score": "3",
"body": "Have you looked at F#? It deals with things like units as well as values, and is [ideal for physics type applications](http://stackoverflow.com/questions/167909/is-f-suitable-for-physics-applications)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T17:59:19.070",
"Id": "38056",
"Score": "1",
"body": "What stops you from mixing up the units? For example, it seems incorrect code like `Speed.FromMeterPerSecond(force.Newton * speed.MeterPerSecond)` would work. I think it's not terrible to allow something like this, but it should not be the normal way you do calculations, if you're striving for compiler-enforced safety."
}
] |
[
{
"body": "<p>The main issue in your code is that you don't control proper combination of units in operations, e.g. you allow summing up speeds with kilograms. </p>\n\n<p>I would rather create a class (or maybe better a struct?) that is aware of unit types as well, and create a number of static/extension methods/operator overloads to convert the value from different units...</p>\n\n<p>Example out of my head (not tested since don't have VS at hand):</p>\n\n<pre><code>public struct Unit\n{\n public sbyte Meters {get; private set}\n public sbyte Kilograms {get; private set}\n public sbyte Seconds {get; private set}\n public sbyte Amperes {get; private set}\n public sbyte Kelvins {get; private set}\n public sbyte Candelas {get; private set}\n public sbyte Moles {get; private set}\n\n public Unit(sbyte meters = 0, sbyte kilograms = 0, sbyte seconds = 0,\n sbyte amperes = 0, sbyte kelvins = 0, sbyte candelas = 0, sbyte moles = 0)\n {\n Meters = meters;\n Kilograms = kilograms;\n Seconds = seconds;\n Amperes = amperes;\n Kelvins = kelvins;\n Candelas = candelas;\n Moles = moles;\n }\n\n //TODO: add operators that combine different units by adding corresponding units. It can be implemented via sbyte[] but I find it more readable if implemented as separate properties. Since it has to be implemented once in this struct it should not be a big deal.\n\n //TODO: you can override ToString and output readable derived SI units like hertz/newton/joule/pascal instead of combination of base units...\n\n //TODO: Add static methods to define common base/derived units, e.g.:\n public static Unit Speed()\n {\n return new Unit(meters = 1, seconds = -1);\n }\n\n public static Unit Newton()\n {\n return new Unit(kilograms = 1, meters = 1, seconds = -2);\n }\n}\n\npublic struct UnitValue\n{\n public double Value {get; private set}\n public Unit Unit {get; private set}\n\n public UnitValue(double value, Unit unit)\n {\n Value = value;\n Unit = unit;\n }\n\n //TODO: overload operators so that they allow summing up unit values with equal units only, and \"sum\" units in case of multiplication.\n\n //TODO: add static methods to define unit values from non-standard units, e.g.:\n public static UnitValue FromKilometersPerHour(double value)\n {\n return new UnitValue(value / 3.6, Unit.Speed());\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T12:58:50.727",
"Id": "38175",
"Score": "0",
"body": "Surely you're failing to take into account the type constraint when you say \"e.g. you allow summing up speeds with kilograms\"? Personally I'd make the f-bound explicit, but as long as in practice the subclasses use themselves as their type arguments the only way to add a speed to a mass is with explicit use of the `SIValue` property and a constructor."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T22:24:52.153",
"Id": "24654",
"ParentId": "24623",
"Score": "2"
}
},
{
"body": "<p>This seems overly complicated. You should only use one unit system in all your code. If some input values use some different units, convert them as soon as you read them. (I assume those input values are taken from some outside source; if there is no input from an outside source, you should keep everything in the same unit system to start with.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-01T12:08:12.717",
"Id": "32066",
"ParentId": "24623",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T08:27:35.390",
"Id": "24623",
"Score": "4",
"Tags": [
"c#",
".net",
"design-patterns"
],
"Title": "Encapsulated double for type safety"
}
|
24623
|
<p>It doesn't happen often, but I sometimes come across cases where I miss Java's checked exceptions, especially in medium sized methods of about 30 odd lines that call outward. Often, the following pattern emerges:</p>
<pre><code>bool Foo(){
LibType l1 = new LibType("bla");
LibType2 smt = l1.bar("context");
...
...
}
</code></pre>
<p>and I want to know when which part of the function has thrown an exception. I know that the external library Lib exposes LibException, and that l1.bar should throw that in some case. But I have no language level guarantees. What I would like is </p>
<pre><code>bool Foo(){
try {
LibType l1 = new LibType("bla");
LibType2 smt = l1.bar("context");
...
...
...
return true;
} catch (LibException le){
//take appropriate action by flogging the library
//log that the exception has occurred in Lib while trying to Foo.
return false;
}
}
</code></pre>
<p>but I can't be sure there will not be any other exceptions. In fact, this doesn't even compile, as not all code paths return a value, so I will have to catch a more generic Exception, which could have come from any part off the method.</p>
<p>What I have done, is create a wrapper function, to ensure that all exceptions will be LibExceptions:</p>
<pre><code>private T Wrapped<T, E>(Func<Exception, E> buildException, Func<T> f) where E : Exception {
try { return f(); }
catch (E) {
throw;
}
catch (Exception ee) {
throw (buildException(ee));
}
}
</code></pre>
<p>so I can now be ensured a block can only throw the wrapping exception by wrapping it like so</p>
<pre><code>bool Foo(){
try {
LibType2 smt = Wrapped(e => new LibException(String.Format("Unexpected exception: {0}", e.Message)), () => {
LibType l1 = new LibType("bla");
return l1.bar("context");
});
...
...
...
return true;
} catch (LibException le){
//take appropriate action by flogging the library
//log that the exception has occurred in Lib while trying to Foo.
return false;
}
}
</code></pre>
<p>I see smells aplenty though, and I am bending stuff in ways I get the feeling it wasn't designed to bend. Is this basically OK? are there things to be on the lookout for? Or is this one off those <code>stop trying to be clever, and slowly back away from the computer</code> moments?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T18:01:44.690",
"Id": "38057",
"Score": "3",
"body": "“this doesn't even compile, as not all code paths return a value” That's not true, the code you posted should compile just fine."
}
] |
[
{
"body": "<p>I really don't see any advantage in your approach.</p>\n\n<p>If you want to catch specific exception from a specific part of the code, do that:</p>\n\n<pre><code>bool Foo(){\n try {\n LibType l1 = new LibType(\"bla\");\n LibType2 smt = l1.bar(\"context\");\n } catch (LibException le){\n //take appropriate action by flogging the library\n //log that the exception has occurred in Lib while trying to Foo.\n return false;\n } \n ...\n ...\n ...\n return true;\n}\n</code></pre>\n\n<p>When a piece of code encounters an exception you didn't expect, it's usually not a good idea to try to handle it anyway. Unexpected exception means your program is now in an unknown, possibly horribly broken state. The safe thing in that case is to crash the application.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T18:10:53.530",
"Id": "24647",
"ParentId": "24624",
"Score": "6"
}
},
{
"body": "<p>You can get some of the help Java checked exceptions give you by using Resharper and a <a href=\"http://exceptionalplugin.codeplex.com/\" rel=\"nofollow\">plugin called Exceptional</a>.</p>\n\n<p>It analyzes the XML docs and is able to add catch blocks for each documented exception.\nYou'll have to build it yourself though, it's not very well maintained. (You'll even have to grab a fork)</p>\n\n<p>That being said, to be able to clean up, I'd rather just catch <code>Exception</code> in addition to LibException. Other exceptions <em>are</em> exceptions, and should be thrown so you can fix the problem rather than cure the symptom.</p>\n\n<pre><code>try\n{\n // whatever\n}\ncatch(LibException)\n{\n // do LibException specific stuff\n // clean up\n}\ncatch\n{\n // clean up\n throw; // crash the system, you shouldn't get this exception in the next version\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T18:35:47.310",
"Id": "38115",
"Score": "1",
"body": "If you want to do some cleanup, use `finally`, not `catch` with `throw;` inside it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T12:37:39.637",
"Id": "38235",
"Score": "0",
"body": "As far as I understood, he'd like to clean up attempted stuff if something went wrong, not if it succeeded. Finally would for instance dispose any unmanaged resources.\n(Of course he could benefit from using transactions, but that's another topic)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T13:53:22.840",
"Id": "24664",
"ParentId": "24624",
"Score": "0"
}
},
{
"body": "<p>Just to build on what @svick said, this is definitely not a good way to handle things.</p>\n\n<p>If you want to catch all exceptions, simply <code>catch (Exception ex)</code>. If you don't want to catch everything, then only catch the specific types you want. There's also the <code>finally</code> block which you can use to do any cleanup which is necessary, regardless of whether or not you've handled the exception. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T14:24:23.410",
"Id": "24666",
"ParentId": "24624",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24647",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T08:48:30.970",
"Id": "24624",
"Score": "4",
"Tags": [
"c#",
"exception-handling"
],
"Title": "Wrapping Exceptions"
}
|
24624
|
<p>The code below is for testing Primes.</p>
<pre><code>testPrime(100000);
testPrime(1000000);
testPrime(10000000);
testPrime(100000000);
</code></pre>
<p>Now my goal is to make the code super fast at finding prime number, min-max, close prime.
Are there any improvements that can be done to the code below to improve the speed for <code>IsPrime</code>?</p>
<pre><code>import java.util.ArrayList;
import java.math.*;
class Primes {
private static long[] as = {2, 7, 61};
private static long modpow(long x, long c, long m) {
long result = 1;
long aktpot = x;
while (c > 0) {
if (c % 2 == 1) {
result = (result * aktpot) % m;
}
aktpot = (aktpot * aktpot) % m;
c /= 2;
}
return result;
}
private static boolean millerRabin(long n) {
outer:
for (long a : as) {
if (a < n) {
long s = 0;
long d = n - 1;
while (d % 2 == 0) {
s++;
d /= 2;
}
long x = modpow(a, d, n);
if (x != 1 && x != n - 1) {
for (long r = 1; r < s; r++) {
x = (x * x) % n;
if (x == 1) {
return false;
}
if (x == n - 1) {
continue outer;
}
}
return false;
}
}
}
return true;
}
public static boolean IsPrime(long num) {
if (num <= 1) {
return false;
} else if (num <= 3) {
return true;
} else if (num % 2 == 0) {
return false;
} else {
return millerRabin(num);
}
}
public static int[] primes(int min, int max) {
ArrayList<Integer> primesList = new ArrayList<Integer>();
for( int i=min; i<max; i++ ){
if( IsPrime(i) ){
primesList.add(i);
}
}
int[] primesArray = new int[primesList.size()];
for(int i=0; i<primesArray.length; i++){
primesArray[i] = (int) primesList.get(i);
}
return primesArray;
}
public static String tostring (int [] arr){
String ans="";
for (int i=0; i<arr.length;i++){
ans= ans+arr[i]+ " ";
}
return ans;
}
public static int closestPrime(int num) {
int count=1;
for (int i=num;;i++){
int plus=num+count, minus=num-count;
if (IsPrime(minus)){
return minus;
}
if (IsPrime(plus)) {
return plus;
}
count=count+1;
}
}
}
//end class
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T13:16:16.163",
"Id": "38039",
"Score": "0",
"body": "Profile it and look where you spent most of the time. I would expect the modpow function., which is not that easy to further optimize."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T06:28:02.153",
"Id": "50607",
"Score": "0",
"body": "perhaps `if (a < n) { continue;}` is better no jump to end of if statement before going to loop, but it would depends on compiler clerverness"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-29T03:42:17.760",
"Id": "104721",
"Score": "0",
"body": "Is `c % 2 == 1` in Java guaranteed to optimize down to the same as `c & 1 == 0`? The reason I ask is because the type of `c` is `long`, which is *signed*, so this might force the JVM to use an actual divide-by-2-and-get-remainder operation rather than simply a boolean 'and' operation to extract the least-significant bit. If so, the speed difference is likely to be very minimal, but it still might be worth profiling things to check. Also, `c /= 2` could be written as `c >>>= 1`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-29T03:56:08.670",
"Id": "104723",
"Score": "0",
"body": "By the way, since this is a code review question, I would suggest a comment pointing the reader to http://en.wikipedia.org/wiki/Miller_rabin or some such page explaining where the list `{ 2, 7, 61 }` comes from, and what the limitations are on your input."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-14T00:27:12.500",
"Id": "164486",
"Score": "1",
"body": "@ToddLehman I'm sure Java optimizes the division by 2 even for signed operands, [but it's slower](http://stackoverflow.com/a/21617265/581205). Together with the zero test it could be optimized without the adjustment, but I don't know i it happens."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-11T16:27:47.560",
"Id": "408670",
"Score": "0",
"body": "When i try to run the code, `isPrime()` doesnt work for `long`. Does anybody have same problem?"
}
] |
[
{
"body": "<p>You could use the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow\">Sieve of Eratosthenes</a> for numbers less than 10 million (you are only going up to 100 million).</p>\n\n<p>I think that checking the low bit <code>(num & 1) == 0</code> is quicker than checking the remainder <code>num % 2 == 0</code>. Similarly, bit shifting is quicker for division or multiplication by 2: <code>d /= 2</code> could be <code>d >> 1</code>.</p>\n\n<p>You might experiment with doing an initial check for division by a few low primes (3, 5, 7, 11) in your IsPrime method and see if that makes a difference.</p>\n\n<p>Finally, for your \"random\" numbers, you might want to choose products of primes, e.g. 3*5*7*11*13..., or maybe that plus 1. Maybe that's crazy. But some \"random\" numbers might provide richer test cases than others, and cause a faster elimination of non-primes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T12:01:06.657",
"Id": "24633",
"ParentId": "24625",
"Score": "4"
}
},
{
"body": "<ul>\n<li><code>if i<2</code> (one test <) is better than is <code>if i<=1</code> (= test and < test) </li>\n<li>change <code>String ans=\"\";</code> in <code>StringBuilder ans=new StringBuilder();</code> </li>\n<li>change <code>for (int i=0; i<arr.length;i++){</code> in <code>for (int i=0,n=arr.length;i<n;i++){</code></li>\n<li>read Joshua Blosh \"Effective Java\" book</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T13:28:59.037",
"Id": "50636",
"Score": "2",
"body": "\"`if i<2` (one test `<`) is better than is `if i<=1` (`=` test and `<` test)\" AFAIK this is completely false. `<=` does **not** need to perform two comparisons, it will simply call a different conditional jump instruction at the machine level, which uses a *slightly* different circuit which takes *exactly* the same time to perform the comparison(keep in mind that if the difference in timing is too small then it's like if it were 0 since pipelines compute in steps of `clock_time/pipeline_steps` seconds."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T13:40:32.410",
"Id": "50640",
"Score": "0",
"body": "@Bakuriu ok! (I've not look how my Java's compiler do with <=) I was told about this optimization with Sybase requester."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-14T00:22:58.073",
"Id": "164485",
"Score": "0",
"body": "Forget about points 1 and 3. These are valid just for dumb compilers, Java can optimize such low level stuff itself."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-24T06:36:18.660",
"Id": "31715",
"ParentId": "24625",
"Score": "0"
}
},
{
"body": "<p>Several improvements: Consider that the test \"if (p % 3 == 0)...\" will identify 33.3% of all numbers as composite. If Miller-Rabin takes longer than three times to test whether p % 3 == 0, adding that test makes the code run faster on average. Same obviously with p % 5 == 0 and so on. You should probably check directly at least up to 100 or so. </p>\n\n<p>For a 32 bit number, you'll do about 32 squaring operations modulo p. However, you can probably do at least four by just accessing a table. For example, when a = 2 any power up to 31 can be taken from a table. That saves probably 10% or more of the work. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-23T15:41:50.407",
"Id": "45145",
"ParentId": "24625",
"Score": "2"
}
},
{
"body": "<p>Java already has <a href=\"http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#isProbablePrime(int)\" rel=\"nofollow noreferrer\"><code>BigInteger.isProbablePrime(int certainty)</code></a> and <a href=\"http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#nextProbablePrime()\" rel=\"nofollow noreferrer\"><code>BigInteger.nextProbablePrime()</code></a>. (There is no method to get the previous probable prime, though, so you'll need to get creative.)</p>\n\n<p>That said, your Miller-Rabin implementation works remarkably quickly and accurately. Testing numbers up to 100 million, I found that it is 100% accurate in that range. To achieve 100% accuracy in that range with <code>BigInteger.isProbablePrime()</code>, you would need a <code>certainty</code> parameter of at least 9.</p>\n\n<p>To obtain a list of primes within a range, you would be better off with the Sieve of Eratosthenes. For comparison, I tried generating a list of primes up to 100 million with three methods:</p>\n\n<ul>\n<li>Sieve of Eratosthenes (using <a href=\"https://codereview.stackexchange.com/a/45152/9357\">@JavaDeveloper's implementation with bugfixes</a>): 3 seconds</li>\n<li>Your <code>primes()</code> function: 37 seconds</li>\n<li>Testing <code>BigInteger.valueOf(i).isProbablePrime(9)</code> for <code>i</code> up to 100 million: ≈ 4 minutes</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-14T00:17:31.500",
"Id": "164484",
"Score": "0",
"body": "It's [provably 100% accurate](http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test#Deterministic_variants_of_the_test) for numbers below 4,759,123,141. But sadly (**as nobody noticed**) it's totally broken for big numbers due to overflow."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-23T19:03:43.727",
"Id": "45153",
"ParentId": "24625",
"Score": "3"
}
},
{
"body": "<p>In your <code>millerRabin()</code> function, the calculation of <code>s</code> and <code>d</code> can be factored out of the loop, as they only depend on <code>n</code>, not <code>a</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-23T19:05:00.790",
"Id": "45154",
"ParentId": "24625",
"Score": "3"
}
},
{
"body": "<p>Sadly nobody noticed that the whole computation is broken for big numbers due to overflow in</p>\n\n<pre><code>private static long modpow(long x, long c, long m) {\n ...\n result = (result * aktpot) % m;\n ...\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>private static boolean millerRabin(long n) {\n ...\n x = (x * x) % n;\n ...\n}\n</code></pre>\n\n<p>I'd suggest changing the signature of</p>\n\n<pre><code>public static boolean IsPrime(long num)\n</code></pre>\n\n<p>to accept <code>int</code> only. And obviously changing the name to <code>isPrime</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-14T00:20:55.380",
"Id": "90699",
"ParentId": "24625",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T09:15:43.543",
"Id": "24625",
"Score": "3",
"Tags": [
"java",
"performance",
"primes"
],
"Title": "Miller-Rabin Prime test (Speed is the main goal)"
}
|
24625
|
<p>I want to create a file consisting <code>take</code> rows of distinct numbers in ascending order. They are randomly taken from the first <code>total</code> integer. The file will be used to make an excerpt as discussed <a href="https://tex.stackexchange.com/q/106456/19356">here</a>.</p>
<p>I realize that my naming convention for identifiers below is not good but please ignore it for the sake of simplicity.</p>
<pre><code>using System;
using System.IO;
using System.Linq;
namespace Karls.Students.Excerpting
{
class Program
{
static void Main(string[] args)
{
int total = int.Parse(args[0]);
int take = int.Parse(args[1]);
int seeder = int.Parse(args[2]);
string filename = args[3];
int[] array = Enumerable.Range(1, total).ToArray();
Random random = new Random(seeder);
for (int i = total - 1; i > 0; i--)
{
int j = random.Next(i+1);
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
File.WriteAllLines(filename, array.Take(take).OrderBy(x => x).Select(x => x.ToString()));
}
}
}
</code></pre>
<p>With best practice in mind, is there anything "bad" in my code?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T11:18:53.153",
"Id": "38030",
"Score": "0",
"body": "In other words: How to make an array (of type `int` with length `m`) containing distinct, ascending ordered numbers in a set of the first `n` **positive** integers (`n>m`)? The difference between two consecutive elements in the array in question must be a random number (not necessarily distinct)."
}
] |
[
{
"body": "<p>With out commenting on the business logic (the class assignment) I would say this about the coding standard as a whole.</p>\n\n<p>My opionion is:\nYou are writing very c style. \nInstead think of C# as oo</p>\n\n<p>So\nSmaller functions, this make it very obvious to anyone reading it whats going on with out trying to understand the actually code. Easier to read = easier to maintain and extend project later on..</p>\n\n<p>Your primary function (usually the public method) should read like an english book. </p>\n\n<p>Also you should check as soon as posible for negetive cases, in theory on top of the function. This helps nesting and mid code aborts.</p>\n\n<p>So with a quick style rewrite (sorry not going to touch the business) something like:</p>\n\n<pre><code>namespace Karls.Students.Excerpting\n{\n class Program\n {\n static void Main(string[] args)\n {\n var commandLineArgs = new CommandLineArgs(args);\n\n var array = CreatePlaceHolderStorage(commandLineArgs.Total);\n\n Randomize(commandLineArgs.Seeder, array);\n\n WriteListToFile(array, commandLineArgs.Filename, commandLineArgs.Take);\n }\n\n private static void Randomize(int seed, int[] array)\n {\n var random = new Random(seed);\n for (int i = array.Count() - 1; i > 0; i--)\n {\n int j = random.Next(i + 1);\n int temp = array[i];\n array[i] = array[j];\n array[j] = temp;\n }\n }\n\n private static int[] CreatePlaceHolderStorage(int total)\n {\n return Enumerable.Range(1, total).ToArray();\n }\n\n\n private static void WriteListToFile(IEnumerable<int> listToPrint, string filename, int sizeToTake)\n {\n File.WriteAllLines(filename, listToPrint.Take(sizeToTake).OrderBy(x => x).Select(x => x.ToString()));\n }\n}\n\npublic class CommandLineArgs\n{\n public int Total { get; set; }\n public int Take { get; set; }\n public int Seeder { get; set; }\n public string Filename { get; set; }\n\n public CommandLineArgs(string[] args)\n {\n Total = int.Parse(args[0]);\n Take = int.Parse(args[1]);\n Seeder = int.Parse(args[2]);\n Filename = args[3];\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T11:57:55.940",
"Id": "24632",
"ParentId": "24627",
"Score": "2"
}
},
{
"body": "<p>Instead of shuffling items yourselves it's easier to apply random sort. So your logic can be rewritten in a single statement:</p>\n\n<pre><code>var random = new Random();\n\nvar result = Enumerable.Range(1, total)\n .OrderBy(i => random.Next())\n .Take(take)\n .OrderBy(i => i);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T09:04:01.410",
"Id": "38161",
"Score": "0",
"body": "I'm ordering by random value, not selecting random values. `OrderBy(i => random.Next())` just assigns a random \"weight\" to each number in sequence 1..total and reorders them correspondingly. The output will correspond to your requirements, `take` unique elements in range 1..total in ascending order. Before -1'ing the answer please try to understand it first."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T09:15:07.707",
"Id": "38162",
"Score": "0",
"body": "What algorithm is used in random sort? fisher-yates shuffle?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T09:42:30.587",
"Id": "38164",
"Score": "0",
"body": "Fisher-Yates shuffle is the one you've specified in your code. The one I specified is another commonly used shuffling method with uniform distribution, usually called as \"random sort\"."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T08:38:20.940",
"Id": "24698",
"ParentId": "24627",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "24698",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T10:00:33.353",
"Id": "24627",
"Score": "0",
"Tags": [
"c#",
"optimization",
"algorithm",
"random"
],
"Title": "How to take the some elements of a list of random numbers and sort them?"
}
|
24627
|
<p>I have to write a program that changes a string's vowels, consonants and other symbols into C, V respectively 0. I've done this but I wonder if there is a more efficient and elegant way to do it. Would appreciate input.</p>
<pre><code>(defun string-to-list (string)
(loop for char across string collect char))
(defun is-vowel (char) (find char "aeiou" :test #'char-equal))
(defun is-consonant (char) (find char "bcdfghjklmnpqrstvwxyz" :test #'char-equal))
(defun letter-type (char)
(if (is-vowel char) "V"
(if (is-consonant char) "C"
"0")))
(defun analyze-word (word-string)
(loop for char across word-string collect (letter-type char)))
</code></pre>
<p>Moreover, I would like to make it a string, how could I do that? Should I define a function that would iterate through the list and make it a string or is it an easier way to do it?</p>
<p>I've got it, for the ones interested, the code is below. Used map to do it.</p>
<pre><code>(defun string-to-list (string)
(loop for char across string collect char))
(defun is-vowel (char) (find char "aeiou" :test #'char-equal))
(defun is-consonant (char) (find char "bcdfghjklmnpqrstvwxyz" :test #'char-equal))
(defun analyze_word (word-string)
(loop for char across word-string collect (letter-type char)))
(defun letter-type (char)
(cond ((find char "aeiou" :test #'char-equal) #\V)
((alpha-char-p char) #\C)
(t #\0)))
(defun change_string (string)
(map 'string #'letter-type "analyze-word")
)
</code></pre>
|
[] |
[
{
"body": "<p>First, <a href=\"http://dept-info.labri.u-bordeaux.fr/~idurand/enseignement/PFS/Common/Strandh-Tutorial/indentation.html\" rel=\"nofollow\">proper indentation</a> helps a lot. I do appreciate you not putting the closing parens on separate lines though. Thank you.</p>\n\n<pre><code>(defun string-to-list (string)\n (loop for char across string collect char))\n\n(defun is-vowel (char) (find char \"aeiou\" :test #'char-equal))\n\n(defun is-consonant (char) (find char \"bcdfghjklmnpqrstvwxyz\" :test #'char-equal))\n\n(defun letter-type (char)\n (if (is-vowel char) \"V\"\n (if (is-consonant char) \"C\"\n \"0\")))\n\n(defun analyze-word (word-string)\n (loop for char across word-string collect (letter-type char)))\n</code></pre>\n\n<hr>\n\n<p>We're talking about Common Lisp, so there's no call to go defining your own <code>string-to-list</code>, especially if you're doing it in terms of <code>loop</code>. You can do the same thing with a <code>coerce</code> call.</p>\n\n<pre><code>CL-USER> (coerce \"an example\" 'list)\n(#\\a #\\n #\\ #\\e #\\x #\\a #\\m #\\p #\\l #\\e)\n</code></pre>\n\n<p>Though now that I look at it, you don't call <code>string-to-list</code> anywhere anyway, so we may as well just remove the definition.</p>\n\n<pre><code>(defun is-vowel (char) (find char \"aeiou\" :test #'char-equal))\n\n(defun is-consonant (char) (find char \"bcdfghjklmnpqrstvwxyz\" :test #'char-equal))\n\n(defun letter-type (char)\n (if (is-vowel char) \"V\"\n (if (is-consonant char) \"C\"\n \"0\")))\n\n(defun analyze-word (word-string)\n (loop for char across word-string collect (letter-type char)))\n</code></pre>\n\n<hr>\n\n<p>Common Lisp convention is to use a suffix of <code>p</code> or <code>-p</code> for predicates, rather than an <code>is</code> prefix.</p>\n\n<pre><code>(defun vowel-p (char) (find char \"aeiou\" :test #'char-equal))\n\n(defun consonant-p (char) (find char \"bcdfghjklmnpqrstvwxyz\" :test #'char-equal))\n\n(defun letter-type (char)\n (if (vowel-p char) \"V\"\n (if (consonant-p char) \"C\"\n \"0\")))\n</code></pre>\n\n<hr>\n\n<p>You can use <code>cond</code> rather than chaining <code>if</code>s. Typically, this makes the intent clearer.</p>\n\n<pre><code>(defun letter-type (char)\n (cond ((vowel-p char) \"V\")\n ((consonant-p char) \"C\")\n (t \"O\")))\n</code></pre>\n\n<hr>\n\n<p>If you want to make the result of <code>analyze-word</code> a string, you'll need to return a character rather than a string from <code>letter-type</code></p>\n\n<pre><code>(defun letter-type (char)\n (cond ((vowel-p char) #\\V)\n ((consonant-p char) #\\C)\n (t #\\O)))\n</code></pre>\n\n<p>At that point, you can <code>coerce</code> its result.</p>\n\n<pre><code>CL-USER> (coerce (analyze-word \"supercalifragilistiwhateverthefuck\") 'string)\n\"CVCVCCVCVCCVCVCVCCVCCVCVCVCCCVCVCC\"\n</code></pre>\n\n<hr>\n\n<p>Since your function is taking a sequence of characters, and returning a sequence of characters in the same form, it's actually easier to define <code>analyze-word</code> in terms of <code>map</code> than in terms of <code>loop</code> (in my experience, this is atypical but still worth looking out for).</p>\n\n<pre><code>(defun analyze-word (word-string)\n (map 'string #'letter-type word-string))\n</code></pre>\n\n<p>That will take \"the function named <code>letter-type</code>\", apply it to each element of <code>word-string</code> and return the resulting <code>string</code>. This also saves you from having to coerce its result after the fact.</p>\n\n<pre><code>CL-USER> (analyze-word \"supercalifragilistiwhateverthefuck\")\n\"CVCVCCVCVCCVCVCVCCVCCVCVCVCCCVCVCC\"\n</code></pre>\n\n<p>Take this last point with a grain of salt though, because if you ever need to re-write <code>analyze-word</code> to return something like <code>(list :consonants 21 :vowels 13)</code>, you'll be right back to <code>loop</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T14:52:39.010",
"Id": "24637",
"ParentId": "24634",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T13:24:08.427",
"Id": "24634",
"Score": "2",
"Tags": [
"strings",
"lisp",
"common-lisp"
],
"Title": "LISP - Modify string"
}
|
24634
|
<p>I have a dashboard like interface, that can have many tabs. There can be as many or as few tabs as the user likes, with the user being allowed to re order them as they wish. Exactly like browsers do.</p>
<p>My problem is moving the tabs position, for example, look at these tabs: </p>
<pre><code>[Sales] [Admin] [Finance] [Development]
</code></pre>
<p>If the user wants to move the <code>[Development]</code>(index 3) tag to be after <code>[Sales]</code>, giving it a new index of 1, how should I bump Finance and Development along to 2 and 3 respectively?</p>
<p>I am using JSON to store it so <code>data.dashboard[0].sequence</code> merely means the sequence value for the first dashboard.</p>
<p>At the moment I am using the following bit of code, which seems a bit hacky and not as efficient as it could be. The function is called with the start index(3 in this case) and the desired or end index (1 in this case). I've tried my best to explain with the comments, but feel free to ask anything you don't understand:</p>
<pre><code>function changeSequence(start, end){
var newVal = 999;
for(d=0;d<data.dashboards.length;d++){
if(data.dashboards[d].sequence == start){ // set [Development] to 999 temporarily
data.dashboards[d].sequence = newVal;
}
}
if(start > end){
for(i=start; i>end; i--){
var d = i;
d--;
for(j=0;j<data.dashboards.length;j++){ // if [Development] (index3) is after
if(data.dashboards[j].sequence == d){ // [Admin] (index1), bump indexes
data.dashboards[j].sequence = i; // 1 and 2 along one (to 2 and 3)
}
}
}
} else {
for(i=start; i<end; i++){
var d = i;
d++;
for(j=0;j<data.dashboards.length;j++){ // else if [Development] (index3) is
if(data.dashboards[j].sequence == d){ // before [Admin] (index1), which it
data.dashboards[j].sequence = i; // isn't in this case, bump them all
} // down one
}
}
}
for(d=0;d<data.dashboards.length;d++){
if(data.dashboards[d].sequence == newVal){ // then set [Development]'s new
data.dashboards[d].sequence = end; // index to what its meant to be
}
}
}
</code></pre>
<p>This code works, but I feel like I've gone the long way and simply going from</p>
<pre><code>[Sales] [Admin] [Finance] [Development]
</code></pre>
<p>to</p>
<pre><code>[Sales] [Development] [Admin] [Finance]
</code></pre>
<p>Should be that hard</p>
<p>Edit: Still learning, so even unrelated ways to improve my code would be great</p>
|
[] |
[
{
"body": "<p>Fundamentally, you should probably use the array's own ordering. It'd remove the need for a <code>sequence</code> number that you manually have to track and update. Instead, you can simply pluck index 3 out of the array, and splice it in at index 1, and not worry about sequence numbers at all.</p>\n\n<p>But if you can't/won't get the <code>data.dashboards</code> array to behave like that, you can take a detour.</p>\n\n<p>Now, I highly, <em>highly</em> doubt this is the most efficient way of doing things - it's certainly not elegant - but it's straightforward to follow.</p>\n\n<p>Say you have this:</p>\n\n<pre><code>var data = {\n dashboards: [ // random ordering\n {name: \"Development\", sequence: 3},\n {name: \"Sales\", sequence: 0},\n {name: \"Finance\", sequence: 2},\n {name: \"Admin\", sequence: 1}\n ]\n};\n</code></pre>\n\n<p>Get everything sorted first:</p>\n\n<pre><code>var sorted = data.dashboards.sort(function(a, b) {\n return a.sequence - b.sequence;\n});\n</code></pre>\n\n<p>So now we have an array where the objects are ordered according to their sequence</p>\n\n<pre><code>seq | name\n------------------\n0 | Sales\n1 | Admin\n2 | Finance\n3 | Development\n</code></pre>\n\n<p>Then, if we can assume that the sequence numbers are indeed sequential with no gaps or repeats, we could (again) just splice & splice to get the right order.<br>\nBut let's say we can be sure that index equals sequence number. In that case, loop until we find it, pluck it, and reinsert it:</p>\n\n<pre><code>var currSequence = 3, // the target's current number\n newSequence = 1, // the target's desired number\n dashboard;\n\n// find and move the target\nfor( var i = 0, l = sorted.length ; i < l ; i++ ) {\n if( sorted[i].sequence === currSequence ) {\n dashboard = sorted[i];\n sorted.splice(i, 1); // remove the target\n sorted.splice(newSequence, 0, dashboard); // re-insert it at its new position\n break;\n }\n}\n</code></pre>\n\n<p>Now, we have the right order, but not the right sequence numbers:</p>\n\n<pre><code>seq | name\n------------------\n0 | Sales\n3 | Development\n1 | Admin\n2 | Finance \n</code></pre>\n\n<p>Finally, reset the sequence numbers</p>\n\n<pre><code>for( i = 0, l = sorted.length ; i < l ; i++ ) {\n sorted[i].sequence = i;\n}\n</code></pre>\n\n<p>And we get</p>\n\n<pre><code>seq | name\n------------------\n0 | Sales\n1 | Development\n2 | Admin\n3 | Finance\n</code></pre>\n\n<p>Neatly sequential numbering and ordering, regardless of the original array's order and sequence values. The original <code>data.dashboards</code> array is still in the same scrambled order as before, but the sequence number of each object is now correct.</p>\n\n<p>Here a <a href=\"http://jsfiddle.net/77fDL/\" rel=\"nofollow\">jsfiddle</a></p>\n\n<hr>\n\n<p>Actually, here's a simpler one that I believe works in all cases, regardless of array ordering, as long as the sequence numbers are sequential already:</p>\n\n<pre><code>var currSequence = 3, // the target's current number\n newSequence = 1, // the target's desired number\n correction = currSequence > newSequence ? 1 : -1,\n lower = Math.min(currSequence, newSequence),\n upper = Math.max(currSequence, newSequence),\n dashboard;\n\nfor( var i = 0, l = data.dashboards.length ; i < l ; i++ ) {\n dashboard = data.dashboards[i];\n if( dashboard.sequence == currSequence ) {\n dashboard.sequence = newSequence;\n } else if( dashboard.sequence >= lower && dashboard.sequence <= upper ) {\n dashboard.sequence += correction;\n }\n}\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/77fDL/1/\" rel=\"nofollow\">Here's a demo</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T08:00:40.933",
"Id": "38073",
"Score": "0",
"body": "Thanks for the reply, I can see you went to a lot of effort. The only issue I can is that you order the tabs then reset the sequence numbers. There was something I didn't mention, `data.dashboards[i]` also contains a `charts[]` property that contains data to generate charts specific to that tab, so unless I am mistaken, those charts would get shuffled around and placed on the wrong tabs, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T08:52:19.280",
"Id": "38079",
"Score": "0",
"body": "Nevermind, I've used your later, simpler one and that works just as my current code works, yet obviously a lot cleaner. Thanks a lot! :) My only question is why `var i = 0, l = data.dashboards.length ; i < l ;` instead of `i=0;i<data.dashboards.length;`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T09:10:01.103",
"Id": "38081",
"Score": "0",
"body": "@Andy Not sure I understand your first question (not that it matters now). Anyway, the `var i = 0, l = data.dashboards.length` is a habit of mine. Getting the length once and storing it as `l` is faster, because the loop can do the `i < l` comparison on each iteration, instead of getting the array's `length` each time. Getting `length` is slower, since `length` is calculated when you ask for it. Of course, _it doesn't matter at all_ for a small array like this. For large arrays, it'll help, though. I just always do it out of habit. Good practice, but unnecessary in this case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T09:12:28.217",
"Id": "38082",
"Score": "0",
"body": "Yeah don't worry about the first question. I'll stick to the shorter code inside the loop purely because there can never be more than 10 dashboards, so you're right it won't affect performance. Though I will definitely keep that in mind for the future. Thanks for all the help."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T19:12:34.560",
"Id": "24649",
"ParentId": "24640",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24649",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T16:35:36.093",
"Id": "24640",
"Score": "2",
"Tags": [
"javascript",
"array",
"json"
],
"Title": "Most efficient way to insert into ordered sequence"
}
|
24640
|
<p>I wrote a simple program to remove duplicates from a String without using additional buffer.</p>
<p>The program should filter the duplicates and return just the unique string.</p>
<p>Example:</p>
<blockquote>
<p><strong>Input:</strong><br>
FOOOOOOOOLLLLLOWWWWWWWWWW UUUUP</p>
<p><strong>Output:</strong><br>
FOLW UP</p>
</blockquote>
<p>I just want to know if the below solution is a good solution for my problem statement.</p>
<pre><code>public class compareString {
public static void main(String args[]) {
removeDuplicateString("FOOOOOOOOLLLLLOWWWWWWWWWW UUUUP");
}
public static void removeDuplicateString(String input) {
String value1 = input;
String value2 = input;
String finalValue = "";
int count = 0;
char char1;
char char2 = 0;
for (int i = 0; i < value1.length(); i++) {
flag = 0;
char1 = value1.charAt(i);
for (int j = 0; j < value2.length(); j++) {
char2 = value2.charAt(j);
if (char1 == char2) {
count++;
}
}
if (count > 1) {
finalValue=finalValue+char1;
i=i+(count-1);
} else {
finalValue = finalValue + char1;
}
count = 0;
}
System.out.println(finalValue);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Thats not working. Try the input: <code>abaa</code> (result: <code>aa</code>)</p>\n\n<p>I do not know what you mean with \"without using additional buffer\", because finalValue is at least an additional buffer (which is kind of necessary. You could create a view, but this will be a bit complex).</p>\n\n<p>An easier approach would be to create a LinkedHastSet. Insert all characters, output the set, done:</p>\n\n<pre><code>public static void removeDuplicateString2(final String input) {\n final Set<Character> set = new LinkedHashSet<>();\n for (int i = 0; i < input.length(); i++)\n set.add(input.charAt(i));\n final StringBuilder stringBuilder = new StringBuilder(set.size());\n for (final Character character : set)\n stringBuilder.append(character);\n System.out.println(stringBuilder);\n}\n</code></pre>\n\n<hr>\n\n<p>About your code:</p>\n\n<pre><code>removeDuplicateString\n</code></pre>\n\n<p>I would call it something like removeMultipleOccurrence</p>\n\n<hr>\n\n<pre><code>String finalValue = \"\";\n</code></pre>\n\n<p>You may use a <code>StringBuilder</code> to reduce string concatenations.</p>\n\n<hr>\n\n<pre><code> String value1 = input;\n String value2 = input;\n</code></pre>\n\n<p>You do not need these variables, just use input instead of value1/2</p>\n\n<hr>\n\n<pre><code> int count = 0;\n char char1;\n char char2 = 0;\n</code></pre>\n\n<p>You do not need char2, and you can put the rest inside the loop to the initializing place.</p>\n\n<hr>\n\n<pre><code> flag = 0;\n</code></pre>\n\n<p>This variable is not defined. </p>\n\n<hr>\n\n<pre><code> if (count > 1) {\n finalValue=finalValue+char1;\n i=i+(count-1);\n } else {\n finalValue = finalValue + char1;\n }\n</code></pre>\n\n<p>You may move the finalValue line from the if/else. Then you can skip the else part, because it is empty.</p>\n\n<hr>\n\n<p>If you combine everything, you could have:</p>\n\n<pre><code>public static void removeMultipleOccurrence(final String input) {\n StringBuilder result = new StringBuilder();\n for (int i = 0; i < input.length(); i++) {\n int count = 0;\n final char char1 = input.charAt(i);\n for (int j = 0; j < input.length(); j++) {\n if (char1 == input.charAt(j)) {\n count++;\n }\n }\n\n if (count > 1)\n i = i + (count - 1);\n result.append(char1);\n }\n System.out.println(result);\n}\n</code></pre>\n\n<p>Hint: This is still not working, just doing the same in a more clear way.<br>\nIf you want to do it in your way, you have to search the string before the current position if you have already the current char.</p>\n\n<p>This could be done in this way:</p>\n\n<pre><code>public static void removeMultipleOccurrence(final String input) {\n String finalValue = \"\";\n for (int i = 0; i < input.length(); i++) {\n int count = 0;\n final char currentChar = input.charAt(i);\n for (int j = 0; j < i; j++) {\n if (currentChar == input.charAt(j)) {\n ++count;\n }\n }\n\n if (!(count > 0))\n finalValue = finalValue + currentChar;\n }\n System.out.println(finalValue);\n}\n</code></pre>\n\n<p>If we look at the count, it is just a boolean, so we end up with:</p>\n\n<pre><code>public static void removeMultipleOccurrence(final String input) {\n final StringBuilder result = new StringBuilder();\n for (int i = 0; i < input.length(); i++) {\n boolean alreadySeen = false;\n final char currentChar = input.charAt(i);\n for (int j = 0; j < i; j++) {\n if (currentChar == input.charAt(j)) {\n alreadySeen = true;\n break;\n }\n }\n\n if (!alreadySeen)\n result.append(currentChar);\n }\n System.out.println(result);\n}\n</code></pre>\n\n<p>We could get rid of the boolean now:</p>\n\n<pre><code>public static void removeMultipleOccurrence(final String input) {\n final StringBuilder result = new StringBuilder();\n withNextChar: for (int i = 0; i < input.length(); i++) {\n final char currentChar = input.charAt(i);\n for (int j = 0; j < i; j++) {\n if (currentChar == input.charAt(j))\n continue withNextChar;\n }\n result.append(currentChar);\n }\n System.out.println(result);\n}\n</code></pre>\n\n<p>Or, we could look in the result, if we have it already:</p>\n\n<pre><code>public static void removeMultipleOccurrence(final String input) {\n final StringBuilder result = new StringBuilder();\n for (int i = 0; i < input.length(); i++) {\n String currentChar = input.substring(i, i + 1);\n if (result.indexOf(currentChar) < 0) //if not contained\n result.append(currentChar);\n }\n System.out.println(result);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T18:04:29.380",
"Id": "24644",
"ParentId": "24641",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "24644",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T17:05:03.213",
"Id": "24641",
"Score": "4",
"Tags": [
"java",
"strings"
],
"Title": "Remove duplicates from string without using additional buffer"
}
|
24641
|
<p>I've constructed a simple class whose entire purpose is to hash passwords securely and simply.</p>
<p>The catch is the PHP version is probably going to be 5.2.x. This means:</p>
<ul>
<li>No <code>CRYPT_BLOWFISH</code></li>
<li>Obviously no <code>password_hash()</code>.</li>
</ul>
<p>The question is, is the following secure? Can it be improved?</p>
<pre><code>/**
* Class Hasher
*
* @package Dependencies\Hasher
*
* Defines hashing mechanism for password saving.
*/
class Hasher {
/**
* @param string $string String for hashing
* @param string $salt Unique salt. The salt is best kept as a very long, very random string.
* @param int $cost Cost parameter. 2^$cost iterations over the hashing algorithm.
*
* @return string
*/
public function algo($string, $salt, $cost) {
$iterations = pow(2, $cost);
$result = "";
for ($i = 0; $i < $iterations; $i++) {
$result = sha1($result . $salt . $string);
}
return $result;
}
/**
* Pass a password through the hashing algorithm. And return the result.
*
* @param string $password
* @param string $salt
* @param int $cost
*
* @return string
*/
public final function hash($password, $salt, $cost = 10) {
return $this->algo($password, $salt, $cost);
}
/**
* Match password through the hashing algorithm against an existing hash to make sure there's a match.
*
* @param string $hash
* @param string $password
* @param string $salt
* @param int $cost
*
* @return bool
*/
public final function verify($hash, $password, $salt, $cost = 10) {
return $this->algo($password, $salt, $cost) == $hash;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Just use PHPass when your PHP version is too low for the native password API instead of trying to roll your own implementation.</p>\n\n<p><a href=\"http://www.openwall.com/phpass/\" rel=\"nofollow\">http://www.openwall.com/phpass/</a></p>\n\n<p><sub><sub>Although you should <strong>really</strong> update your PHP version, but you already know that.</sub></sub></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T18:13:08.163",
"Id": "38058",
"Score": "4",
"body": "You know me. If I had a choice, I'd update."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T18:08:49.227",
"Id": "24645",
"ParentId": "24643",
"Score": "4"
}
},
{
"body": "<p>There are several improvements to this that involve various algorithms that are more cryptographically secure than sha1 (such as sha256 or higher, blowfish, whirlpool, etc.), using strict comparison (to avoid that gotcha with very long hashes loosely comparing when not equal), and including a <a href=\"https://en.wikipedia.org/wiki/CSPRNG\" rel=\"nofollow\">CSPRNG</a> salting function in the class, that takes over when a user does not supply a salt.</p>\n\n<p>However, <code>CRYPT_BLOWFISH</code> is still very usable in PHP < 5.3. In fact, It's usable in PHP 3.0.18 and over, with the use of <a href=\"http://www.openwall.com/phpass/\" rel=\"nofollow\">PHPass</a>, by the same security company who make <a href=\"http://www.openwall.com/john/\" rel=\"nofollow\">John the Ripper</a> (which you should be using to test your class. Try and get the <a href=\"https://dazzlepod.com/uniqpass/\" rel=\"nofollow\">UNIQPASS</a> wordlist. It's really effective!). An alternative to JtR is <a href=\"http://hashcat.net/oclhashcat-plus/\" rel=\"nofollow\">hashcat</a>. There are several defcon talks about correct usage of password crackers to test strength (by the feds), among other uses (by the non-feds).</p>\n\n<p>If you really must roll your own, then consider implementing <a href=\"https://en.wikipedia.org/wiki/Blowfish_%28cipher%29\" rel=\"nofollow\">blowfish manually</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T18:09:27.553",
"Id": "24646",
"ParentId": "24643",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "24646",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T17:34:17.270",
"Id": "24643",
"Score": "3",
"Tags": [
"php",
"security"
],
"Title": "Hasher class for PHP<5.3"
}
|
24643
|
<p>I have made a class to import into my projects to more easily handle the state of the keyboard so I can use stuff like:</p>
<pre><code>if(Keys.returnKey(37)){
</code></pre>
<p>As opposed to setting up key listeners.</p>
<p>Please give this code a general review:</p>
<pre><code>/*
ALWAYS DO THIS FIRST:
Keys.init(stage);
THEN YOU CAN DO THESE:
Keys.returnKey(5);
Keys.returnArray(37,38,39,40);
Keys.returnLastKeyPressed(37,38,39,40);
*/
package{
import flash.events.KeyboardEvent;
import flash.display.DisplayObjectContainer;
public class Keys{
private static var _key_arr:Array=[];
// Contains boolean values for each keycode
private static var _last_key:int=0;
// Last key pressed
private static var _last_valid_key:int=0;
// Last valid key pressed
// PUBLIC FUNCTIONS:
public static function init(STAGE:DisplayObjectContainer){
// Prepares class for use, call this once before you start using the other functions
for (var i=0; i<222; i++){
_key_arr[_key_arr.length]=false;
}
STAGE.addEventListener(KeyboardEvent.KEY_DOWN, keyD);
STAGE.addEventListener(KeyboardEvent.KEY_UP, keyU);
}
public static function returnKey(INDEX:int):Boolean{
// Returns a single value from _key_arr at the index of INDEX
return _key_arr[INDEX]
}
public static function returnArray(... args):Array{
// Returns values from _key_arr to the locations passed as the parameter(s)
var returnMe:Array=[]
for (var i=0; i<args.length; i++){
returnMe[i]=_key_arr[args[i]];
//Extracts the values of the keys passed in as args from the key array.
}
return returnMe;
}
public static function returnLastKeyPressed(... args):int{
// Returns the keyCode of the key most recently depressed
if(args.indexOf(_last_key)!=-1){
_last_valid_key=_last_key;
}
return _last_valid_key
}
// PRIVATE FUNCTIONS:
private static function keyD(event:KeyboardEvent){
// Sets the pressed key's value to true and sets the last key pressed
_key_arr[event.keyCode]=true;
_last_key=event.keyCode;
}
private static function keyU(event:KeyboardEvent){
// Sets the pressed key's value to false
_key_arr[event.keyCode]=false;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Looking at it from a general perspective...</p>\n\n<p>Put your comments that describe functions in javadoc-style outside your functions. Comment blocks before functions are a common format when it comes to describing a function. Because it's at the same indentation level as the function, it can't be mistaken as a comment about a specific section of your function.</p>\n\n<p>Additionally, end each statement with a semicolon. Even when it's not required, for some people it's just as annoying as not ending your sentences with a period. More importantly, by putting the semicolon there, you state that the statement is finished. Right now, it looks like you wanted to say more... but forgot and moved on. Your code then feels unfinished.</p>\n\n<p>Looking at it from a performance perspective... (since it's tagged as such)</p>\n\n<p>From the <a href=\"http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Vector.html\">official documentation</a>, it states that:</p>\n\n<blockquote>\n <p>As a result of its restrictions, a Vector has three primary benefits over an Array instance whose elements are all instances of a single class:</p>\n \n <p>Performance: array element access and iteration are much faster when using a Vector instance than they are when using an Array.</p>\n \n <p>Type safety: in strict mode the compiler can identify data type errors. Examples of data type errors include assigning a value of the incorrect data type to a Vector or expecting the wrong data type when reading a value from a Vector. Note, however, that when using the push() method or unshift() method to add values to a Vector, the arguments' data types are not checked at compile time. Instead, they are checked at run time.</p>\n \n <p>Reliability: runtime range checking (or fixed-length checking) increases reliability significantly over Arrays.</p>\n</blockquote>\n\n<p>The trade-offs for this are that you need to use a sequential set of indices and that you must contain a single type.</p>\n\n<pre><code>for (var i=0; i<222; i++){\n _key_arr[_key_arr.length]=false;\n}\n</code></pre>\n\n<p>But that's what you're doing anyway, so you could just use a vector. That should give it a speed up. Let's look at some more things.</p>\n\n<pre><code> public static function returnArray(... args):Array{\n // Returns values from _key_arr to the locations passed as the parameter(s)\n\n var returnMe:Array=[]\n\n for (var i=0; i<args.length; i++){\n returnMe[i]=_key_arr[args[i]];\n //Extracts the values of the keys passed in as args from the key array.\n }\n\n return returnMe;\n }\n</code></pre>\n\n<p><code>args.length</code> triggers a recalculation of the length of the array. This is unneeded if the array's length doesn't change.\nThus, I prefer to write the following (and it's a standard I follow when writing my own for loops, unless I'm toying with the index or the array's length):</p>\n\n<pre><code>for(var i:uint = 0, isize:uint = args.length; i < isize; i++){\n returnMe[i]=_key_arr[args[i]];\n}\n</code></pre>\n\n<p>This tends to be faster. Of note here are two things. </p>\n\n<p>Namely that </p>\n\n<ol>\n<li>I define <code>isize</code> as the length of the array</li>\n<li>I use <code>uint</code>.</li>\n</ol>\n\n<p>You are not using arrays that will reach the size of <code>MAX_INT</code>, thus there is no reason to use int. <code>args.length</code> returns an <code>uint</code>, and there is a performance penalty for comparing int with uint, compared to comparing uint with uint (because it has to convert it first).</p>\n\n<p>Moving on...</p>\n\n<p>The <a href=\"http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/KeyboardEvent.html#keyCode\">official documentation</a> for <code>KeyboardEvent.keyCode</code> states (and so should your IDE) that its datatype is <code>uint</code>. So make your <code>_last_key</code> and <code>_last_valid_key</code> of datatype <code>uint</code>, as they can't hold negative values anyway. Alternatively, initialize them to -1 to indicate that no keys have been pressed yet.</p>\n\n<p>Additionally, since a vector (you're gonna make your <code>_key_arr</code> a vector, right?) can't have negative indices, alter <code>public static function returnKey(INDEX:int):Boolean</code> to require a <code>uint</code> as well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-22T19:40:24.080",
"Id": "57725",
"ParentId": "24655",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T22:35:17.403",
"Id": "24655",
"Score": "10",
"Tags": [
"performance",
"classes",
"api",
"actionscript-3"
],
"Title": "Key Press Handler"
}
|
24655
|
<p>I'm implementing a login system on app engine (I have to, so please don't tell me to use the User service, or an other way to delegate authentication), and I'm wondering whether this setup is secure.</p>
<pre><code>from pbkdf2 import PBKDF2
import os
salt = os.urandom(8)
password = PBKDF2(passphrase, salt).read(32).encode("hex")
</code></pre>
<p>Would this be a secure way to store passwords?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T09:17:18.293",
"Id": "38163",
"Score": "2",
"body": "If you're building something to last, it's also worth asking: what do I do if this ceases to be secure? PBKDF2, like bcrypt etc., has a difficulty parameter; it would be advisable to pass an explicit parameter (even if it is the same as the default values), and to store that parameter in the database. E.g. `password = '1000:' + PBKDF2(passphrase, salt, 1000).read(32).encode('hex')`. That way you can increase the difficulty parameter as computers get faster and upgrade old users' hashes when they log in."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-07T12:22:32.260",
"Id": "51682",
"Score": "0",
"body": "THX, I ADDED THAT"
}
] |
[
{
"body": "<p>Pretty much, yes. PBKDF2 is a well-established algorithm, and <code>os.urandom</code> is a suitable <a href=\"http://en.wikipedia.org/wiki/CSPRNG\" rel=\"nofollow\"><code>CSPRNG</code></a> that can be used in salt generation on all major platforms (patched, of course).</p>\n\n<p>Your implementation is also brutally simple. The simpler a system, the more secure it can be. Needless complexity leads to insecurities.</p>\n\n<p>So yes, the system is secure, but it is also subject to Moore's law, just like every other computer system or piece of software. To get around this, the number of rounds (iterations) in strong encryption algorithms is a variable taken into account.</p>\n\n<p>In bcrypt, for example, the number of rounds is <code>2^workload</code> (default 12), and in PBKDF2 the number of rounds is an int passed to the function. Beware that if you need to use a Cython interface, your password hashing is a strongly blocking call (this has bitten me before)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T09:16:18.670",
"Id": "24659",
"ParentId": "24657",
"Score": "5"
}
},
{
"body": "<ol>\n<li>The salt should be the same size as the hash.</li>\n<li>As noted by the other answers, always pass in the work units parameter so that you can upgrade the strength of the key stretching over time.</li>\n<li>When you compare hashes during authentication, use a constant time algorithm.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T17:08:37.743",
"Id": "86386",
"Score": "0",
"body": "Why was this downvoted? If something is wrong with the answer, say so in a comment so it can be corrected."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-06T20:25:45.287",
"Id": "32344",
"ParentId": "24657",
"Score": "0"
}
},
{
"body": "<p>Another consideration is that it is becoming better practice to iteratively generate the hash. (Of course, this is only useful if the hashing algorithm isn't a set, but they tend not to be.)</p>\n\n<p>The purpose of this is to hash the hash multiple (say 100) times. This can dramatically increase the amount of time required to break the hashes should they be compromised. Additionally, a precomputed table of hashes becomes really prohibitive since you are no longer dealing simply with a salted hash of a known algorithm.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-06T21:16:47.933",
"Id": "32347",
"ParentId": "24657",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T07:57:31.510",
"Id": "24657",
"Score": "4",
"Tags": [
"python",
"security",
"cryptography"
],
"Title": "Is this a secure way to hash a password?"
}
|
24657
|
<p>I've never done Java GUI's before. After much trouble I've gotten my GUI to look how I want, however it feels as if my code is very inefficient, as if I'm going about this the wrong way?</p>
<pre><code> //main panels
private JPanel westPanel = new JPanel(new BorderLayout());
private JPanel eastPanel = new JPanel(new BorderLayout());
//door panels
private JPanel doorsPanel = new JPanel(new BorderLayout());
private JPanel doorsGrid = new JPanel(new GridBagLayout());
private JPanel doorButtons = new JPanel(new FlowLayout());
//light panels
private JPanel lightsPanel = new JPanel(new BorderLayout());
private JPanel lightsGrid = new JPanel(new GridBagLayout());
private JPanel lightTimerGrid = new JPanel(new GridBagLayout());
private JPanel lightButtons = new JPanel(new FlowLayout());
//list panels
private JPanel listPanel = new JPanel(new BorderLayout());
private JPanel listButtons = new JPanel(new GridBagLayout());
private JLabel itemDesc = new JLabel("Item Name - Item Price");
private JLabel totalPrice = new JLabel("Total Price: ");
doorsPanel.setBorder(BorderFactory.createTitledBorder("Manage Doors: "));
doorsPanel.add(doorsGrid, BorderLayout.NORTH);
doorsPanel.add(doorButtons, BorderLayout.SOUTH);
lightsPanel.setBorder(BorderFactory.createTitledBorder("Manage Lights: "));
lightsPanel.add(lightsGrid, BorderLayout.NORTH);
lightsPanel.add(lightButtons, BorderLayout.SOUTH);
lightsPanel.add(lightTimerGrid, BorderLayout.CENTER);
listPanel.setBorder(BorderFactory.createTitledBorder("Manage Shopping List: "));
listPanel.add(listButtons, BorderLayout.EAST);
westPanel.add(doorsPanel, BorderLayout.NORTH);
westPanel.add(lightsPanel, BorderLayout.CENTER);
eastPanel.add(listPanel, BorderLayout.SOUTH);
add(westPanel, BorderLayout.WEST);
add(eastPanel, BorderLayout.EAST);
</code></pre>
<p><img src="https://i.stack.imgur.com/AEpbO.png" alt="Current GUI layout"></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T21:34:29.320",
"Id": "38088",
"Score": "4",
"body": "What's wrong with your code? It seems OK to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T21:39:47.930",
"Id": "38089",
"Score": "2",
"body": "If it looks like you want it, it should be ok. I like the design..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T21:40:45.513",
"Id": "38090",
"Score": "5",
"body": "Gui layouts almost always take a large amount of code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T21:50:01.357",
"Id": "38091",
"Score": "2",
"body": "I would split the different parts into separate classes (at least three: Doors, Lights, and Shopping List), and a top class that contain these classes. Also if this is your first UI (not just Java UI) I would read a bit about the MVC pattern."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T11:21:16.957",
"Id": "38092",
"Score": "0",
"body": "to expand on the comment by @osundblad Doors, Lights and ShoppingList might be Observer's."
}
] |
[
{
"body": "<p>Your code seems perfectly fine!</p>\n\n<p>However...</p>\n\n<p>If all of this code is in the same block (e.g., a constructor or a layout builder method), I would recommend that you break up the layout code into smaller functions. That will improve readability and code structure a bit.</p>\n\n<p>Also, you should definately familiarize yourself with some GUI builders for Java (in my case it was WindowBuilder for Eclipse). Writing layout code by hand can be a pain and a source of bugs that you won't be able to resolve easily.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T10:35:02.620",
"Id": "27588",
"ParentId": "24660",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T21:30:00.607",
"Id": "24660",
"Score": "4",
"Tags": [
"java",
"swing",
"user-interface"
],
"Title": "Java/Swing GUI code/layout, am I doing this wrong?"
}
|
24660
|
<p>I am new to C++ and am looking to expand my knowledge. Below is a simple program that I've made. I would like to know how it could be improved, in any way. The introduction of new ways to do things is what I am looking for. These could be anything from improving efficiency to validating input - just whatever you think is most important or beneficial.</p>
<pre><code>float calculate(float x, char y, float z) {
float answer;
switch (y) {
case '+':
answer = x + z;
break;
case '-':
answer = x - z;
break;
case '/':
answer = x / z;
break;
case '*':
answer = x * z;
break;
default:
return(0);
}
cout <<"= "; return answer;
}
int main() {
float num1;
float num2;
char aOp;
cout << ">> ";
cin >> num1 >> aOp >> num2;
cout << calculate(num1, aOp, num2) << endl << endl;
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p><strong>Headers</strong>. Did you leave out the includes and function prototype at the top for simplicity or something? If not, you need to put them here otherwise your program will not compile.</p></li>\n<li><p><strong>Function-returning and displaying</strong>. The last statement in your function along with the printing of the function's return value in <code>main()</code> <em>will</em> work, but it's not a good way to write it.</p>\n\n<p>Instead, move the <code>cout <<\"= \";</code> from your function (just keep <code>return answer;</code>) to your <code>std::cout</code> statement in <code>main()</code>.</p></li>\n<li><p><strong>Function arguments/parameters</strong>. You may want to keep like-types together for clarity and so that you don't mismatch them, which would cause bugs. Whichever order is easiest to remember.</p>\n\n<p>For instance, consider these:</p>\n\n<pre><code>calculate(num1, num2, aOp); // function call\ncalculate(float x, float y, char z) {} // function definition\n</code></pre></li>\n<li><p><strong>Early return in <code>switch</code></strong>. Instead of having a local variable to update and return at the end, you could instead return from the respective <code>case</code>:</p>\n\n<pre><code>switch (y) {\n case '+': return x + z;\n case '-': return x - z;\n case '/': return x / z;\n case '*': return x * z;\n default: std::logic_error(\"invalid operator\"); // from <stdexcept>\n}\n</code></pre>\n\n<p>Notice this <code>default</code> statement. If the user enters an invalid operator, but no input validation was done beforehand, and exception will be thrown. Overall, it's best to have a useful <code>default</code>, and this is one example.</p></li>\n<li><p>You should also make sure the user isn't dividing by 0. If so, don't let the calculation take place, otherwise there will be problem. For such a case, you can just terminate from <code>main()</code> early:</p>\n\n<pre><code>if (num2 == 0 && aOp == '/')\n{\n std::cout << \"You cannot divide by 0! Terminating...\";\n return EXIT_FAILURE;\n}\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T14:43:47.320",
"Id": "24668",
"ParentId": "24663",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "24668",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T13:47:29.833",
"Id": "24663",
"Score": "6",
"Tags": [
"c++",
"beginner",
"calculator"
],
"Title": "Four-function calculator design"
}
|
24663
|
<p>I am bashing my head against how to solve this puzzle. Is there any super SQL expert out there who can lend some help</p>
<p>I have a database with the following structure.</p>
<pre><code>adjlevel | scheme | holder | client | companyID | Rate
</code></pre>
<p>A rate can be held in this table based on either of the following keys</p>
<pre><code>level + companyId + scheme + holder + client
</code></pre>
<p>OR </p>
<pre><code>level + companyId + scheme + holder
</code></pre>
<p>OR </p>
<pre><code>level + companyId + scheme
</code></pre>
<p>OR </p>
<pre><code>level + companyId
</code></pre>
<p>There will always be one record per level. Therefore I need to write a query that looks at all the above criteria starting with the most filters first and eliminating one criteria at a time until I find the required record.</p>
<p>I have written a function to do the above but it is very slow.</p>
<pre><code>ALTER FUNCTION [dbo].[Hourly_Rate]
(
-- Add the parameters for the function here
@ncompanyid numeric(2),
@client varchar(100),
@scheme varchar(100),
@holder varchar(100),
@nadjlevel numeric(3),
@date_done datetime
)
RETURNS Numeric(5)
AS
BEGIN
DECLARE @cmode varchar(1),
@level numeric(1),
@counter numeric(1),
@retval Numeric(5)
set @cmode = 'T'
set @level = 1 -- @level controls which filter to apply
set @counter = 1 -- @counter = loop counter
WHILE @counter <= 9
BEGIN
SELECT @retval = bhrlyrate FROM [MYDATABASE].dbo.inv_hrrate WHERE
adjlevel = @nadjlevel
and cmode = @cmode
and companyid = @ncompanyid
and client = case when @level <= 3 THEN @client ELSE '' END
and scheme = case when @level <= 2 THEN @scheme ELSE '' END
and holder = case when @level <= 1 THEN @holder ELSE '' END
and dworkedfrom <= case when @date_done = '30 december 1899' then dworkedfrom ELSE @date_done END
and dworkedto >= case when @date_done = '30 december 1899' then dworkedto ELSE @date_done END
IF @@rowcount > 0 -- Break if record found
BREAK;
IF @level = 4
-- T search mode unsuccessful change to A mode,
-- Reassign a few variables
--- and continue searching
BEGIN
SET @cmode = 'A'
SET @level = 0
set @date_done = '30 december 1899'
END
S ET @counter = @counter + 1
SET @level = @level + 1
END
-- If record is not in hourly rate table then pick default rate from company
IF @counter = 8 and @retval = 0
SELECT @retval = CO.hrly_rate FROM company CO WHERE companyid =
@ncompanyid;
RETURN @retval
END
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T14:51:46.193",
"Id": "38099",
"Score": "0",
"body": "Define: \"super slow\"."
}
] |
[
{
"body": "<p>I would pull all the possible rates and just sort by the most specific.</p>\n\n<pre><code>SELECT @retval = bhrlyrate FROM [MYDATABASE].dbo.inv_hrrate WHERE \nadjlevel = @nadjlevel \nand cmode = @cmode\nand companyid = @ncompanyid \nand (client = @client or client = '')\nand (holder = @holder OR (holder = '' AND client = ''))\nand (scheme = @scheme or (scheme = '' AND holder = '' AND client = ''))\nand dworkedfrom <= case when @date_done = '30 december 1899' then dworkedfrom ELSE @date_done END\nand dworkedto >= case when @date_done = '30 december 1899' then dworkedto ELSE @date_done END\nORDER BY scheme DESC, holder DESC, client DESC \n</code></pre>\n\n<p>That would eliminate some of the looping and requerying you are doing. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T08:03:29.620",
"Id": "38157",
"Score": "0",
"body": "Just one more thing. Is there any way you can select the top record from the resulting set if multiple rows are returned."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T19:04:03.480",
"Id": "38194",
"Score": "0",
"body": "Yes. Use the TOP specifier. `SELECT TOP 1 ...` http://msdn.microsoft.com/en-us/library/ms189463.aspx"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T17:50:39.303",
"Id": "24674",
"ParentId": "24667",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24674",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T14:26:46.077",
"Id": "24667",
"Score": "2",
"Tags": [
"sql"
],
"Title": "SQL Query based on results of preceding query"
}
|
24667
|
<p>Which is best practice for creating an enum-like lookup for templates? I enjoy being able to bring up my templates with VS IntelliSense so either works for me.</p>
<p>Option 1 (<code>enum</code>/<code>Dictionary</code> combo):</p>
<pre><code>public enum Template
{
AccountInformation = 1,
Registration = 2,
Signed = 3
}
static readonly IDictionary<Template, String> TemplateData = new Dictionary<Template, String>()
{
{Template.AccountInformation, "accountinfo.txt"},
{Template.Registration, "registration.txt"},
{Template.Signed, "signed.txt"}
};
</code></pre>
<p>Option 2 (<code>static</code> class):</p>
<pre><code>public static class Template
{
public static String AccountInformation = "accountinfo.txt";
public static String Registration = "registration.txt";
public static String Signed = "signed.txt";
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T16:29:15.733",
"Id": "38107",
"Score": "2",
"body": "Option #1, but make the declaration `static readonly IDictionary<>`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T16:46:01.053",
"Id": "38110",
"Score": "0",
"body": "I have fixed the declaration, this is the option I have initially chosen so it is good to know that I may have picked the correct one."
}
] |
[
{
"body": "<p>I think this depends on the logical meaning of the string.</p>\n\n<p>If there is a fixed number of valid values, then you should use your first option, use the enum almost everywhere, and convert to <code>string</code> using the dictionaly at the last possible place. (By “fixed” I mean that the string can have only a small fixed set of values in each version of the application, but the set of possible values may change between versions.)</p>\n\n<p>On the other hand, if the values represent some set of “usual” values, but other values are also a possibility (e.g. a user-specified file name), the I would use option 2.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T18:43:16.093",
"Id": "24678",
"ParentId": "24669",
"Score": "1"
}
},
{
"body": "<p>Try this:</p>\n\n<pre><code>public enum Template\n{\n [StringValue(\"accountinfo.txt\")]\n AccountInformation = 1,\n [StringValue(\"registration.txt\")]\n Registration = 2,\n [StringValue(\"signed.txt\")]\n Signed = 3\n}\n</code></pre>\n\n<p>For more information: <a href=\"http://www.codeproject.com/Articles/11130/String-Enumerations-in-C\" rel=\"nofollow\">String Enumerations in C#</a></p>\n\n<p>Otherwise, I prefer your second option.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-18T09:51:48.617",
"Id": "253148",
"Score": "0",
"body": "Additionally I find you should name the enum EmailTemplate and its values AccountInformationEmail or RegistrationEmail or SignedEmail."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-03T20:15:57.297",
"Id": "25784",
"ParentId": "24669",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "25784",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T16:00:44.173",
"Id": "24669",
"Score": "3",
"Tags": [
"c#",
"comparative-review"
],
"Title": "Email template referencer"
}
|
24669
|
<p>I have written a program that, given an amount, returns the interest you would receive on that figure. There are 3 interest rate bands as follows:</p>
<ul>
<li>1% - £0 to £1000</li>
<li>2% - £1000 to £5000</li>
<li>3% - £5000+</li>
</ul>
<p>Can anyone tell me if the following is a good solution or are the <code>if</code> statements too restrictive?</p>
<pre><code>public BigDecimal calc(BigDecimal amt) {
if(amt.compareTo(new BigDecimal(1001))==-1){
interest = amt.divide(new BigDecimal("100"));
}else if(amt.compareTo(new BigDecimal(5001))==-1){
interest = amt.multiply(0.02);
}else{
interest = amt.multiply(0.03);
}
return interest;
}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>are the 'if' statements too restrictive?</p>\n</blockquote>\n\n<p>I am not sure if the statements correspond the the given specification.\nYou have to clarify the corner cases. I would say, 1000.01 belongs to 2%.</p>\n\n<p>Rest is probably mostly fine, with some small problems:</p>\n\n<pre><code>public BigDecimal calc(BigDecimal amt) {\n</code></pre>\n\n<p>Do not use abbreviations. Could be amount or american totals, or whatever?</p>\n\n<hr>\n\n<pre><code>amt.compareTo(new BigDecimal(1001))==-1\n</code></pre>\n\n<p>Try to use the compareTo in this way: <code>x.compareTo(y) <relation> 0</code><br>\nWhere <code><relation></code> is one of <code>{<, <=, ==}</code> (you could use <code>{>=, >}</code>, too. But you can go without them if you rearrange the variables from the compareTo call)<br>\nDo not rely on -1 or +1. This is not necessarily the general contract.</p>\n\n<hr>\n\n<pre><code>amt.multiply(0.02)\n</code></pre>\n\n<p>There is no double argument method here. And even if, you should avoid float/double in any way if you handle concurrency because of rounding and representating errors.</p>\n\n<hr>\n\n<p>If you have only this small cases, I would use static constants (could be more difficult if you have more cases)</p>\n\n<p>All together, it could look like this:</p>\n\n<pre><code>private static BigDecimal ONE_PERCENT = new BigDecimal(\"0.01\");\nprivate static BigDecimal TWO_PERCENT = new BigDecimal(\"0.02\");\nprivate static BigDecimal THREE_PERCENT = new BigDecimal(\"0.03\");\nprivate static BigDecimal ONE_THOUSAND = new BigDecimal(\"1000\");\nprivate static BigDecimal FIVE_THOUSAND = new BigDecimal(\"5000\");\n\npublic BigDecimal calc(final BigDecimal amount) {\n //]-infinity, 0[\n if (amount.compareTo(BigDecimal.ZERO) < 0)\n return amount;\n // [0, 1000]\n else if (amount.compareTo(ONE_THOUSAND) <= 0)\n return amount.multiply(ONE_PERCENT);\n // ]1000, 5000]\n else if (amount.compareTo(FIVE_THOUSAND) <= 0)\n return amount.multiply(TWO_PERCENT);\n // ]5000, infinity[\n else\n return amount.multiply(THREE_PERCENT);\n}\n</code></pre>\n\n<p>If your specification says to 1000 means 1000 is not included, you can easily modify the <code><=</code> to <code><</code>. I have added the corresponding comments.</p>\n\n<p>Final word: Write some unit tests to test it. Especially the corner cases.</p>\n\n<hr>\n\n<p>In response to <a href=\"https://codereview.stackexchange.com/questions/24670/interest-calculator-design/24675?noredirect=1#comment38145_24675\">Interest calculator</a> :</p>\n\n<pre><code>private static BigDecimal ONE_PERCENT = new BigDecimal(\"0.01\");\nprivate static BigDecimal TWO_PERCENT = new BigDecimal(\"0.02\");\nprivate static BigDecimal TWO_POINT_FIVE_PERCENT = new BigDecimal(\"0.025\");\nprivate static BigDecimal THREE_PERCENT = new BigDecimal(\"0.03\");\nprivate static BigDecimal FOUR_PERCENT = new BigDecimal(\"0.04\");\nprivate static BigDecimal FIVE_PERCENT = new BigDecimal(\"0.05\");\nprivate static BigDecimal ONE_THOUSAND = new BigDecimal(\"1000\");\nprivate static BigDecimal FIVE_THOUSAND = new BigDecimal(\"5000\");\nprivate static BigDecimal TEN_THOUSAND = new BigDecimal(\"10000\");\n\npublic BigDecimal calc(final BigDecimal amount, final int years) {\n if (years < 0)\n throw new IllegalArgumentException(\"years can not be negative: \" + years);\n if (amount.compareTo(BigDecimal.ZERO) < 0)\n return BigDecimal.ZERO;\n switch (years) {\n case 0:\n if (amount.compareTo(ONE_THOUSAND) <= 0)\n return amount.multiply(ONE_PERCENT);\n else if (amount.compareTo(FIVE_THOUSAND) <= 0)\n return amount.multiply(TWO_PERCENT);\n else\n return amount.multiply(THREE_PERCENT);\n case 1:\n if (amount.compareTo(ONE_THOUSAND) <= 0)\n return amount.multiply(ONE_PERCENT);\n else if (amount.compareTo(FIVE_THOUSAND) <= 0)\n return amount.multiply(TWO_POINT_FIVE_PERCENT);\n else\n return amount.multiply(FOUR_PERCENT);\n case 2:\n default:\n if (amount.compareTo(ONE_THOUSAND) <= 0)\n return amount.multiply(TWO_PERCENT);\n else if (amount.compareTo(FIVE_THOUSAND) <= 0)\n return amount.multiply(THREE_PERCENT);\n else if (amount.compareTo(TEN_THOUSAND) <= 0)\n return amount.multiply(FOUR_PERCENT);\n else\n return amount.multiply(FIVE_PERCENT);\n }\n}\n</code></pre>\n\n<p>You could put every case in a separate method, this depends a bit on the number and complexity of cases.</p>\n\n<p>At some point, you will (should) use a database to do this. I assume, the numbers can be changed somewhere, then you will need them at some changeable place anyway. And a database is quite good in doing such range searches. (something like select percentage from table where year = and amount = (select max(amount) from table where < amount and year = order by amount desc))</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T19:07:58.710",
"Id": "38118",
"Score": "0",
"body": "Thanks. Would your design change if at a later date an additional band was added, e.g 6000+ is 8%?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T20:42:03.633",
"Id": "38141",
"Score": "0",
"body": "@heyya99 - Potentially, if you're going to keep adding bands, you want some sort of mapped setup where you can find the 'relevant' entry, then use that to find the relevant percentage. This can be done with two (sorted by amount!) arrays, and a binary search method (and comparator)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T20:55:17.653",
"Id": "38145",
"Score": "0",
"body": "What would the solution be if the follow was added? Customers who have been with the bank for over a certain amount of time will be offered a different set of rates. The new bands are as follows:\n\nAfter one year:\n\n1% - £0 to £1000\n2.5% - £1000 to £5000\n4% - £5000+\n\nAfter two years:\n\n2% - £0 to £1000\n3% - £1000 to £5000\n4% - £5000 to £10000\n5% - £10000+"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T11:43:37.213",
"Id": "38167",
"Score": "0",
"body": "I have modified my answer to reflect the comments. first question: yes, see answer from clockword-muse, too. This could be done with a database. Second question: this \"just\" creates one level more of branching."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-15T05:40:57.730",
"Id": "177307",
"Score": "0",
"body": "In reality, you would never define a constant as TWO_PERCENT or even as TWO. These would be TIER_1 , TIER_2 &c. Nor would they be constants as \"transfer pricing\" may dictate rates be set according to market, which could be twice a day. It would be a very special case of a 1 year fixed term deposit we are coding for here otherwise. But I suppose it needed to be a simple example and requirements may have been explicit. Beware of business analysts writing code."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T17:58:16.603",
"Id": "24675",
"ParentId": "24670",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T16:05:59.623",
"Id": "24670",
"Score": "1",
"Tags": [
"java",
"finance"
],
"Title": "Interest calculator"
}
|
24670
|
<p>I'm working on a project where I need to solve for one of the roots of a quartic polymonial many, many times. Is there a better, i.e., faster way to do this? Should I write my own C-library? The example code is below.</p>
<pre><code># this code calculates the pH of a solution as it is
# titrated with base and then plots it.
import numpy.polynomial.polynomial as poly
import numpy as np
import matplotlib.pyplot as plt
# my pH calculation function
# assume two distinct pKa's solution is a quartic equation
def pH(base, Facid1, Facid2):
ka1 = 2.479496e-6
ka2 = 1.87438e-9
kw = 1.019230e-14
a = 1
b = ka1+ka2+base
c = base*(ka1+ka2)-(ka1*Facid1+ka2*Facid2)+ka1*ka2-kw
d = ka1*ka2*(base-Facid1-Facid2)-kw*(ka1+ka2)
e = -kw*ka1*ka2
p = poly.Polynomial((e,d,c,b,a))
return -np.log10(p.roots()[3]) #only need the 4th root here
# Define the concentration parameters
Facid1 = 0.002
Facid2 = 0.001
Fbase = 0.005 #the maximum base addition
# Generate my vectors
x = np.linspace(0., Fbase, 200)
y = [pH(base, Facid1, Facid2) for base in x]
# Make the plot frame
fig = plt.figure()
ax = fig.add_subplot(111)
# Set the limits
ax.set_ylim(1, 14)
ax.set_xlim(np.min(x), np.max(x))
# Add my data
ax.plot(x, y, "r-") # Plot of the data use lines
#add title, axis titles, and legend
ax.set_title("Acid titration")
ax.set_xlabel("Moles NaOH")
ax.set_ylabel("pH")
#ax.legend(("y data"), loc='upper left')
plt.show()
</code></pre>
<p>Based on the answer, here is what I came up with. Any other suggestions?</p>
<pre><code># my pH calculation class
# assume two distinct pKa's solution is a quartic equation
class pH:
#things that don't change
ka1 = 2.479496e-6
ka2 = 1.87438e-9
kw = 1.019230e-14
kSum = ka1+ka2
kProd = ka1*ka2
e = -kw*kProd
#things that only depend on Facid1 and Facid2
def __init__(self, Facid1, Facid2):
self.c = -(self.ka1*Facid1+self.ka2*Facid2)+self.kProd-self.kw
self.d = self.kProd*(Facid1+Facid2)+self.kw*(self.kSum)
#only calculate things that depend on base
def pHCalc(self, base):
pMatrix = [[0, 0, 0, -self.e], #construct the companion matrix
[1, 0, 0, self.d-base*self.kProd],
[0, 1, 0, -(self.c+self.kSum*base)],
[0, 0, 1, -(self.kSum+base)]]
myVals = la.eigvals(pMatrix)
return -np.log10(np.max(myVals)) #need the one positive root
</code></pre>
|
[] |
[
{
"body": "<p>NumPy computes the roots of a polynomial by first constructing the companion matrix in Python and then solving the eigenvalues with LAPACK. The companion matrix case looks like this using your variables (as <code>a</code>==1):</p>\n\n<pre><code>[0 0 0 -e\n 1 0 0 -d\n 0 1 0 -c\n 0 0 1 -b]\n</code></pre>\n\n<p>You should be able to save some time by updating a matrix like this directly on each iteration of <code>base</code>. Then use <code>numpy.linalg.eigvals(m).max()</code> to obtain the largest eigenvalue. See <a href=\"https://github.com/numpy/numpy/blob/master/numpy/polynomial/polynomial.py#L1390\" rel=\"nofollow\">the sources</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T20:22:31.837",
"Id": "38140",
"Score": "0",
"body": "Yes, this works. I had already caught the need for a max(). I'm also thinking I could use a class construction to initialize some invariants, so I don't have to recalculate them each time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T21:33:50.927",
"Id": "38151",
"Score": "1",
"body": "Did some timing work with the full problem. Original code (using polynomial module) 5.48 sec, first step (using eigenvalue approach) 2.76 sec, final step (using eigenvalues and class as shown above) 2.68 sec."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T18:05:21.813",
"Id": "24676",
"ParentId": "24671",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "24676",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T16:26:46.280",
"Id": "24671",
"Score": "2",
"Tags": [
"python",
"numpy"
],
"Title": "Using numpy polynomial module - is there a better way?"
}
|
24671
|
<p>I have created the following stored procedure which duplicates a record in a table and also all its related records in other tables however since I am a newbie to SQL I would appreciate it if someone could review my code and show me how it could be improved and whether there are any hazards.</p>
<pre><code> USE [Neptune2Dev]
GO
/****** Object: StoredProcedure [dbo].[DuplicateItemInBatch] Script Date: 03/04/2013 17:55:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[DuplicateItemInBatch] @batchID AS INT , @numInBatch AS INT
AS
declare @itemIdToBeDuplicated as int
declare @duplicatedItemID as int
declare @URI as varchar(max)
declare @itemOrganisationID as int
declare @duplicateItemOrganisationID as int
BEGIN TRY
BEGIN TRANSACTION;
--increment all proceeding numbInbatch fileds to accomodiate the new item being duplicated
UPDATE items SET numinbatch = numinbatch + 1
WHERE numinbatch > @numInBatch AND BatchID = @batchID
select @itemIdToBeDuplicated = ID from items i where i.BatchID = @batchID and i.NumInBatch = @numInBatch
select @URI = URI from ItemMedia where ID = @itemIdToBeDuplicated
--duplicate the item and insert it into the table
insert into items
select
i.SupplierID, i.Title, i.PubDate, i.Body, i.StatusID,
i.IsRelevant, i.ClipDuration, i.ResearchDuration,
i.Comments, i.ItemTypeID, i.PageNumber, i.BatchID,
i.NumInBatch + 1, i.OverrideDate, i.MediaChannelID,
i.Size, i.PreviouslyCompleted
from items i where i.ID = @itemIdToBeDuplicated
select @duplicatedItemID = SCOPE_IDENTITY();
select @itemOrganisationID = ID from ItemOrganisations where ItemID = @itemIdToBeDuplicated
insert into ItemOrganisations
select @duplicatedItemID, OrganisationID, comment, rating from ItemOrganisations where ID = @itemOrganisationID
select @duplicateItemOrganisationID = SCOPE_IDENTITY();
insert into ItemOrganisationMessages
select @duplicateItemOrganisationID, MessageID from ItemOrganisationMessages where ItemOrganisationID = @itemOrganisationID
insert into ItemOrganisationIssues
select @duplicateItemOrganisationID, IssueID from ItemOrganisationIssues where ItemOrganisationID = @itemOrganisationID
insert into ItemByLines
select @duplicatedItemID, ByLineID from ItemByLines where ItemID = @itemIdToBeDuplicated
insert into ItemDocumentLink
select ItemDocumentID, @duplicatedItemID from ItemDocumentLink where ItemID = @itemIdToBeDuplicated
insert into ProfileResults
select ProfileId, @duplicatedItemID from ProfileResults where ItemID = @itemIdToBeDuplicated
insert into ItemNotes
select @duplicatedItemID,Quote,Theme,Rating,Comment,IsBad from ItemNotes where ItemID = @itemIdToBeDuplicated
IF @URI <> null
BEGIN
insert into ItemMedia values (@duplicatedItemID, @URI)
END
ELSE
PRINT N'No Article to be duplicated '
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
BEGIN
PRINT
ERROR_NUMBER() +' ' + ERROR_MESSAGE()
ROLLBACK TRANSACTION;
END;
END CATCH;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T20:58:30.167",
"Id": "38147",
"Score": "0",
"body": "Your comment for updating the `numInBatch` doesn't match (probably most) people's expectation for 'proceeding' (that is, that lower numbers come 'first'). Aside from that, you may have better luck by using float-point entries for sorting, because then you (usually) don't have to update _every_ row during re-orders - you just place it midway between the destination. Beyond that, **always** list the columns you're inserting into (re-creating the table may change column order). See if your version of SQL Server allows selections from inserts (data-change references)"
}
] |
[
{
"body": "<p>Here are some comments in no particular order:</p>\n\n<ul>\n<li>Your <code>CATCH</code> block - including comments - is a copy and paste from the <a href=\"http://msdn.microsoft.com/en-us/library/ms189797.aspx\" rel=\"nofollow noreferrer\">documentation</a>. While it's always good to read the documentation, please remember that the examples are there to illustrate specific features and you shouldn't assume that they're usable as-is in production code</li>\n<li>If an error occurs in the <code>TRY</code> block, your <code>CATCH</code> block commits if possible anyway, is this what you intended? <code>XACT_STATE()</code> tells you that the transaction <em>can</em> be committed, not that it <em>should</em> be. See <a href=\"https://stackoverflow.com/questions/2836082/why-would-you-commit-a-transaction-within-a-catch-clause\">this SO question</a> for more information.</li>\n<li>Your <code>CATCH</code> block doesn't examine or log the error message (using <a href=\"http://msdn.microsoft.com/en-us/library/ms175069.aspx\" rel=\"nofollow noreferrer\"><code>ERROR_NUMBER()</code></a> and similar functions), so if an error does occur you will have no idea what it was</li>\n<li>Always list all column names in an <code>INSERT</code>; this gives you some security if the table structure changes</li>\n<li>You <a href=\"http://msdn.microsoft.com/en-us/library/ms188795.aspx\" rel=\"nofollow noreferrer\">cannot compare</a> <code>NULL</code> values with the standard comparison operators, you need to write <code>IF @URI IS NULL</code> instead</li>\n<li><a href=\"http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/11/bad-habits-to-kick-avoiding-the-schema-prefix.aspx\" rel=\"nofollow noreferrer\">Always use schema names</a> to reference objects in code</li>\n<li>Using <code>BEGIN</code> and <code>END</code> to wrap the entire stored procedure body is not required but usually good practice, otherwise it's easy to forget where the procedure ends and accidentally add some code that you didn't mean to</li>\n<li>Most procedures should <a href=\"http://msdn.microsoft.com/en-us/library/ms189837.aspx\" rel=\"nofollow noreferrer\"><code>SET NOCOUNT ON</code></a> at the beginning</li>\n</ul>\n\n<p>And please <em>always</em> mention your SQL Server version (2005, 2008, 2008R2, 2012) and edition (Standard, Enterprise, Express) because that determines which language features are available.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T21:21:53.267",
"Id": "38202",
"Score": "0",
"body": "thanks for the reply, Ive edited the catch block, will this cause the transaction to roll back if there is an error?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T13:44:42.793",
"Id": "38243",
"Score": "0",
"body": "Yes, if the transaction can be rolled back (which was the point of using `XACT_STATE()`. But note that [not all errors can be caught](http://msdn.microsoft.com/en-us/library/ms175976.aspx)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T17:56:55.297",
"Id": "24720",
"ParentId": "24677",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "24720",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T18:34:29.977",
"Id": "24677",
"Score": "2",
"Tags": [
"sql",
"sql-server",
"t-sql"
],
"Title": "How can I improve the following stored procedure?"
}
|
24677
|
<p>This code seems to work, but I'd like someone with shell-fu to review it.</p>
<ul>
<li>Is the temp file a good idea? How would I do without?</li>
<li>Is sed the right tool?</li>
<li>Any other general advice for improving my shell script</li>
</ul>
<h1>Script/Code to Review:</h1>
<pre><code># Grab max field lengths from each .hbm.xml file and
# put them into the corresponding .java file
for myFile in $(find generatedSchema/myApp/db/ -name *.hbm.xml)
do
# Calculate the java file name
javaFile=${myFile/%\.hbm\.xml/.java}
echo $javaFile
# Find each field name and length and format it for the java file.
# Save result lines to temp.txt
sed -n '/<property name="[^"]\+" type="string">/{
N
s/ \+<property name="\([^"]\+\)" type="string">\n \+<column name="[^"]\+" length="\([0-9]\+\)".*/ @SuppressWarnings({"UnusedDeclaration"}) public static final int MAX_\1 = \2;/p}' $myFile >temp.txt
# Load results from temp file into a shell variable
str=""
while read line
do
echo $line
str="$str\n $line"
done < temp.txt
# Put new lines after the serialVersinUID line in the existing Java file.
sed -i -e "s/^ private static final long serialVersionUID = [0-9]\+L;$/\0\n$str/" $javaFile
# clean up
rm temp.txt
done
</code></pre>
<h1>Existing Input .hbm.xml file excerpt:</h1>
<pre><code><?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.myCo.CodeReview" table="code_review" catalog="stackexchange">
<!-- ... -->
<property name="address1C" type="string">
<column name="address1_c" length="50" />
</property>
<property name="address2C" type="string">
<column name="address2_c" length="50" />
</property>
<!-- etc. -->
</code></pre>
<h1>Existing Input Java File:</h1>
<pre><code>// ... preserve java code above
private static final long serialVersionUID = 20130318164201L;
// ... preserve java code below
</code></pre>
<h1>Desired Output Java File:</h1>
<pre><code>// ... preserved java code above
private static final long serialVersionUID = 20130318164201L;
@SuppressWarnings({"UnusedDeclaration"}) public static final int MAX_address1C = 50;
@SuppressWarnings({"UnusedDeclaration"}) public static final int MAX_address2C = 50;
// ... preserved java code below
</code></pre>
<h1>Background</h1>
<p>This script generates Java objects that represent database tables. It modifies the output of the Hibernate Database Reverse-Engineering tools to add maximum field length tokens to my Java objects that match the length of those columns in the database.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T16:12:33.723",
"Id": "38318",
"Score": "2",
"body": "I'd suggest using something which actually understood XML, as opposed to a sed script which will be fooled by totally valid XML. You might want to look at xslt?"
}
] |
[
{
"body": "<h3>1. Comments on your code</h3>\n\n<ol>\n<li><p>Your example input file is not a <a href=\"http://en.wikipedia.org/wiki/Well-formed_document\" rel=\"nofollow noreferrer\">well-formed XML document</a>. An XML document must have a <em>single</em> root element, but your example has two. What tool did you use to generate this file? You should ask yourself how it went wrong.</p>\n\n<p>(If you're just writing it \"by hand\" in some other program using a bunch of <code>print</code> statements, you might ask yourself why you are using XML at all rather than something simple like CSV. You clearly can't be intending to process these file using standard XML tools, since most XML tools will refuse to process ill-formed documents.)</p></li>\n<li><p>In the <code>find</code> command:</p>\n\n<pre><code>find generatedSchema/myApp/db/ -name *.hbm.xml\n</code></pre>\n\n<p>the pattern <code>*.hbm.xml</code> would be expanded by the shell (rather than the <code>find</code> command) if there happened to be any files matching the pattern in the directory where this command is being run. So single-quote the pattern to make sure this can't happen:</p>\n\n<pre><code>find generatedSchema/myApp/db/ -name '*.hbm.xml'\n</code></pre>\n\n<p>You might also consider adding the argument <code>-type f</code> to ensure that the names returned all refer to regular files. (It's not very likely in your case that someone will name a directory <code>foo.hbm.xml</code>, but adding a <code>-type</code> argument to a <code>find</code> command is often good practice.)</p></li>\n<li><p>In this line you don't need to escape the dots:</p>\n\n<pre><code>javaFile=${myFile/%\\.hbm\\.xml/.java}\n</code></pre>\n\n<p>The pattern in <code>${VAR/pat/rep}</code> here is not a regular expression, so dots are not special. For example:</p>\n\n<pre><code>$ FOO='a.b.c'\n$ echo ${FOO/./|}\na|b.c\n</code></pre></li>\n<li><p>You use regular expressions to transform your XML into Java source. Now, as I'm sure you're aware, <a href=\"https://stackoverflow.com/q/1732348/68063\">you can't reliably process XML using regular expressions</a>. Perhaps what you've got here works because you control the format of these XML files. But really you should be using an XML-aware tool. See section 2 below.</p></li>\n<li><p>You use a temporary file to store the output of your <code>sed</code> command, and then load it into a variable using a loop over its lines.</p>\n\n<p>You don't need this loop, because you can load the contents of a file into a variable by writing:</p>\n\n<pre><code>VARIABLE=$(<filename)\n</code></pre>\n\n<p>And you don't need the temporary file either, because you can load the output of a command into a variable by writing</p>\n\n<pre><code>VARIABLE=$(command)\n</code></pre>\n\n<p>So just write</p>\n\n<pre><code>str=$(sed -n \"...\")\n</code></pre></li>\n<li><p>You could choose better variable names than <code>myFile</code> (why yours?) and <code>str</code> (what's in the string?).</p></li>\n<li><p>In your last <code>sed</code> command, you use the expression <code>s/pattern/\\0\\n$str/</code> to append <code>$str</code> after every match of <code>pattern</code>. You might consider using <code>p;c</code> instead so that you can simplify the pattern (it doesn't have to match the whole line any more):</p>\n\n<pre><code>sed -i -e \"/^private static final long serialVersionUID/{p;c\\\n$str\n}\"\n</code></pre></li>\n<li><p>You expand variables <code>myFile</code> and <code>javaFile</code> in your script in contexts like this:</p>\n\n<pre><code>sed -i -e \"...\" $javaFile\n</code></pre>\n\n<p>This will go wrong if the variable <code>javaFile</code> contains spaces. You should double-quote the variable to ensure that it's treated as a single argument to <code>sed</code> even if it contains spaces. (Perhaps you know in this case that it can't contain spaces, but double-quoting variables containing filenames is still a good habit to get into.)</p>\n\n<pre><code>sed -i -e \"...\" \"$javaFile\"\n</code></pre></li>\n<li><p>I don't like the way you modify the Java source code in-place. This would be dangerous if this is your original Java source code, because a bug in your script could overwrite the Java source code with nonsense and break your build. (But since I can't see the rest of your build system I can't tell if this concern is justified.)</p>\n\n<p>If the whole Java file is automatically generated, wouldn't it be better to do it in one go rather than piecemeal like this? I have a feeling that there are more improvements to be made to this code generation process.</p></li>\n</ol>\n\n<h3>2. Using a programming language with XML support</h3>\n\n<p>If you need to process data from XML documents, then use a programming language together with an XML parsing library.</p>\n\n<p>For example, here's how you might rewrite this same script in Python. First, you'd change the way you generate your <code>.hbm.xml</code> files so that they are well-formed XML documents. Let's suppose that they now look like this:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code><properties>\n <property name=\"address1C\" type=\"string\">\n <column name=\"address1_c\" length=\"50\" />\n </property>\n <property name=\"address2C\" type=\"string\">\n <column name=\"address2_c\" length=\"50\" />\n </property>\n</properties>\n</code></pre>\n\n<p>Then you might write the following Python program:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/python\n\nimport fileinput\nimport sys\nimport xml.etree.ElementTree\n\ndef main():\n # Check command-line argument.\n hbm_xml_filename = sys.argv[1]\n ext = '.hbm.xml'\n if not hbm_xml_filename.endswith(ext):\n raise RuntimeError(\"Filename {} doesn't end with {}\"\n .format(hbm_xml_filename, ext))\n\n # Load property names and maximum lengths from input file.\n tree = xml.etree.ElementTree.parse(hbm_xml_filename)\n properties = []\n for property in tree.findall('property[@type=\"string\"]'):\n column = property.find('column')\n properties.append(dict(name = property.attrib['name'],\n length = column.attrib['length']))\n\n # Rewrite Java in-place to add \"MAX_name = length;\" declarations.\n java_filename = hbm_xml_filename.replace(ext, '.java')\n for line in fileinput.input(files=[java_filename], inplace=True):\n sys.stdout.write(line)\n if line.startswith('private static final long serialVersionUID'):\n sys.stdout.write('\\n')\n for p in properties:\n sys.stdout.write(\n '@SuppressWarnings({{\"UnusedDeclaration\"}}) '\n 'public static final int MAX_{name} = {length};\\n'\n .format(**p))\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>You'll see that I've used the <a href=\"http://docs.python.org/3/library/xml.etree.elementtree.html#module-xml.etree.ElementTree\" rel=\"nofollow noreferrer\"><code>xml.etree.ElementTree</code> module</a> to parse and query the XML, I've used an <a href=\"http://www.w3.org/TR/xpath20/\" rel=\"nofollow noreferrer\">XPath query</a> to find all properties with the attribute <code>type=\"string\"</code>, and I've used the <a href=\"http://docs.python.org/3/library/fileinput.html\" rel=\"nofollow noreferrer\"><code>fileinput</code> module</a> to update the Java source code in-place.</p>\n\n<p>Then you can run this Python program from your shell script:</p>\n\n<pre><code>find generatedSchema/myApp/db/ -type f -name '*.hbm.xml' |\nwhile read property_file; do\n add_property_lengths.py \"$property_file\"\ndone\n</code></pre>\n\n<h3>3. Addendum</h3>\n\n<p>You said you were having some difficulty getting <code>VAR=$(command)</code> to work. You should be able to verify that it works in general by testing it in the shell:</p>\n\n<pre><code>$ NUMBERS=$(yes '' | head | nl -ba)\n$ echo $NUMBERS\n1 2 3 4 5 6 7 8 9 10\n</code></pre>\n\n<p>Clearly we have different versions of <code>sed</code> (I'm using the BSD-ish version that comes with Mac OS X, so I had to specify <code>-E</code> for extended regular expressions and change the regular expression syntax a bit) but the following works for me:</p>\n\n<pre><code>VAR=$(sed -E -n '/ *<property name=\"([^\"]+)\" type=\"string\">/{\n N\n s/ *<property name=\"([^\"]+)\" type=\"string\">\\n *<column name=\"[^\"]+\" length=\"([0-9]+)\".*/ @SuppressWarnings({\"UnusedDeclaration\"}) public static final int MAX_\\1 = \\2;/\n p\n}' \"$myFile\")\n</code></pre>\n\n<p>so you should be able to figure out how to make something like it work for you (if you must do it this way).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T02:34:57.673",
"Id": "38453",
"Score": "0",
"body": "#2,3,6,8: Changes made and all work; thanks! #1: XML is an *excerpt* (fixed post). #7: Interesting, but p and c are sed-specific; no change made. #5: Error: `sed: -e expression #1, char 153: unterminated 's' command` I think it has to do with newlines #9: Ultimate output is a patch file. Everything in git, script makes multiple backups... \"Wouldn't it be better to do it in one go?\" Great question! Wish I could post whole project. I was trying to leverage existing tools, but after so many shims, the original tools are doing less than half the work. Thanks much for your time and Python code!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T08:08:42.950",
"Id": "38462",
"Score": "0",
"body": "Ah, an *excerpt*! This had me puzzled."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T09:05:09.597",
"Id": "38466",
"Score": "0",
"body": "See updated answer for my response to your comment on #5."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T11:29:41.120",
"Id": "24851",
"ParentId": "24684",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "24851",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T20:58:27.293",
"Id": "24684",
"Score": "4",
"Tags": [
"bash",
"shell",
"sed"
],
"Title": "Bash Shell Script uses Sed to create and insert multiple lines after a particular line in an existing file"
}
|
24684
|
<p>Please check if my tables specs agree with business rules. Also, please explain the differences between <code>CONSTRAINT</code>, <code>FOREIGN KEY</code> and <code>CONSTRAINT FOREIGN KEY</code>.</p>
<p>I have four MySQL tables (<code>USER</code>, <code>NAME</code>, <code>PATIENT</code> and <code>DOCTOR</code>) with the following rules:</p>
<ol>
<li>A patient must have a name</li>
<li>A patient can be a user</li>
<li>A doctor must have a name</li>
<li>A doctor must be a user</li>
<li>A patient can be a doctor and vice versa...</li>
<li>By 3 & 5, if a patient is a doctor that patient must be a user</li>
</ol>
<hr>
<pre><code>CREATE TABLE USER (
userName VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL UNIQUE,
userId MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
userEmail VARCHAR(100) NOT NULL,
userPassword VARCHAR(64) NOT NULL,
PRIMARY KEY(userId))
</code></pre>
<hr>
<pre><code>CREATE TABLE PATIENT (
patientId MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
userId MEDIUMINT UNSIGNED,
patientBirthday CHAR(8), # yyyymmdd
patientBirthplace VARCHAR(50),
patientGender TINYINT(1) UNSIGNED, # 0:male 1:female
patientBloodType TINYINT(1) UNSIGNED,
PRIMARY KEY(patientId),
CONSTRAINT FOREIGN KEY(userId) REFERENCES USER(userId)
ON DELETE CASCADE ON UPDATE CASCADE)
</code></pre>
<hr>
<pre><code>CREATE TABLE DOCTOR (
doctorId MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
userId MEDIUMINT NOT NULL UNSIGNED,
nameId MEDIUMINT NOT NULL UNSIGNED,
PRIMARY KEY(patientId),
CONSTRAINT FOREIGN KEY(userId) REFERENCES USER(userId)
CONSTRAINT FOREIGN KEY(nameId) REFERENCES USER(nameId)
ON DELETE CASCADE ON UPDATE CASCADE)
</code></pre>
<hr>
<pre><code>CREATE TABLE NAME (
nameId MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
userId MEDIUMINT UNSIGNED,
lastName VARCHAR(100) NOT NULL,
firstName VARCHAR(100) NOT NULL,
PRIMARY KEY(nameId),
CONSTRAINT FOREIGN KEY(userId) REFERENCES USER(userId)
ON DELETE CASCADE ON UPDATE CASCADE)
</code></pre>
|
[] |
[
{
"body": "<p>The <code>CONSTRAINT</code> word used within a <code>CREATE TABLE</code> or <code>ALTER TABLE</code> tells MySQL engine that this value is not a separate column, but rather it is applied on a column within the table. </p>\n\n<p>The <code>FOREIGN KEY</code> word tells MySQL that whatever is in that field <strong>must</strong> reference a valid <code>PRIMARY KEY</code> from the other table on <code>INSERT</code> or <code>UPDATE</code> record, otherwise an error is raised. </p>\n\n<p><code>CONSTRAINT FOREIGN KEY</code> is simply how you phrase it. For more information I suggest <a href=\"http://dev.mysql.com/doc/refman/5.1/en/create-table-foreign-keys.html\" rel=\"nofollow\">reading up about it in the manual</a>. </p>\n\n<p>Now for your criteria:</p>\n\n<ol>\n<li><p>A patient must have a name: FALSE</p>\n\n<p>That one is not true, unless you added either of those two to your <code>CREATE TABLE PATIENT</code></p>\n\n<ul>\n<li><code>NOT NULL</code> to the <code>userID</code> column and a <code>CONSTRAINT FOREIGN KEY (userID) REFERENCES USER(userID)</code>\nor, preferably in my opinion:</li>\n<li><code>nameID MEDIUMINT NOT NULL, CONSTRAINT FOREIGN KEY(nameID) REFERENCES NAME(nameID),</code></li>\n</ul></li>\n<li><p>A patient can be a user: TRUE</p></li>\n<li><p>A doctor must have a name: TRUE</p></li>\n<li><p>A doctor must be a user: TRUE</p></li>\n<li><p>A patient can be a doctor and vice versa...: TRUE (via <code>userID</code>)</p></li>\n<li><p>By 3 & 5, if a patient is a doctor that patient must be a user: TRUE</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-21T23:22:21.903",
"Id": "51343",
"ParentId": "24685",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "51343",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T21:16:15.423",
"Id": "24685",
"Score": "3",
"Tags": [
"sql",
"mysql"
],
"Title": "Tables for doctor and patients"
}
|
24685
|
<p>I'm self-studying Java and have a question about one of the end-of-chapter exercises. The chapter focus is on inheritance and the book hasn't officially introduced polymorphism so I'm trying to stay within those bounds. </p>
<p>The exercise is:</p>
<blockquote>
<p>Write an inheritance hierarchy for classes Quadrilateral, Trapezoid, Parallelogram, Rectangle and Square. Use Quadrilateral as the superclass of the hierarchy. Create and use a Point class to represent the points in each shape. Make the hierarchy as deep(i.e., as many levels) as possible. Specify the instance variables and methods for each class. The private instance variables of Quadrilateral should be the x-y coordinate pairs for the four endpoints of the Quadrilateral. Write a program that instantiates objects of your classes and outputs each object's area(except Quadrilateral).</p>
</blockquote>
<p>My classes are below and they compile and work OK.</p>
<p>Questions:</p>
<ol>
<li><p>The exercise statement</p>
<blockquote>
<p>The private instance variables of Quadrilateral should be the x-y coordinate pairs for the four endpoints of the Quadrilateral.</p>
</blockquote>
<p>I put the x-y coordinate instance variables in my Point class because it seemed to fit better and if I didn't, what purpose would Point serve other than to hold the four points. With the way that I did it, it also calculates the distance between the points which seems to fit better to me. Comments?</p></li>
<li><p>I thought it would make more sense to use Point class inside Square directly instead of going through Quadrilateral like I did. I used Quadrilateral because each sub-class will need points. Taking Point out of Quadrilateral would make it have even less functionality than it does. Of course it doesn't make sense to add a class just for the sake of adding a class but I'm kind of in that position by trying to meet the exercise objectives. Comments? </p></li>
<li><p>Any other general feedback would be welcome. Does it look professional? Even though it's kind of small, would it be accepted in the corporate world? </p></li>
</ol>
<p></p>
<pre><code>package exercise9_8;
public class Point {
private int distanceX, distanceY;
private int x0, x1, y0, y1;
public Point( int x0, int x1, int y0, int y1 ){
this.x0 = x0;
this.x1 = x1;
this.y0 = y0;
this.y1 = y1;
setDistanceX();
setDistanceY();
}
private void setDistanceX(){
distanceX = x1 - x0;
}
public int getDistanceX(){
return distanceX;
}
private void setDistanceY(){
distanceY = y1 - y0;
}
public int getDistanceY(){
return distanceY;
}
}
package exercise9_8;
public class Quadrilateral {
Point point;
public Quadrilateral( int x0, int x1, int y0, int y1 ){
point = new Point( x0, x1, y0, y1 );
}
protected int getDistanceX(){
return point.getDistanceX();
}
protected int getDistanceY(){
return point.getDistanceX();
}
}
package exercise9_8;
public class Square extends Quadrilateral{
private int area;
public Square( int x0, int x1, int y0, int y1 ){
super( x0, x1, y0, y1 );
setArea();
}
private void setArea(){
area = super.getDistanceX() * super.getDistanceY();
}
public int getArea(){
return area;
}
}
package exercise9_8;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class SquareTestNG {
@Test(enabled = true)
public void testGetNumberOfPoints(){
Square sq = new Square( 5, 3, 5, 3 );
assertEquals(sq.getArea(), 4);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>While the problem description isn't very clear, I expect the intention was for you to use <code>Point</code> to encapsulate a single (x, y) pair and use it in <code>Quadrilateral</code> et al. However, your version contains <em>two</em> points and thus should be called <code>Line</code> or <code>Segment</code>. What is the reason for this?</p>\n\n<p>I would remove the setters from <code>Point</code> to make it immutable. For one thing, they aren't needed by the problem. But more importantly immutable objects are easier to reason about and use in multi-threaded environments (later).</p>\n\n<p>While a square can be modeled using either pair of diagonally-opposite points, this won't work for any of the other shapes. <code>Quadrilateral</code> should contain four <code>Point</code>s. You're free to have <code>Square</code> accept two points in its constructor, or a single point with a width and height, and calculate the four points from them to pass to the superclass.</p>\n\n<p>As for the hierarchy (you only show two classes so far), consider that a square is a special type of rectangle and should extend it rather than <code>Quadrilateral</code>. There are other cases like this, and you should start by listing out the properties and constraints of each shape. This will help you determine the optimum class hierarchy.</p>\n\n<p>Pro tip: I would bet that the <code>@Test</code> annotation's <code>enabled</code> property defaults to <code>true</code>. If that's correct, you can omit it for brevity.</p>\n\n<p><strong>Update</strong></p>\n\n<p>In two-dimensional geometry, a <em>point</em> is represented with two coordinates named <em>x</em> and <em>y</em>.</p>\n\n<pre><code>(3, 5)\n</code></pre>\n\n<p>A <a href=\"http://en.wikipedia.org/wiki/Line_segment\" rel=\"nofollow\"><em>line segment</em></a> is defined as the set of all points directly between two endpoints. It has a length equal to the distance between its endpoints.</p>\n\n<pre><code>(3, 5) to (3, 7)\n</code></pre>\n\n<p>A <em>line</em> is similar to a segment except that it extends past the endpoints out to infinity on both ends.</p>\n\n<p>A <em>polygon</em> (e.g. a square or <a href=\"http://en.wikipedia.org/wiki/Quadrilateral\" rel=\"nofollow\">quadrilateral</a>) is formed by connecting segments in a closed loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T15:16:00.527",
"Id": "38185",
"Score": "0",
"body": "_However, your version contains two points and thus should be called Line or Segment. What is the reason for this?_\nIgnorance on my part. I was having trouble getting started and picked the simplest shape I could. \nThanks for your response. I don't have enough cred here to vote yet."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T17:57:45.767",
"Id": "38190",
"Score": "0",
"body": "@Gary - I've updated my answer with some basic geometry definitions which should get you moving in the right direction."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T00:05:08.600",
"Id": "24688",
"ParentId": "24687",
"Score": "1"
}
},
{
"body": "<p>First of all, I'd change how the <code>Point</code> class functions because like David Harkness said, your Point class resembles that of a <code>Line</code>. I would have it representing two values <code>(x, y)</code> and include functions that would make it easier to find the area of a shape. Here's an example:</p>\n\n<pre><code> public class Point {\n\n public float x;\n public float y;\n\n public Point(float x, float y) {\n this.x = x;\n this.y = y;\n }\n\n public static float distanceTo(Point from, Point to) {\n // Distance formula\n return Math.sqrt(Math.pow(to.x - to.y, 2) + Math.pow(from.x - from.y, 2));\n }\n</code></pre>\n\n<p>Using that point class, I could implement it into a <code>Shape</code> class to centralize a <code>getArea()</code> function. To have different types of shapes, you could extend the Shape class from other classes and specify how many points each class or override the <code>getArea()</code> function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T15:19:08.853",
"Id": "38186",
"Score": "0",
"body": "Thanks for your response and taking the time to explain this."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T02:21:21.567",
"Id": "24691",
"ParentId": "24687",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T22:42:37.643",
"Id": "24687",
"Score": "3",
"Tags": [
"java",
"inheritance"
],
"Title": "My self-study inheritance and sub-class exercise"
}
|
24687
|
<p>I have completed my homework with directions as follows:</p>
<blockquote>
<p>Declare and implement a class named Binary. This class will have a
method named printB(int n) that prints all binary strings of length n.
For n = 3, it will print</p>
<pre><code>000
001
010
011
100
101
110
111
</code></pre>
<p>in this order.</p>
</blockquote>
<p>Is there any way to make this shorter or more efficient?</p>
<pre><code>import java.util.Scanner;
class Binary
{
String B;
int temp;
void printB(int n)
{
for(int i = 0; i < Math.pow(2,n); i++)
{
B = "";
int temp = i;
for (int j = 0; j < n; j++)
{
if (temp%2 == 1)
B = '1'+B;
else
B = '0'+B;
temp = temp/2;
}
System.out.println(B);
}
}
}
class Runner
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter n:");
int n = in.nextInt();
Binary myB = new Binary();
myB.printB(n);
}
}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>Is there any way to make this shorter or more efficient?</p>\n</blockquote>\n\n<p>Yes, we can do some things.</p>\n\n<pre><code>for(int i = 0; i < Math.pow(2,n); i++)\n</code></pre>\n\n<p>You calculate the pow for every iteration. The pow call takes some time (compared to basic things like multiplication or addition), you should do it only once.</p>\n\n<pre><code>B = \"\";\nB = '1'+B;\nB = '0'+B;\n</code></pre>\n\n<p>You will create a lot of string copies for every string concatenation. This costs a lot of perfomance. In general, you should use a <code>StringBuilder</code>.<br>\nIn this special case, we could even use a char array.</p>\n\n<pre><code>for(int i = 0; i < Math.pow(2,n); i++)\nif (temp%2 == 1)\ntemp = temp/2;\n</code></pre>\n\n<p>You could use bit manipulations. But depending on the jvm or hotspot compiler, this will be done anyway.</p>\n\n<pre><code>void printB(int n)\n B = \"\";\n int temp = i;\n</code></pre>\n\n<p>Overall point: avoid abbreviations.</p>\n\n<hr>\n\n<p>All together, it could be like this:</p>\n\n<pre><code>void printAllBinaryUpToLength(final int length) {\n if (length >= 63)\n throw new IllegalArgumentException(\"Current implementation supports only a length < 63. Given: \" + length);\n final long max = 1 << length;\n for (long i = 0; i < max; i++) {\n long currentNumber = i;\n final char[] buffer = new char[length];\n int bufferPosition = buffer.length;\n while (bufferPosition > 0) {\n buffer[--bufferPosition] = (char) (48 + (currentNumber & 1));\n currentNumber >>>= 1;\n }\n System.out.println(buffer);\n }\n}\n</code></pre>\n\n<p>Calculates (without printing, printing takes the great majority of every loop) results up to 25 (2^25 = ~33*10^6) in less than a second. Should be enough.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T20:31:34.077",
"Id": "418911",
"Score": "0",
"body": "You should explain what the magic number 48 means. Or better yet, avoid it by writing `'0'`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T10:38:07.080",
"Id": "418961",
"Score": "0",
"body": "It seems regressive that your code has a maximum length while OP's doesn't."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T16:43:21.637",
"Id": "442429",
"Score": "0",
"body": "It has the same restriction as the original specification, namely a maximum amount of last power of two before max integer. In the original specification, this bound is introduced by `Math.pow(2,n)`. In the case of a specification that requires a larger bound, we may switch to `long`or `BigInteger`. However, we may also use a simple recursive approach where the bound is only given by the stack depth (or the time of life)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T12:28:17.357",
"Id": "24707",
"ParentId": "24690",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-04-04T01:35:33.927",
"Id": "24690",
"Score": "9",
"Tags": [
"java"
],
"Title": "Print all binary strings of length n"
}
|
24690
|
<p>The code below implements an intrusive lock-free queue that supports multiple concurrent producers and consumers.</p>
<p>Some features:</p>
<ul>
<li>Producers and consumers work on separate ends of the queue most of the time.</li>
<li>The fast path for producers and consumers has 4 atomic ops.</li>
<li>Version numbers are used to prevent the ABA problem.</li>
<li>Threads assist other threads in completing their operations, they're never blocked waiting for another thread to do something.</li>
</ul>
<p>I'm particularly interested in comments regarding the correctness of this design. Unless proven otherwise I'm assuming that this code is broken, although I've tried to the best of my ability to have a correct lock-free implementation.</p>
<pre><code>#include <cstdint>
#include <atomic>
struct LockfreeNode
{
std::atomic<LockfreeNode>* next;
uintptr_t version;
LockfreeNode()
: next(nullptr)
, version(0)
{
}
LockfreeNode(std::atomic<LockfreeNode>* next, uintptr_t version)
: next(next)
, version(version)
{
}
};
template <class T>
class LockfreeQueue
{
public:
typedef LockfreeNode Node;
typedef std::atomic<Node> AtomicNode;
typedef typename AtomicNode T::* NodeMemberPointer;
LockfreeQueue(NodeMemberPointer node)
: mNodeMember(node)
{
mSentinel = Node(&mSentinel, PreviousVersion(1));
mHead = Node(&mSentinel, 1);
mTail = Node(&mSentinel, 1);
}
void Queue(const T& element)
{
AtomicNode* node = ToNode(element);
QueueNode(node, 0);
}
T* Dequeue()
{
AtomicNode* result = DequeueNode();
return result ? ToElement(result) : nullptr;
}
private:
void QueueNode(AtomicNode* node, uintptr_t generation)
{
// Capture the tail to figure out what the last node is. The last node can be a
// regular node or it can be the sentinel.
//
// - Regular node:
//
// A->s->B->C N ; C is the last node, N is the new node
// 1 2 2 2
// ^ ^
// h t
// 2 2
//
// - Sentinel:
//
// B->C->D->s N
// 2 2 2 2
// ^ ^
// h t
// 3 3
Node tail = mTail.load(std::memory_order_acquire); // (Q.1)
// Note that other threads could update the tail in (Q.5) in the meantime,
// invalidating our local copy above. In that case none of the operations below
// will have any effect and we'll end up looping again, retrying the queueing
// operation with a fresh copy of the tail captured in (Q.5).
Node last;
bool queued = false;
// The loop below will continue until we've successfully queued the new node.
// While looping, we'll potentially be helping complete other in-progress
// operations initiated by other threads.
for (;;)
{
// Check whether the last node is the sentinel or not so that we can build
// the right comparand for the CAS operation in (Q.4).
if (tail.next == &mSentinel)
{
// The last node is the sentinel, which means one of two things:
//
// - A consumer thread is potentially still in the process of bumping
// the sentinel, having executed (Q.4) and (Q.5) already but not
// necessarily the final head swing in (Q.3):
//
// s->B->C->D->s ; Both 's' entries refer to the same sentinel
// 2 2 2 2 2
// ^ ^
// h t ; The head might not have been swung to B yet
// 2 3
//
// If the operation is still ongoing, all that remains to do is to swing
// the head forward in (Q.3), allowing consumers to start dequeueing the
// next generation of elements that would now be to the left of the
// sentinel. If the operation has been completed already by another
// thread then our CAS in (Q.3) will do nothing because the head version
// number won't match the comparand there. After that, if we were
// originally trying to queue a regular node then we'll go ahead with the
// rest of the loop iteration and try to do that (Q.4) using the
// comparand we'll build in 'last' below, otherwise we'll just return.
//
// - The list was empty and a producer thread is in the process of
// queueing the first node of a new generation, having linked it to the
// sentinel in (Q.4) but not having swung the tail forward to it in (Q.5)
// yet:
//
// s->B ; B is being queued by a producer
// 2 2
// ^ ^
// h t ; The tail hasn't been updated yet
// 2 2
//
// In this case we need to help that thread complete the queueing
// operation by swinging the tail in (Q.5) before doing anything else.
// Our CAS in (Q.3) will fail because the head version number won't match
// the comparand, and the next CAS in (Q.4) will fail as well because the
// sentinel version number won't match the comparand we'll build in
// 'last' either. After that we'll try swinging the tail in (Q.5) and
// proceed to loop again to perform our original operation.
// The first thing to do is capture the contents of the sentinel to
// determine what node follows it, so we can swing the head to that node
// in (Q.3) and so we can link the new node to it later in (Q.4). Note
// that we ignore the actual sentinel version here when building the
// 'last' comparand and always set it to the version prior to the tail's.
// This is to make sure that the CAS in (Q.4) only succeeds in the case
// where the sentinel has nothing linked to the right:
//
// B->C->D->s ; The sentinel isn't linked to anything
// 2 2 2 2 ; The sentinel version is lower than the tail
// ^ ^
// h t
// 2 3
//
// And so that it fails in the case where another node was linked to it
// without the tail having been swung forward yet:
//
// s->B ; The sentinel is already linked to something
// 2 2 ; The sentinel version is same as the tail
// ^ ^
// h t ; The tail needs to be swung forward first
// 2 2
last = mSentinel.load(std::memory_order_acquire); // (Q.2)
last.version = PreviousVersion(tail.version);
// We now have copy of the sentinel with a pointer to the node we need to
// swing the head to.
//
// Other threads could invalidate this copy of the sentinel by linking a
// new node to it in (Q.4). In that case, the head update in (Q.3) would
// have necessarily been performed already by another thread, so our CAS
// operations in (Q.3) and (Q.4) would have no effect. We may still end
// up helping the other threads by swinging the tail forward for them in
// (Q.5) if they haven't done so already:
//
// B->C->D->s->E ; E was queued by another thread
// 2 2 2 3 3
// ^ ^
// h t ; We may be able to swing the tail later
// 3 3
//
// Note that we don't need to read the current head here, since we know
// what its contents must be if it's still pointing to the sentinel:
//
// s->B->C->D->s
// 2 2 2 2 2
// ^ ^
// h t ; Head still pointing to the sentinel
// 2 3 ; Head version number is same as sentinel's
Node head(&mSentinel, last.version);
Node newHead(last.next, tail.version);
// Swing the head forward to complete the sentinel bump operation. If the
// head had already been updated in (Q.3) by another thread then the CAS
// below will fail:
//
// B->C->D->s ; B, C and D can now be dequeued
// 2 2 2 2
// ^ ^
// h t ; The head was updated
// 3 3
//
// This operation will also update the head version to match the tail.
mHead.compare_exchange_strong(head,
newHead,
std::memory_order_acq_rel); // (Q.3)
}
else
{
// The last node is a regular node. Unless another producer has just
// linked a new node to it we know that the contents of that node will
// be a pointer to the tail and the tail's version:
//
// A->s->B->C N ; C has known contents
// 1 2 2 2
// ^ ^
// h t
// 2 2
//
// If on the other hand there is a node linked to it then the comparand
// below won't match and the CAS in (Q.4) will fail, after which we'll
// swing the tail forward to help the other thread complete its queueing
// operation and then we'll retry our own operation:
//
// A->s->B->C->D N ; D was queued by another producer
// 1 2 2 2 2
// ^ ^
// h t ; The tail may not have been updated yet
// 2 2
last = Node(&mTail, tail.version);
}
// If we're trying to bump the sentinel we'll know that it has now been
// bumped when the tail version is different than the one passed to this
// function. This is the only test we need to detect this condition,
// regardless of which part this thread played in the bumping. We can just
// check the tail version because it must have been updated in (Q.5) during
// the sentinel bump and, if so, the head must have been swung in (Q.3)
// already if we're at this point.
if (node == &mSentinel && tail.version != generation)
{
queued = true;
}
// At this point we can return if the node has been successfully queued.
if (queued)
{
break;
}
// If we're queueing a regular node (as opposed to the sentinel) then we need
// to set the node's version number to that of the tail before linking it.
// Sentinels instead have their version number updated by someone else in
// (Q.4) when a new node is queued after them.
//
// Also, we set the new node's next pointer to this queue's tail, which allows
// us to make sure that in the event that this node is removed from this queue
// and inserted in another queue that is using the same version number while a
// producer thread here was about to link something to that node in (Q.4) that
// CAS operation fails since the node's next pointer will necessarily be
// different. By making newly-queued nodes point to something unique to each
// queue (such as the head or tail) we ensure that the CAS will properly fail
// in this case.
if (node != &mSentinel)
{
// This operation could be non-atomic.
node->store(Node(&mTail, tail.version), std::memory_order_relaxed);
}
// Link the new node to the last node.
//
// - If the last node was the sentinel, then this operation will have the side
// effect of incrementing the sentinel's version number to match the head and
// tail, signaling consumers that there is now a new generation of elements to
// the right of the sentinel ready to be dequeued:
//
// B->C->D->s->N ; N has been queued after the sentinel
// 2 2 2 3 3 ; The sentinel's version has been updated
// ^ ^
// h t
// 3 3
//
// - If someone else has linked a node to the last node after we read the tail
// but before we got to execute (Q.4) then the CAS below will fail, we'll get
// back a copy of the pointer to that newly-queued node, and we'll go ahead
// and help that other thread complete its queueing operation by potentially
// swinging the tail forward in (Q.5) for them. We will then proceed to loop
// again and retry our operation with a fresh copy of the tail:
//
// A->s->B->C->D N ; D was queued by another thread before us
// 1 2 2 2 2
// ^ ^
// h t ; The tail might not have been updated yet
// 2 2
//
// - If the last node was dequeued by a consumer in the meantime then we would
// be accessing it after it's been removed from the data structure, which is
// safe under the assumption that storage for removed nodes is not released
// until this any other threads have finished accessing it.
//
// In this case the CAS below is guaranteed to fail due to one of the
// following three scenarios. First, if the consumer thread has executed
// (D.3) to acquire ownership of the node for removal then the node won't
// be pointing to the tail anymore (since it must have had something linked
// to it prior to the removal, at the very least the sentinel) so it won't
// match our CAS comparand that expects a pointer to the tail:
//
// C->D->E->s N ; C's being dequeued, no longer points to tail
// 2 2 2 2
// ^ ^
// h t
// 3 3
//
// If the node has been readded to this queue after being dequeued, and it
// happens to be the last node again when we get to (Q.4) below, that CAS is
// also going to fail because the node's version number must have increased
// when requeueing it:
//
// D->E->s->C N ; C has been requeued
// 2 2 3 3 ; C's version number has increased
// ^ ^
// h t
// 3 3
//
// Finally, if the node was removed from this queue and added to another
// queue, and the node was assigned the same version number on that queue
// as when it was on this one, then the CAS below will still fail because
// the node will no longer be pointing to this queue's tail; it will either
// be pointing to the other queue's tail if it's currently the last node
// there, or to some other node if it's not the last one. In either case it
// won't match our comparand that expects a pointer to our tail.
Node newLast(node, tail.version);
if (tail.next->compare_exchange_strong(last,
newLast,
std::memory_order_acq_rel)) // (Q.4)
{
// The new node has been successfully queued. We can exit the loop on the
// next iteration.
//
// - If the new node was a regular node, it could have been linked to
// either another regular node or the sentinel. If it was queued to the
// sentinel then this operation had the side effect of incrementing the
// sentinel's version:
//
// B->C->D->s->N ; N was linked to the sentinel
// 2 2 2 3 3 ; The sentinel's version number was updated
// ^ ^
// h t ; The tail needs to be swung forward
// 3 3
//
// or
//
// A->s->B->C->N ; N was linked to a regular node
// 1 2 2 2 2
// ^ ^
// h t ; The tail needs to be swung forward
// 2 2
//
// The only operation left to do in this case is to swing the tail forward
// in (Q.5).
//
// - If the new node was the sentinel then it must have been linked to a
// regular node, and its version number won't be updated:
//
// s->B->C->s ; The sentinel was queued
// 2 2 2 2 ; The sentinel version hasn't been updated yet
// ^ ^
// h t ; The head and tail need to be swung forward
// 2 2
//
// In this case there are two operations left to do: swinging the tail in
// (Q.5) and swinging the head in (Q.3).
last = newLast;
queued = true;
}
// Swing the tail forward, using the contents of the last node that we
// captured above in (Q.4) to figure out what the next node to swing it to is.
// It could be the node that we queued ourselves or it could be someone else's
// node if they beat us to (Q.4).
//
// - If the new node is the sentinel then we need to increase the tail version
// in this operation. New nodes linked after this point will use this new
// version number. This will effectively signal that a new generation of
// elements will start after the sentinel:
//
// s->B->C->s
// 2 2 2 2
// ^ ^
// h t
// 2 3 ; The tail version was updated
//
// - If someone else has updated the tail for us in (Q.5), then the CAS below
// will fail due to a comparand mismatch, which can manifest in two different
// ways. First, if another thread has swung the tail and it's now pointing to
// a node different than the previous last node then the comparand pointer
// will differ:
//
// A->s->B->C->N ; C was the last node
// 1 2 2 2 2
// ^ ^
// h t ; The tail has been updated by someone else
// 2 2 ; It's now pointing to something other than C
//
// On the other hand, if the previous last node was dequeued and then later
// requeued, and it happens to be the last node again when we execute (Q.5),
// then the comparand pointer will match but the version number will
// necessarily be different, since the node now belongs to a future
// generation:
//
// N->s->C ; C was dequeued and requeued
// 2 3 3
// ^ ^
// h t ; Tail version number is different than before
// 2 3
Node newTail(last.next, (last.next == &mSentinel) ?
NextVersion(tail.version) :
tail.version);
if (mTail.compare_exchange_strong(tail,
newTail,
std::memory_order_acq_rel)) // (Q.5)
{
// We have succeeded in swinging the tail.
//
// - If the node pointed to by the tail is a regular node then we've now
// finished queueing it:
//
// A->s->B->C->N ; N is now fully queued
// 1 2 2 2 2
// ^ ^
// h t
// 2 2
//
// If this was our node then we'll exit the loop on the next iteration.
// Otherwise we've just helped someone else complete their operation and
// will loop again to retry ours.
//
// - If the node is the sentinel then it's not considered fully bumped
// until we swing the head in (Q.3) during the next iteration.
//
// s->B->C->s
// 2 2 2 2
// ^ ^
// h t ; The head hasn't been updated yet
// 2 2
tail = newTail;
}
}
}
AtomicNode* DequeueNode()
{
AtomicNode* result = 0;
// Capture the head to figure out what the first node is. The first node can be a
// regular node or it can be the sentinel:
//
// - Regular node:
//
// A->s->B->C
// 1 2 2 2
// ^ ^
// h t
// 2 2
//
// - Sentinel:
//
// s->B->C->D
// 2 2 2 2
// ^ ^
// h t
// 2 2
Node head = mHead.load(std::memory_order_acquire); // (D.1)
// Loop until we've either successfully dequeued an element or the queue is empty.
while (!result)
{
// We have captured the current head and know what the first node is.
//
// - If the first node is a regular node, another consumer thread could
// dequeue it before us, updating the head in (D.3) in the process. We'll
// detect that in (D.3) too because our CAS there will fail with a comparand
// mismatch, which could be due to two reasons. First, if another consumer
// has dequeued that node then it must have updated the head to point to some
// other node, so the node pointer in the comparand will differ:
//
// A B->s->C ; A was dequeued by someone else
// 1 2 2
// ^ ^
// h t ; The head no longer points to A
// 2 2
//
// On the other hand, if the node was dequeued and then later requeued, and it
// happens to be the first node on the list again when we execute (D.3), then
// the comparand pointer will match but the head version number will
// necessarily be different, since the head must have crossed the sentinel
// at least once to reach the requeued node:
//
// A->s->D->E ; A was dequeued in gen 1 and readded in gen 2
// 2 3 3 3
// ^ ^
// h t
// 3 3 ; The head has a different version than before
//
// In both these cases we'll simply loop again to retry the operation.
//
// - If the first node is the sentinel and it's currently in the process of
// being bumped to the end of the list, other producer or consumer threads
// could update the head in (Q.3) during the final step of the sentinel bump
// operation before we get a chance to do it ourselves. In that case, we will
// enter QueueNode to bump the sentinel but will end up doing nothing because
// the work will have already been done:
//
// s B->C->D->s ; The sentinel has already been bumped
// 2 2 2 2
// ^ ^
// h t
// 3 3
// Now capture the contents of the first node to figure out what the second
// node is:
//
// A->B->s->C ; B is the second node
// 1 1 2 2
// ^ ^
// h t
// 2 2
//
// Note that the first node could have been dequeued by another thread as
// we're about to access its storage. We assume that storage for dequeued
// nodes is not freed until this thread and any other thread holding a pointer
// to them is done accessing it:
//
// A B->s->C ; A was dequeued by someone else
// 1 2 2
// ^ ^
// h t
// 2 2
Node first = head.next->load(std::memory_order_acquire); // (D.2)
// Check whether the first node is a regular node or whether it's the
// sentinel. If it's a regular node we can go ahead and attempt the
// dequeueing.
if (head.next != &mSentinel)
{
// The first node is a regular node.
// We now attempt to swing the head to acquire ownership of the first
// node, which if successful means that we're allowed to dequeue it.
// If the CAS fails then another consumer has dequeued the node before
// us and we'll loop again to retry with a fresh copy of the head.
Node newHead(first.next, head.version);
if (mHead.compare_exchange_strong(head,
newHead,
std::memory_order_acq_rel)) // (D.3)
{
// We have acquired ownership of the first node, so we can return it.
Node emptyNode(nullptr, 0);
head.next->store(emptyNode, std::memory_order_release); // (D.4)
result = head.next;
}
}
else
{
// The first node is the sentinel.
// Check whether the queue is empty or whether there are elements after
// the sentinel. We can perform this check by just comparing the
// sentinel's version number with the head's. An empty queue has a
// sentinel with a lower version number than the head:
//
// s
// 0
// ^ ^
// h t
// 1 1
//
// On the other hand, a non-empty queue has sentinel and head with
// identical version numbers. This is because during the linking of a
// new node to the right of the sentinel in (Q.4) the sentinel's version
// number must have been updated to match:
//
// s->A
// 1 1
// ^ ^
// h t
// 1 1
if (first.version != head.version)
{
// The queue is empty, so we return null.
break;
}
// The queue is non-empty but the sentinel is at the front of the list.
// Before we're allowed to dequeue any elements we need to bump the
// sentinel to the end of the queue. This operation is almost identical
// to queueing a regular node, so we let QueueNode handle all the details.
// We must pass the current version number so that QueueNode can detect
// when the sentinel bump is complete.
QueueNode(&mSentinel, head.version);
head = mHead.load(std::memory_order_acquire); // (D.5)
}
}
return result;
}
static uintptr_t NextVersion(uintptr_t version)
{
return version != UINTPTR_MAX ? version + 1 : uintptr_t(1);
}
static uintptr_t PreviousVersion(uintptr_t version)
{
return version != 1 ? version - 1 : UINTPTR_MAX;
}
T* ToElement(AtomicNode* node) const
{
uintptr_t offset = uintptr_t(&(static_cast<T*>(0)->*mNodeMember));
return reinterpret_cast<T*>(uintptr_t(node) - offset);
}
AtomicNode* ToNode(const T& element) const
{
return const_cast<AtomicNode*>(&(element.*mNodeMember));
}
private:
__declspec(align(64)) NodeMemberPointer mNodeMember; // Shared, read-only
__declspec(align(64)) AtomicNode mSentinel; // Shared, read-write
__declspec(align(64)) AtomicNode mHead; // Mostly consumer-only
__declspec(align(64)) AtomicNode mTail; // Mostly producer-only
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T15:06:45.073",
"Id": "43419",
"Score": "0",
"body": "Any Benchmarks on this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-30T21:58:21.103",
"Id": "43619",
"Score": "1",
"body": "Filipe, now that I'm a bit more confident about the correctness of this implementation I ran some micro-benchmarks which you can see [here](https://docs.google.com/spreadsheet/ccc?key=0AmMjMuBIgQXDdDZ2cTcxTG5tY2tSQ2hMRmlYUGNpM1E&usp=sharing). In short, the queue as shown above is decently fast, with some added spinwaits on retries it becomes quite fast, and with a few further tweaks to remove seemingly unnecessary atomic ops (Q.2 and the relaxed store in QueueNode, and D.3 in DequeueNode when dequeuing a regular node) it is the second-fastest queue I've found. Here's hoping it's correct."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-02T13:45:46.003",
"Id": "43739",
"Score": "0",
"body": "Thanks for the results. In comparison to dimitris queue your queue looks really promissing. But why do you get less throughput while increasing the Thread count? Am i missing something?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-03T16:34:37.933",
"Id": "43811",
"Score": "1",
"body": "That's because the benchmark measures throughput under maximum contention, where threads do nothing except queueing and dequeueing elements (no work done per element). It's not a real world scenario, but I think it's very useful to compare how lock free implementations handle contention since that's what they're really good at. If work were done per element you would see throughput increase as threads increase. Dmitry's queue is pretty amazing, so I'd suggest checking that one out if you want something to use in production. It has slightly different properties than mine though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T00:21:50.637",
"Id": "64099",
"Score": "0",
"body": "Do you have a simple usage example? I've tried to put together a quick test but am afraid I am missing something obvious."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T02:48:03.590",
"Id": "64294",
"Score": "0",
"body": "Apologies Joe, I hit the character limit on my post so couldn't add any examples. Also I'm writing this on my phone so hopefully I don't make any mistakes. The queue in intrusive, so maybe that's the unclear part. Here's some minimal code sample: struct Item { int data; mutable std::atomic<LockfreeNode> node; }; LockfreeQueue<Item> queue(&Item::node); Item a = { 1 }, b = { 2 }; queue.Queue(a); queue.Queue(b); Item* pa = queue.Dequeue(); Item* pb = queue.Dequeue(); Item* pc = queue.Dequeue(); assert(pa == &a); assert(pb == &b); assert(!pc);"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-28T17:35:40.157",
"Id": "130003",
"Score": "0",
"body": "On what system have you benchmarked this? How many cores? My experience with lockfree algorithm is that they are always wastefull on single cores and often degrade when the contention (far) exceeds the the number of cores."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-02T19:59:49.777",
"Id": "130552",
"Score": "0",
"body": "This was on a Xeon E5-1620 with 4 physical cores and 8 hardware threads. You're right in that when contention greatly exceeds the number of cores total throughput with these algorithms decreases, but I don't think it decreases any more so than you would experience with locks. You're also right in that these algorithms are certainly not optimal for single cores; in that case you could maybe switch your queue implementation with a non-thread-safe one at runtime."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-26T13:27:14.757",
"Id": "136135",
"Score": "0",
"body": "@FilipeSantos Lock free doesn't mean wait free. For example, a [CAS](http://en.wikipedia.org/wiki/Compare-and-swap) could need to loop several times, so that would not be wait free. An example of something that *is* wait free would be using an atomic exchange to atomically grab a counter and set it to zero - there is no possibility of another thread interfering with the exchange (cache miss doesn't count) so it is wait free."
}
] |
[
{
"body": "<p>I just have some stylistic things for a start:</p>\n\n<ul>\n<li><p>Since your custom types are in PascalCase, your function names should instead be in camelCase or in snake_case. This isn't a requirement, but it makes it easier to distinguish between them.</p></li>\n<li><p>The naming convention used for the <code>private</code> members looks like a form of Hungarian Notation, which is quite disliked in strongly-typed languages such as C++. It is more common to prefix members with <code>m_</code> instead, though you may not need to do that here.</p></li>\n<li><p>Some functions such as <code>NextVersion()</code>, <code>PreviousVersion()</code>, and <code>ToElement()</code> don't modify the argument, so those arguments should be <code>const&</code> in order to avoid a copy.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-26T18:40:46.557",
"Id": "74943",
"ParentId": "24696",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T07:09:45.097",
"Id": "24696",
"Score": "16",
"Tags": [
"c++",
"thread-safety",
"lock-free",
"atomic",
"producer-consumer"
],
"Title": "Lock-free multiple-consumer multiple-producer queue"
}
|
24696
|
<p>I've created the following string manipulation function for randomizing my passed string in Lua:</p>
<pre><code>require "string"
require "math"
math.randomseed( os.time() )
function string.random( self )
local tTemporary, tNew = {}, {}
if not self or self:len() < 5 then
return nil
end
self:gsub( "%a", function( cChar )
table.insert( tTemporary, cChar )
end
)
for i = 1, #tTemporary, 1 do
local iRandom = math.random(1, #tTemporary)
tNew[i] = tTemporary[iRandom]
table.remove( tTemporary, iRandom )
end
return table.concat(tNew, " ")
end
</code></pre>
<p>Can this be optimized/more-randomised?</p>
|
[] |
[
{
"body": "<p>A couple of points to consider:</p>\n\n<ul>\n<li>Calling your function <code>shuffle</code> instead of <code>random</code> would be a better name since that's really what it's doing.</li>\n<li>The extra intermediate tables aren't really necessary to perform the shuffle. A single table is enough and you can perform the shuffle in-place right on that table.</li>\n<li>Consider a better separation between the process of shuffling and how the input is stored. For example, if you have your shuffle function take a table instead then that function can be reused on any kind of data and not just strings.</li>\n<li>I would do away with the Hungarian notation and just drop the type prefix on the variable names. Remember Lua variables themselves doesn't have a type. If you later change what that variable refers to then the Hungarian notation becomes misleading.</li>\n</ul>\n\n<p>So I would refactor your original code into two functions. Here's one possibility:</p>\n\n<pre><code>function shuffle(self)\n if type(self) ~= 'table' then return nil end\n\n for i = #self, 2, -1 do\n local randi = math.random(i)\n self[i], self[randi] = self[randi], self[i]\n end\n return self\nend\n\nfunction shuffle_words(str)\n local strtable = {}\n for each in str:gmatch(\"%a+\") do\n table.insert(strtable, each)\n end\n return table.concat(shuffle(strtable), ' ')\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-04T05:58:02.333",
"Id": "39936",
"Score": "0",
"body": "`\"%a+\"` should be `\"%a\"`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-05T20:47:49.113",
"Id": "40007",
"Score": "0",
"body": "This is just an example of course, it assumes the input string is a bunch of words delimited by whitespace. If you have a different set of constraints then yes you *should* change the regex pattern to fit your needs."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-04T03:32:24.780",
"Id": "25794",
"ParentId": "24700",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "25794",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T10:10:15.953",
"Id": "24700",
"Score": "4",
"Tags": [
"strings",
"random",
"lua"
],
"Title": "Generating random strings"
}
|
24700
|
<p>I've implemented a simple program that finds all prime numbers between two integer inputs using Sieve of Eratosthenes, but the online judge is still complaining that the time limit is exceeding. Maybe I'm doing something wrong, but how can I optimize (or debug if necessary) my code?</p>
<pre><code>#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int t;
unsigned int i, j, k;
cin >> t;
int m, n;
cin >> m >> n;
if (n - m <= 100000 && m <= n && 1 <= m && n <= 1000000000)
{
int a[n - m + 1];
for (j = 0; j < n - m + 1; ++j)
{
a[j] = m + j;
}
for (j = 2; j <= sqrt (n); ++j)
{
for (k = 0; k < n - m + 1; ++k)
{
if (a[k] % j == 0 && a[k] != 0)
{
break;
}
}
for (; k < n - m + 1; k = k + j)
{
if (a[k] != j)
{
a[k] = 0;
}
}
}
if (a[0] == 1)
{
a[0] = 0;
}
for (j = 0; j < n - m + 1; ++j)
{
if (a[j])
{
cout << a[j] << endl;
}
}
cout << endl;
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T12:02:12.497",
"Id": "38173",
"Score": "0",
"body": "I don't know enough about C++ to offer any feedback on your code, but take a look through the primes tag -- there are several questions that discuss how to implement the Sieve of Eratosthenes and other prime-seeking algorithms."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T13:09:03.553",
"Id": "38178",
"Score": "0",
"body": "This code can be made much more readable just by reducing the vertical spacing – namely, moving opening braces to the previous line and removing redundant braces."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T13:13:23.933",
"Id": "38180",
"Score": "0",
"body": "@KonradRudolph: I agree, and such a change is common in Javascript. However, most C++ programmers seem to prefer braces being on their own line, never omitting redundant braces."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T13:30:08.090",
"Id": "38182",
"Score": "0",
"body": "never used Java, so i'm a typical c++ programmer :)"
}
] |
[
{
"body": "<h3>General Comments:</h3>\n<p>In C++ prefer not to use <code>using namespace std;</code><br />\nSee: <a href=\"https://stackoverflow.com/q/1452721/14065\">https://stackoverflow.com/q/1452721/14065</a> and nearly every other C++ question on code review.</p>\n<p>Prefer one line per variable.</p>\n<pre><code>unsigned int i, j, k;\n</code></pre>\n<p>Also try and give you variables meaningful names.</p>\n<p>Technaiclly variable length arrays (VLA) are not part of C++ (they are an extension inherited from C99).</p>\n<pre><code>int a[n - m + 1];\n</code></pre>\n<p>Prefer to use std::vector instead.</p>\n<p>Main is special and does not need a return</p>\n<pre><code>return 0; // If not used the compiler will plant `return 0`\n</code></pre>\n<p>I only use a return in main when there is a possibility of a failure being reported. Your code always returns true and you can indicate that the program is not expected to fail by not using any returns.</p>\n<h3>Algorithm</h3>\n<p>A more efficient prime finding algorithm is <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">Sieve of Eratosthenes</a></p>\n<p>There are several questions already on this subject a quick search should find them.</p>\n<h3>Style</h3>\n<p>A agree with @Konrad Rudolph that the vertical spacing is a bit extreme.</p>\n<p>Unlike @Kondrad I personally I like having all the braces {} even if they are not required as they help solve potential problems with macros (but these are rare nowadays). So there may be some compromise here.</p>\n<p>I also like my braces horizontally aligned like you.<br />\nBut this is usually a team decision and you don't get a choice (majority rule and being consistent with the code base is more important in terms of readability).</p>\n<p>Sometime you can use a compromise:</p>\n<pre><code> if (a[k] != j)\n { a[k] = 0; // I only do this if its a single liner.\n }\n\n // Alternatively\n a[k] = (a[k] != j) ? 0 : a[k];\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T20:42:41.717",
"Id": "38197",
"Score": "0",
"body": "emm, i have solved my problem, was every time reconstructing my sieve, thanks for comments on my style of coding"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T20:45:32.230",
"Id": "38198",
"Score": "0",
"body": "i have used \"using namespace std\" for simplicity, otherwise i don't use it in header files but use in implementation files; haven't given meaningful names because there was pressure in the size of code; \"return 0\" is my personal habit as well as horizontal align of braces; but thanks, that was a very useful comment on my code"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T17:57:52.677",
"Id": "24721",
"ParentId": "24701",
"Score": "2"
}
},
{
"body": "<p>You say you have implemented a Sieve of Eratosthenes but the code doesn't do\nwhat I understand from the Wiki page. Maybe you have changed it now, as your\ncomment to Loki's comment implies.</p>\n\n<p>Here are a few extra comments to add to those from @LokiAstari </p>\n\n<ul>\n<li><p>Use of <code>unsigned</code> is not necessary or desirable. Just use <code>int</code> unless there\nis good reason for an unsigned (e.g. when you have a bitmap or similar)</p></li>\n<li><p>You repeat the expression <code>n - m + 1</code> several times. Although the compiler\nwill optimise this away, the reader has to read it each time. Best to put\nsuch an expression into a constant, e.g.:</p>\n\n<pre><code> const int range = n - m + 1;\n</code></pre></li>\n<li><p>Variables <code>i</code> and <code>t</code> are functionally unused. </p></li>\n<li><p><code>main</code> takes argc/argv parameters. Also, it is normal not to do all the work\nin <code>main</code>, although for a small program like this that is perhaps irrelevant.</p></li>\n<li><p>Your initial <code>if</code> clause might be better inverted to avoid the indentation\ncaused. Also note that it is easy to mistake the precedence of operators, so\nbrackets are safer:</p>\n\n<pre><code>if ((n - m > 10000000) || (m >= n) || (m < 0) || (n > 1000000000)) {\n // print an error\n exit(1);\n}\n</code></pre></li>\n<li><p>In general it is better to use functions to aeparate parts of a program into\nsmall units that are easily tested or otherwise verified. The overhead of a\nfunction call is often zero (the compiler can optimise the call away). So\nsome of your loops could be extracted into functions - but <strong>only</strong> if using a\nfunction is 'makes sense' (which takes experience to decide).</p></li>\n<li><p>The Sieve of Eratosthenes doesn't really need any division. It is probably\nbetter to compute all primes from 2 upwards and then just print the ones\nrequested rather than trying to start at the specified minimum bound.</p></li>\n<li><p>Nested loops are in my opinion best avoided. </p></li>\n<li><p>You say you used short names to keep the program short. \nBut even your short names are not well\nconsidered. For example, the first loop uses <code>j</code> as a loop variable to\ninitialise the sieve: access to the sieve uses <code>a[j]</code>. The following loop\nuses <code>j</code> as a loop variable but it is never used to access the sieve -\ninstead the inner loop uses <code>k</code> as a variable: <code>if (a[k] % j == 0....</code>.\nMaybe this is nit-picking but consistency is an important aspect of\nprogramming. Note also that loop variables are often best defined in the\nloop:</p>\n\n<pre><code>for (int i = 0; i < range; ++i) { \n etc\n}\n</code></pre></li>\n</ul>\n\n<p>Here is my attempt at the sieve, for what it is worth:</p>\n\n<pre><code>#include <stdio.h>\n#define SIZE 1000000\n\nstatic void prime_set(char *sieve, int n, size_t size)\n{\n for (int i = n + n; i < (int) size; i += n) {\n sieve[i] = 1;\n }\n}\n\nstatic int prime_next(char *sieve, int n, size_t size)\n{\n for (int i = n + 1; i < (int) size; ++i) {\n if (!sieve[i])\n return i;\n }\n return 0;\n}\n\nstatic void prime_print(const char *sieve, int min, int max)\n{\n for (int i = min; i < max; ++i) {\n if (!sieve[i]) {\n printf(\"%d\\n\", i);\n }\n }\n}\n\nint main(int argc, char **argv)\n{\n const int min = 1;\n const int max = SIZE;\n int prime = 1;\n char sieve[SIZE] = {0};\n\n while ((prime = prime_next(sieve, prime, SIZE)) != 0) {\n prime_set(sieve, prime, SIZE);\n }\n /* remaining zeros in sieve are primes */\n prime_print(sieve, min, max);\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T07:51:00.400",
"Id": "38221",
"Score": "0",
"body": "thanks, actually, in small programs i forget about making other functions or using reasonable names to variables, now considering to change that habit"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T07:51:23.873",
"Id": "38222",
"Score": "0",
"body": "speaking about unsigned - why is it bad to iterate with unsigned int?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T12:46:59.737",
"Id": "38236",
"Score": "0",
"body": "It is not the iteration itself, but the use of an unsigned in combination with signed numbers. This can cause unexpected errors and will cause compiler warnings if you enable the right options. See http://soundsoftware.ac.uk/c-pitfall-unsigned for a discussion of unsigned"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T23:42:59.783",
"Id": "24738",
"ParentId": "24701",
"Score": "3"
}
},
{
"body": "<p>Have a think about what your code actually does when it tries to remove the multiples of a large prime, lets say 31263 (just guessing that it's a prime). You start at the beginning of the sieve, using trial division to check if each number is divisible by 31263. That will take on average about 15,600 attempts. But then you continue the search if that number was already removed, which will take exactly 31263 attempts. The first multiple of 31263 that wasn't yet removed is 31263^2. So there is an excellent chance that you actually divide <em>every</em> number in the interval by 31263, and that is absolutely killing the performance.</p>\n\n<p>If you are examining numbers from m to n, and trying to remove multiples of a prime p, the first multiple is ((m - 1) / p) + 1) * p. <em>One</em> calculation. </p>\n\n<p>And usually you make a sieve for odd numbers only - saves you 75% of the work (since you remove multiples of all numbers, including even ones, which is pointless once multiples of 2 are removed).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-23T13:25:00.303",
"Id": "45140",
"ParentId": "24701",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24721",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T10:37:00.110",
"Id": "24701",
"Score": "1",
"Tags": [
"c++",
"optimization",
"algorithm",
"primes"
],
"Title": "Prime Number Generator algorithm optimization"
}
|
24701
|
<p>Think of the numpad number layout.</p>
<p><code>hvd = horizontal, vertical or diagonal</code></p>
<p><code>coord = 1,2 or 3</code> if horizontal or vertical and 1 or 2 if diagonal (1 is up, 2 is down)...</p>
<p><code>hello('v', 2)</code> - Asking for the second vertical column etc</p>
<pre><code>def hello(hvd, coord):
if hvd == 'h':
print "horizontal it is"
if coord == 1:
print "789"
elif coord == 2:
print "456"
elif coord == 3:
print "789"
else:
print "coord is wrong"
elif hvd == 'v':
print "vertical it is"
if coord == 1:
print "741"
elif coord == 2:
print "852"
elif coord == 3:
print "963"
else:
print "coord is wrong"
elif hvd == 'd':
print "diagonal it is"
if coord == 1:
print "159"
elif coord == 2:
print "753"
else:
print "coord is wrong"
else:
print "hvd is wrong"
</code></pre>
<p>I just want a critique on this function. I am interested in knowing if there is a nicer way to do what I am doing and if there is anything wrong with my code.</p>
<p>It seems quite hard to look at especially since it contains place holder statements and the actual statements I want might be 10 lines long each... Would be unwieldy surely?</p>
|
[] |
[
{
"body": "<p>A nicer way to do the same would be to use a dictionary:</p>\n\n<pre><code>def hello(hvd, coord): \n d = {'h': [\"789\", \"456\", \"123\"],\n 'v': [\"741\", \"852\", \"963\"], \n 'd': [\"159\", \"753\"]}\n try:\n print d[hvd][coord-1]\n except IndexError:\n print \"coord is wrong\"\n except KeyError:\n print \"hvd is wrong\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-29T13:06:52.497",
"Id": "207124",
"Score": "1",
"body": "Are you sure you want to print from inside the function? Isn't returning a value more reusable?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-30T06:45:15.567",
"Id": "207277",
"Score": "1",
"body": "@Caridorc Yes, that would be a further improvement. alexwlchan has that angle covered now."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T13:47:51.037",
"Id": "24710",
"ParentId": "24703",
"Score": "6"
}
},
{
"body": "<p>A few suggestions:</p>\n\n<ul>\n<li><p><strong>A function should either do some work, or return a value – not both.</strong> Your function is (1) deciding which set of digits to return, and (2) printing them to stdout. It should just return the set of digits, and let the caller decide how to use them.</p></li>\n<li><p><strong>Don’t use print statements for errors.</strong> Raise exceptions instead – that allows callers to handle problems gracefully with <code>try … except</code>, rather than having to parse what just got sent to stdout.</p>\n\n<p>As a corollary, it would be good for your error messages to include the invalid value. This can be useful for debugging – if your function is several layers deep and throws an exception, it may not be obvious to the end user what the bad value was.</p>\n\n<p>You may also want to specify valid values.</p></li>\n<li><p><strong>Use a dictionary for the values, not multiple if branches.</strong> This is a more concise and readable way to express the information.</p></li>\n<li><p><strong>You can be more defensive to user input.</strong> If the user enters 'H', 'V' or 'D', their intention is unambiguous – but your code will reject it. Perhaps lowercase their input first?</p></li>\n<li><p><strong>I have no idea why the function is called hello().</strong> It doesn’t tell me anything about what the function does. There’s not a docstring either. A better name and documentation would tell me:</p>\n\n<ul>\n<li>What the function is supposed to do</li>\n<li>What arguments I’m supposed to supply</li>\n</ul>\n\n<p></p></p>\n\n<p>You’ve already written most of this in the question – just put it in the code!</p>\n\n<p></p></p></li>\n</ul>\n\n<p></p></p>\n\n<p>Here’s a partially revised version:</p>\n\n<pre><code>def numpad_digits(hvd, coord):\n digits = {\n \"h\": [\"123\", \"456\", \"789\"],\n \"v\": [\"741\", \"852\", \"963\"], \n \"d\": [\"159\", \"753\"]\n }\n try:\n # Offset by one - the user will be thinking of a 1-indexed list\n return digits[hvd.lower()][coord-1]\n except IndexError:\n raise ValueError(\"Invalid value for coord: %s\" % coord)\n except KeyError:\n raise ValueError(\"Invalid value for hvd: %s\" % hvd)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-29T16:42:43.233",
"Id": "112233",
"ParentId": "24703",
"Score": "3"
}
},
{
"body": "<p>The danger of having the programmer do the computer's work is that you might do it wrong. In this case, it's impossible to get the \"123\" row due to a copy-and-paste bug.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-29T17:38:01.170",
"Id": "112239",
"ParentId": "24703",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T11:51:31.947",
"Id": "24703",
"Score": "3",
"Tags": [
"python"
],
"Title": "Numpad number layout"
}
|
24703
|
<p>Is this the most efficient way to find if a number is prime? I can't think of a better way and it seems to run pretty quickly.</p>
<pre><code> public boolean primes(int num){
for(int i = 2; i < num; i++){
if(num % i == 0){
System.out.println(num + " is not prime");
return false;
}
}
System.out.println(num + " is prime");
return true;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T13:16:08.667",
"Id": "38181",
"Score": "1",
"body": "Probably even the deterministic variant of Miller-Rabin primality testing is much faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T12:18:45.023",
"Id": "38237",
"Score": "0",
"body": "Have you checked Ferma tests or variants? e.g. [here is nice discussion](http://codereview.stackexchange.com/questions/24625/miller-rabin-prime-test-speed-is-the-main-goal)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T20:54:07.320",
"Id": "38622",
"Score": "0",
"body": "This is my favorite discussion of primality testing: http://stackoverflow.com/questions/9625663/calculating-and-printing-the-nth-prime-number"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-04T06:27:59.277",
"Id": "326054",
"Score": "2",
"body": "I have asked this question to be closed as asking for more efficient primarily testing is not code review related. Having side effects in this code is definitely code review related. What is \"System.out.println\" doing in middle of a Boolean method?"
}
] |
[
{
"body": "<p>A faster method would be to skip all even numbers and only try up to the square root of the number.</p>\n\n<pre><code>public static boolean isPrime(int num){\n if ( num > 2 && num%2 == 0 ) {\n System.out.println(num + \" is not prime\");\n return false;\n }\n int top = (int)Math.sqrt(num) + 1;\n for(int i = 3; i < top; i+=2){\n if(num % i == 0){\n System.out.println(num + \" is not prime\");\n return false;\n }\n }\n System.out.println(num + \" is prime\");\n return true; \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-15T04:21:39.297",
"Id": "127764",
"Score": "2",
"body": "The code is very good and is just what I did at first. Then I realized that there is no point in adding 1 to the sqrt of num. And of course the printing makes it less efficient, as it is already returning the `boolean` value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-16T23:52:02.627",
"Id": "211651",
"Score": "0",
"body": "It prints 1 as a prime number which is not a prime number."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-03-19T08:55:46.723",
"Id": "299343",
"Score": "0",
"body": "the first if statement should be:\nif(num <= 2 || num%2 == 0){\n return false;\n}"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-04T06:21:10.680",
"Id": "326051",
"Score": "1",
"body": "please refactor this code, it is a bad example of a code that is just suppose to return a true, false but it is having side effects, what is System.out.println doing in middle of a function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-03T06:43:31.153",
"Id": "411548",
"Score": "0",
"body": "This method runs for all odd numbers from 3 to sqrt of input number. But this can be even more improved if we **only divide with prime numbers in that range**. For example; If we are checking for number 131, it makes sense to try to divide it using 3 but does not make sense to divide it with 9. Because if its not divisible by 3 it will never be divisible by 9."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T12:28:21.700",
"Id": "24708",
"ParentId": "24704",
"Score": "21"
}
},
{
"body": "<p>This is what I did:</p>\n\n<pre><code>public static boolean isPrime(int n) {\n\n if((n > 2 && n % 2 == 0) || n == 1) {\n return false;\n }\n\n for (int i = 3; i <= (int)Math.sqrt(n); i += 2) {\n\n if (n % i == 0) {\n return false;\n }\n }\n\n return true;\n }\n</code></pre>\n\n<p>In the first if test, I put the <code>(n > 2 && n % 2 == 0)</code>first, because I think that would short-circuit the <code>||</code> and that evaluation will come more often than <code>n == 1</code> so it should skip that and become true a little bit faster than doing it the other way around.</p>\n\n<p>Also, like Tom pointed out in the accepted answer, you start countin at 3, in order to remove the addition of 1 to the square root, I had to use <code>i <= (int)Math.sqrt(n)</code> otherwise it blows up, I don't know why.</p>\n\n<p>I tested my code with the first 10 thousand primes and it seems ok as I get 104,729 as the 10,000th number, which is correct, it gets the result in 1.324 seconds, which I'm not sure if it's fast or not.</p>\n\n<p>Note: </p>\n\n<p>As ferhan pointed out, with the accepted answer it says that 1 is a prime number, which is not. But with the suggestion from LeTex, I get a weird result and not the correct answer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-04T06:25:42.827",
"Id": "326052",
"Score": "1",
"body": "Thank you for not having used side effects in middle of the method as the accepted answer has done. but just like the accepted answer, this too is far from efficient. But I'll raise that with the question poster instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-04T17:54:22.753",
"Id": "326183",
"Score": "0",
"body": "@Arjang I still have a long way to learn how to code correctly, and I'd really appreciate it if you could point me in the right direction on how to make this code more efficient, thanks in advance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-04T21:26:11.703",
"Id": "326221",
"Score": "1",
"body": "Lord Anubis, god of the under world. Making that particular code efficient is like trying to make bubble sort more efficient, you wont do that. To make that code better though, you already have removed side effects, some how making it simpler but most of all looking up primarility testing to see more efficient ways of doing it. Not all code can be made better, sometimes abandon the code and start clean, separate knowledge domain related problems from structural code problems, also look up \"clean code\" book, SOLID,DRY methodologies, design patterns."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-04T21:29:22.883",
"Id": "326223",
"Score": "0",
"body": "also follow the links under the question, at the top of the page."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-04T05:33:27.480",
"Id": "172043",
"ParentId": "24704",
"Score": "3"
}
},
{
"body": "<p>This program is an efficient one. I have added one more check-in if to get the square root of a number and check is it divisible or not if it's then its not a prime number. </p>\n\n<pre><code>public static void main(String[] args) {\n\n Scanner sc = new Scanner(System.in);\n int T; // number of test cases\n T = sc.nextInt();\n long[] number = new long[T];\n if(1<= T && T <= 30){\n for(int i =0;i<T;i++){\n number[i]=sc.nextInt(); // read all the numbers\n }\n for(int i =0;i<T;i++){\n if(isPrime(number[i]))\n System.out.println(\"Prime\");\n else\n System.out.println(\"Not prime\"); \n }\n }\n else\n return;\n }\n // is prime or not\n static boolean isPrime(long num){\n if(num==1)\n return false;\n if(num <= 3)\n return true;\n if(num % 2 == 0 || num % 3 == 0 || num % (int)Math.sqrt(num) == 0)\n return false; \n for(int i=4;i<(int)Math.sqrt(num);i++){\n if(num%i==0)\n return false;\n }\n return true; \n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T15:17:19.153",
"Id": "227096",
"ParentId": "24704",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "24708",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T12:07:46.340",
"Id": "24704",
"Score": "7",
"Tags": [
"java",
"primes"
],
"Title": "Efficiently determining if a number is prime"
}
|
24704
|
<p><a href="http://angularjs.org/" rel="nofollow">AngularJS</a> is an open-source JavaScript framework for building <a href="http://en.wikipedia.org/wiki/Create,_read,_update_and_delete" rel="nofollow">CRUD</a> centric <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="nofollow">AJAX</a> style web applications. Its goal is to <a href="http://en.wikipedia.org/wiki/Shim_%28computing%29" rel="nofollow">shim</a> the browser to augment the HTML vocabulary with directives useful for building dynamic web-apps.</p>
<p>The Angular philosophy is that UI is best described in declarative form (HTML), and that behavior is best described in imperative form (JavaScript) and that the two should never meet.</p>
<h3>Notable features</h3>
<ul>
<li>Teach your browser new tricks by adding behavior to HTML tags/attributes</li>
<li>Controllers provide code-behind DOM with clear separation from the view</li>
<li>2-way data binding without the need to extend or wrap the model objects</li>
<li>Dependency injection assembles the application <a href="http://blog.angularjs.org/2012/08/getting-rid-of-main.html" rel="nofollow">without <code>'main'</code> method</a></li>
<li>Promises / futures remove many callbacks from code when communicating with server</li>
<li>Form validation</li>
<li>Strong focus on testability</li>
</ul>
<h3>Download</h3>
<ul>
<li>Source code: <a href="https://github.com/angular/angular.js" rel="nofollow">GitHub</a> (<a href="https://github.com/angular/angular.js/issues" rel="nofollow">Issue Tracker</a>)</li>
<li>Files: <a href="http://code.angularjs.org" rel="nofollow">the files</a></li>
</ul>
<h3>Community</h3>
<ul>
<li>Follow us: <a href="http://twitter.com/angularjs" rel="nofollow">Twitter</a>, <a href="https://plus.google.com/u/0/110323587230527980117" rel="nofollow">Google+</a></li>
<li>Subscribe: <a href="http://groups.google.com/group/angular" rel="nofollow">angular@googlegroups.com</a></li>
<li>Hangout: <a href="http://webchat.freenode.net/?channels=angularjs&uio=d4" rel="nofollow">IRC</a></li>
</ul>
<h3>Asking a question</h3>
<ul>
<li>Reduce your issue to a small example</li>
<li>Post a reduced working code on <a href="http://plnkr.co/" rel="nofollow">plnkr.co</a> or <a href="http://jsdiffle.com" rel="nofollow">jsfiddle.net</a></li>
<li>Don't know how? Clone one of these existing <a href="https://github.com/angular/angular.js/wiki/JsFiddle-Examples" rel="nofollow">jsfiddles</a></li>
</ul>
<h3>Getting Started</h3>
<ul>
<li><a href="http://docs.angularjs.org/#!/cookbook/helloworld" rel="nofollow">Hello World!</a></li>
<li><a href="http://docs.angularjs.org/#!/tutorial" rel="nofollow">Tutorial</a></li>
<li><a href="https://github.com/angular/angular-seed" rel="nofollow">Seed application</a> project</li>
<li><a href="https://github.com/joshdmiller/ng-boilerplate/" rel="nofollow">Angular Boilerplate</a> for kickstarting your new AngularJS application</li>
<li>Learn by example and other AngularJS <a href="https://github.com/angular/angular.js/wiki/JsFiddle-Examples" rel="nofollow">jsfiddles</a></li>
<li><a href="http://addyosmani.github.com/todomvc/" rel="nofollow">TodoMVC</a> in many JavaScript frameworks</li>
</ul>
<h3>Developed by <a href="http://google.com" rel="nofollow">Google</a></h3>
<ul>
<li>Miško Hevery <a href="http://misko.hevery.com" rel="nofollow">blog</a> <a href="http://twitter.com/mhevery" rel="nofollow">twitter</a></li>
<li>Igor Minár <a href="http://blog.igorminar.com/" rel="nofollow">blog</a> <a href="http://twitter.com/IgorMinar" rel="nofollow">twitter</a></li>
<li>Vojta Jína <a href="http://twitter.com/vojtajina" rel="nofollow">twitter</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T12:14:43.797",
"Id": "24705",
"Score": "0",
"Tags": null,
"Title": null
}
|
24705
|
Code written using version 1 of the AngularJS open-source JavaScript framework. Use 'angular-2+' for code using later versions.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-04-04T12:14:43.797",
"Id": "24706",
"Score": "0",
"Tags": null,
"Title": null
}
|
24706
|
<p>Is there anything wrong with doing this:</p>
<pre><code>Public Class Form1
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
For value As Integer = 0 To 1000000
Dim p As New Person
p.ID = value
p.DoSomething()
p = Nothing
Next
End Sub
Public Class Person
Dim _ID As Integer
Public WriteOnly Property ID() As Integer
Set(ByVal value As Integer)
_ID = value
End Set
End Property
Public Sub DoSomething()
_ID = _ID + 1
'Do more with ID
End Sub
End Class
End Class
</code></pre>
<p>As appose to this:</p>
<pre><code>Public Class Form1
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
For value As Integer = 0 To 1000000
Person.DoSomething(value)
Next
End Sub
Public Class Person
Public Shared Sub DoSomething(ByVal id As Integer)
id = id + 1
'Do more with ID
End Sub
End Class
End Class
</code></pre>
<p>I have written some code similar to that in sample 1. I have read online that code 1 can cause problems when threading is involved, but I do not understand why? Are there any other problems with sample 1? Sample 1 meets my requirements better.</p>
|
[] |
[
{
"body": "<p>In sample1, as you call it, you have an instance field which you change. Therefore, the <code>Person</code> class you are using is <strong>mutable</strong>. Mutable classes are prominent to concurrency issues if a single instance is manipulated by multiple threads, <strong>unless explicit synchronization</strong> mechanism is <em>properly</em> involved.</p>\n\n<p>In sample2, if you pass the value in the method, and you are not modifying the state of the <code>Person</code> class as you do your business logic, then the code is thread safe. No other thread can access the local variable <code>id</code> and modify it concurrently, since it is visible to the current thread only. So there is no need to apply a synchronization mechanism.</p>\n\n<p>However, sample2 may not be appropriate enough for your concrete requirements. If you give more code clues on what happens in the method in question, then a more-accurate advice can be given.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T14:47:32.923",
"Id": "24714",
"ParentId": "24713",
"Score": "3"
}
},
{
"body": "<p>The reason that the first example would be considered problematic when multiple threads are involved, is because in that example, a <code>Person</code> object maintains state (i.e. data) and it has methods that act upon that state. There's nothing wrong with designing classes that way, per se, and it doesn't mean that the class cannot be used by multi-threaded applications safely--it just makes multi-threading more difficult.</p>\n\n<p>For instance, consider this example:</p>\n\n<pre><code>Public Class Form1\n Dim _p As New Person\n\n Private Sub DoWork(value As Integer)\n _p.Id = value\n _p.DoSomething()\n End Sub\n\n ' ... Code that calls DoWork on multiple threads ...\n\n Public Class Person\n Dim _id As Integer\n Public WriteOnly Property Id() As Integer\n Set(ByVal value As Integer)\n _id = value\n End Set\n End Property\n\n Public Sub DoSomething()\n _id = _id + 1\n 'Do more with Id\n End Sub\n End Class\nEnd Class\n</code></pre>\n\n<p>Let's say that in the above example, the <code>DoWork</code> method is called from two different threads simultaneously, and the order that the lines are processed is like this:</p>\n\n<ol>\n<li>Thread A sets <code>_p.Id = 1</code></li>\n<li>Thread B sets <code>_p.Id = 10</code></li>\n<li>Thread A calls <code>_p.DoSomething</code> which increments <code>_p.Id</code> to <code>11</code></li>\n<li>Thread B calls <code>_p.DoSomething</code> which increments <code>_p.Id</code> to <code>12</code></li>\n</ol>\n\n<p>As you can see, that would certainly be undesired behavior. There are three ways to fix this problem. The first way is to use one of the available synchronization techniques to make sure that only one thread uses the object at a time, for instance:</p>\n\n<pre><code>Private Sub DoWork(value As Integer)\n SyncLock _p\n _p.Id = value\n _p.DoSomething()\n End SyncLock\nEnd Sub\n</code></pre>\n\n<p>By synchronously locking on the object, if a second thread tries to call <code>DoWork</code> at the same time, the second thread's execution will be blocked (i.e. hung) until the first thread's call to <code>DoWork</code> is complete. The problem with this approach is that, at least to some extent, it defeats the purpose of multi-threading because only one thread can do that part of the work at a time.</p>\n\n<p>The second way to fix this would be to have each thread create a new <code>Person</code> object so that they don't interfere with each other. For instance, instead of having the <code>_p</code> object declared as a class-level field, you could just create a new <code>Person</code> object inside the <code>DoWork</code> method, like this:</p>\n\n<pre><code>Private Sub DoWork(value As Integer)\n Dim p As New Person()\n p.Id = value\n p.DoSomething()\nEnd Sub\n</code></pre>\n\n<p>The third way to fix this would be to use your second example. By fixing the <code>Person</code> class so that it is a stateless class, multiple threads can call the same object as often at the same time as necessary because the data is stored outside of the <code>Person</code> class. So, as long as each thread is instantiating a separate object to store the data before passing it into the <code>Person</code> object, all the threads can share the same <code>Person</code> object without needing to worry about collisions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T21:15:30.460",
"Id": "38504",
"Score": "0",
"body": "Thanks. +1. I assume that if I do not create any Threads myself i.e. using the Thread class, then there is no issues?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T11:41:27.033",
"Id": "38554",
"Score": "1",
"body": "It's not a matter of how you create your threads--it's a matter, rather, of how the threads use your `Person` class. If multiple threads share the same `Person` object, then you should have some concerns. If they each use their own independent `Person` object, then it's not a concern (unless the `Person` class contains shared members or shares dependencies between instances)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T16:16:54.157",
"Id": "38572",
"Score": "0",
"body": "Thanks for the helpful comment. I assume that if I do not explicitly create any Threads then there is no issue to even think about? The reason I ask is because I know that ASP.NET uses MTA's (multi threaded apartments)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T16:19:53.310",
"Id": "38573",
"Score": "0",
"body": "Correct. If you are not explicitly making your code multi-threaded, none of it is an immediate concern."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T16:44:16.627",
"Id": "38575",
"Score": "0",
"body": "Thanks I assume that the fact that ASP.NET uses MTA is insignificant. I know what MTA's are in theory but I do not understand the relationship between MTAs and threads (System.Thread). Thanks again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T17:18:24.343",
"Id": "38577",
"Score": "0",
"body": "Can you confirm that MTA's are insignificant if Threads (system.thread) are not used?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T17:23:25.727",
"Id": "38578",
"Score": "0",
"body": "I can't speak absolutely authoritatively on that, but from what I do know, I would say that you don't have to worry about it. It's not an issue of whether or not the threads are MTA, it's just a matter of whether or not the threads are sharing objects. In a typical ASP.NET situation, it seems highly-unlikely that your threads are going to be sharing objects with each other without you doing so quite on purpose."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T18:57:05.047",
"Id": "38602",
"Score": "0",
"body": "Thanks. Finally, is sample 1 Person an example of a service class as it is providing a service to the form?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T23:16:47.037",
"Id": "38635",
"Score": "0",
"body": "I can't answer that. Sounds like a great new question to ask :)"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T16:13:09.703",
"Id": "24863",
"ParentId": "24713",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24714",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T14:37:11.067",
"Id": "24713",
"Score": "2",
"Tags": [
"design-patterns",
"vb.net"
],
"Title": "Objects and instance variables in loops"
}
|
24713
|
<p>I've leaped into SASS and am loving it. I'm asking for comments here on whether my SASS is well-formatted. </p>
<p>Here's the original CSS based on Zurb's Foundation Pagination styles, but adapted for use with Laravel's built-in pagination: </p>
<pre><code>div.pagination ul { display: block; height: 24px; margin-left: -5px; }
div.pagination ul li { float: left; display: block; height: 24px; color: #999; font-size: 14px; margin-left: 5px; }
div.pagination ul li a { display: block; padding: 1px 7px 1px; color: #555; font-weight: normal}
div.pagination ul li:hover a,
div.pagination li a:focus { background: $bgltblue; }
div.pagination ul li.disabled a { cursor: default; color: #999; }
div.pagination ul li.disabled:hover a,
div.pagination li.disabled a:focus { background: transparent; }
div.pagination ul li.active a { background: $headblue; color: white; font-weight: normal; cursor: default; }
div.pagination ul li.active a:hover,
div.pagination li.active a:focus { background: $headblue; }
</code></pre>
<p>Here's my manual conversion to SASS:</p>
<pre><code>div.pagination {
ul {
display: block; height: 24px; margin-left: -5px;
li {
float: left; display: block; height: 24px; color: #999; font-size: 14px; margin-left: 5px;
a {
display: block; padding: 1px 7px 1px; color: #555; font-weight: normal;
}
&:hover a {
background: $bgltblue;
}
&.disabled {
a {
cursor: default; color: #999;
}
&:hover a {
background: transparent;
}
}
&.active {
a {
background: $headblue; color: white; font-weight: normal; cursor: default;
&:hover {
background: $headblue;
}
}
}
}
}
li {
a:focus {
background: $bgltblue;
}
&.disabled {
a:focus {
background: transparent;
}
}
&.active {
a:focus {
background: $headblue;
}
}
}
}
</code></pre>
<p>I'd like to know if you think I have reduced it correctly, and where I might make improvements. I plan to replace the colours with <code>var</code>s already.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-05T20:33:46.930",
"Id": "49069",
"Score": "0",
"body": "Doesn't Foundation already use Sass?"
}
] |
[
{
"body": "<p>Some comments on your style of selecting:</p>\n\n<ul>\n<li><code>div.pagination</code> is overqualified. A container is almost always going to be a div, so you just can write <code>.pagination</code></li>\n<li>In many cases, there is no use for an extra container. You might as well apply the <code>pagination</code> class to the list itself: <code><ul class=\"pagination\"></code></li>\n<li><p>You also have a lot of redundancy in your selectors because you always use <code>ul</code> and <code>li</code> in the chains. This is not necessary and could be made easier:</p>\n\n<pre><code>.pagination ul {}\n\n/* li's can only appear in lists, no need to add it to the selector */\n.pagination li {}\n\n/* The only links inside your pagination are usually in relation to the pagination */\n.pagination a {}\n</code></pre></li>\n<li><p>If you have lists inside your pagination that need separate styling, use separate classes or place them outside of the actual pagination</p></li>\n<li>Don't overqualify the <code>.active</code> and <code>.disabled</code> classes as well. They will end up being on the list items anyway</li>\n</ul>\n\n<p><strong>Conclusion:</strong></p>\n\n<p><strong>You nest far too deep.</strong> Avoid nesting selectors deeper than 2–3 levels. Otherwise you get bloated CSS like this.</p>\n\n<p><strong>Compare my SCSS to yours:</strong></p>\n\n<pre><code>.pagination {\n display: block;\n height: 24px;\n margin-left: -5px;\n\n li {\n float: left;\n display: block;\n height: 24px;\n color: #999;\n font-size: 14px;\n margin-left: 5px;\n\n &:hover a {\n background: $bgltblue;\n }\n\n &.disabled {\n a {\n cursor: default;\n color: #999;\n\n &:hover,\n &:focus {\n background: transparent;\n }\n }\n }\n\n &.active {\n a {\n background: $headblue;\n color: white;\n font-weight: normal;\n cursor: default;\n\n &:hover,\n &:focus {\n background: $headblue;\n }\n }\n }\n }\n\n a {\n display: block;\n padding: 1px 7px 1px;\n color: #555;\n font-weight: normal;\n\n &:focus {\n background: $bgltblue;\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-25T11:31:48.503",
"Id": "40036",
"ParentId": "24716",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "40036",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T16:44:45.660",
"Id": "24716",
"Score": "12",
"Tags": [
"beginner",
"css",
"sass"
],
"Title": "Comments on SASS from CSS for a SASS beginner"
}
|
24716
|
<p>I have written a small snippet to validate a substring in a string in O(n). I have tested the code using some combinations. I require your help to let me know if there are any bugs in my code with respect to any other cases that I might have missed out:-</p>
<pre><code>class StringClass( object ):
def __init__( self, s ):
self._s = s
def __contains__( self, s ):
ind = 0
for ch in self._s:
if ind < len( s ) and ch == s[ind]:
ind += 1
elif ind >= len( s ):
return True
elif ch == s[0]:
ind = 1
elif ch != s[ind]:
ind = 0
if ind >= len( s ):
return True
if __name__ == '__main__':
s = StringClass( 'I llove bangaolove' )
print 'love' in s
</code></pre>
<p>PS: Here, Instead of trying to find the string 'love' in 'I llove bangalove', I'm using the other method: i.e. to find if the string 'I llove bangalove' contains 'love'. </p>
<p>Please let me know if there are any corrections to be made here.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T18:20:19.363",
"Id": "38191",
"Score": "0",
"body": "this is O(n), but incorrect (as @Poik pointed out). There are no O(n) algorithms for string matching, maybe O(n+m), using Rabin-Karp or Knuth-Morris-Pratt (n=length of string, m=length of string to match). Look them up."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T15:12:27.397",
"Id": "38315",
"Score": "1",
"body": "@Gabi Purcaru: if you need to check multiple substrings in the same string then there are better than `O(n+m)` algorithms if you preprocess the string first e.g., a [suffix array + LCP](http://en.wikipedia.org/wiki/Suffix_array) can give you `O(m + log n)` and suffix trees can give you O(m) substring search."
}
] |
[
{
"body": "<p>Your implementation seems ok, although I would test some corner cases before starting the iteration, ask yourself:</p>\n\n<p>What should be done in the case <code>s is None</code>? or <code>s == ''</code>? (Both can be handled in python simply by <code>if s:</code>.</p>\n\n<p>Besides that, your implementation seems correct, implement some unit tests to cover the corners cases and the expected results.</p>\n\n<p>About the complexity, it's linear in the length of the string you created the object with.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T17:09:57.720",
"Id": "38188",
"Score": "0",
"body": "Hey Pcalcao, thanks for that answer. Actually, I'm looking for any unit test which might fail for this program, but, couldn't figure any. So, can you help in testing whre this code will break (apart from the corner cases)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T17:11:52.290",
"Id": "38189",
"Score": "0",
"body": "I don't see any cases from reading the code, that probably means that it's working out alright."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T17:06:16.267",
"Id": "24718",
"ParentId": "24717",
"Score": "0"
}
},
{
"body": "<p>One case that you missed is replication in the search string.</p>\n\n<pre><code>>>> '1213' in StringClass('121213')\nFalse\n>>> '1213' in '121213'\nTrue\n</code></pre>\n\n<p>This is because your class is already past the second one before it sees a difference and has to start completely over.</p>\n\n<p>Asides from that, the empty string and None cases are problems, as is mentioned in other answers.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T17:25:36.260",
"Id": "24719",
"ParentId": "24717",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "24719",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T16:50:08.520",
"Id": "24717",
"Score": "0",
"Tags": [
"python"
],
"Title": "Possible Bugs in substring program"
}
|
24717
|
<p>I'm working on Project Euler's <a href="http://projecteuler.net/problem=23" rel="nofollow">problem #23</a>, which is</p>
<blockquote>
<p>Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers</p>
</blockquote>
<p>I came up with this algorithm. Find all abundant numbers under 28123 (defined <code>Numeric#abundant?</code>), this is slow and could be faster if skipped primes, but is fairly fast (less than 4 secs):</p>
<pre><code>abundant_numbers = (12..28123).select(&:abundant?)
</code></pre>
<p>Find all numbers that can be expressed as the sum of 2 perfect numbers:</p>
<pre><code>inverse_set = abundant_numbers.each.with_index.inject([]) do |a,(n,index)|
a.concat(
abundant_numbers[index..abundant_numbers.size-1]
.take_while { |i| (n+i) <= 28123 }.map { |i| n+i }
)
end.to_set
</code></pre>
<p>The rest them from all the integers under 28123 and sum them all:</p>
<pre><code>solution_set = (1..28123).set - inverse_set
solution_set.reduce(:+)
</code></pre>
<p><strong>Benchmarked:</strong></p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>▸ time ruby 0023.rb
real 0m20.036s
user 0m19.593s
sys 0m0.352s
▸ rvm use 2.0.0
▸ time ruby 0023.rb
Solution: 4*****1
real 0m7.478s
user 0m7.348s
sys 0m0.108s
</code></pre>
</blockquote>
<p>It works, but it's a little bit slow, takes about 20secs to solve, and I hear people around saying it can be solved within miliseconds. I'm sure many of you will have a quick insight on what have I missed.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T11:39:56.470",
"Id": "38230",
"Score": "0",
"body": "Why to optimize the PE solution, which finishes in the slowest language in far less, than a minute?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T14:42:13.423",
"Id": "38255",
"Score": "0",
"body": "Holy sh#t. Upgrading to ruby 2 got execution time down to 7 secs."
}
] |
[
{
"body": "<p>Your idea is perfectly fine (subtracting all sum of pairs from the candidates range), but I would write it differently:</p>\n\n<pre><code>xs = (1..28123)\nabundants = xs.select(&:abundant?)\nsolution = (xs.to_set - abundants.repeated_combination(2).to_set { |x, y| x + y }).sum\n</code></pre>\n\n<p>With a similar idea, this is probably faster (but also a bit less declarative):</p>\n\n<pre><code>xs = (1..28123)\nabundants = xs.select(&:abundant?).to_set\nsolution = xs.select { |x| abundants.none? { |a| abundants.include?(x - a) } }.sum\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T11:38:35.353",
"Id": "38229",
"Score": "0",
"body": "Why not `reduce(:+)`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T12:08:50.377",
"Id": "38233",
"Score": "0",
"body": "@Nakilon: Well, it's not necessary, but it gives you one thing less to worry about (is the input empty?). It does no harm to add the identity element of the operation. Anyway, I've abstracted it as `sum`, problem solved :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T14:45:08.093",
"Id": "38256",
"Score": "1",
"body": "This is about 1 second faster than mine, but yay!, readability counts :)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T09:59:42.963",
"Id": "24752",
"ParentId": "24723",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24752",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T18:23:58.067",
"Id": "24723",
"Score": "1",
"Tags": [
"ruby",
"programming-challenge",
"primes"
],
"Title": "Optimizing code for Project-Euler Problem #23"
}
|
24723
|
<p>This plugin is meant to filter through a table based on column header text that matches options given to it.
check it out here: <a href="http://jsfiddle.net/CEZx7/1/" rel="nofollow" title="Filter Table Plugin">Filter Table Plugin</a></p>
<p>Plugin code below for reference:</p>
<pre><code>//framework from http://jqueryboilerplate.com/
; (function ($, window, document, undefined) {
var pluginName = "filterTable",
defaults = {
};
function Plugin(element, options) {
this.element = element;
this.options = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function () {
$el = $(this.element);
$table = $('#' + $el.data('filtertable'));
var filterColumnNames = ($el.attr('data-filtercolumns')).split(',');
var filterColumns = new Array();
var altRowCSS = $el.data('filteralternatingcss');
//get the column index of the column we'll be filtering on
$table.find('th').each(function (i) {
for (j in filterColumnNames) {
if ($(this).text().trim() == filterColumnNames[j]) {
filterColumns.push(i + 1);
}
}
});
$el.keyup(function () {
var query = $(this).val();
var numDisplayed = 0;
//remove any no result warnings
$table.find('#noResultsRow').remove();
//hide all rows
$table.find('tr').removeClass(altRowCSS).hide();
//show the header row
$table.find('tr:first').show();
for (i in filterColumns) {
$table.find('tr td:nth-child(' + filterColumns[i] + ')').each(function () {
if ($(this).text().toLowerCase().indexOf(query.toLowerCase()) >= 0) {
$(this).parent().show();
numDisplayed++;
}
});
}
if (numDisplayed == 0) {
$tr = $('<tr>');
$tr.attr('id', 'noResultsRow');
$td = $('<td>').attr('colspan', $table.children('tbody').children('tr').children('td').length);
$td.html('No results for filter "' + query + '."');
$td.css({ textAlign: 'center' });
$tr.append($td);
$table.children('tbody').append($tr);
}
$table.find('tr:visible :odd').addClass(altRowCSS);
});
$el.keyup();
},
};
$.fn[pluginName] = function (options) {
return this.each(function () {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName, new Plugin(this, options));
}
});
};
})(jQuery, window, document);
</code></pre>
<p>Any improvements I can make?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T19:26:03.350",
"Id": "38195",
"Score": "0",
"body": "Forgot to mention one thing I might add is matching against whole words only - instead of 'ter' matching filter and terminal, it would only match terminal."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T01:38:10.437",
"Id": "58975",
"Score": "1",
"body": "Did you mean you're only matching at the start of the word? Neither `terminal` or `filter` are whole word matches of `ter`."
}
] |
[
{
"body": "<ol>\n<li><p>You have: </p>\n\n<pre><code>this._defaults = defaults;\n</code></pre>\n\n<p>This is redundant as the declaration :</p>\n\n<pre><code>var pluginName = \"filterTable\",\n defaults = {\n };\n</code></pre>\n\n<p>Can be accessed anywhere in your plugin.</p></li>\n<li><p>Declare all variables that you use. This is a really good practice to have change lines like:</p>\n\n<pre><code> $el = $(this.element);\n $table = $('#' + $el.data('filtertable'));\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>var $el = $(this.element);\nvar $table = $('#' + $el.data('filtertable'));\n</code></pre>\n\n<p>JavaScript will let you use them without but you'll run into issues otherwise.</p></li>\n<li><p>Variables need meaningful names so their lives don't seem meaningless and they despair. </p>\n\n<blockquote>\n <p><a href=\"http://thecodelesscode.com/case/34\" rel=\"nofollow\">Invective! Verb your expletive nouns!</a></p>\n</blockquote>\n\n<pre><code>$table.find('th').each(function (i)\n{\n for (j in filterColumnNames)\n {\n if ($(this).text().trim() == filterColumnNames[j])\n {\n filterColumns.push(i + 1);\n }\n }\n });\n</code></pre>\n\n<p>What is <code>i</code>? index? columnIndex?<br>\nWhat is <code>j</code>? currentColumnName?</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T01:53:15.667",
"Id": "36094",
"ParentId": "24728",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T19:24:24.107",
"Id": "24728",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "What improvements can I make to this table filtering jQuery Plugin?"
}
|
24728
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.