body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I'm working on a clone of <a href="http://www.kongregate.com/games/crovy/hunter-story" rel="nofollow">Hunter Story</a>. You shoot monsters with your bow. Recently I implemented collision detection, this is all working correctly, and I don't think the code needs any dramatic optimisations. The only thing I'm a bit worried about is how exactly I implemented it. I'm not sure if it complies with OOP standards.</p>
<p>The relevant code:</p>
<p>Level:</p>
<pre><code>public class Level extends Entity
{
public static ArrayList<Monster> onScreenMonsters = new ArrayList<Monster>(); //holds all monsters on the screen
public static ArrayList<Arrow> activeArrows = new ArrayList<Arrow>(); //holds all arrows on the screen
private void removeMonsters()
{
for (int i = 0; i < onScreenMonsters.size(); i++)
{
Monster m = onScreenMonsters.get(i);
if (m != null && m.getX() < 0)
{
onScreenMonsters.remove(m); //removes monsters that are out of bounds.
}
if (!m.isAlive()) //set to false when monster has been hit (Will be modified once I properly implement damage, etc.)
{
onScreenMonsters.remove(m);
monstersLeft--;
}
}
}
public static void removeInactiveArrows()
{
for (int i = 0; i < Level.activeArrows.size(); i++)
{
Arrow a = Level.activeArrows.get(i);
if (a != null && a.getY() > 720 - 130)
{
Level.activeArrows.remove(a); //Remove arrows that are out of bounds
}
if (!a.isActive())
Level.activeArrows.remove(a); //Remove all arrows that are inactive (have hit a target)
}
}
private void CheckCollision(Arrow a, Monster m)
{
boolean collision = true;
if (a.hasHit())
collision = false;
else if (a.getX2() < m.getX())
collision = false;
else if (a.getY2() < m.getY())
collision = false;
else if (a.getY() > m.getY2())
collision = false;
else if (a.getX() > m.getX2())
collision = false;
if (collision)
{
a.setHit(true); //prevents arrows from hitting multiple targets.
m.onCollision(a);
a.onCollision(m);
}
}
}
</code></pre>
<p>Monster:</p>
<pre><code>public class Monster extends Entity
{
private boolean alive = true;
public boolean isAlive()
{
return alive;
}
public void setAlive(boolean alive)
{
this.alive = alive;
}
public void onCollision(Arrow a) //a is not used at the moment, but I will need it later to determine damage, etc.
{
setAlive(false);
}
}
</code></pre>
<p>Arrow:</p>
<pre><code>public class Arrow extends Entity
{
private boolean active = true;
private boolean hit = false;
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public boolean hasHit() {
return hit;
}
public void setHit(boolean hit) {
this.hit = hit;
}
public void onCollision(Monster m) //m is not used at the moment, but I might need it later.
{
setActive(false);
setHit(true);
}
}
</code></pre>
<p>Entity Base Class (gives the other classes a position and a size, etc):</p>
<pre><code>public abstract class Entity implements Updateable, Renderable
{
private float x;
private float y;
private float width;
private float height;
public float getX()
{
return x;
}
public void setX(float x)
{
this.x = x;
}
public float getY()
{
return y;
}
public void setY(float y)
{
this.y = y;
}
public float getX2() {
return x + width;
}
public float getY2() {
return y + height;
}
}
</code></pre>
<p>(Keep in mind that I've left out all irrelevant code. If you want to see the sources, follow the link below).</p>
<p>It's quite a bit of code, but I'm not looking for code optimisations. I only need to know whether this is a good OOP implementation. Would I be better off having a separate CollisionDetector class, where I pass my colliders (Arrow and Monster) in? Should I implement the collision checking in the colliders themselves? Or is there perhaps something I haven't thought of?</p>
<p>If you want to see the full project, check <a href="https://www.dropbox.com/sh/92ezyysrizblos1/fyaCEuU1a6" rel="nofollow">here</a>. It's made in Java with the Slick2D framework.</p>
|
[] |
[
{
"body": "<p>You could add an abstract <code>onCollision()</code> method to Entity and move the <code>CheckCollision</code> method to Entity so it would be: </p>\n\n<pre><code>arrow.checkCollision(monster)\n</code></pre>\n\n<p>That is all that I can think of, it looks pretty solid to me.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T22:44:25.540",
"Id": "25510",
"ParentId": "25346",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "25510",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-22T17:44:35.623",
"Id": "25346",
"Score": "2",
"Tags": [
"java",
"object-oriented"
],
"Title": "Collision detection implementation"
}
|
25346
|
<p>Depending on external OO libraries is really bad, using prototypes/new has some limitations, using only hashes has others. Dealing with classes was always a pain in JavaScript and it didn't help that every library has it's own way to deal with ti. But since some time I've finally "set" with this design:</p>
<pre><code>function my_class(extend,init){
var self = extend || {};
var private = 5;
self.public = 5;
self.get_private = function(){
return private;
};
for (var key in init) self[key] = init[key];
return self;
};
</code></pre>
<p>Tests:</p>
<pre><code>var instance = my_class();
// publics and privates
console.log(instance.public);
console.log(instance.get_private());
// methods never lose context
(function(method){
console.log(method());
})(instance.get_private);
// multiple inheritance trivial
var random_obj = {a:1,b:2,c:3};
my_class(random_obj); // now random_obj inherits my_class
// serializable, store in a DB and recover it with:
var serialized = JSON.stringify(instance);
var instance = my_class({},JSON.parse(serialized));
console.log("Instance: ",instance);
</code></pre>
<p>I'm surprised how this simple design solves all the problems of the other approaches. Prototypes make multiple inheritance hard, hashes won't allow privates, there's no more the "this" binding issue, instances are JSON-serializable, all that without depending on external libraries. Is there any cons to this method, or something that is hard to do with it - or can I just go and start preaching about it?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-22T20:10:48.940",
"Id": "39295",
"Score": "0",
"body": "What is the point of privates if anybody can retrieve them? Normally privates are only accessible to the actual methods, not to the public."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-22T20:13:32.377",
"Id": "39296",
"Score": "0",
"body": "What do you mean? It's just an example that privates are possible this way, it's not in some patterns. And privates have a point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-22T20:23:59.617",
"Id": "39297",
"Score": "0",
"body": "I'm asking what is the point of privates that are not private? You have an accessor for the privates that make it so anyone in the world can get access to them. They are not private."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-22T20:25:13.470",
"Id": "39298",
"Score": "0",
"body": "@jfriend00 What is not private? They're private, you can't access them without providing a public accessor."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-22T20:28:18.450",
"Id": "39299",
"Score": "0",
"body": "@jfriend00 are you asking because I retrieved it's value on `get_private()`? In this case it could be useful to make a member-variable read-only, but it's just a demonstration."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-22T20:51:19.627",
"Id": "39301",
"Score": "0",
"body": "Similar to what is described here: http://javascript.crockford.com/private.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T20:12:06.193",
"Id": "40411",
"Score": "0",
"body": "@jfriend00, privates make immutability possible (at least in this context)."
}
] |
[
{
"body": "<p>What about regular inheritance? Is <code>extend</code> supposed to be the superclass?</p>\n\n<pre><code>foo = { foo: \"bar\" };\n\na = my_class(foo);\nb = my_class(foo);\n\na.foo = \"baz\";\nconsole.log(b.foo);\n\n--> \"baz\";\n</code></pre>\n\n<p>I would expect <code>a</code> and <code>b</code> to have their own state, yet they share a single <code>foo</code> property.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T00:36:53.753",
"Id": "39306",
"Score": "0",
"body": "No, maybe I expressed myself bad on that code. Extend is any object you want to transform into my_class. Init contains variables you want to overwrite over my_class's defaults."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T03:35:25.050",
"Id": "39312",
"Score": "0",
"body": "@Dokkat - Okay, so how do you perform regular inheritance--extend the behavior of `parent_class` by adding/overriding those of `my_class`? This is the 99% of OOP that must exist before addressing the 1% of multiple-inheritance that can usually be implemented by other means (i.e. composition and interfaces)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T03:56:34.123",
"Id": "39314",
"Score": "0",
"body": "Inheritance by overriding methods: `sub_class = function(ext){ super_class(ext); ext.method = function(){}; return ext; };` now just call sub_class(obj) and it'll inherit super_class, except for that particular method, which will be of sub_class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T03:58:03.660",
"Id": "39315",
"Score": "0",
"body": "@David_Harkness and if you want to reuse the superclass's method, just replace the method definition I shown by something like `var super_method = ext.method(); ext.method = function(){ super_method(); ... };` voila, you didn't overwrite method completely on inheritance, but combined both. No need for complications at all...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T22:19:36.150",
"Id": "39461",
"Score": "0",
"body": "@Dokkat - That looks rather complicated for handling the 99% case to make the 1% case a little easier. Perhaps a real-world example demonstrating inheritance, overriding, private/public properties and methods would help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T09:46:40.050",
"Id": "39563",
"Score": "0",
"body": "How is that complicated!? At all?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-22T23:48:26.377",
"Id": "25353",
"ParentId": "25350",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-22T20:07:42.747",
"Id": "25350",
"Score": "1",
"Tags": [
"javascript",
"optimization",
"object-oriented"
],
"Title": "I've finally found a satisfactory way to create classes on JavaScript. Are there any cons to it?"
}
|
25350
|
<p>I wanted to review my design strategy for CSV parser.
I have 4 CSV files, which have different layouts as shown below.
Each row of a CSV file will be mapped to a class. For example, if <code>CSV_FILE_A</code> has 10 rows, a list contains 10 objects of ObjA will be returned after calling parser function. For CSV_FILE_B of 5 entries, a list of 5 ObjB will be returned.</p>
<pre><code>CSV_FILE_A: LONG, STR, STR
CSV_FILE_B: LONG, LONG
CSV_FILE_C: LONG, LONG, STR, LONG
CSV_FILE_D: LONG, LONG, LONG
</code></pre>
<p>I designed an interface like this.</p>
<pre><code>public interface CSVParser<T> {
public List<T> parseCSVFile(String fileName);
}
</code></pre>
<p>And I have created 4 different parsers, which implement the interface and have a different logic of parsing the CSV file. The code below is a complete implementation for CSV_FILE_B. The other three parsers will have the same structures but different <code>if-else</code> statements for setting object fields and different object types in the type of List. </p>
<pre><code>public class csvBParser implements CSVParser {
@Override
public List<ObjectB> parseCSVFile(String fileName) {
List<ObjectB> list = new ArrayList<ObjectB>();
try {
ClassLoader classLoader = Thread.currentThread()
.getContextClassLoader();
InputStream is = classLoader.getResourceAsStream(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = "";
StringTokenizer token = null;
int lineNum = 0, tokenNum = 0;
while ((line = br.readLine()) != null) {
if (lineNum == 0){
lineNum++;
continue;
}
token = new StringTokenizer(line, ",");
ObjectB objB = new ObjectB();
while (token.hasMoreTokens()) {
String nextToken = token.nextToken();
boolean isTokenNull = false;
if (nextToken.equalsIgnoreCase("null"))
isTokenNull = true;
if (!isTokenNull) {
if (tokenNum == 0) {
objB.setObjBId(Long.valueOf(nextToken));
} else if (tokenNum == 1) {
objB.setObjBSndId(Long.valueOf(nextToken));
} else {
System.err.println("Invalid Token Number "
+ tokenNum);
}
}
tokenNum++;
}
list.add(objB);
tokenNum = 0;
lineNum++;
}
} catch (Exception e) {
System.err.println("Parse Error " + e.getMessage());
}
return list;
}
}
</code></pre>
<p>And, I finally uses a factory to create an instance of a parser. </p>
<pre><code>public class CSVParserFactory {
public static CSVParser getParser(TableType type) {
CSVParser parser = null;
if(type == A){
parser = new csvAParser();
}
else if(type == B){
parser = new csvBParser();
}
else if(type == C){
parser = new csvCParser();
}
else if(type == D){
parser = new csvDParser();
}
/*
* more parsers will be added later
*/
else{
throw new IllegalArgumentException ("No such table type");
}
return parser;
}
}
</code></pre>
<p>The parser is being called like this. Each element in the list is corresponding to a row in the CSV file</p>
<pre><code>CSVParser parser = CSVParserFactory.getParser(TableType.A);
List list = parser.parseCSVFile(CSV_FILE_A);
</code></pre>
<p>Do you guys have any suggestions of this design pattern?
If I consider a code factorization, what do I need to do?</p>
<p>Thanks in advance. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T16:10:41.377",
"Id": "39337",
"Score": "0",
"body": "do you really need a different type to be sent back for each file type? I think a better design would like record set : one class representing a row of data; with properties : getType(), getNumberValues() ... and methods : getValueAsString(int index), getValueAsLong(int index), ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T14:17:54.213",
"Id": "39422",
"Score": "0",
"body": "the getParser() method really seems to belong on TableType"
}
] |
[
{
"body": "<p>For starters, consider having an abstract class to do the line-by-line reading, and having your concrete classes implement the code on converting one line into the desired object?</p>\n\n<p>Also, the multiple <code>if-else-if</code> can be slightly improved by replacing it with a <code>switch</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T05:02:35.177",
"Id": "39317",
"Score": "2",
"body": "Code examples would be a +1"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T04:07:36.557",
"Id": "25357",
"ParentId": "25354",
"Score": "2"
}
},
{
"body": "<p>First, there would be much duplication between the parser classes. This kind of duplication should be avoided. If you find a bug in the way the csv is being parsed, you now have to fix it in multiple places. Consider using the <a href=\"http://en.wikipedia.org/wiki/Template_method_pattern\" rel=\"nofollow\">template method pattern</a>. In this scenario, you would extract the common logic into an abstract superclass with 1 or more abstract \"template methods\" that would be implemented by the subclasses. For instance, the abstract superclass could parse the fields into an array or strings, then pass the array to a method to construct an object using those fields.</p>\n\n<pre><code>public abstract class AbstractCSVParser<T> implements CSVParser<T> {\n\n public List<T> parseCSVFile(String fileName) {\n List<T> list = new ArrayList<T>();\n\n // for each line...\n String[] fields = // parse line into an array of strings\n T obj = buildObject(fields);\n list.add(obj);\n\n return list;\n }\n\n protected abstract T buildObject(String[] fields);\n\n}\n\npublic class csvBParser extends AbstractCSVParser<ObjectB> {\n\n protected ObjectB buildObject(String[] fields) {\n ObjectB obj = new ObjectB();\n // populate object with fields\n return obj;\n }\n\n}\n</code></pre>\n\n<hr>\n\n<p>In the parsing code, the <code>InputStream</code> and <code>BufferedReader</code> are never closed. Make sure you close resources when you are done with them, and make sure it is happening inside a <code>finally</code> block.</p>\n\n<pre><code>BufferedReader br = new BufferedReader(new InputStreamReader(is));\ntry {\n // do work with br\n}\nfinally {\n br.close();\n}\n</code></pre>\n\n<p>If you are using Java 7, you should check out the <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow\">try-with-resources</a> statement. The above example could be written like this:</p>\n\n<pre><code>try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {\n // do work with br\n} // close is called automatically at the end of the try block\n</code></pre>\n\n<hr>\n\n<p>In this example, the parser classes appear to be stateless. Given this, <code>CSVParserFactory</code> doesn't really need to return a new instance every time. One option to simplify <code>CSVParserFactory</code> is to initialize a static <code>Map</code> containing the parser instances.</p>\n\n<pre><code>public class CSVParserFactory {\n\n private static final Map<TableType, CSVParser> PARSERS = new HashMap<TableType, CSVParser>() {{\n put(A, new csvAParser());\n put(B, new csvBParser());\n put(C, new csvCParser());\n // etc\n }};\n\n public static CSVParser getParser(TableType type) {\n CSVParser parser = PARSERS.get(type);\n if (parser == null) {\n throw new IllegalArgumentException(\"No such table type\");\n }\n return parser;\n }\n\n}\n</code></pre>\n\n<p>If you don't want this, and still want to create the parser instances each time, you could use the same strategy with the class names instead of instances, then create the instance using reflection.</p>\n\n<hr>\n\n<p>Finally, you may want to consider passing an <code>InputStream</code> to <code>parseCSVFile</code> instead of a file name. This would allow more flexibility of the source of the data. The current implementation is very specific as to the source.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T09:59:07.207",
"Id": "25364",
"ParentId": "25354",
"Score": "3"
}
},
{
"body": "<p>public interface CSVParser looks good. Plus have a base class for parers. then you need just one concrete class for now that \ntakes an List of with each element of a type csv type. the array has the number of columns in csv and each type is the data type of corresponding column - string or long</p>\n\n<pre><code> //if parser is thread safe declare it as class static else declare here\n public static CSVParser getParser(TableType type) {\n if(type == A){ \n //So you need for type A:\n if(csvParserA == null){//cache it\n List<CSVType> lst = new ArrayList<CSVTYpe>();\n lst.add(CSVType.LONG);\n lst.add(CSVType.STR);\n lst.add(CSVType.LONG);\n csvParserA = new CsvParser(lst)\n }\n return csvParserA; \n}\n else if(type == B){\n //like make list init new parser and cache it\n } \n</code></pre>\n\n<p>The impl can be improved to make use of information given in constructor. So you have one final code for these four types, make it perfect and works for all. </p>\n\n<p>Only cache if its thread safe else make a new one every time. I think its thread safe as no class instance data changes once its set in constructor.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T15:11:33.250",
"Id": "39334",
"Score": "0",
"body": "Did not show the class deceleration - but would be class static instance, if its thread safe (and only then check if its null and init it first time only). If its not thread safe then you would declare it and initialize it in the if(type == A) block (do away with the is null check)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T11:27:24.130",
"Id": "25365",
"ParentId": "25354",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T00:28:58.613",
"Id": "25354",
"Score": "4",
"Tags": [
"java",
"design-patterns",
"csv"
],
"Title": "Design Strategy of CSV Parser"
}
|
25354
|
<p>After experimenting with a <a href="https://codereview.stackexchange.com/questions/25248/sorted-trie-implementation-in-c">sorted trie implementation in C</a>, I felt that I understood tries pretty well, but was having trouble explaining how they work. Since the C code was based on existing code, I wanted to try it again in another language, from scratch.</p>
<p>Here's what I came up with. I tried to make it as minimal as possible. These tries aren't sorted, and nodes only reference a <code>child</code> and <code>next</code> node; <code>parent</code> and <code>prev</code> aren't used. I did give the "leaves" of the trie a <code>name</code> property, which is the full key. This isn't currently used, but it's useful for debugging, and it would be useful if a trie iterator were added (like <code>Trie_dump</code> from the question linked above).</p>
<p>I'm interested in feedback on the code itself this time, but not so much on things like white space, braces, semicolons, etc. I'm comfortable with the formatting the way it is. I'd be interested in an alternative to that labeled loop, though, and all other feedback is welcome.</p>
<hr>
<h2>Trie structure</h2>
<p>Each node in the trie can have a <code>key</code>, a <code>value</code>, a <code>next</code> node, and a <code>child</code> node. In this diagram, each node is represented by a circle. The "root" node is at the left, the green "leaf" nodes are at the right, and the "branch" nodes are in the middle.</p>
<p>Each <code>key</code> is a single character (circled letters below). The "branches" have keys, while each "leaf" holds a value.</p>
<p><img src="https://i.stack.imgur.com/rftvb.png" alt="Trie diagram"></p>
<p>In the diagram, nodes appear to have multiple children. For example, the first "r" node has "u" and "o" children. Internally, nodes just have a <code>child</code> property; the first child. The next child is available in the first child's <code>next</code> property, and so on. It may help to think of <code>child</code> as "first child" and <code>next</code> as "next sibling."</p>
<hr>
<h2><code>trie.js</code></h2>
<pre><code>function Trie(parent, prev, key, value) {
if (key !== void 0)
this.key = key; // single-character key
if (value !== void 0)
this.value = value; // user-defined value
if (prev)
prev.next = this; // next sibling node
else if (parent)
parent.child = this; // first child node
}
// put a key/value pair in the trie
Trie.prototype.put = function(name, value) {
var i = 0, t = this, len = name.length, prev, parent;
down: while (t.child) {
parent = t;
t = t.child;
// if first child didn't match, get next sibling
while (t.key != name[i]) {
if (!t.next) {
prev = t;
t = parent;
break down;
}
t = t.next;
}
// key already exists, update the value
if (++i > len) {
t.value = value;
return;
}
}
// found any existing parts of the key, add the rest
t = new this.constructor(t, prev, name[i]);
while (++i <= len)
t = new this.constructor(t, null, name[i]);
t.name = name;
t.value = value;
};
// get a value from the trie at the given key
Trie.prototype.get = function(name) {
var i = 0, t = this.child, len = name.length;
while (t) {
if (t.key == name[i]) {
if (i == len)
return t.value;
t = t.child;
++i;
} else {
t = t.next;
}
}
};
</code></pre>
<hr>
<h2>Demos</h2>
<p>Here are links to a few demos. The simple demo puts some test data in a trie, gets it back out, and dumps it to the console. The fancy demo puts the same test data in a trie and draws a diagram like the one above.</p>
<p>Simple demo: <a href="http://jsfiddle.net/4Yttq" rel="nofollow noreferrer">http://jsfiddle.net/4Yttq</a></p>
<p>Fancy demo: <a href="http://jsfiddle.net/4Yttq/1/" rel="nofollow noreferrer">http://jsfiddle.net/4Yttq/1/</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T08:58:25.470",
"Id": "39328",
"Score": "0",
"body": "Just personal preference, but I think you're using a weird coding style. `while (++i <= len)` isn't something comprehensible. Not using braces for `if`, etc. The code is pretty, but it feels like magic on first sight."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T12:52:04.573",
"Id": "39329",
"Score": "2",
"body": "`break down;` :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T15:48:57.057",
"Id": "39336",
"Score": "0",
"body": "@mellamokb I couldn't resist..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T18:28:46.137",
"Id": "39360",
"Score": "0",
"body": "@Dagg Well, other than my solution and Florian's \"no magic\" suggestion, it looks like all I can suggest is to use verbose variable names. If you plan to do sorted tries, binary tree? I think it would increase access times due to depth, but let's have jsPerf be the judge of that."
}
] |
[
{
"body": "<p>Well, first of all, my optimization is an overhaul of your method. The concept is still tries. But I went for the JS route for several reasons:</p>\n\n<ul>\n<li><p>We're in JavaScript. Linked lists in C would be like Arrays/Objects in JS. Since we have them available, why not use them instead?</p></li>\n<li><p>In tries, you use a key for each entry. You'd have to loop over and find it when using linked lists or arrays. In JS, we have objects that are key-value pairs, which make it a bit easier to implement.</p></li>\n<li><p><a href=\"http://jsperf.com/tries#run\" rel=\"nofollow\">Performance is a bit better</a>, except on Opera browsers. Performance may be due to the lesser loops and property access.</p></li>\n<li><p>The code is shorter</p></li>\n</ul>\n\n<p>The structure:</p>\n\n<pre><code>{\n \"t\": {\n \"key\": \"t\",\n \"r\": {\n \"key\": \"r\",\n \"u\": {\n \"key\": \"u\",\n \"e\": {\n \"key\": \"e\",\n \"value\": \"yes\",\n \"name\": \"true\"\n },\n \"c\": {\n \"key\": \"c\",\n \"k\": {\n \"key\": \"k\",\n \"value\": \"vehicle\",\n \"name\": \"truck\"\n }\n }\n },\n \"o\": {\n \"key\": \"o\",\n \"w\": {\n \"key\": \"w\",\n \"e\": {\n \"key\": \"e\",\n \"l\": {\n \"key\": \"l\",\n \"value\": \"dig\",\n \"name\": \"trowel\"\n }\n }\n }\n }\n }\n },\n \"h\": {\n \"key\": \"h\",\n \"a\": {\n \"key\": \"a\",\n \"t\": {\n \"key\": \"t\",\n \"value\": \"head\",\n \"name\": \"hat\"\n },\n \"l\": {\n \"key\": \"l\",\n \"t\": {\n \"key\": \"t\",\n \"value\": \"hold it\",\n \"name\": \"halt\"\n }\n },\n \"m\": {\n \"key\": \"m\",\n \"value\": \"pig\",\n \"name\": \"ham\",\n \"m\": {\n \"key\": \"m\",\n \"e\": {\n \"key\": \"e\",\n \"r\": {\n \"key\": \"r\",\n \"value\": \"nail\",\n \"name\": \"hammer\"\n }\n }\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>As for <a href=\"http://jsfiddle.net/4Yttq/9/\" rel=\"nofollow\">the code that operates this</a>, notes are on the comments:</p>\n\n<pre><code>function Trie(key) {\n this.key = key;\n this.value;\n //children are merged with this object since collision is minimal\n}\n\nTrie.prototype.put = function (name, value) {\n\n var node = this,\n nameLength = name.length,\n i = 0,\n currentLetter;\n\n //the only major change is this single loop which zips through the collection\n //if the node exists, make it current and proceed\n //if not, we create it, make it current and proceed\n for (i = 0; i < nameLength; i++) {\n currentLetter = name[i];\n node = node[currentLetter] || (node[currentLetter] = new Trie(currentLetter));\n }\n\n node.value = value;\n node.name = name;\n\n};\n\nTrie.prototype.get = function (name) {\n\n var node = this,\n nameLength = name.length,\n i, node;\n\n //same idea, zip through the collection\n //in this case we break if we hit a dead end\n for (i = 0; i < nameLength; i++) {\n if (!(node = node[name[i]])) break;\n }\n\n //only when the loop went over all letters will we find a value\n //if not, well, we don't find anything\n return (i === nameLength) ? node.value : 'not found';\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T16:10:50.017",
"Id": "39338",
"Score": "0",
"body": "I guess I should have mentioned that I'm planning on porting it back to C eventually, so I wanted to keep the linked lists; using `children` like this almost feels like cheating. I did retrofit the trie with a `children` property for the diagram example, but it doesn't take advantage of it at all. The constructor has the `undefined` checks to avoid creating properties with undefined values, just to make the data easier to inspect... they could go. Other than that, this is only a few lines shorter... does it perform better?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T16:12:16.533",
"Id": "39339",
"Score": "0",
"body": "@Dagg Ahh, I see. Performance, I'll post a jsPerf shortly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T16:54:25.713",
"Id": "39342",
"Score": "0",
"body": "+1 for the perf, although it's just a *tiny* bit faster for me... I think if use the sorted trie, I might be able to beat it. I tried adding the d3 stuff to your fiddle, thinking it would work since it used a `children` property, but d3 triggered an error like `d3 \"Object #<Object> has no method 'map'` ... any idea what's going on there?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T16:58:28.753",
"Id": "39343",
"Score": "0",
"body": "@Dagg I modified the latest revision, 9, to have no `children` property to further lessen the code. [Revision 8 still has `children`](http://jsfiddle.net/4Yttq/8/). Also, `children` isn't an array, but an object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T17:48:40.327",
"Id": "39348",
"Score": "1",
"body": "Ah, right, it's expecting an array. Merging `children` seems like a good idea, there shouldn't be any collision as long as no single-character property names are used. I'm still curious whether a sorted, linked trie can outperform this, or whether the linked trie code can be reduced significantly, but this is starting to look pretty good as a minimal JS solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-20T05:04:14.893",
"Id": "218197",
"Score": "0",
"body": "Noob question here. Why put the functions as prototypes instead of putting them in function Trie(key) {}? Would there be any benefit to defining Trie as var Trie = function(key) {}?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-10T01:13:44.733",
"Id": "228117",
"Score": "0",
"body": "@DanielJacobson Putting them on the prototype ensures that there is only one copy of that method in memory at a time. It also saves times when constructing the object to put it in the prototype rather than in the constructor."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-10T01:15:29.657",
"Id": "228118",
"Score": "0",
"body": "I produced [a better jsperf](http://jsperf.com/tries/2) that doesn't re-run the implementation code on each test. It also compares against some similar data structures available in Javascript. On my system the JS Style implementation is about 6 times faster than the C-style. And of course, just using an Object-dictionary blows both out of the water."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T15:54:16.940",
"Id": "25377",
"ParentId": "25359",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T06:24:12.743",
"Id": "25359",
"Score": "13",
"Tags": [
"javascript",
"linked-list",
"hash-map",
"trie"
],
"Title": "Simple trie implementation in JavaScript"
}
|
25359
|
<p>I have 3 classes: a transmitter, a view for displaying and a recording view for flushing the screen contents into a file. The view and the recording view classes register themselves from their constructor in the transmitter, which keeps them in a HashMap. The transmitter implements all the view and recording view classes' interfaces, and delegates the incoming method invocations to them based on the actually registered implementors.</p>
<p>To make things clear:</p>
<pre><code>public interface IRecordingView {
public void recordingViewMethod1();
public void recordingViewMethod2();
}
public class RecordingView implements IRecordingView {
public RecordingView {
Transmitter.getInstance().register(this);
}
@Override public void recordingViewMethod1() { ... }
@Override public void recordingViewMethod2() { ... }
}
public interface IView {
public void viewMethod1();
public void viewMethod2();
}
public class View implements IView {
public View() {
Transmitter.getInstance().register(this);
}
@Override public void viewMethod1() { ... }
@Override public void viewMethod2() { ... }
}
public class Transmitter implements IRecordingView, IView {
private static final Transmitter instance = new Transmitter();
private HashMap<Class, Set> register = new HashMap<Class, Set>();
public Transmitter() {
for (Class cl : this.getClass().getInterfaces()) {
register.put(cl, new HashSet());
}
}
public void register(Object listener) {
for (Class interf : register.keySet()) {
if (interf.isInstance(listener)) {
Set implementors = register.get(interf);
implementors.add(listener);
}
}
}
@Override public void viewMethod1() {
for (IView delegate : register.get(IView.class)) {
delegate.viewMethod1();
}
}
@Override public void recordingViewMethod1() {
for (IRecordingView delegate : register.get(IRecordingView.class)) {
delegate.recordingViewMethod1();
}
}
// and so on for the rest of the methods
}
</code></pre>
<p>This is the basic concept of the legacy code. Of course there are many transmitters, each implementing more interfaces, with each interface having more methods. Is there an optimal and/or elegant way to further reduce code size? The delegation mechanism looks quite the same in every method, but I don't want to mess with reflection.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T16:53:00.480",
"Id": "39341",
"Score": "1",
"body": "Why no reflection? Have you considered code generation (compile time or runtime)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T21:04:22.480",
"Id": "39368",
"Score": "0",
"body": "This is a real-time diagnostic measurement tool, I can't afford any performance issues which I'm mostly afraid of. However, I'll do some benchmarking tomorrow to see if any delays occur. Thank you anyway for the support :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T09:00:55.350",
"Id": "39497",
"Score": "0",
"body": "Well, I finally decided to do it with reflection and it seems to do the trick. Please add your comment as an answer so I can accept it :)"
}
] |
[
{
"body": "<p>Why no reflection? Have you considered code generation (compile time or runtime)?</p>\n\n<hr>\n\n<p>Here's an idea based on proxies and reflection. I haven't actually tried any of this, so the idea might break down at some point, but here goes.</p>\n\n<p>Create an interface for the transmitter that extends all of the interfaces the transmitter will implement:</p>\n\n<pre><code>public interface ITransmitter extends IRecordingView, IView { ... }\n</code></pre>\n\n<p>Have the transmitter class implement that interface and return the singleton instance as that interface:</p>\n\n<pre><code>public class Transmitter implements ITransmitter {\n public static ITransmitter getInstance() { ... }\n}\n</code></pre>\n\n<p>The instance returned is actually a proxy created using <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Proxy.html\" rel=\"nofollow\">java.lang.reflect.Proxy</a> with an <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/InvocationHandler.html\" rel=\"nofollow\">InvocationHandler</a> that will delegate the appropriate method invocations using reflection.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T15:58:46.043",
"Id": "25499",
"ParentId": "25361",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "25499",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T08:03:21.840",
"Id": "25361",
"Score": "1",
"Tags": [
"java",
"delegates"
],
"Title": "Refactoring Java transmitter delegate implementation"
}
|
25361
|
<pre><code><div id="members">
<div id="inputRow0">
<input id="input0_0" class="input" type="text" /><br/>
<input id="input0_1" class="input" type="text" /><br/>
<input id="input0_2" class="input" type="text" />
</div>
<div id="inputRow1">
<input id="input1_0" class="input" type="text" /><br/>
<input id="input1_1" class="input" type="text" /><br/>
<input id="input1_2" class="input" type="text" />
</div>
<div id="inputRow2">
<input id="input2_0" class="input" type="text" /><br/>
<input id="input2_1" class="input" type="text" /><br/>
<input id="input2_2" class="input" type="text" />
</div>
</div>
<br /><a id="add-more" href="#">add-more</a> <a id="remove-last" href="#">remove-last</>
</code></pre>
<p>js part that we need to deal with:</p>
<pre><code>$("#inputRow1").hide();
$("#inputRow2").hide();
$("#remove-last").hide();
$("#add-more").click(function(){
//count how many *direct children* elements are hidden.
var hiddenElements = $('#members >:hidden').length;
$("#remove-last").show();
if (hiddenElements === 2) {
$("#inputRow1").show();
} else if(hiddenElements === 1) {
$("#inputRow2").show();
$(this).hide();
}
});
$("#remove-last").click(function(){
//count how many *direct children* elements are hidden.
var hiddenElements = $('#members >:hidden').length;
$("#add-more").show();
if (hiddenElements === 0) {
$("#inputRow"+2).hide();
} else if (hiddenElements === 1) {
$("#inputRow"+hiddenElements).hide();
$(this).hide();
}
});
</code></pre>
<p>Working example:
<a href="http://jsfiddle.net/URkuW/" rel="nofollow">http://jsfiddle.net/URkuW/</a></p>
|
[] |
[
{
"body": "<p>What problem are you trying to solve? I've left your code doing the same things but rather than interrogate the DOM each time I've cached everything in local variables. </p>\n\n<pre><code>// Execute code in an Immediately Invoked Function Expression (IIFE)\n// This helps stop your variables polluting the global scope.\n(function () { \n\n // opt in to ECMAScript 5's strict mode \n \"use strict\";\n\n // As we aren't changing the DOM just store all of the selectors in \n // local variables - it's cheaper than hitting the DOM each time.\n var inputRow1 = $('#inputRow1').hide(), \n inputRow2 = $('#inputRow2').hide(),\n addRowLink = $('#add-more'),\n removeRowLink = $(\"#remove-last\").hide(),\n // rather than checking the DOM for number of hidden children,\n // just keep track of the last row visible (0, 1 or 2)\n lastRowVisible = 0; \n\n\n addRowLink.click(function(event) {\n // stop the default action of the click event.\n event.preventDefault();\n\n // This is the initial state with only the first 3 input boxes showing\n // we need to show row 1 and the remove last link as well as increment the\n // last row visible to 1.\n if (lastRowVisible === 0) {\n removeRowLink.show();\n inputRow1.show();\n ++lastRowVisible;\n // The first two rows are visible. Show the last row and hide the add-more\n // link as well as increment the last row visible to 2.\n } else if (lastRowVisible === 1) {\n addRowLink.hide();\n inputRow2.show();\n ++lastRowVisible;\n } \n });\n\n removeRowLink.click(function(event){\n // stop the default action of the click event.\n event.preventDefault();\n\n // All 3 rows currently visible: need to hide the last row, show\n // the add-more link and decrement the last row visible to 1.\n if (lastRowVisible === 2) {\n addRowLink.show();\n inputRow2.hide();\n --lastRowVisible;\n\n // 2 rows currently visible: need to hide the second row and the\n // remove-last link and decrement the last row visible to 0.\n } else if (lastRowVisible === 1) {\n removeRowLink.hide();\n inputRow1.hide();\n --lastRowVisible;\n } \n }); \n}());\n</code></pre>\n\n<p>Here's a working fiddle: <a href=\"http://jsfiddle.net/RobH/CDVBs/1/\" rel=\"nofollow\">http://jsfiddle.net/RobH/CDVBs/1/</a></p>\n\n<p>Have you considered a solution that starts with only 3 inputs and then creates extra inputs instead of showing ones that are already declared but hidden?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T14:45:52.940",
"Id": "25373",
"ParentId": "25369",
"Score": "3"
}
},
{
"body": "<p>Don't feel intimidated by the following wall of text, I just like to over explain stuff sometimes. I think it's better to have more information than have too little.</p>\n\n<p>First of all and probably the most important thing you could do to improve this code it to cache your selections. When you write this: <code>$(\"#someElement\")</code>, jQuery has to jump into the DOM and look through all elements that would match that selection. Keep in mind that DOM manipulations are the most expensive when it comes to performance/resources. So you should really do a search only once, and save your results for future use.</p>\n\n<p>Just put 'em in variables: <code>var someElement = $(\".someElement\");</code>\nThen in your code just replace <code>$(\".someElement\");</code> with <code>someElement</code> and do all your stuff on it. As a rule of thumb, if you use a selection more than once, you should cache it.</p>\n\n<p>Best place, in my opinion, to do that is at the top of your code. By placing all your variables and selections at the top, you can see at a glance all the elements (or at least most of the elements) that are going to be used/manipulated in the code.</p>\n\n<p>Next thing you could do is save some function calls. The <code>.click()</code> method you use if you read through the jQuery source code, you'll see that it simply calls the <code>.on()</code> method and passes in the stuff you set. It would be better if you just went straight to the point by using the <code>.on(\"click\", function(){});</code> directly. This way you save a few function calls. Not a tremendous improvement, but something that will benefit you in the long run.</p>\n\n<p>In your click functions you also might want to prevent the default browser action on a link, which is to direct the page to that link. Since you just want to perform something on your page and don't actually want the browser to leave the page you should prevent that action.\nYou can do it by passing in <code>e</code> for <code>event</code> and running <code>e.preventDefault();</code>. If you want to read more on this I would suggest <a href=\"http://css-tricks.com/return-false-and-prevent-default/\" rel=\"nofollow\">this article by Chris Coyier</a>.</p>\n\n<p>Also since you are showing and hiding quite a bit, it might be hard to keep track of what is showed or hidden at any given time. I say don't worry about it. Let jQuery magically handle it by using the <code>.toggle()</code> method instead. If the element is hidden it will show it, but if it's not hidden then it will hide it. Simple and easy. If there's a point where you want to be specific about it you can always just use the methods you're using now.</p>\n\n<p>Here is your code with these examples in them. Keep in mind that these are simple improvements which don't really change the order/logic of your code but just help you make it better. Anyways here:</p>\n\n<pre><code>var addMore = $(\"#add-more\"), //Separate variables with comma\n removeLast = $(\"#remove-last\"),\n //For these next three you could use members.children() \n //or some other method and not have to do this at all\n inputRow0 = $(\"#inputRow0\"),\n inputRow1 = $(\"#inputRow1\"),\n inputRow2 = $(\"#inputRow2\");\n\naddMore.on(\"click\", function(e) {\n //Prevent the default action\n e.preventDefault();\n\n //count hidden elements\n var hiddenElements = $('#members >:hidden').length;\n removeLast.toggle();\n\n if (hiddenElements === 2) {\n inputRow1.toggle();\n } else if (hiddenElements === 1) {\n inputRow2.toggle();\n $(this).hide();\n }\n});\n\nremoveLast.on(\"click\", function(e) {\n e.preventDefault();\n\n var hiddenElements = $('#members >:hidden').length;\n addMore.toggle();\n\n if (hiddenElements === 0) {\n inputRow2.toggle();\n } else if (hiddenElements === 1) {\n inputRow1.toggle();\n $(this).hide();\n }\n});\n</code></pre>\n\n<p>If you wanted to change your code a bit here's an example with using child selectors. If you have question about any of these methods just let me know and I can explain them. You can also read up the jQuery documentation for each one to get a better idea of what's going on. Also here's a Fiddle: <a href=\"http://jsfiddle.net/jonnysooter/WuxgK/\" rel=\"nofollow\">http://jsfiddle.net/jonnysooter/WuxgK/</a>.</p>\n\n<pre><code>var addMore = $(\"#add-more\"), //Separate variables with comma\n removeLast = $(\"#remove-last\");\n\n$(\"#members div:first-child\").nextAll().hide();\n\naddMore.on(\"click\", function(e){\n e.preventDefault();\n //count hidden elems\n var hiddenElements = $('#members >:hidden').length +1;\n removeLast.show();\n\n $(\"#members div:nth-child(\" + hiddenElements + \")\").show();\n if(hiddenElements === 2){\n //Test for 2 because we add 1 in the variable\n $(this).hide();\n }\n});\n\nremoveLast.on(\"click\", function(e){\n e.preventDefault();\n\n var hiddenElements = $('#members >:hidden').length +2;\n addMore.show();\n\n $(\"#members div:nth-child(\" + hiddenElements + \")\").hide();\n if(hiddenElements === 3) {\n $(this).hide();\n }\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T14:57:35.790",
"Id": "25375",
"ParentId": "25369",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "25373",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T13:22:46.883",
"Id": "25369",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"html",
"form"
],
"Title": "Showing or hiding groups of three text fields"
}
|
25369
|
<p>My team and I wrote the following Nhibernate wrapper which gives generic retrieval and save/update functions and a possibility to send a function as a paramater which may contain several save/update calls which will be committed or rollback transactionally:</p>
<pre><code>public class DB
{
private const string sessionKey = "NHibernate.Db";
private static bool keepSessionOpen = false;
[ThreadStatic]
private static ISession threadStaticSession = null;
private static ISessionFactory sessionFactory;
static DB()
{
sessionFactory = new SessionFactoryManager().CreateSessionFactory();
}
public static Boolean TransactionalMethod(Func<Boolean> transactionalMethod)
{
ITransaction transaction = null;
Boolean hasActiveTranaction = Session.Transaction.IsActive;
try
{
if (hasActiveTranaction == false)
transaction = Session.BeginTransaction();
if (!transactionalMethod())
{
if (hasActiveTranaction == false)
transaction.Rollback();
return false;
}
if (hasActiveTranaction == false)
transaction.Commit();
return true;
}
catch
{
if (hasActiveTranaction == false)
transaction.Rollback();
return false;
}
}
public static ISession Session
{
get
{
ISession localSession;
if (HttpContext.Current == null)
{
if (threadStaticSession == null)
{
Trace.WriteLine(" session==null");
threadStaticSession = sessionFactory.OpenSession();
System.Diagnostics.Trace.WriteLine("Starting static session");
}
Trace.WriteLine(" session!=null");
localSession = threadStaticSession;
}
else
{
if (HttpContext.Current.Items.Contains(sessionKey))
{
localSession = (ISession)HttpContext.Current.Items[sessionKey];
}
else
{
localSession = sessionFactory.OpenSession();
System.Diagnostics.Trace.WriteLine("Starting Http session");
HttpContext.Current.Items[sessionKey] = localSession;
keepSessionOpen = true;
}
}
return localSession;
}
}
public static IList<T> Get<T>() where T : class
{
return Session.QueryOver<T>().List();
}
public static IList<T> Get<T>(Expression<Func<T, Boolean>> filter) where T : class
{
return Session.QueryOver<T>().Where(filter).List();
}
public static Boolean MultipleSave<T>(IList<T> items) where T : class
{
return TransactionalMethod(() =>
{
try
{
foreach (T item in items)
{
Session.SaveOrUpdate(item);
}
return true;
}
catch (Exception)
{
return false;
}
});
}
public static Boolean Save<T>(T item) where T : class
{
return MultipleSave<T>(new List<T>() { item });
}
}
</code></pre>
<p>I may Call it like this:</p>
<pre><code>Boolean transactionSucceeded = DB.TransactionalMethod(() =>
{
if (!DB.Save<Card>(newCardSession) || !DB.Save<Card>(oldCardSession))
return false;
return true;
});
</code></pre>
<p>if I want the 2 saves to be executed as 1 transaction.</p>
<p>Is this ok? We would be glad to hear about points for improvements.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T15:23:59.107",
"Id": "39427",
"Score": "0",
"body": "Why do this instead of the standard way? This seems unnecessarily complex."
}
] |
[
{
"body": "<ul>\n<li><p>If a method returns false it is a failure, it also is failure if it throws. If you had (could?) stick with exceptions only: </p>\n\n<p>try { /* do sthg*/ return true; } catch (Exception) { return false; }</p></li>\n</ul>\n\n<p>constructs would be unnecessary. You already have two: in <code>MultipleSave</code> and <code>TransactionalMethod</code>. You also only need to call <code>MultipleSave</code> from <code>Save</code> in order to wrap it in the try-catch construct above. </p>\n\n<p>If you stick with <code>Exception</code>s :</p>\n\n<pre><code>DB.TransactionalMethod(() =>\n {\n if (!DB.Save<Card>(newCardSession) || !DB.Save<Card>(oldCardSession))\n return false;\n return true;\n });\n</code></pre>\n\n<p>becomes:</p>\n\n<pre><code>DB.TransactionalMethod(() =>\n {\n DB.Save<Card>(newCardSession);\n DB.Save<Card>(oldCardSession));\n });\n</code></pre>\n\n<ul>\n<li><p>Also <code>catch (Exception) { return false; }</code> squashes exceptions. You would want to log exceptions in order to diagnose why a command has failed. Did NHibernate generate invalid SQL, were your schemas invalid, did db die, was network connection lost?</p></li>\n<li><p><code>ISessionFactory</code>, <code>ISession</code>, <code>ITransaction</code> all implement <code>IDisposable</code>; if you do not use them in a <code>using</code> block, you will probably leak resources. </p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T11:54:42.203",
"Id": "25421",
"ParentId": "25370",
"Score": "2"
}
},
{
"body": "<h2>[ThreadStatic] - DO NOT use in threadpool environment (like ASP.NET)</h2>\n\n<p>When the threads' lifetime isn't managed by us do not use ThreadStatic variables becouse the threads will be reused after every request (in ASP.NET) and we can accidently share variables and their status across multiple threads!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T16:06:41.977",
"Id": "25433",
"ParentId": "25370",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T13:37:08.463",
"Id": "25370",
"Score": "1",
"Tags": [
"c#"
],
"Title": "A Generic NHibernate wrapper with transactionality"
}
|
25370
|
<p>In response to my <a href="https://codereview.stackexchange.com/questions/25155/is-this-method-doing-too-much">previous question</a>, I've refactored my class quite a bit. I've truncated my class a bit, because I have several methods that are very similar, with the exception of the query for the database. The class itself is at the 930 line number. </p>
<p>So, a little background. I'm not only the sole programmer on this project, but also in the company. And this is the first time I've ever attempted anything like this (only out of school 3 years). The purpose of the program is to query a local database, and generate a daily report. I've broken it up into two projects: <code>WPF</code>, and <code>Report class library</code> (what you see below). I already knew I didn't want the UI project to actually do the calculations. So I broke it off into the class library. I also knew I didn't want to just query the whole database and store ALL it's data in memory. So, I have each calculation calling a query method. I had looked into stored procedures, but this is a SQLite database, and stored procedures aren't supported.</p>
<p>Now, with all that in mind, I'm not really sure how best to improve this any further. So here I am, asking you guys: Is this too over the top, or is it fine?</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using MySql.Data.MySqlClient;
using NLog;
namespace DailyReport
{
public class Report
{
#region Global Variables
#region Enums
public enum TimePeriod
{
Daily, Total, None
}
#endregion Enums
private static readonly Logger Logger = LogManager.GetLogger("ReportLogger");
public string ConnectionStringFile { get; private set; }
#region Query Parameters
public string StartTime { get; set; }
public string EndTime { get; set; }
public string Date { get; set; }
#endregion Query Parameters
#endregion Global Variables
#region Constructors
public Report(string stringFileName, DateTime date = default(DateTime), string start = "0", string end = "0")
{
Logger.Info("Creating a new Report...");
StartTime = start;
EndTime = end;
Date = date.ToString("yyyy-MM-dd");
SetStartEndTimes();
ConnectionStringFile = string.Format(@"Data Source=C:\path\{0}.hdd;Version=3;New=False;Compress=True;", stringFileName);
Logger.Info("Report Created");
}
public Report()
{
}
#endregion Constructors
#region Calculations
#region Hours
/// <summary>
/// Drilling Hours
/// </summary>
/// <param name="period">Enum: Period of time</param>
/// <param name="timeFrame">Bool: If the calculation is for a specific time frame</param>
/// <returns>Double: Drilling Hours</returns>
public double DrillingHours(TimePeriod period = TimePeriod.Daily, bool timeFrame = false)
{
Logger.Info("Calculating Drilling Hours...");
const string query = "SELECT timestamp FROM myDatabase WHERE measured_dist = bit_loc AND rop > 0";
var tempList = GetDatabaseResults(timeFrame, query, period);
var drillingHours = CalculateHours(tempList);
Logger.Info(period + " Drilling Hours calculated.");
return drillingHours;
}
/// <summary>
/// Circulating Hours
/// </summary>
/// <param name="period">Enum: Period of time</param>
/// <param name="timeFrame">Bool: If the calculation is for a specific time frame</param>
/// <returns>Double: Circulating Hours</returns>
public double CirculatingHours(TimePeriod period = TimePeriod.Daily, bool timeFrame = false)
{
Logger.Info("Calculating Circulating Hours...");
const string query = "SELECT timestamp FROM myDatabase WHERE pump_press > 100";
var tempList = GetDatabaseResults(timeFrame, query, period);
var circulatingHours = CalculateHours(tempList);
Logger.Info(period + " Circulating Hours calculated.");
return circulatingHours;
}
/// <summary>
/// NonDrillingActivity Hours
/// </summary>
/// <param name="period">Enum: Period of time</param>
/// <param name="timeFrame">Bool: If the calculation is for a specific time frame</param>
/// <returns>Double: NonDrillingActivity Hours</returns>
public double NonDrillingActivityHours(TimePeriod period = TimePeriod.Daily, bool timeFrame = false)
{
Logger.Info("Calculating NonDrillingActivity Hours...");
const string query = "SELECT timestamp FROM myDatabase WHERE pump_press <= 100 AND rop = 0";
var tempList = GetDatabaseResults(timeFrame, query, period);
var nonDrillingActivityHours = CalculateHours(tempList);
Logger.Info(period + " NonDrillingActivity Hours calculated.");
return nonDrillingActivityHours;
}
#endregion Hours
/// <summary>
/// Footage
/// </summary>
/// <param name="period">Enum: Period of time</param>
/// <param name="timeFrame">Bool: If the calculation is for a specific time frame</param>
/// <returns>Double: Footage</returns>
public double Footage(TimePeriod period = TimePeriod.Daily, bool timeFrame = false)
{
Logger.Info("Calculating Footage...");
var query = period == TimePeriod.Daily ? "SELECT measured_dist FROM myDatabase WHERE date = @Date" : "SELECT measured_dist FROM myDatabase";
var tempList = GetDatabaseResults(timeFrame, query);
var dailyDepths = tempList.Select(Convert.ToDouble).ToList();
dailyDepths.Sort();
var footage = Math.Round((dailyDepths.Last() - dailyDepths.First()), 2, MidpointRounding.AwayFromZero);
Logger.Info(period + " Footage calculated.");
return footage;
}
/// <summary>
/// ROP Average
/// </summary>
/// <param name="footage">Double: Footage drilled for the day</param>
/// <param name="drillingHours">Double: Drilling hours for the day</param>
/// <param name="period">Enum: Period of time</param>
/// <returns>Double: ROP Average</returns>
public double RopAVG(double footage, double drillingHours, TimePeriod period = TimePeriod.Daily)
{
Logger.Info("Calculating ROP Avg...");
double ropAvg = 0;
if(footage > 0 && drillingHours > 0)
{
ropAvg = Math.Round(footage / (drillingHours*60), 2, MidpointRounding.AwayFromZero);
}
Logger.Info(period + " ROP Avg calculated.");
return ropAvg;
}
/// <summary>
/// Pump Strokes
/// </summary>
/// <param name="pump">Int: Pump being evaluated</param>
/// <param name="drillingHours">Double: Drilling hours for the day</param>
/// <param name="period">Enum: Period of time</param>
/// <param name="timeFrame">Bool: If the calculation is for a specific time frame</param>
/// <returns>Double: Pump Strokes</returns>
public double PumpStrokes(int pump, double drillingHours, TimePeriod period = TimePeriod.Daily, bool timeFrame = false)
{
Logger.Info("Calculating Pump strokes...");
string query;
switch(pump)
{
case 1:
query = period == TimePeriod.Daily
? "SELECT pump_1_strokes_pm FROM myDatabase WHERE date = @Date"
: "SELECT pump_1_strokes_pm FROM myDatabase";
break;
case 2:
query = period == TimePeriod.Daily
? "SELECT pump_2_strokes_pm FROM myDatabase WHERE date = @Date"
: "SELECT pump_2_strokes_pm FROM myDatabase";
break;
default:
throw new NoDataException("There is no pump number " + pump);
}
IEnumerable<string> tempList;
switch (period)
{
case TimePeriod.Daily:
tempList = GetDatabaseResults(timeFrame, query);
break;
case TimePeriod.Total:
tempList = GetDatabaseResults(timeFrame, query, period);
break;
default:
throw new NoDataException("This should never happen.");
}
var pumpStrokes = tempList.Select(Convert.ToDouble).ToList();
var totalStrokes = Math.Round((pumpStrokes.Sum() / pumpStrokes.Count) * (drillingHours * 60), 2,
MidpointRounding.AwayFromZero);
Logger.Info(period + pump + " Pump strokes calculated.");
return totalStrokes;
}
/// <summary>
/// PSI Max
/// </summary>
/// <param name="period">Enum: Period of time</param>
/// <param name="timeFrame">Bool: If the calculation is for a specific time frame</param>
/// <returns>Double: PSI Max</returns>
public double PsiMAX(TimePeriod period = TimePeriod.Daily, bool timeFrame = false)
{
Logger.Info("Calculating Max PSI...");
var query = period == TimePeriod.Daily ? "SELECT pump_press FROM myDatabase WHERE date = @Date" : "SELECT pump_press FROM myDatabase";
var tempList = GetDatabaseResults(timeFrame, query);
var psiList = tempList.Select(Convert.ToDouble).ToList();
var psiMax = Math.Round(psiList.Max(), 2, MidpointRounding.AwayFromZero);
Logger.Info(period + " Max PSI calculated.");
return psiMax;
}
/// <summary>
/// Torque Avg
/// </summary>
/// <param name="drillingHours">Double: Drilling hours for the day</param>
/// <param name="period">Enum: Period of time</param>
/// <param name="timeFrame">Bool: If the calculation is for a specific time frame</param>
/// <returns>Double: Torque Avg</returns>
public double TorqueAVG(double drillingHours, TimePeriod period = TimePeriod.Daily, bool timeFrame = false)
{
Logger.Info("Calculating Avg Torque...");
var query = period == TimePeriod.Daily ? "SELECT torque FROM myDatabase WHERE date = @Date" : "SELECT torque FROM myDatabase";
var tempList = GetDatabaseResults(timeFrame, query);
var torqueList = tempList.Select(Convert.ToDouble).ToList();
if(torqueList.Sum() > 0 && drillingHours > 0)
{
var torqueAvg = Math.Round((torqueList.Sum() / torqueList.Count), 2, MidpointRounding.AwayFromZero);
Logger.Info(period + " Avg Torque calculated.");
return torqueAvg;
}
Logger.Info("Torque Avg = 0 because torque sum = " + torqueList.Sum() + " or DrillingHours = " + drillingHours);
return 0;
}
/// <summary>
/// SPM Avg
/// </summary>
/// <param name="pumpStrokes1"></param>
/// <param name="pumpStrokes2"></param>
/// <param name="drillingHours">Double: Drilling hours for the day</param>
/// <param name="period">Enum: Period of time</param>
/// <param name="timeFrame">Bool: If the calculation is for a specific time frame</param>
/// <returns>Double: SPM Avg</returns>
public double SpmAVG(double pumpStrokes1, double pumpStrokes2, double drillingHours, TimePeriod period = TimePeriod.Daily, bool timeFrame = false)
{
Logger.Info("Calculating Avg SPM...");
var totalPumpStrokes = pumpStrokes1 + pumpStrokes2;
if (totalPumpStrokes > 0 && drillingHours > 0)
{
var spmAvg = Math.Round(totalPumpStrokes/(drillingHours*60), 2, MidpointRounding.AwayFromZero);
Logger.Info(period + " Avg SPM calculated.");
return spmAvg;
}
Logger.Info("SPM Avg = 0 because spm sum = " + totalPumpStrokes + " or DrillingHours = " + drillingHours);
return 0;
}
/// <summary>
/// PSI Off Bottom
/// </summary>
/// <param name="period">Enum: Period of time</param>
/// <param name="timeFrame">Bool: If the calculation is for a specific time frame</param>
/// <returns>Double: PSI Off Bottom</returns>
public double PsiOffBottom(TimePeriod period = TimePeriod.Daily, bool timeFrame = false)
{
Logger.Info("Calculating PSI off bottom...");
const string query = "SELECT pump_press FROM myDatabase WHERE measured_dist != bit_loc";
var tempList = GetDatabaseResults(timeFrame, query, period);
var psiList = tempList.Select(Convert.ToDouble).ToList();
var psiOffBottom = Math.Round(psiList.Max(), 2, MidpointRounding.AwayFromZero);
Logger.Info(period + " PSI off bottom calculated.");
return psiOffBottom;
}
#endregion Calculations
#region Everything Else
private static double CalculateHours(IEnumerable<string> projectHours)
{
return Convert.ToDouble(Math.Round(TimeCalculations(ConvertStringListToDateTimeList(projectHours)).TotalHours, 2, MidpointRounding.AwayFromZero));
}
private IEnumerable<string> GetDatabaseResults(bool timeFrame, string query, TimePeriod period = TimePeriod.None)
{
var daily = period == TimePeriod.Daily;
query = BuildQuery(query, daily, timeFrame);
var tempList = ExecuteQuery(query);
if (tempList.Any())
{
return tempList;
}
throw new NoDataException("There was no data for the selected time frame. Please select another.");
}
private static TimeSpan TimeCalculations(IList<DateTime> timeStamps)
{
var interval = new TimeSpan(0, 0, 10);
var totalTime = new TimeSpan();
for (var j = 0; j < timeStamps.Count - 1; j++)
{
if (timeStamps[j + 1].Subtract(timeStamps[j]) > interval) continue;
var timeDifference = timeStamps[j + 1].Subtract(timeStamps[j]);
totalTime = totalTime.Add(timeDifference);
}
return totalTime;
}
private List<string> ExecuteQuery(string query)
{
Logger.Info("Executing query...");
var tempList = new List<string>();
try
{
using (var connection = new SQLiteConnection(ConnectionStringFile))
{
using (var command = new SQLiteCommand(query, connection))
{
connection.Open();
command.Parameters.Add(new SQLiteParameter("@Date", Date));
command.Parameters.Add(new SQLiteParameter("@StartTime", StartTime));
command.Parameters.Add(new SQLiteParameter("@EndTime", EndTime));
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
for (var i = 0; i < reader.FieldCount; i++)
{
tempList.Add(reader.GetValue(i).ToString());
} // for
} // while
} // using reader
} // using command
} // using connection
} // try
catch (Exception ex)
{
Logger.Error(ex.Message);
}
Logger.Info("Query complete");
return tempList;
}
private static string BuildQuery(string query, bool daily, bool timeFrame)
{
Logger.Info("Building query...");
const string dailyAdd = " AND date = @Date";
const string timeFrameAdd = " AND timestamp BETWEEN @StartTime AND @EndTime";
// Stack Overflow would HATE this so much
if (daily)
{
query += dailyAdd;
}
if (timeFrame)
{
query += timeFrameAdd;
}
Logger.Info("Query built");
return query;
}
// The list of strings should be DateTimes so that we can calculate hours
private static List<DateTime> ConvertStringListToDateTimeList(IEnumerable<string> stringList)
{
var dateTimeList = stringList.Select(Convert.ToDateTime).ToList();
return dateTimeList;
}
/// <summary>
/// Get list of unique dates. These are dates that have information in the database.
/// </summary>
/// <returns>List of unique dates</returns>
public List<string> GetUniquesDates()
{
var dates = new List<string>();
const string query = "SELECT date FROM myDatabase";
try
{
using (var connection = new SQLiteConnection(ConnectionStringFile))
{
using (var command = new SQLiteCommand(query, connection))
{
connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
for (var i = 0; i < reader.FieldCount; i++)
{
dates.Add(reader.GetValue(i).ToString());
}
}
}
}
}
}
catch (Exception ex)
{
Logger.Error(ex.Message);
}
dates.Sort();
return dates.Distinct().ToList();
}
/// <summary>
/// Sets the global variables for StartTime and EndTime
/// </summary>
/// StartTime and EndTime won't change at all throughout the live of the Report object
private void SetStartEndTimes()
{
// Because the timestamp retrieved will be a string, and will be in "yyyy-MM-dd HH:mm:ss" format
if (StartTime.Equals("0")) return;
StartTime = Date + string.Format(StartTime, "HH:mm:ss");
EndTime = Date + string.Format(EndTime, "HH:mm:ss");
}
#endregion Everything Else
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T17:05:01.637",
"Id": "39344",
"Score": "1",
"body": "Am I the only one left who hates `var`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T17:13:56.760",
"Id": "39345",
"Score": "6",
"body": "@banging - Yes?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T19:54:03.137",
"Id": "39448",
"Score": "0",
"body": "Does it make sense to call Report()? If not I would remove that and consider making the End, Start and Date properties private set."
}
] |
[
{
"body": "<p>It looks like some of the methods are simply calculating the max or average. You might be able to move these types of calculations into the queries by using the corresponding aggregate functions. For example:</p>\n\n<pre><code>SELECT MAX(pump_press) FROM myDatabase\nSELECT AVG(torque) FROM myDatabase\n</code></pre>\n\n<p>I believe the <code>Footage</code> calculation could even be done using:</p>\n\n<pre><code>SELECT MAX(measured_dist) - MIN(measured_dist) FROM myDatabase\n</code></pre>\n\n<hr>\n\n<p>I would also discourage the use of variables with names like <code>tempList</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T18:21:08.807",
"Id": "39359",
"Score": "0",
"body": "That's a good call. This is the first project where I've worked extensively with databases, so I'm still learning the ins and outs."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T16:32:23.783",
"Id": "25380",
"ParentId": "25372",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "25380",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T14:36:40.790",
"Id": "25372",
"Score": "4",
"Tags": [
"c#"
],
"Title": "Is this class too over the top?"
}
|
25372
|
<p>I just started learning C and the online book contained the exercise 'implement a stack'. So I did, but thought I'd put it here, because I still don't feel comfortable with pointers.</p>
<p>So here it is:</p>
<pre><code>#include <stdlib.h>
#include <stdio.h>
struct StackItem {
struct StackItem *previous;
int value;
};
void stack_push(struct StackItem **current, int value) {
struct StackItem *tmp = malloc(sizeof(struct StackItem));
tmp->previous = *current;
tmp->value = value;
*current = tmp;
}
void stack_pop(struct StackItem **current) {
if ((*current)->previous != NULL) {
struct StackItem *tmp = (*current)->previous;
free(*current);
*current = tmp;
} else printf("%s\n", "Previous is NULL");
}
void stack_print(struct StackItem *current) {
printf("%d\n", current->value);
while (current->previous != NULL) {
current = current->previous;
printf("%d\n", current->value);
}
}
int main(int argc, char **argv) {
struct StackItem *current = malloc(sizeof(struct StackItem));
current->value = 2147483647;
current->previous = NULL;
char input[10];
int i = 0;
while (i < 10) {
puts("Enter integer value to add to the stack:");
gets(input);
char *end;
int newVal = (int)strtol(input, &end, 10);
if (*end != '\0') { puts("That was no integer value."); --i; }
else stack_push(&current, newVal);
++i;
}
stack_print(current);
puts("Stack printed once.");
i = 0;
while (i < 10) {
stack_pop(&current);
i++;
}
stack_print(current);
puts("Stack printed twice.");
return 0;
}
</code></pre>
<p>Is there anything wrong/not good (I mean two different things here) with this?</p>
|
[] |
[
{
"body": "<p>Your code looks nice and compiles cleanly - good signs. Some comments, nevertheless:</p>\n\n<ul>\n<li><p>all functions except <code>main</code> should be declared <code>static</code></p></li>\n<li><p>the opening brace { for a function should be in column 0</p></li>\n<li><p><code>stack_print</code> should take a <code>const</code> parameter, as you are not modifying the stack:</p>\n\n<pre><code> void stack_print(const struct StackItem *current)\n</code></pre></li>\n<li><p>the stack variable name <code>current</code> would be better as (for example) <code>stack</code></p></li>\n<li><p>you define the stack <code>current</code> by allocating a <code>StackItem</code> but never use\nthis item. It would be better to define the stack using just a pointer:</p>\n\n<pre><code> struct StackItem *current = NULL;\n</code></pre>\n\n<p>this involves some changes to other functions because the 'empty stack'\ncondition is no longer <code>(*current)->previous == NULL</code> but simply <code>*current\n== NULL</code>. This affects <code>stack_pop</code> and <code>stack_print</code>. The latter becomes:</p>\n\n<pre><code>void stack_print(const struct StackItem *current)\n{\n while (current != NULL) {\n printf(\"%d\\n\", current->value);\n current = current->previous;\n }\n}\n</code></pre></li>\n<li><p>for-loops are often better than while loops - eg when you are counting\nthrough a range. And the loop variable is best declared in the loop where\npossible:</p>\n\n<pre><code>for (int i = 0; i < 10; ++i) {\n stack_pop(&current);\n}\n</code></pre></li>\n<li><p>using constants in the code like 10 is often a bad idea. Some are fine (eg\nthe 10 in the <code>strtol</code> call, but the loops would be better having a #defined\nlimit</p>\n\n<pre><code>#define N_VALUES 10\n\nfor (int i = 0; i < N_VALUES; ++i) {...}\n</code></pre>\n\n<p>Such #defines go at the top of the file after the #includes </p></li>\n<li><p><code>gets</code> is not safe and should not be used. Using <code>gets</code> with a buffer of 10\nbytes, if the user types in more than 10 characters the buffer overflows and\noverwrites the call stack (not your stack but the process stack). Use\n<code>fgets</code> instead:</p>\n\n<pre><code>fgets(input, (int) sizeof input, stdin);\n</code></pre></li>\n<li><p>there is no error handling, but that is ok for an exercise. In a real\nprogram, you would want to check that <code>malloc</code> does not fail (using <code>perror</code>\nto print an error message if it does - an then you have to decide what to do\nabout the failure) and you might want to return success or failure from\nthe push/pop functions.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T17:30:39.357",
"Id": "39582",
"Score": "0",
"body": "A great answer overall, but reading a few of your points the question 'why?' comes to mind. Especially the point on curly braces. I'm new to C, but not to programming, so I already read about that discussion, and to me it seems it's more a kind of religious Apple-vs-Android-like debate. Sorry for the late response."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T18:08:22.957",
"Id": "39584",
"Score": "0",
"body": "Functionally it makes no difference where the brace goes; column 0 is just convention. Putting the brace in another place gains nothing and will irritate some experienced readers of your code. Those readers (having seen and or suffered code from many others who had their own 'style') may well assume that you are inexperienced or less competent than you actually are on the basis of your style. That is just how it is :-) Any other 'why's, let me know and I'll update the answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T15:38:52.013",
"Id": "25376",
"ParentId": "25374",
"Score": "4"
}
},
{
"body": "<p>It's good overall, but I do have a few suggestions.</p>\n\n<p>(Looks like William Morris beat me to a few of these, but there's a few different ones too :p.)</p>\n\n<hr>\n\n<p>Rather than using the top node as the container, I'd be tempted to make a <code>Stack</code> that then contains <code>StackItem</code>.</p>\n\n<pre><code>struct Stack\n{\n StackItem* top;\n size_t size; /* example of meta-data */\n};\n</code></pre>\n\n<p>This would allow passing around a structure and letting functions modify it rather than passing an item by double reference and having the function modify your pointer.</p>\n\n<p>Also, you get the added bonus of stack-related meta data. For example, suppose you wanted to generalize this stack. You would need to store data about how big each element is. With this structure, that's simple. You just throw in another field (and of course put handling for it in the initialization and whatnot). In the <code>StackItem**</code> version, you're suddenly stuck repeating that information in every instance of <code>StackItem</code>.</p>\n\n<p>Oh, this also means your sentinel node is no longer required, which can be kind of nice (though it can also complicate some algorithms).</p>\n\n<hr>\n\n<p>Your methods should return error codes. What if malloc fails in <code>stack_push</code>? What if <code>(*current)->previous</code> is <code>NULL</code> in <code>stack_pop</code>?</p>\n\n<p>Printing errors in non-user interaction code tends to be bad. Printing communicates with the user, not the code. Your code has no idea stack_pop failed, only your user does. If you pass an error message to the calling code, that code can then choose what to do. It might silently ignore the error, it might alert the user, or it might decide to have a forced freak out. Who knows. The point though is that the calling code needs to be able to decide for itself what to do. Sometimes just alerting the user isn't sufficient.</p>\n\n<hr>\n\n<p>Other than fully printing or manually handling the struct traversal, how do you get the top element of the stack? Either <code>stack_pop</code> should handle this, or there should be a <code>stack_top</code>.</p>\n\n<p>(<code>int stack_pop(struct StackItem* current, int* popped);</code> for example.)</p>\n\n<hr>\n\n<p>There's a some problems with your IO in <code>main</code>.</p>\n\n<p>First, an int can be 10 characters. This means your <code>input</code> buffer needs to be 11 characters (10 + <code>'\\0'</code>).</p>\n\n<p>More importantly though, <code>gets</code> should be avoided. What if instead of a wellformed int or a string <= 10 characters, I decide to put in <code>aaaaaaaaaaaaaa</code>. Best case, a segfault just happened. Worst case, the stack frame just got modified in a very odd (and potentially insecure) way. (On modern operating systems, the segfault option is almost certainly going to happen, but this should still be avoided at all costs.)</p>\n\n<p>Anyway, I would replace gets with fgets. That way you get the safety of specifying buffer size.</p>\n\n<hr>\n\n<p>It's way overkill in this situation, but if you decide to go the library-esque route, I would encapsulate your data in a way that the calling code never has to know what's in the struct behind the scene. (This is called an <a href=\"http://en.wikipedia.org/wiki/Opaque_data_type\" rel=\"nofollow noreferrer\">opaque data type</a>). This way your calling code just has to know how to use the exposed API, not the nitty-gritty details.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/2301454/what-defines-an-opaque-type-in-c-and-when-are-they-necessary-and-or-useful\">This</a> explains it pretty well.</p>\n\n<p>All in all, if you decide to go the opaque route, I would have an API similar to:</p>\n\n<pre><code>int stack_init(Stack* s);\nint stack_destroy(Stack* s);\nint stack_push(Stack* s, int val);\nint stack_pop(Stack* s, int* val);\nsize_t stack_size(void); /* so you can alloc Stacks -- Stack* s = malloc(stack_size()); */\nint stack_top(const Stack* s, int* val); /* optional */\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T16:05:31.637",
"Id": "25378",
"ParentId": "25374",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "25378",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T14:57:12.883",
"Id": "25374",
"Score": "4",
"Tags": [
"c",
"stack"
],
"Title": "Another stack implementation (in C)"
}
|
25374
|
<p>Instead of using the ProgressBar plugin, this script displays the progress bar for async requests on the page. Could anyone provide any feedback on this, especially if there will be any issues like cross browser compatibility, etc?</p>
<pre><code><div class="overlay">
<div class="progress">
<img src="@Url.Content("~/content/images/loading.gif")" />Loading...
</div>
</div>
//displays progress bar
$('.overlay').ajaxStart(function () {
$(this).css({ height: $(document).height(), width: $(document).width() }).show();
$(this).find(".progress").css({ top: $(window).height() / 2, left: $(window).width() / 2 });
}).ajaxStop(function () {
$(this).hide();
});
.overlay
{
position: fixed !important;
position: absolute; /*ie6*/
width: 100%;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
background-color: #000;
filter: alpha(opacity=20);
opacity: 0.2;
-moz-opacity: 0.2;
-khtml-opacity: 0.2;
-webkit-opacity: 0.2;
z-index: 10004;
display: none;
filter: progid:DXImageTransform.Microsoft.Alpha(opacity=20); /*ie6*/
}
.overlay .progress
{
position: absolute;
z-index: 10005;
background: #fff;
color: #000;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-27T15:43:46.420",
"Id": "50935",
"Score": "0",
"body": "There are websites to test browser compatibility; or, you can test across the main browsers yourself, I download safari, opera, firefox, ie 9 and 10 to test websites"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-06T15:01:09.270",
"Id": "60498",
"Score": "0",
"body": "Is IE6 still a concern for this project? It is largely considered to be a dead browser, and jQuery's support for older IE versions has been waning."
}
] |
[
{
"body": "<p>My 2 cents : </p>\n\n<ul>\n<li><p>I definitely learned something today, I didnt know about <code>ajaxStart</code> / <code>ajaxStop</code>, excellent question.</p></li>\n<li><p>In my eyes this should work on most recent browsers, but as Skippy says, you ought to test yourself on every browser.</p></li>\n<li><p>Minor nitpicking, you could remove these from .overlay</p></li>\n</ul>\n\n<blockquote>\n<pre><code>top: 0px;\nleft: 0px;\nright: 0px;\nbottom: 0px;\nwidth: 100%;\n</code></pre>\n</blockquote>\n\n<p>or as per cimmanon remove the resizing in jQuery:</p>\n\n<blockquote>\n<pre><code>$(this).show();\n</code></pre>\n \n <p>Which is admittedly more in line with the hiding code.</p>\n</blockquote>\n\n<ul>\n<li>Minor nitpicking but <code>background: #fff;</code> should be <code>background-color: #fff;</code></li>\n</ul>\n\n<p>All in all, I will definitely borrow your code ;)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-06T14:58:23.163",
"Id": "60497",
"Score": "0",
"body": "Removing the styles as you suggest makes it not overlay anymore: http://cssdeck.com/labs/hhyxcw7u. Width can go, but top/right/bottom/left are necessary for the desired effect."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-06T15:21:06.627",
"Id": "60499",
"Score": "0",
"body": "Check this : http://jsfiddle.net/konijn_gmail_com/8e4Ps/ your link does not have the jQuery code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-06T15:40:24.467",
"Id": "60504",
"Score": "0",
"body": "If anything, setting the width/height via jQuery is redundant (and inefficient), not the CSS."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-06T14:27:29.060",
"Id": "36780",
"ParentId": "25379",
"Score": "3"
}
},
{
"body": "<p>Realizing that you are trying to make reusable code, I figured I would share my methodology, as I believe it will extend your structure here.</p>\n\n<p>I like to wrap everything into an object with functions appropriate to AJAX, and I added in your <code>.overlay</code> components:</p>\n\n<pre><code>var ajax = {\n showProgressBar:function($overlay){\n var $doc = $(document),\n $win = $(window);\n\n $overlay\n .css({\n height:$doc.height(),\n width:$doc.width(),\n display:'block'\n })\n .find('.progress')\n .css({\n top:($win.height() / 2),\n left:($win.width() / 2)\n });\n },\n hideProgressBar:function($overlay){\n $overlay.hide();\n },\n abortActive:function(){\n var self = this;\n\n if(($.active > 0) && (self.active !== undefined)){\n self.active.abort();\n }\n },\n clearActive:function(){\n this.active = undefined;\n },\n send:function($type,$url,$data,$success,$error,$abort){\n var self = this,\n $overlay = $('.overlay'),\n $beforeSend = ($abort ? function(){\n self.abortActive();\n self.showProgressBar($overlay);\n } : function(){\n self.showProgressBar($overlay); \n }),\n $complete = ($abort ? function(){\n self.clearActive();\n self.hideProgressBar($overlay);\n } : function(){\n self.hideProgressBar($overlay); \n }),\n curFunc = $.ajax({\n type:$type,\n url:$url,\n data:$data,\n beforeSend:$beforeSend\n }).success($success).error($error).complete($complete);\n\n this.active = ($abort ? curFunc : self.active);\n }\n };\n</code></pre>\n\n<p>And then it is called with an example of something like this:</p>\n\n<pre><code>ajax.send(\n 'POST',\n 'requires/submitSomething.php',\n {\n id:$someId,\n type:$someType\n },\n function(data){\n alert('Successful! The response message was: '+data.message);\n },\n function(data){\n alert('Error! The response message was: '+data.message);\n },\n false\n);\n</code></pre>\n\n<p>This is obviously super generic, but should do the trick. A quick explanation:</p>\n\n<ul>\n<li>the <code>beforeSend</code> setting will fire a callback function prior to sending the AJAX, which is where you want to load your progress gif</li>\n<li>the <code>complete</code> setting will fire a callback function once everything else completes, including the <code>success</code> / <code>error</code> functions, so it is where you want to hide the progress gif</li>\n<li>in the <code>success</code> / <code>error</code> functions, you can include the response data and manipulate as you wish</li>\n<li>the use of <code>this</code> in the <code>send</code> function refers to the object parent, hence able to see the other functions rather than referring to them by name</li>\n<li>the ajax call is assigned to a variable to allow for aborting the call mid-stream before starting another (if another action overrides it, for example) ... the reason for the use of <code>this</code> rather than <code>self</code> is because we need to assign it to the object rather than just reference the existing objects within it</li>\n<li>the function creation is based on the boolean you pass in for <code>$abort</code>, to determine if your AJAX call should stop all current AJAX calls or have it run in parallel (depending on your usage)</li>\n</ul>\n\n<p>And a few small tweaks I made to your existing jQuery code to optimize:</p>\n\n<ul>\n<li>cached <code>$(document)</code>, <code>$(window)</code>, and <code>$('.overlay')</code> as they are used more than once in the functions</li>\n<li>consolidated your <code>.show()</code> function into the previous CSS statement (as the default is to basically perform a <code>.css({display:'block'})</code> statement ... if you have overridden this with a custom function, you can return as needed)</li>\n<li>chained the calls to <code>$('.overlay')</code> and <code>$('.progress')</code>, as they were both based on <code>$(this)</code></li>\n</ul>\n\n<p>This function should give you a good starting point, and you can modify as needed if you need additional parameters. The only additional parameter I advise against is the use of <code>dataType</code>; for some reason, everyone using <code>json</code> likes to include <code>dataType</code> in their AJAX call (which is an intelligent guess, not a true marker) instead of doing it right. Don't be \"that guy\", put your appropriate header declaration in the files you are loading via AJAX and it will be bulletproof.</p>\n\n<p>Hope this helped.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T10:28:16.570",
"Id": "38268",
"ParentId": "25379",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T16:24:12.850",
"Id": "25379",
"Score": "11",
"Tags": [
"javascript",
"jquery",
"asp.net",
"css",
"ajax"
],
"Title": "Display progress bar to show async request status using jQuery"
}
|
25379
|
<p>I've finally finished my converter and have determined that it works, but I'm trying to make it cleaner and/or more practical (primarily with the <code>switch</code> statements). I could probably put more things into functions, but it'll be needless unless I can replace the <code>switch</code> statements with something simpler.</p>
<p>Are there other methods of performing these conversions that would use less code, or are these methods good enough? I am also using <code>unsigned long long</code> so that I can work with large numbers, but I can always change that if it may not be the best thing to do.</p>
<pre><code>#include <iostream>
#include <string>
typedef unsigned long long uInt64;
uInt64 calculatePower(uInt64, uInt64);
uInt64 binaryToDecimal(std::string);
uInt64 hexadecimalToDecimal(std::string);
std::string decimalToBinary(uInt64);
std::string binaryToHexadecimal(std::string);
int main()
{
std::string binary, hex;
uInt64 decimal;
uInt64 choice;
std::cout << "\n\n* Decimal -> Binary & Hex (1)\n";
std::cout << "* Binary -> Decimal & Hex (2)\n";
std::cout << "* Hex -> Binary & Decimal (3)\n\n";
std::cin >> choice;
if (choice == 1)
{
std::cout << "\n> Decimal Input: ";
std::cin >> decimal;
std::string binaryOutput = decimalToBinary(decimal);
std::string hexOutput = binaryToHexadecimal(binaryOutput);
std::cout << "\n Decimal Output: " << binaryOutput;
std::cout << "\n Hex Output : " << hexOutput << "\n\n\n";
}
else if (choice == 2)
{
std::cout << "\n> Binary Input: ";
std::cin.ignore();
std::getline(std::cin, binary);
uInt64 decimalOutput = binaryToDecimal(binary);
std::string hexOutput = binaryToHexadecimal(binary);
std::cout << "\n Hex Output : " << hexOutput;
std::cout << "\n Decimal Output: " << decimalOutput << "\n\n\n";
}
else if (choice == 3)
{
std::cout << "\n> Hex Input: ";
std::cin.ignore();
std::getline(std::cin, hex);
uInt64 decimalOutput = hexadecimalToDecimal(hex);
std::string binaryOutput = decimalToBinary(decimalOutput);
std::cout << "\n Binary Output : " << binaryOutput;
std::cout << "\n Decimal Output: " << decimalOutput << "\n\n\n";
}
system("PAUSE");
}
uInt64 calculatePower(uInt64 base, uInt64 exponent)
{
uInt64 total = 1;
for (uInt64 iter = 0; iter < exponent; iter++)
total *= base;
return total;
}
uInt64 binaryToDecimal(std::string binary)
{
uInt64 decimal = 0;
uInt64 exponent = 0;
std::string::reverse_iterator iter;
for (iter = binary.rbegin(); iter != binary.rend(); iter++)
{
if (*iter == '1')
decimal += calculatePower(2, exponent);
exponent++;
}
return decimal;
}
uInt64 hexadecimalToDecimal(std::string binary)
{
uInt64 decimal = 0;
uInt64 exponent = 0;
std::string::reverse_iterator iter;
for (iter = binary.rbegin(); iter != binary.rend(); iter++)
{
switch (*iter)
{
case '1':
decimal += calculatePower(16, exponent);
break;
case '2':
decimal += (2 * calculatePower(16, exponent));
break;
case '3':
decimal += (3 * calculatePower(16, exponent));
break;
case '4':
decimal += (4 * calculatePower(16, exponent));
break;
case '5':
decimal += (5 * calculatePower(16, exponent));
break;
case '6':
decimal += (6 * calculatePower(16, exponent));
break;
case '7':
decimal += (7 * calculatePower(16, exponent));
break;
case '8':
decimal += (8 * calculatePower(16, exponent));
break;
case '9':
decimal += (9 * calculatePower(16, exponent));
break;
case 'A':
decimal += (10 * calculatePower(16, exponent));
break;
case 'B':
decimal += (11 * calculatePower(16, exponent));
break;
case 'C':
decimal += (12 * calculatePower(16, exponent));
break;
case 'D':
decimal += (13 * calculatePower(16, exponent));
break;
case 'E':
decimal += (14 * calculatePower(16, exponent));
break;
case 'F':
decimal += (15 * calculatePower(16, exponent));
break;
}
exponent++;
}
return decimal;
}
std::string decimalToBinary(uInt64 decimal)
{
std::string binary, newBinary = "";
std::string::reverse_iterator iter;
uInt64 remainder;
while (decimal > 0)
{
remainder = decimal % 2;
if (remainder == 0)
binary += '0';
else if (remainder == 1)
binary += '1';
decimal /= 2;
}
for (iter = binary.rbegin(); iter != binary.rend(); iter++)
{
newBinary += *iter;
}
return newBinary;
}
std::string binaryToHexadecimal(std::string binary)
{
std::string hex, newHex = "";
std::string::reverse_iterator iter;
uInt64 incr = 1;
uInt64 exponent = 0;
uInt64 total = 0;
for (iter = binary.rbegin(); iter != binary.rend(); iter++)
{
if (*iter == '1')
total += calculatePower(2, exponent);
if (incr == 4)
{
switch (total)
{
case 1:
hex += '1';
break;
case 2:
hex += '2';
break;
case 3:
hex += '3';
break;
case 4:
hex += '4';
break;
case 5:
hex += '5';
break;
case 6:
hex += '6';
break;
case 7:
hex += '7';
break;
case 8:
hex += '8';
break;
case 9:
hex += '9';
break;
case 10:
hex += 'A';
break;
case 11:
hex += 'B';
break;
case 12:
hex += 'C';
break;
case 13:
hex += 'D';
break;
case 14:
hex += 'E';
break;
case 15:
hex += 'F';
break;
}
incr = 0;
exponent = -1;
total = 0;
}
incr++;
exponent++;
}
newHex += "0x";
for (iter = hex.rbegin(); iter != hex.rend(); iter++)
{
newHex += *iter;
}
return newHex;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T17:30:32.073",
"Id": "39346",
"Score": "0",
"body": "Are you willing to the code tied to ASCII? If so, the easiest simplification I see is to use c - '0' to get offsets. Like `decimal += (*iter - '0') * calculatePower(16, exponent)`. (Technically not tied to ASCII; just requires that '0'...'9' be contiguous.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T17:36:32.487",
"Id": "39347",
"Score": "0",
"body": "I am, if it'll go in place of the `switch` statements. Even what I have now is clear, but very bloated. Maybe I can work something out with a `char` array..."
}
] |
[
{
"body": "<p>You repeated calls to <code>calculatePower</code> are rather inefficient. There is no need to\ncall this every time round a loop. In <code>binaryToDecimal</code>, you could do this:</p>\n\n<pre><code> std::string::const_reverse_iterator i = b.rbegin();\n for (int exp = 0; i != b.rend(); ++i, ++exp) {\n if (*i == '1') {\n decimal += (1 << exp);\n }\n }\n</code></pre>\n\n<p>and in <code>hexadecimalToDecimal</code>:</p>\n\n<pre><code> std::string::const_reverse_iterator i = h.rbegin();\n for (int exp = 0; i != h.rend(); ++i, exp += 4) {\n {\n int n = 0;\n if ((*i >= '0') && (*i <= '9')) {\n n = *i - '0';\n }\n else if ((*i >= 'a') && (*i <= 'f')) {\n n = *i - 'a';\n }\n else if ((*i >= 'A') (*i <= 'F')) {\n n = *i - 'A';\n }\n decimal += (n << exp);\n }\n</code></pre>\n\n<p>For <code>binaryToHexadecimal</code> it would be easier to convert binary to machine\n(what you call decimal) and then machine to hex.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T18:35:20.540",
"Id": "25389",
"ParentId": "25381",
"Score": "2"
}
},
{
"body": "<p><em>system</em> is bad. Either use <code>getchar()</code>, set your IDE to pause after execution, or use a terminal when running a terminal program.</p>\n\n<hr>\n\n<p>The <code>typedef</code> for <code>uint64</code> should just be <code>uint64_t</code> from <code>stdint.h</code>.</p>\n\n<hr>\n\n<p>Your input reading should be checked. For example, <code>std::cin >> choice;</code> can fail. It should be</p>\n\n<pre><code>if (!(std::cin >> choice)) { /* handle this */ }\n</code></pre>\n\n<p>If you're thinking you're ok because choice is checked to be either 1, 2, or 3, you're not ok. You're just almost certainly ok. If the read fails, choice will still have an indeterminate value. That could mean 1, 2, or 3.</p>\n\n<hr>\n\n<p>You can basically replace all of your <code>ToDecimal</code> functions with <code>strtoul</code> (C >= C89) or <code>strtoull</code> (C >= C99). An <code>unsigned long</code> is only gauranteed to be 4 bytes, so you'll want the <code>strtoull</code> version.</p>\n\n<hr>\n\n<p>Similarly, <code>sprintf()</code> can convert to hex for you (format <code>llX</code>).</p>\n\n<hr>\n\n<p>If you're not willing to do that, but you're willing to assume that '0'...'9' is always contiguous, you can use the class <code>value = c - '0'</code> shortcut.</p>\n\n<p>As an example, you could simplify your beastly <code>hexidecimalToDecimal()</code>:</p>\n\n<pre><code>uint64_t hexadecimalToDecimal(const std::string& binary)\n{\n uint64_t decimal = 0;\n uint64_t power = 1;\n std::string::const_reverse_iterator iter;\n\n for (iter = binary.rbegin(); iter != binary.rend(); iter++)\n {\n const char ch = std::tolower(*iter);\n if (ch >= 'a') {\n decimal += (ch - 'a') * power;\n } else {\n decimal += (ch - '0') * power;\n }\n power *= 16;\n }\n\n return decimal;\n}\n</code></pre>\n\n<hr>\n\n<p>When arguments are NOT modified, they should be passed as <code>const</code> references. This avoids the overhead of copying. (And it's part of a larger concept called const-correctness.)</p>\n\n<hr>\n\n<p>I tend to put arguments names in declarations. In this situation, it's a marginal concern since all of the functions have very obvious parameters, but in some cases, it can be quite confusing to see a declaration and wonder what the different params are.</p>\n\n<hr>\n\n<p>Unless performance is tight, I'd be tempted to implement everything in terms of decimal. For example, <code>binaryToHex(bin): decimalToHex(binaryToDecimal(bin))</code></p>\n\n<hr>\n\n<p>Speaking of performance, if you wanted to, you could inline the exponent calculations instead of recalculating it from scratch every time.</p>\n\n<pre><code>uint64_t binaryToDecimal(const std::string& binary)\n{\n uint64_t decimal = 0;\n uint64_t p = 1;\n std::string::const_reverse_iterator iter;\n\n for (iter = binary.rbegin(); iter != binary.rend(); iter++)\n {\n if (*iter == '1')\n decimal += p;\n p *= 2;\n }\n\n return decimal;\n}\n</code></pre>\n\n<p>(And if you're really paranoid about performance, you'll want that <code>iter++</code> to be <code>++iter</code> as it avoid a potential copy)</p>\n\n<hr>\n\n<p>If for some odd reason you don't want to do that, <code>calculatePower()</code> can be optimized in many different ways:</p>\n\n<ul>\n<li>Use the <code>double</code> version and just cast back to <code>uint64_t</code>.</li>\n<li>Use powers of 2 and abuses of shifting (x<sup>16</sup> = <code>x << 4</code>)</li>\n<li>Use <a href=\"https://stackoverflow.com/a/1505791/567864\">divide and conquer style</a></li>\n</ul>\n\n<hr>\n\n<blockquote>\n<pre><code>remainder = decimal % 2;\n\nif (remainder == 0)\n binary += '0';\nelse if (remainder == 1)\n binary += '1';\n</code></pre>\n</blockquote>\n\n<p>As remaining can only be 0 <= <code>remainder</code> <= 1, the <code>else if</code> is unnecessary. I would just use:</p>\n\n<pre><code>if (decimal % 2 == 0) {\n binary += '0';\n} else {\n binary += '1';\n}\n</code></pre>\n\n<hr>\n\n<p>You can use std::reverse (from <code><algorithm></code>) rather than your manual reversal loop.</p>\n\n<p>Example:</p>\n\n<pre><code>std::string decimalToBinary(uint64_t decimal)\n{\n std::string binary;\n while (decimal > 0)\n {\n if (decimal % 2 == 0)\n binary += '0';\n else \n binary += '1';\n decimal /= 2;\n }\n std::reverse(binary.begin(), binary.end());\n return binary;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T22:32:04.557",
"Id": "39372",
"Score": "0",
"body": "I've added what I have now. I still need to simplify `binaryToHex`, or I can just keep it this way. I'll look at the input validation later."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T03:44:01.537",
"Id": "39381",
"Score": "0",
"body": "Should be `<cstdint>` instead of `<stdint.h>` and if you want to be really pedantic, `std::uint64_t`. Otherwise, +1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T04:39:56.007",
"Id": "39383",
"Score": "0",
"body": "@Yuushi Yeah, I definitely should have mentioned the C++11 version (no sign that he's using C++11, but he everyone should probably be headed that direction). With `stdint.h` though, `std::uint64_t` is actually wrong. Non c* version is guaranteed to put the types in the global namespace, but not in `std`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T04:45:40.140",
"Id": "39384",
"Score": "0",
"body": "Yeah, that needs a logical connection in there - `<cstdint>` => `std::uint64_t` since it's the other way around (guaranteed to be in `std` but not in global). Have to love the interop rules sometimes..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T05:17:24.663",
"Id": "39386",
"Score": "0",
"body": "Eh makes sense since name spacing is almost always desirable, but C doesn't have namespaces. What I don't get is why stdint didn't get a C++ version until C++11 (though I'm sure I can google it -- they probably just thought the types could be global...)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T15:35:34.320",
"Id": "39428",
"Score": "1",
"body": "In C++11 If a read fails. The value is guaranteed to be zero. From **n3376**: See [istream.formatted.arithmetic] => [facet.num.get.virtuals] Stage 3: `The numeric value to be stored can be one of: 1: zero, if the conversion function fails to convert the entire field. ios_base::failbit is assigned to err. 2: ....`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T15:39:42.297",
"Id": "39429",
"Score": "0",
"body": "There is no assumption that char 0-9 are consectuive: From **n3376** See [lex.charset] `the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T16:37:04.983",
"Id": "39431",
"Score": "0",
"body": "@Corbin, I can confirm to you that I'm NOT currently on C++11. When I tried to use `strtoull`, my IDE did not recognize it (but it did recognize `strtoul`, although I would have to use `unsigned long` instead). I currently use Visual C++ 2010 Express, if that helps any. Either way, I may prefer to decline from using that function since I need to see the logic in my own program. On the contrary, I am interested in seeing how `sprintf` can help me here, once I figure out how to use it. I'm open to other methods (shorter than mine), of course."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T19:14:55.780",
"Id": "39442",
"Score": "0",
"body": "I am now writing a function called `hexadecimalToBinary` that entirely uses ASCII offsets (different offsets if the hex value is 0-9 or A-F) and my existing `decimalToBinary` function. I'll post that here sometime."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T00:57:12.227",
"Id": "39478",
"Score": "0",
"body": "@LokiAstari Ah, did not know either of those were guaranteed. Will edit my answer accordingly in a bit."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T18:44:12.457",
"Id": "25390",
"ParentId": "25381",
"Score": "5"
}
},
{
"body": "<p>Perhaps I'm missing something, but is there a reason you aren't converting to <code>unsigned long long</code> first with any of a set of functions, then formatting the output in a separate set of functions? e.g.:</p>\n\n<pre><code>unsigned long long fromHex(std::string& number);\nunsigned long long fromBin(std::string& number);\nunsigned long long fromDec(std::string& number);\nstd::string toHex(unsigned long long number);\nstd::string toBin(unsigned long long number);\nstd::string toDec(unsigned long long number);\n</code></pre>\n\n<p>It seems a bit inconsistent to use the term \"decimal\" for an <code>int</code> in system representation. It would just be confusing, if not for the problematic differences in function signatures between each of the <code>XtoY</code> functions. If it was more uniform, you could:</p>\n\n<pre><code>class NumberFormat {\npublic:\n static virtual unsigned long long from(std::string& number);\n static virtual std::string to(unsigned long long number);\n std::string description;\n}\n</code></pre>\n\n<p>Then, you can make your list of number formats more declarative; construct an array, output the descriptions, and have the user pick what will effectively become an index into the array for the source format. Then read the destination format and numeric string, in either order. </p>\n\n<p>As it stands, the input method is needlessly coupled to a finite set of formats and their names, as is the source/destination pairings.</p>\n\n<p>I once wrote a hex-by-default calculator/expression evaluator in assembly, so I'm the last guy that's going to call a wheel-reinvention foul on you; in fact, I like the general theme of your code because I've never seen a number formatter that covers absolutely everything, like your binary output's adding leading zeroes to pad 4 bit groups. Bravo on making a wheel that spins exactly like you want it to.</p>\n\n<p>With regard to the conversions themselves, I see more twos complement math than is necessary. In particular, I see several <code>%</code>s while converting to binary. If I'm interested in a number's binary representation, I will probably find the equivalent ones complement operations in your code just as readable, if not more so. The sequence:</p>\n\n<pre><code>if (usersDecimal & 1) {\n newBinary += '1';\n} else {\n newBinary += '0';\n}\nusersDecimal >>= 1;\n</code></pre>\n\n<p>just screams \"I am extracting a single bit from the number and printing it!\" to me, whereas with <code>%</code> and <code>/=</code>, it seems like you might be calculating something at first glance. And, if you <em>really</em> like brevity:</p>\n\n<pre><code>newBinary += ((usersDecimal & 1) + '0');\nusersDecimal >>= 1;\n</code></pre>\n\n<p>will get the job done. Not particularly clean, though.</p>\n\n<p>Other than that, the particulars of the conversions are good. Stuff like constants for <code>DIGIT_OFFSET</code> strike a good balance between efficiency and readability.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-03T08:02:47.387",
"Id": "36554",
"ParentId": "25381",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "25390",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T16:35:01.423",
"Id": "25381",
"Score": "5",
"Tags": [
"c++",
"integer",
"number-systems"
],
"Title": "Decimal/binary/hex converter"
}
|
25381
|
<p>I wrote this code for <a href="http://projecteuler.net/index.php?section=problems&id=75" rel="noreferrer">Project Euler problem 75</a>, which asks how many integers ≤ 1500000 exist, where the integer is a perimeter length that can be divided into three integer-length sides of a right triangle in one unique way.</p>
<p>I was curious if anyone knew how to improve its speed. It runs fine, but I'm just looking to improve my own coding know-how.</p>
<pre><code>from functools import reduce
import math
primes=set([2,3,5,7,11,13,17,19,23])
def isPrime(n):
n=abs(n)
if n in primes:
return True
if n<2:
return False
if n==2:
return True
if n%2==0:
return False
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0:
return False
primes.add(n)
return True
def aFactors(n):
if isPrime(n):
return [1,n]
return set(reduce(list.__add__,([i,n//i] for i in range(1,int(math.sqrt(n))+1) if n%i==0)))
count=0
number=12
while number<=1500000:
p=number/2
f=aFactors(p)
triangles=[]
pairs=[(i, int(p/i)) for i in f]
add=triangles.append
for i in pairs:
mList=aFactors(i[0])
pairsOfmc=[(k,int(i[0]/k)) for k in mList]
for j in pairsOfmc:
add((2*i[1]*i[0]-i[1]*i[1]*j[0],2*i[0]*i[1]-2*i[0]*j[1],2*i[0]*j[1]+i[1]*i[1]*j[0]-2*i[0]*i[1]))
r=0
while r<len(triangles):
if any(triangles[r][i]<=0 for i in range(len(triangles[r]))):
del triangles[r]
else:
l=list(triangles[r])
l.sort()
triangles[r]=tuple(l)
r+=1
trianglesFinal=list(set(triangles))
for i in trianglesFinal:
print(number, i)
if len(trianglesFinal)==1:
count+=1
number+=2
print(count)
</code></pre>
<p>Please note that I am not looking for a different calculating method (I am sure there is one, but, for me, Project Euler is about finding your own methods. Using yours would, to me, be cheating). However, any faster functions, ways to combine blocks of code, simplified tests, or the like (such as not checking ever other number, but every xth number, etc) would be greatly appreciated!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T20:06:05.227",
"Id": "39364",
"Score": "0",
"body": "Probably not what you are looking for but in my opinion if you are worried about run time, then python is not the right language to use. It is hard to fine tune and optimize in general. It is design for rapid prototyping more then for efficient code."
}
] |
[
{
"body": "<p>For the record, this is <a href=\"http://projecteuler.net/index.php?section=problems&id=75\" rel=\"noreferrer\">Project Euler problem 75</a>.</p>\n\n<h3>1. Admonition</h3>\n\n<p>You write:</p>\n\n<blockquote>\n <p>Please note that I am not looking for a different calculating method (I am sure there is one, but, for me, Project Euler is about finding your own methods. Using yours would, to me, be cheating.) </p>\n</blockquote>\n\n<p><em>Abandon this attitude!</em> A key part of programming — just as important as coding — is developing a wide repertoire of algorithms and techniques that you can apply to problems you face. Although for your own intellectual satisfaction it's great to discover algorithms on your own, you should always go on to compare your solution to the best solutions discovered by others, so that you can improve your repertoire for the next problem.</p>\n\n<p>In particular, when you want to speed up a program, it's counterproductive to say, \"I don't want to implement a different algorithm, I just want to speed up the code I wrote\". The biggest speedups come from finding better algorithms.</p>\n\n<p>You say that your program \"runs fine\" but that doesn't seem to be true. Project Euler says:</p>\n\n<blockquote>\n <p>Each problem has been designed according to a \"one-minute rule\", which means that although it may take several hours to design a successful algorithm with more difficult problems, an efficient implementation will allow a solution to be obtained on a modestly powered computer in less than one minute.</p>\n</blockquote>\n\n<p>I tried running your program, but after ten minutes it still had not produced an answer (and my laptop was running hot), so I killed it.</p>\n\n<p>So in section 2 below I'll be using a smaller test size, 100,000 instead of 1,500,000, to keep the runtimes manageable.</p>\n\n<h3>2. Piecewise optimization</h3>\n\n<ol>\n<li><p>Your program is hard to test from the interactive interpreter because it has code at the top level. Better to put the main program inside a function so that you can call it from interpreter and then add an <a href=\"http://docs.python.org/2/library/__main__.html\" rel=\"noreferrer\"><code>if __name__ == '__main__':</code></a> section so that you can run it as a script if you want to.</p>\n\n<p>I've used the function name <code>problem75</code>, and it takes an argument, which is the largest value of the length of wire in the problem. Now:</p>\n\n<pre><code>>>> from timeit import timeit\n>>> timeit(lambda:problem75(10**5),number=1)\n12 (3, 4, 5)\n24 (6, 8, 10)\n30 (5, 12, 13)\n[... much output deleted ...]\n33.87288845295552\n</code></pre></li>\n<li><p>The <code>print</code> statement near the end of the main loop is unnecessary. This saves about 3 seconds, bringing the time down to 31.0 seconds.</p></li>\n<li><p>Your function <code>aFactors</code> makes an initial call to <code>isPrime</code>, taking \\$ O(\\sqrt n) \\$, in order to avoid a loop that also takes \\$ O(\\sqrt n) \\$. The test costs as much as it saves, so it's not worth it. Remove the call to <code>isPrime</code> and rewrite the function like like this:</p>\n\n<pre><code>def factors(n):\n \"\"\"Return the set of factors of n.\"\"\"\n result = set([1, n])\n add = result.add\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n add(i)\n add(n // i)\n return result\n</code></pre>\n\n<p>Here I've picked a better name for the function, written a docstring explaining what it does, and cached the value of <code>result.add</code> so that it does not need to be looked up each time arounnd the loop. This saves about 4 seconds; time now 27.7 seconds.</p></li>\n<li><p>Since the only thing you do with the set of factors is to turn it into pairs which you then iterate over, why not <em>generate</em> the pairs, like this:</p>\n\n<pre><code>def product_pairs(n):\n \"\"\"Generate pairs (i, j) such that i * j = n.\"\"\"\n yield 1, n\n yield n, 1\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n j = n // i\n yield i, j\n yield j, i\n</code></pre>\n\n<p>and then process them like this:</p>\n\n<pre><code>triangles = []\nappend = triangles.append\nfor i in product_pairs(number // 2):\n for j in product_pairs(i[0]):\n append((2*i[1]*i[0]-i[1]*i[1]*j[0],2*i[0]*i[1]-2*i[0]*j[1],2*i[0]*j[1]+i[1]*i[1]*j[0]-2*i[0]*i[1]))\n</code></pre>\n\n<p>This avoids having to construct an intermediate list in memory. This saves about 3 seconds; time now 24.3 seconds.</p></li>\n<li><p>Instead of writing <code>for i in product_pairs(...):</code> and then looking up <code>i[0]</code> and <code>i[1]</code>, split up the pair into two variables when you assign it in the loop, like this:</p>\n\n<pre><code>for i, j in product_pairs(number // 2):\n for k, l in product_pairs(i):\n append((2*j*i - j*j*k, 2*i*j - 2*i*l, 2*i*l + j*j*k - 2*i*j))\n</code></pre>\n\n<p>This avoids the sequence lookups. This saves about 3 seconds; time now 21.2 seconds.</p></li>\n<li><p>You construct a list of triangles, some of which have sides with negative or zero length. You then go through the list and <code>del</code> the triangles which are invalid. But <code>del</code> on a list is a potentially expensive operation: it has to copy the remainder of the list to keep it contiguous. See the <a href=\"http://wiki.python.org/moin/TimeComplexity\" rel=\"noreferrer\">TimeComplexity page</a> on the Python wiki for the cost of basic operations on Python's built-in data structures, where you can see that \"delete item\" operation on a list takes \\$O(n)\\$.</p>\n\n<p>So don't add these invalid triangles to the list in the first place. In fact, don't bother with the list at all, just construct the set of triangles directly:</p>\n\n<pre><code>triangles = set()\nadd = triangles.add\nfor i, j in product_pairs(number // 2):\n for k, l in product_pairs(i):\n triangle = 2*j*i - j*j*k, 2*i*j - 2*i*l, 2*i*l + j*j*k - 2*i*j\n if all(side > 0 for side in triangle):\n add(tuple(sorted(triangle)))\n</code></pre>\n\n<p>This saves about 6 seconds; time now 15.1 seconds.</p></li>\n<li><p>You can avoid some repeated multiplications by naming the various products of <code>i</code>, <code>j</code>, <code>k</code>, and <code>l</code>:</p>\n\n<pre><code>for i, j in product_pairs(number // 2):\n for k, l in product_pairs(i):\n p, q, r = 2 * j * i, j * j * k, 2 * i * l\n triangle = p - q, p - r, r + q - p\n if all(side > 0 for side in triangle):\n add(tuple(sorted(triangle)))\n</code></pre>\n\n<p>This saves about 1 second; time now 13.9 seconds.</p></li>\n</ol>\n\n<p>And I'm afraid that's as far as I got by applying piecewise speedups to your code. About 60% speedup in total. The revised program now gets the solution to the full Project Euler problem in about eight minutes on my laptop:</p>\n\n<pre><code>>>> timeit(lambda:main(1500000),number=1)\n[... solution deleted ...]\n467.3059961795807\n</code></pre>\n\n<p>Perhaps some other participant here can make more piecewise progress, but for dramatic speedups, you really need ...</p>\n\n<h3>3. A better algorithm</h3>\n\n<p>(Avert your eyes if you must.)</p>\n\n<p>The basic insight is that instead of iterating over the perimeter and finding the Pythagorean triples with that perimeter, we can iterate over all Pythagorean triples in some more convenient order, and keep count of how many triangles are found at each perimeter length.</p>\n\n<p>We can further speed things up by only <a href=\"http://en.wikipedia.org/wiki/Formulas_for_generating_Pythagorean_triples\" rel=\"noreferrer\">generating the primitive Pythagorean triples</a>, and then multiplying the primitive triples by successive numbers 1, 2, 3, ... to generate the remaining Pythagorean triples in the required range. In fact, we only need to multiply their perimeters.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple\" rel=\"noreferrer\">Euclid’s formula</a> can be used to generate all primitive Pythagorean triples. Given coprime positive integers \\$m\\$ and \\$n\\$, with \\$m > n\\$, and exactly one of \\$m\\$ and \\$n\\$ even, $$ \\eqalign{ a &= m^2 − n^2 \\\\ b &= 2mn \\\\ c &= m^2 + n^2} $$ is a primitive Pythagorean triple.</p>\n\n<p>The remaining subtlety is that Euclid’s formula doesn’t generate triples in order by length of the perimeter, so there needs to be some way to determine when to stop. My strategy in the code below is to iterate over ascending values of \\$m\\$. The perimeter of the triple is \\$a + b + c = 2m^2 + 2mn\\$, which is at least \\$2m(m + 1)\\$, since \\$n ≥ 1\\$. So \\$2m(m + 1)\\$ is a lower bound on the perimeter for which all triples have been generated so far. When this exceeds the limit, we can stop the search: there are no more triples to be found in the required range.</p>\n\n<pre><code>from collections import Counter\nfrom fractions import gcd\nfrom itertools import count\n\ndef coprime(m, n):\n \"\"\"Return True iff m and n are coprime.\"\"\"\n return gcd(m, n) == 1\n\ndef all_primitive_triples():\n \"\"\"Generate all primitive Pythagorean triples, together with a lower\n bound on the perimeter for which all triples have been generated\n so far.\n\n \"\"\"\n for m in count(1):\n for n in range(1, m):\n if (m + n) % 2 and coprime(m, n):\n a = m * m - n * n\n b = 2 * m * n\n yield a, b, m * m + n * n, 2 * m * (m + 1)\n\ndef problem75(limit=1500000):\n \"\"\"Return the number of values of L <= limit such that there is\n exactly one integer-sided right-angled triangle with perimeter\n L.\n\n \"\"\"\n triangles = Counter()\n for a, b, c, q in all_primitive_triples():\n if q > limit:\n break\n p = a + b + c\n for i in range(p, limit + 1, p):\n triangles[i] += 1\n return sum(n == 1 for n in triangles.values())\n</code></pre>\n\n<p>This solves the Project Euler problem in a more reasonable amount of time:</p>\n\n<pre><code>>>> timeit(problem75, number=1)\n2.164217948913574\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T22:58:30.753",
"Id": "39373",
"Score": "3",
"body": "On the subject of more piecewise progress, the double for-loop to split a number into 3 factors can be replaced with a method which returns product triples. I got a further 30% speedup (from 9 secs to 6 secs) this way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T23:27:24.317",
"Id": "39374",
"Score": "0",
"body": "Pure awesomeness, codereview really needs a +2"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T00:33:28.770",
"Id": "39378",
"Score": "4",
"body": "Half tempted to edit this post and add all manner of bolding to **The biggest speedups come from finding better algorithms.**"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T14:31:37.887",
"Id": "72288",
"Score": "0",
"body": "I found the [linear algebra approach](https://en.wikipedia.org/wiki/Tree_of_primitive_Pythagorean_triples) to generateing all primative pythagorean tripples more intuitive."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T14:35:11.533",
"Id": "72289",
"Score": "0",
"body": "@awashburn: With the linear algebra approach, it's not so easy to see how to bound the perimeter for which all triples have been generated so far, which is a crucial part of solving this problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T00:56:51.203",
"Id": "72416",
"Score": "0",
"body": "@GarethRees I generated them recursively in a trinary-tree, only expanding a branch when the perimeter was below the bound. The recursive approach translates well into functional languages."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T20:55:49.747",
"Id": "25396",
"ParentId": "25388",
"Score": "51"
}
},
{
"body": "<p>It is not necessary to construct all the triangles to find out if there is exactly one: you can stop when you've found two.</p>\n\n<p>Some little things to clean up the code that should give a minor speedup too:</p>\n\n<p>Instead of indexing <code>(triangles[r][i]<=0 for i in range(len(triangles[r])))</code>, iterate directly:</p>\n\n<pre><code>(x <= 0 for x in triangles[r])\n</code></pre>\n\n<hr>\n\n<p><code>reduce(list.__add__, ...</code> looks ugly to me and creates some intermediate lists you can avoid by:</p>\n\n<pre><code>(j for i in range(1,int(math.sqrt(n))+1) if n%i==0 for j in (i,n//i))\n</code></pre>\n\n<hr>\n\n<p>Instead of the outer <code>while</code> loop you can use:</p>\n\n<pre><code>for number in range(12, 1500001, 2): \n</code></pre>\n\n<p>(This is for Python 3, in Python 2 <code>xrange</code> should be used)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T08:36:49.867",
"Id": "39392",
"Score": "0",
"body": "I tried out the \"stop when you've found two triangles\" approach, but found that it actually made things slower. (The test doesn't succeed often enough to pay for its own cost.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T09:27:16.790",
"Id": "39397",
"Score": "0",
"body": "@GarethRees Is this in reference to your best effort? I get almost 40 % time reduction using this trick, when my starting point is the OP's code plus an optimization similar to your number 6."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T06:50:15.760",
"Id": "25407",
"ParentId": "25388",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T18:12:36.453",
"Id": "25388",
"Score": "25",
"Tags": [
"python",
"performance",
"programming-challenge",
"computational-geometry"
],
"Title": "Speed up solution to Project Euler problem 75"
}
|
25388
|
<p>Say, there is a class with some methods, that have <code>try catch</code> blocks. I need to accumulate messages from all inner exceptions of generated exception and use <code>throw new Exception(exceptionMessages)</code>. <br />
I came up with two possible solutions:</p>
<ol>
<li>Create a private method, concatenate inner exception messages, return a <code>string</code> and raise an exception in a caller method. (<code>SomeMethod1</code> below);</li>
<li>Create a private method, concatenate inner exception messages and raise exception inside it. (<code>SomeMethod2</code> below);</li>
</ol>
<p><strong>Code snippet</strong>:</p>
<pre><code>class SomeClass
{
private void _raiseException(Exception ex)
{
var exceptionMessages = new StringBuilder();
do
{
exceptionMessages.Append(ex.Message);
ex = ex.InnerException;
}
while (ex != null);
throw new Exception(exceptionMessages.ToString());
}
private string _getInnerExceptions(Exception ex)
{
var exceptionMessages = new StringBuilder();
do
{
exceptionMessages.Append(ex.Message);
ex = ex.InnerException;
}
while (ex != null);
return exceptionMessages.ToString();
}
public void SomeMethod1()
{
try
{
//some code to try
}
catch (Exception e)
{
throw new Exception(this._getInnerExceptions(e));
}
}
public void SomeMethod2()
{
try
{
//some code to try
}
catch (Exception e)
{
this._raiseException(e);
}
}
}
</code></pre>
<p>Which one of them would be better, or is there another way of doing it, or maybe this approach is not good at all?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T20:37:49.333",
"Id": "39365",
"Score": "0",
"body": "Both approaches are the same but I would preferred 1st one (SomeMethod1()) - it's more clear that you are rethrowing exception and not just swallowing it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T20:40:03.957",
"Id": "39366",
"Score": "3",
"body": "Why don't you use `AggregateException` instead?"
}
] |
[
{
"body": "<h2>Svick is right</h2>\n\n<p>Use the AggregateException class to collect all exceptions you need. With AggregateException everyone can prepare it's own code to handle the multiple exception situation but with your original solution they have to handle a huge string in a stock exception class. How can be this usefull?</p>\n\n<h2>Storing exception.Message</h2>\n\n<p>It's bad. If you store only the exceptions' messages you will loose a lot of information and the types of the exceptions. How would you handle an exception if only the Message is what you have? Parsing it? And we havent talked about the specific properties of specific exceptions like some validation exception which can contain the unvalid property name and value for an object.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T08:37:41.637",
"Id": "39393",
"Score": "0",
"body": "Thanks for pointed that out, I'm implementing the `AggregateException` then."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T05:23:44.400",
"Id": "25404",
"ParentId": "25391",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "25404",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T19:14:55.710",
"Id": "25391",
"Score": "4",
"Tags": [
"c#",
"exception-handling",
"exception"
],
"Title": "Accumulating inner exception messages"
}
|
25391
|
<p>I need to fast fill a memory block in C#, so I wrote something like this (in Free Pascal Compiler + Lazarus in 64 bit mode):</p>
<pre><code>// ECX = Ptr64
// EDX = Count
// R8 = Value
PROCEDURE Fill64 (VAR Ptr64; Count: QWord; Value: QWord);
BEGIN
ASM
PUSH RDI
MOV RDI, RCX // Destination Index = Ptr64
MOV RAX, R8 // Accumulator = Value
MOV RCX, RDX // Counter Register = Count
TEST RCX, RCX // If RCX is 0, set ZF (zero flag)
JZ @Exit // Exit if ZF is set
REP STOSQ // Fill memory using 64 bit value from RAX register
@Exit:
POP RDI
END;
END;
</code></pre>
<p>And I use it from C#: </p>
<pre><code>[DllImport ("MemUtil64.dll", EntryPoint = "Fill64", CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe void Fill64 (void* ptr, ulong count, ulong value);
</code></pre>
<p>If this code okay, and fastest possible?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T22:09:12.217",
"Id": "39371",
"Score": "2",
"body": "have you tested it against other possible implementations for speed?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T09:32:47.330",
"Id": "39402",
"Score": "4",
"body": "The code is okay if unsafe is okay for you. You should understand that there is a possible vulnerability. Regarding performance, I see your question on SO (http://stackoverflow.com/questions/16178211/filling-memory-using-specified-value-performance), it has a good link in comments. Probably SSE would be faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T00:15:28.603",
"Id": "39475",
"Score": "0",
"body": "@Jean-Bernard: Speed is OK, and its around 3GB/s when AIDA64 tells I have 5,5GB/s memory. It can be faster, but need SSE and advanced cache/tlb optimizations which I cannot understand. Comparing to pure C#, its 50% faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T00:18:09.567",
"Id": "39476",
"Score": "0",
"body": "@Kefir: Yes, I will delete this stack overflow duplicate."
}
] |
[
{
"body": "<p>Unfortunately the answer is CPU-dependent. For example <a href=\"https://android.googlesource.com/kernel/omap/+/038b0a6d8d32db934bba6a24e74e76e4e327a94f/arch/x86_64/lib/memset.S\">here</a> is Android's memset implementation: it uses <code>rep stosq</code> for some CPUs and a different more complicated implementation (avoiding <code>rep stosq</code>) for others.</p>\n\n<p>For further details, on Intel CPUs, refer to the \"Enhanced REP MOVSB and STOSB operation (ERMSB)\" section of the <a href=\"http://www.intel.com/content/dam/doc/manual/64-ia-32-architectures-optimization-manual.pdf\">Intel® 64 and IA-32\nArchitectures\nOptimization Reference Manual</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-03T12:10:48.583",
"Id": "74710",
"Score": "0",
"body": "Thanks. Rep Stosq is enough fast for me. Gives me 60% of mem bandwidth on my cpu. That optimization guide anyway is very useful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-01T23:42:14.693",
"Id": "43178",
"ParentId": "25393",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "43178",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-04-23T19:35:36.323",
"Id": "25393",
"Score": "7",
"Tags": [
"c#",
"assembly",
"delphi"
],
"Title": "Fastest fill memory with specified 64-bit value"
}
|
25393
|
<p>I'm currently following the tutorials over at <a href="http://www.rubymonk.org" rel="noreferrer">RubyMonk</a>, and one of the problems I need to solve is to write a <code>subtract</code> function that would meet these conditions:</p>
<blockquote>
<ul>
<li>invoking <code>subtract(4, 5)</code> should return <code>-1</code> </li>
<li>invoking <code>subtract(-10, 2, 3)</code> should return <code>-15</code> </li>
<li>invoking <code>subtract(0, 0, 0, 0, -10)</code> should return <code>10</code> </li>
</ul>
</blockquote>
<p>Coming from a traditional imperative programming background (C, Lua, Java, etc.), my first attempt would have been something like this:</p>
<pre><code>def subtract *numbers
start = numbers[0]
tail = numbers.drop(1)
for i in tail do
start -= i
end
return start
end
</code></pre>
<p>But, this just felt wrong in Ruby, and I don't doubt that it is. Trying to use a more Ruby-esque style, I thought it would be better to use some of <code>Array</code>'s methods.</p>
<p>Here is my latest version: </p>
<pre><code>def subtract *numbers
(numbers.drop 1).inject(numbers[0]) { |x, y| x-y}
end
</code></pre>
<p>One thing to note is that this is essentially the same thing as above, I just moved most of the looping into <code>Array#inject</code>. To me, simply moving logic isn't a new style per se, and so conceptually this is nothing new to me.</p>
<p>Therefore my questions are:</p>
<ul>
<li>Is this true Ruby style? If not, how could I make it so, and how would that new style differ from the current?</li>
<li>Is there any way to improve readability? ('Cause honestly the current version lacks quite a bit).</li>
</ul>
|
[] |
[
{
"body": "<p>Some notes:</p>\n\n<ul>\n<li><p><code>def subtract *numbers</code>: While Ruby allows to omit parens, the community consensus is that it makes signatures harder to read. </p></li>\n<li><p><code>(numbers.drop 1)</code>: When you have to write parens like this, it's a signal that you should just write them in the method call. It looks like Scala or Haskell, not Ruby.</p></li>\n<li><p>As @Nakilon pointed out, you can drop the <code>drop</code>/<code>first</code>, a fold without an initial value takes the first one.</p></li>\n<li><p>The identity value for subtraction is <code>0</code>, let's use it for empty inputs.</p></li>\n<li><p><code>xs.inject(initial) { |acc, x| acc.method(x) }</code> -> <code>xs.inject(initial, :method)</code></p></li>\n</ul>\n\n<p>We can now write:</p>\n\n<pre><code>def subtract(*numbers)\n numbers.inject(0, :-)\nend\n</code></pre>\n\n<blockquote>\n <p>For me, simply moving logic isn't a new style per se, and so conceptually this is nothing new to me.</p>\n</blockquote>\n\n<p>I don't agree. The steps followed are conceptually the same, yes, but the use of a widely known generic abstraction like <code>reduce</code>/<code>inject</code> has reduced the overall complexity. Of course, one abstraction does not make much difference, but dozens of them change the way a whole program describes what it's doing. And that's what programing is about: building abstractions to reduce complexity. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T23:57:45.473",
"Id": "39377",
"Score": "0",
"body": "Okay thank you for the guidance. :) I agree that abstraction is key. I just felt that perhaps Ruby had a more awesome, totally new, nothing a C programmer could of thought up way of doing it. :P \n\n_P.S. I actually wanted my Ruby to look like Haskell, but okay, whatever...*shrugs* haha_"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T09:38:28.220",
"Id": "39403",
"Score": "0",
"body": "@Miguel. In fact we can write `numbers.inject(0, :-)` as Nakilon suggested. In any case, nothing special about Ruby on this regard, that can be done in any language that supports basic functional programming."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T20:54:00.270",
"Id": "25395",
"ParentId": "25394",
"Score": "4"
}
},
{
"body": "<p>I don't understand, why do you need <code>.first</code> and <code>.drop</code>:</p>\n\n<pre><code>def subtract(*numbers)\n numbers.inject{ |acc, x| acc - x }\nend\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>def subtract(*numbers)\n numbers.inject :-\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T07:27:39.843",
"Id": "25411",
"ParentId": "25394",
"Score": "3"
}
},
{
"body": "<p>They are NOT the same:<br>\nOriginal: \"invoking subtract(4, 5) should return -1\"</p>\n\n<pre><code>def subtract(*numbers)\n numbers.inject :-\nend\nsubtract(4,5) -> -9\n</code></pre>\n\n<p>How do we get the correct result with nice Ruby code?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-16T10:29:34.760",
"Id": "369069",
"Score": "1",
"body": "Are you answering or asking? This space is reserved for answering only."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-16T10:10:21.053",
"Id": "192184",
"ParentId": "25394",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "25395",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T19:50:34.913",
"Id": "25394",
"Score": "6",
"Tags": [
"ruby"
],
"Title": "Subtraction accumulator"
}
|
25394
|
<p>The following code I devised to compute a <a href="http://en.wikipedia.org/wiki/Determinant" rel="nofollow">determinant</a>:</p>
<pre><code>module MatrixOps where
determinant :: (Num a, Fractional a) => [[a]] -> a
determinant [[x]] = x
determinant mat =
sum [s*x*(determinant (getRest i mat)) | i <- [0..n-1], let x = (head mat) !! i
s = (-1)^i]
where n = length $ head mat
getRest :: (Num a, Fractional a) => Int -> [[a]] -> [[a]]
getRest i mat = removeCols i (tail mat)
removeCols :: (Num a, Fractional a) => Int -> [[a]] -> [[a]]
removeCols _ [] = []
removeCols i (r:rs) = [r !! j | j <- [0..n-1], j /= i] : removeCols i rs
where n = length r
</code></pre>
<p>I have a few general questions about the style of my code and practices:</p>
<ul>
<li><p>Is a very "Haskell" solution? I come from an OOP background and I am still learning functional programming.</p></li>
<li><p>Is there a better way to space this out? I feel like some of the code is not very readable (this may just be because I am new), especially the definition of <code>determinant mat = ...</code></p></li>
<li><p>Is this code considerably "clean?"</p></li>
</ul>
|
[] |
[
{
"body": "<p>Just a few thoughts:</p>\n\n<ul>\n<li>Your method (IIUC) is conceptually correct, but has computation complexity <em>O(n!)</em> where <em>n</em> is the dimension of a given matrix. If you need better complexity (polynomial in <em>n</em>), you have to use another solution, such as using PLU decomposition described <a href=\"http://en.wikipedia.org/wiki/Determinant#Calculation\" rel=\"nofollow\">here</a>.</li>\n<li><p>Be aware that since Haskell lists are essentially linked lists, getting <em>i</em>-th element using <code>(!!)</code> takes <em>O(i)</em>. So your code</p>\n\n<pre><code>[r !! j | j <- [0..n-1], j /= i] \n</code></pre>\n\n<p>has <em>O(n<sup>2</sup>)</em> complexity. You could express it in <em>O(n)</em> for example using <a href=\"http://www.haskell.org/ghc/docs/latest/html/libraries/base/Data-List.html#v%3asplitAt\" rel=\"nofollow\"><code>splitAs</code></a> as</p>\n\n<pre><code>let (left, right) = splitAt i r\n in left ++ (tail right)\n</code></pre>\n\n<p>The same applies for <code>i <- [0..n-1], let x = (head mat) !! i</code>. You could do something like</p>\n\n<pre><code>(i, x) <- zip [0..] (head mat)\n</code></pre>\n\n<p>instead.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T12:13:54.053",
"Id": "41151",
"Score": "0",
"body": "@mjgpy3 to add the oscillating sign there, `(i, sx) <- zip [0..] (zipWith (*) (cycle [1,-1]) $ head mat)` can be used. Or `(zipWith ($) (cycle [id, negate]) ...)`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T05:31:08.097",
"Id": "25405",
"ParentId": "25397",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "25405",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T23:20:18.513",
"Id": "25397",
"Score": "2",
"Tags": [
"haskell",
"functional-programming",
"recursion"
],
"Title": "Recursive Determinant"
}
|
25397
|
<p>Below is the basic shell of an application I am working on that is part of a Webhosting Control Panel. This part is for the DNS records management.</p>
<p>So in my code below, I have taken away all the main functionality as it's not relevant to my question and to make it less cluttered.</p>
<p>On the page I have between 12-15 JavaScript <code>Events</code> ranging from <code>click events</code> to <code>keypress event</code> to <code>keydown events</code> etc...</p>
<p>Right now I have these main functions...</p>
<pre><code>dnsRecords.init()
dnsRecords.events.init()
dnsRecords.records.addRow(row)
dnsRecords.records.save()
dnsRecords.records.undoRow(row)
dnsRecords.records.deleteRow(row)
</code></pre>
<p>I have put all my <code>Events</code> into <code>dnsRecords.events.init()</code>. So each <code>Event</code> basically calls or passes Data to the <code>dnsRecords.records</code> functions.</p>
<p>Since I am new to JavaScript I am wanting to know if there is anything really wrong with this method or is there is a better location or way to put all those different Events?</p>
<p>Is it generally a good idea or not to put all my <code>Events</code> into 1 area like that and then have the fire of other functions instead of cluttering there callback area with logic code?</p>
<p>Also note, I am not looking to use Backbone or some other Framework at this time, just want to know a good way to structure a small single page application like this. Thank you. </p>
<pre><code>var dnsRecords = {
unsavedChanges : false,
init: function() {
dnsRecords.events.init();
},
events: {
init: function() {
// If user trys to leave the page with UN-SAVED changes, we will Alert them to...
$(window).on('beforeunload',dnsRecords.events.promptBeforeClose);
$(document).on('keypress','#typeMX div.hostName > input',function() {
$(document).off('keypress','#typeMX div.hostName > input');
});
// Activate SAVE and UNDO Buttons when Record Row EDITED
$(document).on("keydown", "#dnsRecords input" ,function() {
});
// Add new Record Row
$("#dnsRecords div.add > .btn").click(function(e) {
e.preventDefault();
});
// Mark Record as "Deleted" and change the view of it's Row to reflect a Deleted item
$(document).on("click", ".delete" ,function(e) {
dnsRecords.records.deleteRow($(this));
e.preventDefault();
});
// Show Undo button when editing an EXISTING ROW
$(document).on("keydown","div.dnsRecord input[type='text']",function() {
});
// Undo editing of an EXISTING ROW
$("button.undo").on("click",function() {
dnsRecords.records.undoRow($(this));
});
//Save Changes
$("#dnsTitle a.save").click(function() {
zPanel.loader.showLoader();
});
//Undo ALL Record Type Changes
$("#dnsTitle a.undo").click(function() {
});
$("form").submit(function() {
});
},
},
records: {
addRow: function(record) {
// All the code to Add a record here
},
save: function() {
// All the code to Save a record here
},
undoRow: function(row) {
// All the code to Undo a record here
},
deleteRow: function(row) {
// All the code to Delete a record here
dnsRecords.unsavedChanges = true;
},
}
};
$(function(){
dnsRecords.init();
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T05:26:22.343",
"Id": "39387",
"Score": "0",
"body": "Is this code standalone? or are there other parts of your application using this `dnsRecords` stuff? which parts?"
}
] |
[
{
"body": "<p>What you are doing seems pretty much the standard way to do this sort of thing with Javascript and jQuery . </p>\n\n<p>A few pointers:</p>\n\n<p>Often, you wrap functions with other anonymous functions, for example:</p>\n\n<pre><code>$(\"#dnsTitle a.save\").click(function() {\n zPanel.loader.showLoader();\n});\n</code></pre>\n\n<p>Could likely become:</p>\n\n<pre><code>$(\"#dnsTitle a.save\").click(zPanel.loader.showLoader)\n</code></pre>\n\n<p>Speaking of which, every time you have an anonymous function that handles considerable amount of code, you should consider extracting it to a named method.</p>\n\n<blockquote>\n <p>Is it generally a good idea or not to put all my Events into 1 area like that and then have the fire of other functions instead of cluttering there callback area with logic code?</p>\n</blockquote>\n\n<p>Yes, it is. Generally your event listeners when writing this sort of code 'control' the flow of events. That area (like in your code) is in charge of negotiating between your data and user/presentation, letting the logic layer know when the change happened. It is generally cleaner to register all such handlers in a specific place.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T04:45:49.930",
"Id": "39385",
"Score": "0",
"body": "sounds like some good valid advice, thank you"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T02:55:23.037",
"Id": "25399",
"ParentId": "25398",
"Score": "3"
}
},
{
"body": "<p>General tips:</p>\n\n<ul>\n<li><p>Use semi-colons. In JS, although they are optional, you should use them to avoid syntax errors, especially when minifying.</p></li>\n<li><p>To modularize your code, wrap them in a closure. Consider it your \"sandbox\" for your code.</p></li>\n</ul>\n\n<p>As for the rest, it's in the comments</p>\n\n<pre><code>//enclosing it in a closure so we won't spill to the global scope\n//a general tip I keep is that \n//if this module performs something only it should do, then keep it in the scope (private)\n//everything that others can use (public) gets exposed via the namespace\n(function (window, document, $, undefined) {\n\n //we cache a few useful values, like jQuery wrapped window and document\n var $window = $(window),\n $document = $(document),\n\n //here's an example of exposing. we expose this object as dnsRecords\n //to the global scope. Since assignment operations \"spill left\"\n //the same object gets assigned to the local dnsRecord\n //we do this since every access to a property (something dot something)\n //is an overhead. also, assigning to a variable is shorter anyway.\n dnsRecords = window.dnsRecords = {\n unsavedChanges: false\n addRow: function (record) {},\n save: function () {},\n undoRow: function (row) {},\n deleteRow: function (row) {\n dnsRecords.unsavedChanges = true;\n }\n };\n\n //here, we declare your init methods\n //like stated above, since only this module uses init, it's kept in the scope\n //rather than it being exposed\n function bindDom() {\n\n //we then use the cached values\n $window.on('beforeunload', dnsRecords.promptBeforeClose);\n\n //did you know that the on method returns the object it operated on\n //which means it returns $document, which also means we can chain on\n //also, I suggest you delegate to the nearest available parent\n //for shorter delegation. In this code you have, the event needs\n //to \"bubble\" to the document root in order for handlers to execute\n //which is also an overhead, and the same reason live was deprecated\n\n $document\n .on('keypress', '#typeMX div.hostName > input', function () {\n $document.off('keypress', '#typeMX div.hostName > input');\n })\n .on(\"keydown\", \"#dnsRecords input\", function () {\n\n })\n .on(\"click\", \".delete\", function (e) {\n dnsRecords.deleteRow($(this));\n e.preventDefault();\n })\n .on(\"keydown\", \"div.dnsRecord input[type='text']\", function () {\n\n });\n\n $(\"#dnsRecords div.add > .btn\").click(function (e) {\n e.preventDefault();\n });\n\n $(\"button.undo\").on(\"click\", function () {\n dnsRecords.undoRow($(this))\n });\n\n $(\"#dnsTitle a.save\").click(function () {\n zPanel.loader.showLoader();\n });\n\n $(\"#dnsTitle a.undo\").click(function () {});\n\n $(\"form\").submit(function () {});\n }\n\n //you can declare other functions here as well to split operations\n function someOtherInitStuff(){\n ...\n }\n\n //I notice your init function is called on documentReady\n //why not merge it in the module, and make that function your init\n $(function () {\n\n //call stuff you want to init\n bindDom();\n someOtherInitStuff();\n });\n\n}(this, document, jQuery));\n\n//out here, your exposed methods are like:\ndnsRecords.addRow();\ndnsRecords.save();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T07:23:57.757",
"Id": "39390",
"Score": "0",
"body": "Thanks for the demo, I have been reading more about thios style of \"modules\" today. As far as this particular code, it does not need to be accessed anywhere else and all my functions are called from the different Events on the page, so possibly everything could be private? I was looking at some of your other posts to, good stuff"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T07:27:32.710",
"Id": "39391",
"Score": "0",
"body": "@jasondavis Yup, you can keep everything in the module. You can turn `unsavedChanges` into a local variable, and discard the `window.dnsRecords`. That way, `dnsRecords` is a collection of operations that is only accessible from the inside."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T07:03:12.687",
"Id": "25409",
"ParentId": "25398",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "25409",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T02:32:17.920",
"Id": "25398",
"Score": "-2",
"Tags": [
"javascript"
],
"Title": "Structuring Events in JavaScript"
}
|
25398
|
<p>Inspired by xkcd and a couple of praising blog posts, I decided to try out Lisp. It seemed that the best-supported dialect was Racket, itself a variant of Scheme, so I went with that and wrote an infix mathematical expression parser to get familiar with the basic concepts.</p>
<p>That was a mind-bending experience considering I never did functional programming. Not having mutable variables (or not using them, anyways) and having to use recursion instead of loops was a little hard for my imperative mind.</p>
<p>Anyways, I came up with this. My goal was to parse infix mathematical expressions with correct precedence and parentheses. It supports additions, subtractions, multiplications and divisions. It works, but it's probably full of hints that I'm new at this, and I would like to know which parts could have been made more idiomatic.</p>
<pre class="lang-lisp prettyprint-override"><code>#lang racket
;; usage: (reduce (tokenize))
;; tokenizing function
(define (tokenize)
(define (-tokenize-operator first)
(cond
([equal? first #\+] (list + (read-char)))
([equal? first #\-] (list - (read-char)))
([equal? first #\*] (list * (read-char)))
([equal? first #\/] (list / (read-char)))))
(define (-tokenize-number first)
(define (--char->number char)
(let ([ascii-zero (char->integer #\0)])
(- (char->integer char) ascii-zero)))
(define (--read-number initial)
(let ([char (read-char)])
(if (char-numeric? char)
(--read-number (+ (--char->number char) (* initial 10)))
(list initial char))))
(if (char-numeric? first)
(--read-number (--char->number first))
'()))
(define (-tokenize-openparen first)
(if (equal? first #\()
(list #\( (read-char))
'()))
(define (-tokenize first endchar)
(if (equal? first endchar)
'()
(let ([operator (-tokenize-operator first)]
[number (-tokenize-number first)]
[openparen (-tokenize-openparen first)])
(cond
([pair? operator] (cons (car operator) (-tokenize (cadr operator) endchar)))
([pair? number] (cons (car number) (-tokenize (cadr number) endchar)))
([pair? openparen] (list (-tokenize (cadr openparen) #\))))
(else (tokenize))))))
(let ([first (read-char)])
(-tokenize first #\newline)))
;; parsing and evaluation function
(define (reduce tokens)
(define (-operator-priority op)
(cond
([ormap (lambda (p) (equal? p op)) (list + -)] 1)
([ormap (lambda (p) (equal? p op)) (list * /)] 2)))
(define (-rvalue list max-priority)
(define (--lower-parentheses parenthesed-expression next-tokens)
(let ([paren-result (car (-rvalue parenthesed-expression 0))])
(-rvalue (cons paren-result next-tokens) max-priority)))
(define (--reduce-rvalue lvalue next-tokens)
(let* ([operator (car next-tokens)]
[priority (-operator-priority operator)]
[then (cdr next-tokens)])
(if (> priority max-priority)
(let* ([rvalue (-rvalue then priority)]
[value (operator lvalue (car rvalue))])
(-rvalue (cons value (cdr rvalue)) max-priority))
list)))
(let ([lvalue (car list)]
[next-tokens (cdr list)])
(if (pair? lvalue)
(--lower-parentheses lvalue next-tokens)
(if (pair? next-tokens)
(--reduce-rvalue lvalue next-tokens)
list))))
(car (-rvalue tokens 0)))
</code></pre>
<p>Thanks!</p>
|
[] |
[
{
"body": "<p>Here are my review comments on the tokeniser:</p>\n\n<ol>\n<li><p>It's unusual to prefix symbols with <code>-</code>. The indentation should be enough to tell you the \"nesting level\" of the inner functions, without having to put <code>-</code>s in front.</p></li>\n<li><p>Your inner <code>-tokenize</code> could be hoisted into a named <code>let</code>, so that your <code>tokenize</code> function looked like this (I will make other changes to the function later, but for now I try to keep as close to your original code as possible):</p>\n\n<pre><code>(define (tokenize)\n ;; other internal definitions\n\n (let recur ([first (read-char)]\n [endchar #\\newline])\n (if (equal? first endchar)\n '()\n (let ([operator (-tokenize-operator first)]\n [number (-tokenize-number first)]\n [openparen (-tokenize-openparen first)])\n (cond\n ([pair? operator] (cons (car operator) (recur (cadr operator) endchar)))\n ([pair? number] (cons (car number) (recur (cadr number) endchar)))\n ([pair? openparen] (list (recur (cadr openparen) #\\))))\n (else (recur (read-char) #\\newline)))))))\n</code></pre></li>\n<li><p>Character comparisons can use <code>eqv?</code> instead of <code>equal?</code>. Not really a biggie, but usually I reserve <code>equal?</code> for deep comparisons.</p></li>\n<li><p>Use <code>#f</code> for false/null values, not <code>'()</code>. In Scheme, <code>#f</code> is the only false value there is; <code>'()</code> is a true value (like everything else). Though, instead of all those different tokenising helpers, and calling them all and then only using one of the return values, it would be nicer to test directly in the <code>cond</code>.</p></li>\n<li><p>Instead of all the repeated <code>(read-char)</code>s, you might consider using a port stream instead. Create one using <code>sequence->stream</code>, then you can call <code>stream-first</code> and <code>stream-rest</code> on it.</p></li>\n</ol>\n\n<p>With all that in mind, I'd write the tokeniser like so:</p>\n\n<pre><code>(define (tokenize [port (current-input-port)])\n (let recur ([str (sequence->stream (in-input-port-chars port))])\n (cond [(stream-empty? str) '()]\n [(char-numeric? (stream-first str))\n (let loop [(str str)\n (digits '())]\n (if (and (not (stream-empty? str))\n (char-numeric? (stream-first str)))\n (loop (stream-rest str) (cons (stream-first str) digits))\n (cons (string->number (list->string (reverse digits)))\n (recur str))))]\n [(char-whitespace? (stream-first str))\n (recur (stream-rest str))]\n [else (cons (stream-first str) (recur (stream-rest str)))])))\n</code></pre>\n\n<p>(Comments on the evaluator to come later.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T06:06:02.970",
"Id": "25406",
"ParentId": "25400",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "25406",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T03:05:21.077",
"Id": "25400",
"Score": "3",
"Tags": [
"lisp",
"scheme",
"racket"
],
"Title": "Scheme/Racket: idiomatic infix math evaluator"
}
|
25400
|
<p>Database schema: describes the structure of the information within a database system. The schema is formalized using integrity constraints, which may be expressed as a series of sentences to describe the data, structure of the database and properties of the database. The database schema provides the blue print for future modifications (CRUD, changes in data model etc.).</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T04:19:24.727",
"Id": "25401",
"Score": "0",
"Tags": null,
"Title": null
}
|
25401
|
<p>I have the following contact form included with my wordpress theme as a template.</p>
<p>Now a user on Stackoverflow pointed out that this form has some serious security vulnerabilities.</p>
<p>Could someone please point them out and tell me where I can improve</p>
<p>Form:</p>
<pre><code><?php
/*
* Template Name: Contact Form Page
*/
if(isset($_POST['submitted'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactName']) === '') {
$nameError = __("You forgot to enter your name.", "site5framework");
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) === '') {
$emailError = __("You forgot to enter your email address.", "site5framework");
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$emailError = __("You entered an invalid email address.", "site5framework");
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['comments']) === '') {
$commentError = __("You forgot to enter your comments.", "site5framework");
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['comments']));
} else {
$comments = trim($_POST['comments']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$msg .= "------------User Info------------ \r\n"; //Title
$msg .= "User IP: ".$_SERVER["REMOTE_ADDR"]."\r\n"; //Sender's IP
$msg .= "Browser Info: ".$_SERVER["HTTP_USER_AGENT"]."\r\n"; //User agent
$msg .= "Referrer: ".$_SERVER["HTTP_REFERER"]; //Referrer
$emailTo = ''.of_get_option('sc_contact_email').'';
$subject = 'Contact Form Submission From '.$name;
$body = "Name: $name \n\nEmail: $email \n\nMessage: $comments \n\n $msg";
$headers = 'From: '.$name.' <'.$email.'>' . "\r\n" . 'Reply-To: ' . $email;
if(mail($emailTo, $subject, $body, $headers)) $emailSent = true;
}
}
get_header();
?>
<div id="content" class="container clearfix">
<!-- page header -->
<div class="container clearfix ">
<?php if(of_get_option('sc_contact_map') != '') { ?>
<!-- contact map -->
<div id="contact-map">
<?php echo of_get_option('sc_contact_map') ?>
</div>
<!-- end contact map -->
<?php } else if(of_get_option('sc_showpageheader') == '1' && get_post_meta($post->ID, 'snbpd_ph_disabled', true) != 'on' ) : ?>
<?php if(get_post_meta($post->ID, 'snbpd_phitemlink', true)!= '') : ?>
<?php
$thumbId = get_image_id_by_link ( get_post_meta($post->ID, 'snbpd_phitemlink', true) );
$thumb = wp_get_attachment_image_src($thumbId, 'page-header', false);
?>
<img class="intro-img" alt=" " src="<?php echo $thumb[0] ?>" alt="<?php the_title(); ?>" />
<?php elseif (of_get_option('sc_pageheaderurl') !='' ): ?>
<?php
$thumbId = get_image_id_by_link ( of_get_option('sc_pageheaderurl') );
$thumb = wp_get_attachment_image_src($thumbId, 'page-header', false);
?>
<img class="intro-img" alt=" " src="<?php echo $thumb[0] ?>" alt="<?php the_title(); ?>" />
<?php else: ?>
<img class="intro-img" alt=" " src="<?php echo get_template_directory_uri(); ?>/library/images/inner-page-bg.jpg" />
<?php endif ?>
<?php endif ?>
</div>
<!-- content -->
<div class="container">
<h1><?php the_title(); ?> <?php if ( !get_post_meta($post->ID, 'snbpd_pagedesc', true)== '') { ?>/<?php }?> <span><?php echo get_post_meta($post->ID, 'snbpd_pagedesc', true); ?></span></h1>
<article id="post-<?php the_ID(); ?>" <?php post_class('clearfix'); ?> role="article">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div class="page-body clearfix">
<?php the_content(); ?>
</div>
<div class="one-third">
<div class="caddress"><strong><?php _e('Address:', 'site5framework') ?></strong> <?php echo of_get_option('sc_contact_address') ?></div>
<div class="cphone"><strong><?php _e('Phone:', 'site5framework') ?></strong> <?php echo of_get_option('sc_contact_phone') ?></div>
<div class="cphone"><strong><?php _e('Fax:', 'site5framework') ?></strong> <?php echo of_get_option('sc_contact_fax') ?></div>
<div class="cemail"><strong><?php _e('E-mail:', 'site5framework') ?></strong> <a href="mailto:<?php echo of_get_option('sc_contact_email') ?>"><?php echo of_get_option('sc_contact_email') ?></a></div>
</div>
<div class="two-third last">
<div id="messages">
<p class="simple-error error" <?php if($hasError != '') echo 'style="display:block;"'; ?>><?php _e('There was an error submitting the form.', 'site5framework'); ?></p>
<p class="simple-success thanks"><?php _e('<strong>Thanks!</strong> Your email was successfully sent. We should be in touch soon.', 'site5framework'); ?></p>
</div>
<form id="contactForm" method="POST">
<div class="one-third">
<label for="nameinput"><?php _e("Your name", "site5framework"); ?></label>
<input type="text" id="nameinput" name="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="requiredField"/>
<span class="error" <?php if($nameError != '') echo 'style="display:block;"'; ?>><?php _e("You forgot to enter your name.", "site5framework");?></span>
</div>
<div class="one-third last">
<label for="emailinput"><?php _e("Your email", "site5framework"); ?></label>
<input type="text" id="emailinput" name="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>" class="requiredField email"/>
<span class="error" <?php if($emailError != '') echo 'style="display:block;"'; ?>><?php _e("You forgot to enter your email address.", "site5framework");?></span>
</div>
<div class="two-third">
<label for="nameinput"><?php _e("Area/Rep", "site5framework"); ?></label>
<select>
<option>Area 1 - Engela</option>
<option>Area 2 - Francois</option>
<option>Area 3 - Johan</option>
</select>
</div>
<div class="two-third">
<label for="Mymessage"><?php _e("Your message", "site5framework"); ?></label>
<textarea cols="20" rows="20" id="Mymessage" name="comments" class="requiredField"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>
<span class="error" <?php if($commentError != '') echo 'style="display:block;"'; ?>><?php _e("You forgot to enter your comments.", "site5framework");?></span>
</div>
<br class="clear" />
<input type="hidden" name="submitted" id="submitted" value="true" />
<button type="submit" id="submitbutton" class="button small round orange"><?php _e(' &nbsp;SEND MESSAGE&nbsp; ', 'site5framework'); ?></button>
</form>
</div>
<?php endwhile; ?>
</article>
<?php else : ?>
<article id="post-not-found">
<header>
<h1><?php _e("Not Found", "site5framework"); ?></h1>
</header>
<section class="post_content">
<p><?php _e("Sorry, but the requested resource was not found on this site.", "site5framework"); ?></p>
</section>
<footer>
</footer>
</article>
<?php endif; ?>
</div>
</div> <!-- end content -->
<?php get_footer(); ?>
</code></pre>
|
[] |
[
{
"body": "<p>And they didn't give ANY more detail? That was mean! </p>\n\n<p>I think they meant cross site scripting attacks since your form does not check for the form's referrer, or remove html or JavaScript, and you echo out what the user has typed in that means they could add JavaScript to your site. Conceivably someone could set something on their website that posts to your form that executes JavaScript on your site; <a href=\"https://en.wikipedia.org/wiki/Cross-site_scripting\" rel=\"nofollow\">https://en.wikipedia.org/wiki/Cross-site_scripting</a> </p>\n\n<p>see this simple example</p>\n\n<pre><code><form action='<?=$_SERVER['PHP_SELF']?>' method='post'>\n<?php\n $value = (!empty($_POST['hello'])) ? $_POST['hello'] : '';\n?>\n<input type=\"text\" name=\"hello\" value=\"<?=$value?>\" />\n<input type='submit'/>\n</form>\n</code></pre>\n\n<p>If I run that in a browser I get the box, I type in test and the value is \"test\" on page reload but if I type in </p>\n\n<pre><code>\"><script>alert('danger!')</script>\n</code></pre>\n\n<p>note the <code>\"></code> which ends the input field allowing the code to run. now imagine if that was code that grabbed people's login cookies, or worse provided a login or registration form that sent your customers details to a spammer</p>\n\n<p>as it happens google chrome tells me</p>\n\n<pre><code>Refused to execute a JavaScript script. Source code of script found within request.\n</code></pre>\n\n<p>and everything is safe... but people with older browsers beware!</p>\n\n<p>Some other things to address</p>\n\n<ul>\n<li><p>as touched on above check the referrer is not coming from a remote site before sending the email; you might want to consider letting a blank referrer through for people with web privacy software but a referrer from some dodgy sounding hacker domain? ignore that submission</p></li>\n<li><p>you are not using wordpress' nonce feature, <a href=\"http://codex.wordpress.org/Function_Reference/wp_nonce_field\" rel=\"nofollow\">http://codex.wordpress.org/Function_Reference/wp_nonce_field</a> that </p></li>\n</ul>\n\n<blockquote>\n <p>The nonce field is used to validate that the contents of the form\n request came from the current site and not somewhere else. A nonce\n does not offer absolute protection, but should protect against most\n cases. It is very important to use nonce fields in forms</p>\n</blockquote>\n\n<ul>\n<li><p>I don't know of anything in particular that affects the php mail function, and it will depend on what server OS you are using, but there might be vulnerabilities in that similar to the JS problem, you might want to look into updates / know issues for your platform to make sure people can't force your server to send emails, a <strong>theoretical</strong> example if the name field is posted as some malformed string</p>\n\n<p>^'; \\r\\n; bcc: spamvictim@example.com</p></li>\n</ul>\n\n<p>could email anything to anyone; but I stress that is only theoretical, that syntax I invented - more research for your specific platform(s) is required.</p>\n\n<ul>\n<li><p>you are using eregi which has been deprecated a while in favor of the preg functions, I have not heard of any security issues with it (but then I haven't looked because I use preg), but best change because you might find it removed from php soon.</p></li>\n<li><p>your form does not check for maximum length of comment, so unless there is something at the webserver level to stop it, someone could post huge comments to you which would then jam up your email or your servers sendmail - never seen this happen, but still.</p></li>\n<li><p>you might want to consider using a service like <a href=\"http://akismet.com/\" rel=\"nofollow\">http://akismet.com/</a> to protect your form from spammers (that may even protect you from a lot of the above)</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T16:27:10.670",
"Id": "25536",
"ParentId": "25416",
"Score": "4"
}
},
{
"body": "<pre><code>if(function_exists('stripslashes')) {\n</code></pre>\n\n<p>OMG! You don't know if the function is available? You should. And you should never run it without checking whether you need to - which implies you don't know if you've got addslashes enabled - which you should never do for any reason.</p>\n\n<p>This construct seems messy to me:</p>\n\n<pre><code>$nameError = __(\"You forgot to enter your name.\", \"site5framework\");\n$hasError = true;\n...\n$emailError = __(\"You forgot to enter your email address.\", \"site5framework\");\n$hasError = true;\n...\nif(!isset($hasError)) {\n</code></pre>\n\n<p>Wouldn't it be better to just use:</p>\n\n<pre><code>$formError[]= __(\"You forgot to enter your name.\", \"site5framework\");\n...\n$formError[]= __(\"You forgot to enter your email address.\", \"site5framework\");\n...\nif (!count($formError)) {\n</code></pre>\n\n<p>There's multiple XSS vulnerabilities due to you echoing un-sanitized content back out to the email content (if the email is viewed via a browser) and in the html sent to the browser. Also the isset() condition is adding nothing here (OK it suppresses a strict warning - but is that really worth the effort?). Instead of:</p>\n\n<pre><code><input type=\"text\" id=\"nameinput\" \n name=\"contactName\" value=\n \"<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>\" \n class=\"requiredField\"/>\n</code></pre>\n\n<p>Consider:</p>\n\n<pre><code><input type=\"text\" id=\"nameinput\" \n name=\"contactName\" value=\n \"<?php echo @htmlentities($_POST['contactName']);?>\" \n class=\"requiredField\"/>\n</code></pre>\n\n<p>Your code is vulnerable to <a href=\"http://www.securephpwiki.com/index.php/Email_Injection\" rel=\"nofollow\">email header injection</a>.</p>\n\n<p>Also there is the opportunity to exploit MUA vulnerabilities since you don't force an encoding on the email body.</p>\n\n<p>Also, even running on Wordpress, there's a chance this could be abused to launch a flood of emails on your server. If your MTA throttles outgoing emails, this could create a huge backlog. If it doesn't throttle emails you could get blacklisted due to volume. Either way you could use up any bandwidth quota.</p>\n\n<p>Note that you should NEVER sanitize input. You should ALWAYS sanitize output.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T08:25:25.177",
"Id": "39749",
"Score": "0",
"body": "+1 for sanitizing OUTPUT. Sanitizing INPUT provides a buffer in the case that it has mistakenly been OUTPUT without translated for the new context, (i.e. String -> HTML Attribute Value for example). Us developers make mistakes, so until we have tools to validate that all of our OUTPUT is sanitized correctly, it is a sensible precautionary measure to sanitize both."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T23:21:22.933",
"Id": "25665",
"ParentId": "25416",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T08:12:40.540",
"Id": "25416",
"Score": "3",
"Tags": [
"php",
"security",
"form"
],
"Title": "Wordpress php Contact Form - Security flaws"
}
|
25416
|
<p>I got a piece of code I'm not pleased with; Does anyone would have a better idea?</p>
<pre><code>def myFunc(verbose=True):
if not verbose:
print = functools.partial(globals()['print'], file=open(os.devnull, 'w'))
else:
# Required, othewise I got the error 'local print variable was referenced before being declared' a few lines below…
print = globals()['print']
# Bunch of code with tons of print calls […]
</code></pre>
<p>I also tried the classical <code>sys.stdout = open(os.devnull, 'w')</code> but it can't work with my code because my print function is defined as such at the beginning of the code:</p>
<pre><code>print = functools.partial(print, file=codecs.getwriter('utf8')(sys.stdout.buffer)) # Make sure the output is in utf-8
</code></pre>
<p>But I'm not really fan about having to use globals twice.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T09:57:35.307",
"Id": "39409",
"Score": "2",
"body": "It might be worth having a look at the logging facilities offered by Python."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T01:25:19.057",
"Id": "39479",
"Score": "0",
"body": "@Josay Are you talking about the `logging` module? I shall have a look. Last time I tried I couldn't make it work with `cgitb` but I'm not using `cgitb` here so may be it could work. I would still prefer to have a solution which would always work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T01:27:06.783",
"Id": "39480",
"Score": "0",
"body": "@Josay Would it also mean that I would have to change my code anyway? (I mean replacing every print in my function or could I just put something on top just like I did here (I thought about implementing this as a decorator))"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T10:29:40.147",
"Id": "39508",
"Score": "0",
"body": "@JeromeJ: why are you clobbering a global function? that looks like a no-no, can't you name `log` or something?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T08:08:24.827",
"Id": "39559",
"Score": "0",
"body": "@tokland The one at the beginning seems legit to me, everything else is only local (I think I could/should use `locals()` instead of `globals()`). About `log` maybe I could do something like `print = someKindOfLogModified`? (I don't want to rewrite the code of the functions, some aren't mine) But then, if I use `log`, some old probs will come back in some of my other codes (that's why I stopped using `log`, I couldn't make it work everywhere)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T09:18:11.750",
"Id": "39561",
"Score": "0",
"body": "@JeromeJ: fair enough, it's a local clobbering, it's acceptable. If you are going to do this more than once, by all means, abstract it: `print = get_my_print(verbose)`. Btw, the error you get is normal, Python sees `print =` in the first branch so it decides that it's a local variable in this scope."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-02T06:59:14.443",
"Id": "39852",
"Score": "0",
"body": "@tokland Isn't this a valid use case for the `global` keyword? (By the way, in a Unix world, deciding where the output goes is not decided in the code, except to separate standard output and standard error.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-02T07:07:48.610",
"Id": "39853",
"Score": "0",
"body": "Also, deciding on the output encoding is decided using the locale in Python, explicitely encoding everything in UTF-8 is asking for trouble IMHO, and is probably not the best place to fix a problem you're having."
}
] |
[
{
"body": "<p>It depends on what you are looking to do. For localized 'quiet' code, I use this:</p>\n\n<pre><code>class NoStdStreams(object):\n def __init__(self,stdout = None, stderr = None):\n self.devnull = open(os.devnull,'w')\n self._stdout = stdout or self.devnull or sys.stdout\n self._stderr = stderr or self.devnull or sys.stderr\n\n def __enter__(self):\n self.old_stdout, self.old_stderr = sys.stdout, sys.stderr\n self.old_stdout.flush(); self.old_stderr.flush()\n sys.stdout, sys.stderr = self._stdout, self._stderr\n\n def __exit__(self, exc_type, exc_value, traceback):\n self._stdout.flush(); self._stderr.flush()\n sys.stdout = self.old_stdout\n sys.stderr = self.old_stderr\n self.devnull.close()\n</code></pre>\n\n<p>then it is as easy as:</p>\n\n<pre><code>with NoStdStreams():\n print('you will never see this')\n</code></pre>\n\n<p>You could easily adapt it to:</p>\n\n<pre><code>with NoStdStreams(verbose):\n print('you may see this')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T08:14:49.640",
"Id": "39560",
"Score": "0",
"body": "I like your idea but I gotta modify my code (and yours) if I want to use it (because of my way of overwriting `print` so that it doesn't even call `sys.stdout`)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T06:32:20.040",
"Id": "25471",
"ParentId": "25417",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T08:13:16.783",
"Id": "25417",
"Score": "2",
"Tags": [
"python"
],
"Title": "Is there a better way to make a function silent on need?"
}
|
25417
|
<p>I'm not a C programmer, just wanted to make a fast solution to the <a href="https://projecteuler.net/problem=15" rel="nofollow">problem</a>. </p>
<blockquote>
<p>Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.<br>
How many such routes are there through a 20×20 grid?</p>
</blockquote>
<p>Here's my code:</p>
<pre><code>#include <stdio.h>
#define SIZE 21 // grid size + 1
long long int count_routes(long long int cache[SIZE][SIZE], unsigned short x, unsigned short y) {
if (cache[x][y] != 0) {
return cache[x][y];
}
long long int n = 0;
if (x == 0 && y == 0) {
n = 1;
}
else {
n = 0;
if (x > 0) {
n += count_routes(cache, x-1, y);
}
if (y > 0) {
n += count_routes(cache, x, y-1);
}
}
cache[x][y] = n;
return n;
}
int main(void) {
long long int cache[SIZE][SIZE];
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
cache[i][j] = 0;
}
}
printf("%lld\n", count_routes(cache, SIZE-1, SIZE-1));
return 0;
}
</code></pre>
<p>Please share your thoughts about what could be improved in it.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-31T10:31:22.657",
"Id": "137107",
"Score": "2",
"body": "Those are binomial coefficients right? So \\$\\frac{n!}{(n-k)!k!}\\$ where \\$n = 40\\$ and \\$k = 20\\$ should do it?"
}
] |
[
{
"body": "<p>I do not know whether my suggestion makes code faster, but it sure does make it shorter and probably equally fast. It calculates the possibilities dynamically, using the observation that number of ways to get to a square is the sum of numbers of ways to get to the top and the left square, as does yours, but it does not use recursion, so it's perhaps easier to understand or code.</p>\n\n<pre><code>#include <cstdio>\n\nunsigned long long g[21][21];\n\nint main() { \n for (int i = 0; i < 21; ++i) {\n g[i][0] = 1;\n g[0][i] = 1;\n }\n for (int i = 1; i < 21; ++i) {\n for (int j = 1; j < 21; ++j) {\n g[i][j] = g[i-1][j] + g[i][j-1];\n }\n }\n\n printf(\"%lld\\n\", g[20][20]);\n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T14:11:34.473",
"Id": "25426",
"ParentId": "25419",
"Score": "4"
}
},
{
"body": "<p>Taking the amount of points in the grid as the input size(n*m), using recursion forces you to make it <code>O(n*m)</code> in space and time.</p>\n\n<p>If we want to go from (0,0) to (20,20) then we already know that we have to go right 20 times and down 20 times. So we can rephrase the question from \"How many different ways can you go to (20,20)?\" to \"In how many different ways can you go 20 times right and 20 times down?\". The second question is now purely a basic math permutations calculation. The answer to it is $${40\\choose 20} = \\frac{40!}{(40-20)!20!}.$$</p>\n\n<p>In C code</p>\n\n<pre><code>#include <stdio.h>\n\nint main() { \n int res = 1;\n for (int i = 0; i < 20; ++i) {\n res = res * (40-i) / (i+1)\n }\n\n printf(\"%lld\\n\", res);\n return 0;\n}\n</code></pre>\n\n<p>This requires 20 multiplications and 20 divisions. So it is <code>O(n+m)</code> in time, but constant in space.</p>\n\n<p>Note that doing <code>res *= (40-i)/(i+1)</code> will not work. The quotient <code>(40-i)/(i+1)</code> is not an integer for all <code>i</code>. A counterexample is <code>i=1</code> since <code>39%2 = 1</code>. </p>\n\n<p>The way I wrote it, the multiplication <code>res (40 -i)</code> is done first, which ensures the division will yield an integer. </p>\n\n<p>To see this, start with <code>n/1</code> - obviously an integer as <code>1</code> divides any number. The next term is <code>n.(n-1)/1.2</code>; if <code>n</code> is not even, then <code>(n-1)</code> must be. Similarly, <code>n*(n-1)...(n-p)</code> must contain a multiple of <code>p+1</code> somewhere in the product. In this way you can continue and there will always be a factor in the numerator for the 'new' factor in the denomiator to divide out. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-03T16:33:23.263",
"Id": "366956",
"Score": "0",
"body": "You are right. This is a whole in my answer. For i=1 it already fails.\nI'll adjust my answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-06T07:49:41.510",
"Id": "367401",
"Score": "0",
"body": "I don't think it was wrong. And I think I can sketch a proof that it's right in the general case (n choose k). We start with n/1 - obviously an integer as 1 divides any number. The next term is n.(n-1) / 1.2; if n is not even, then (n-1) must be. Similarly, n.(n-1)...(n-p) must contain a multiple of p+1 somewhere in the product. The proof needs to be more rigorous to show that repeated factors are accounted for (e.g. when we reach 4 in the denominator, we've already cancelled a 2 - but we have accumulated a multiple of 4 and a different multiple of 2 in the numerator)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-06T07:52:00.260",
"Id": "367402",
"Score": "0",
"body": "It is important to multiply before dividing, though - so point out that you can't replace `res = res * (40-i) / (i+1)` with `res *= (40-i) / (i+1)`; it would have to be `res *= 40-i; res /= i+1;`. And this (original) solution is actually better than the new (edited) one, because it is less likely to overflow the integer type. This [relevant link](https://blog.plover.com/math/choose.html) might be worth a look."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-06T08:04:00.513",
"Id": "367408",
"Score": "0",
"body": "You are right again and your sketch makes sense. Should I adjust my answer for the 2nd time?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-06T08:12:05.067",
"Id": "367414",
"Score": "0",
"body": "Yes, I think so - I suggest you remove the \"EDIT\" section, and then incorporate something to explain what I wrote in comments (I'll delete the comments once they are no longer needed). Sorry to raise a false alarm!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-30T09:00:53.237",
"Id": "190849",
"ParentId": "25419",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "25426",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T09:15:11.203",
"Id": "25419",
"Score": "4",
"Tags": [
"c",
"programming-challenge",
"dynamic-programming"
],
"Title": "Project Euler #15 -- count possible lattice paths"
}
|
25419
|
<p>This is used to display an accordion with a list of connections using JavaFX. Can you help me to optimize the code to make it much simpler?</p>
<pre><code>package sqlbrowser.navigation;
import java.util.ArrayList;
import java.util.List;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Bounds;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TitledPane;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;
public class Navigation {
// Object for storing conenctions
public static List<dataObj> list = new ArrayList<>();
private ObservableList<dataObj> data;
public class dataObj {
private String conenctionname;
public dataObj(String conenctionname) {
this.conenctionname = conenctionname;
}
public String getConenctionname() {
return conenctionname;
}
public void setConenctionname(String conenctionname) {
this.conenctionname = conenctionname;
}
}
public void initNavigation(Stage primaryStage, Group root, Scene scene) {
VBox stackedTitledPanes = createStackedTitledPanes();
ScrollPane scroll = makeScrollable(stackedTitledPanes);
scroll.getStyleClass().add("stacked-titled-panes-scroll-pane");
scroll.setPrefSize(395, 580);
scroll.setLayoutX(5);
scroll.setLayoutY(32);
root.getChildren().add(scroll);
}
private ScrollPane makeScrollable(final VBox node) {
final ScrollPane scroll = new ScrollPane();
scroll.setContent(node);
scroll.viewportBoundsProperty().addListener(new ChangeListener<Bounds>() {
@Override
public void changed(ObservableValue<? extends Bounds> ov, Bounds oldBounds, Bounds bounds) {
node.setPrefWidth(bounds.getWidth());
}
});
return scroll;
}
/////////////////////////////////////////////////////////////////////////////////////
// Generate accordition with Connections, Tables and Description
private VBox createStackedTitledPanes() {
VBox stackedTitledPanes = new VBox();
stackedTitledPanes.getChildren().setAll(
createConnectionsList("Connections"));
((TitledPane) stackedTitledPanes.getChildren().get(0)).setExpanded(true);
stackedTitledPanes.getStyleClass().add("stacked-titled-panes");
return stackedTitledPanes;
}
//////////////////////////////////////////////////////////////////////////////
// Generate list with Connections
public TitledPane createConnectionsList(String title) {
initObject();
data = FXCollections.observableArrayList(list);
ListView<dataObj> lv = new ListView<>(data);
lv.setCellFactory(new Callback<ListView<dataObj>, ListCell<dataObj>>() {
@Override
public ListCell<dataObj> call(ListView<dataObj> p) {
return new ConnectionsCellFactory();
}
});
AnchorPane content = new AnchorPane();
content.getChildren().add(lv);
// add to TitelPane
TitledPane pane = new TitledPane(title, content);
return pane;
}
static class ConnectionsCellFactory extends ListCell<dataObj> {
@Override
public void updateItem(dataObj item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
setText(item.getConenctionname());
}
}
}
// Insert Some test data
public void initObject() {
dataObj test1 = new dataObj("test data 1");
dataObj test2 = new dataObj("test data 2");
list.add(test1);
list.add(test2);
}
}
</code></pre>
|
[] |
[
{
"body": "<pre><code>scroll.getStyleClass().add(\"stacked-titled-panes-scroll-pane\");\nscroll.setPrefSize(395, 580);\nscroll.setLayoutX(5);\nscroll.setLayoutY(32);\n</code></pre>\n\n<p>these lines can go inside <code>makeScrollable()</code>, which in turn could be refactored with <code>initNavigation()</code> to an external factory class.</p>\n\n<p>Also, class <code>dataObj</code>(which I would capitalize to <code>DataObj</code>) could also be moved to an external class. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T10:16:10.940",
"Id": "25483",
"ParentId": "25424",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T13:23:20.947",
"Id": "25424",
"Score": "1",
"Tags": [
"java",
"javafx"
],
"Title": "Displaying an accordion with a list of connections"
}
|
25424
|
<p>I'm working on JavaScript <a href="http://en.wikipedia.org/wiki/Bookmarklet" rel="nofollow noreferrer">bookmarklet</a> that lets users send a text and link to a site.</p>
<p>This is the bookmarklet:</p>
<pre><code>javascript:(function(){new_script=document.createElement('SCRIPT');new_script.src='http://bookmarklet.example.com/js/bookmarklet.js?v=1';document.getElementsByTagName('head')[0].appendChild(new_script);new_script.type='text/javascript';})();
</code></pre>
<p>This is the JavaScript for it:</p>
<pre><code>if(frames.length>0){
F=' (Frames not supported)'
} else {
F=''
}
Q=document.getSelection();
if(!Q){
void(Q=prompt('Enter a text...'+F+'',''))
};
if(Q){
void (window.open('http://www.example.com/add?url='+encodeURIComponent(window.location)+'&text='+escape(Q)+'&title='+encodeURIComponent(document.title)))
}
</code></pre>
<p>It's the first time I'm using JavaScript, so I would love to hear your feedback on the code. Is there anything that needs to be optimized?</p>
<p>Thanks.
Patrick</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T14:19:53.987",
"Id": "39423",
"Score": "0",
"body": "Where's the `void()` function defined and why are you using it?"
}
] |
[
{
"body": "<p>The loader could be simplified to the following:</p>\n\n<pre><code>javascript:(function () {document.getElementsByTagName('head')[0].appendChild(document.createElement('script')).src = 'http://bookmarklet.example.com/js/bookmarklet.js?v=1'}());\n</code></pre>\n\n<ul>\n<li>No more variables. By the way, you forgot to use <code>var</code>. It causes the variable to be declared as a global.</li>\n<li>Browsers, by default, parse script tags as JavaScript, thus the <code>type</code> can be omitted.</li>\n</ul>\n\n<p>And in your script body, as far as I can understand, it's a script that gets a selected text or, if none selected, lets the user manually input the text and sends it to a server. Thus we have:</p>\n\n<pre><code>//remember that you are loading this script into the global scope. Protect your \n//variables by enclosing it in a closure\n(function () {\n //a ternary if is a short 2-way evaluation (as far as reading is concerned)\n var F = (frames.length > 0) ? ' (Frames not supported)' : '',\n //the OR operator (`||`) could also be used to evaluate stuff\n //here, it returns either document.getSelection(), \n //or if non existent, a prompted value\n Q = document.getSelection() || prompt('Enter a text...' + F + '', '');\n\n //then we execute your command\n window.open('http://www.example.com/add?url=' + encodeURIComponent(window.location) + '&text=' + escape(Q) + '&title=' + encodeURIComponent(document.title))\n\n}());\n</code></pre>\n\n<p>As an additional tip, I suggest you load the url to a hidden <code>iframe</code> for a cleaner interface. You could add listeners (there are hacks for cross domain iframe messaging), to detect a success and show a confirmation UI afterwards.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T17:16:29.233",
"Id": "39533",
"Score": "0",
"body": "Awesome, thanks for your feedback and suggestions! Quick question: I tried the bookmarklet in the Android browser (Android 4) but it's not working. The site loading bar starts but stops at ~20%. Is there a way to make it work for Android? `javascript:(function(){new_script=document.createElement('SCRIPT');new_script.src='http://bookmarklet.example.com/js/bookmarklet.js?v=1';document.getElementsByTagName('head')[0].appendChild(new_script);new_script.type='text/javascript';})();`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T18:08:04.160",
"Id": "39539",
"Score": "0",
"body": "@Patrick Head over to StackOverflow if your code doesn't work on Android."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T16:26:10.703",
"Id": "25434",
"ParentId": "25427",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "25434",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T14:11:41.833",
"Id": "25427",
"Score": "1",
"Tags": [
"javascript",
"optimization"
],
"Title": "JavaScript - Does this bookmarklet need some optimization?"
}
|
25427
|
<p>I still have to implement API keys for client auth, but so far this is what I have for users. This was built using WebAPI and SimpleMembership with Forms Auth:</p>
<p><strong>Is Authenticated:</strong></p>
<pre><code>public class AccountController : ApiController
{
public static DtoService _service = new DtoService();
// GET/api/isAuthenticated
[System.Web.Http.HttpGet]
public HttpResponseMessage IsAuthenticated()
{
try
{
if (User.Identity.IsAuthenticated)
return Request.CreateResponse(HttpStatusCode.OK, WebSecurity.GetUserId(User.Identity.Name));
else
return Request.CreateResponse(HttpStatusCode.OK, false);
}
catch (Exception e)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
}
}
</code></pre>
<p><strong>Login:</strong></p>
<pre><code>// POST /api/login
// [System.Web.Http.AllowAnonymous]
[System.Web.Http.HttpPost]
public HttpResponseMessage LogIn(LoginModel model)
{
if (!ModelState.IsValid)
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
try
{
if (User.Identity.IsAuthenticated)
return Request.CreateResponse(HttpStatusCode.Conflict, "already logged in.");
if (!WebSecurity.UserExists(model.UserName))
return Request.CreateResponse(HttpStatusCode.BadRequest, "User does not exist.");
if (WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
return Request.CreateResponse(HttpStatusCode.OK, "logged in successfully");
}
return Request.CreateResponse(HttpStatusCode.BadRequest, "Login Failed.");
}
catch (Exception e)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
}
}
</code></pre>
<p><strong>Log Out:</strong></p>
<pre><code>// POST /api/logout
[System.Web.Http.HttpPost]
////[ValidateAntiForgeryToken]
// [System.Web.Http.AllowAnonymous]
[Authorize]
public HttpResponseMessage LogOut()
{
try
{
if (User.Identity.IsAuthenticated)
{
WebSecurity.Logout();
return Request.CreateResponse(HttpStatusCode.OK, "logged out successfully.");
}
return Request.CreateResponse(HttpStatusCode.Conflict, "already done.");
}
catch (Exception e)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
}
}
</code></pre>
<p><strong>Register:</strong></p>
<pre><code>// POST: /api/register
[System.Web.Http.HttpPost]
//[ValidateAntiForgeryToken]
public HttpResponseMessage Register(RegisterModel model)
{
if (!ModelState.IsValid)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
try
{
if (User.Identity.IsAuthenticated)
return Request.CreateResponse(HttpStatusCode.Conflict, "User Already Registered and Logged In");
if (WebSecurity.UserExists(model.UserName))
return Request.CreateResponse(HttpStatusCode.Conflict, "User Already Registered");
else
{
// Attempt to register the user
WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
WebSecurity.Login(model.UserName, model.Password);
InitiateDatabaseForNewUser(WebSecurity.GetUserId(model.UserName));
FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);
return Request.CreateResponse(HttpStatusCode.Created, WebSecurity.GetUserId(model.UserName));
}
}
catch (Exception e)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T14:59:06.997",
"Id": "39425",
"Score": "0",
"body": "I think you should not have your logout be a POST operation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T19:44:59.757",
"Id": "39444",
"Score": "0",
"body": "\"public static DtoService _service = new DtoService()\". Is that a typo?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T19:50:48.790",
"Id": "39445",
"Score": "0",
"body": "It's not; I just realized I don't need it though :p Why do you ask?"
}
] |
[
{
"body": "<p>Lets start with your URI's.</p>\n\n<p>GET /api/isAuthenticated - This is not restful I guess. isAuthenticated doesn't sound like it is a resource, instead it sounds like it is a method returning true or false. May be it would help if you read more on Restful architecture.</p>\n\n<p>POST /api/login - Even this sounds like a process but not resource</p>\n\n<p>Instead I would go with /api/authentication URI</p>\n\n<p>On GET it returns authenticated user information\non POST you can send credentials to create a new authentication\non DELETE you delete the authentication resource which means logout.</p>\n\n<p>Above is just for example about how to use Restful URI's. To be blunt, login process should not be done through RESTful URI's as it introduces stateful system where as RESTful API should be stateless. Instead you should use authentication headers of HTTP for authenticating and authorizing a user.</p>\n\n<p>I hope this helps you in understanding RESTful API.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T19:52:26.110",
"Id": "39447",
"Score": "0",
"body": "Thanks for this. What would you suggest for Registration? POST /api/user?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T19:55:03.607",
"Id": "39449",
"Score": "0",
"body": "And - can you give an example of an api call that would log a user in without using restful URIs? I'm having a tough time imagining how this request would work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-24T12:15:58.720",
"Id": "103731",
"Score": "0",
"body": "@RobVious Is it for Intranet or Internet? If it is Intranet then you can just make windows or basic auth. enabled."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T17:50:16.217",
"Id": "25438",
"ParentId": "25428",
"Score": "5"
}
},
{
"body": "<p>For creating new record , please use Post with 201 return code. On successful update, return 200 (or 204 if not returning any content in the body) from a PUT.</p>\n\n<p>To know more about status code please refer: <a href=\"http://en.wikipedia.org/wiki/Http_error_codes\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Http_error_codes</a></p>\n\n<p>IsAuthenticated, Login, Logout are Non-Resource Api Calls. Be sure that the user can tell it is a different type of operation Be pragmatic and make sure that these parts of your API are documented Don’t use them as an execute to build a RPC API</p>\n\n<p>You can separate these by defining as [Route('api/helper/logout')].</p>\n\n<p>Here is the reference document that I have prepared while developing my own web api. I have collected this guideline techniques from various sources and multiple books. \n<a href=\"http://www.doeaccian.com/restful-webapi-best-practices/\" rel=\"nofollow\">http://www.doeaccian.com/restful-webapi-best-practices/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-24T11:42:18.570",
"Id": "57914",
"ParentId": "25428",
"Score": "2"
}
},
{
"body": "<p>You have two responsibilities:</p>\n\n<p>1) A <code>LoginController</code>, which is used to authenticate/log a user in</p>\n\n<p>2) An <code>UserController</code>, which takes care of all actions belonging to the user </p>\n\n<p>So a possible <em>routing schema</em> for the API would be:</p>\n\n<p><strong>(1) POST: <em>api/login</em></strong></p>\n\n<p>Possible Answers: <em>200 OK</em> or <em>401 Unauthorized</em></p>\n\n<p>If an unauthorized user enters a page, where authorization is required, the answer should be: <em>403 Forbidden</em>. The same goes for every REST-action, which needs authentication.</p>\n\n<p><strong>POST: <em>api/logout</em></strong></p>\n\n<p>Possible Answers: <em>200 OK</em></p>\n\n<p><strong>(2) GET: <em>api/users/</em></strong></p>\n\n<p>Possible Answers: <em>200 OK</em> and a list of all users in some output format (JSON/XML whatever).</p>\n\n<p>The client could specify his wishes via <code>Accept</code> e.g. <em>application/json</em> </p>\n\n<p><strong>GET: <em>api/users/{ID}</em></strong></p>\n\n<p>Possible Answers: <em>200 OK</em> including the requested user or <em>404 Not Found</em>. If you keeping track of ex-users a possible answer could be <em>410 Gone</em>.</p>\n\n<p><strong>POST: <em>api/users/</em></strong></p>\n\n<p>Possible Answers: <em>201 Created</em> including the created Ressource in some output format (JSON/XML whatever). If there is anything syntactically wrong (something missing or a field misspelled) with the userinput the answer is: <em>400 Bad Request</em></p>\n\n<p><strong>PUT: <em>api/users/</em></strong></p>\n\n<p>Possible Answers: <em>204 No Content</em></p>\n\n<p><strong>DELETE: <em>api/users/{ID}</em></strong></p>\n\n<p>Possible Answers: <em>204 No Content</em></p>\n\n<p>So far a possible Layout. Now some words to your code:</p>\n\n<pre><code> if (User.Identity.IsAuthenticated)\n return Request.CreateResponse(HttpStatusCode.OK, WebSecurity.GetUserId(User.Identity.Name));\n else\n return Request.CreateResponse(HttpStatusCode.OK, false);\n</code></pre>\n\n<p>If you read, what I wrote above, you understand, that this is misleading. You are branching on the condition <code>User.Identity.IsAuthenticated</code> and returning in both cases <code>HttpStatusCode.OK</code>: That makes no sense at all. Although the request itself is <code>OK</code>, the answer should be a <code>401</code>.</p>\n\n<p>The same goes for:</p>\n\n<pre><code> if (User.Identity.IsAuthenticated)\n return Request.CreateResponse(HttpStatusCode.Conflict, \"already logged in.\");\n if (!WebSecurity.UserExists(model.UserName))\n return Request.CreateResponse(HttpStatusCode.BadRequest, \"User does not exist.\");\n if (WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))\n {\n FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);\n return Request.CreateResponse(HttpStatusCode.OK, \"logged in successfully\");\n }\n return Request.CreateResponse(HttpStatusCode.BadRequest, \"Login Failed.\");\n</code></pre>\n\n<p>If the user is already authenticated, there is no need to adress this case. You are responding with <code>409 Conflict</code> which is wrong: there are no ressources conflicting. A reason to throw a <code>409</code> is: e.g. when you have a content management system with a versioning field, and a user wants to update with a version number which is lower than the current one; then that is a <code>Conflict</code>\nOr when you wrote</p>\n\n<pre><code> if (WebSecurity.UserExists(model.UserName))\n return Request.CreateResponse(HttpStatusCode.Conflict, \"User Already Registered\");\n</code></pre>\n\n<p>That indeed is a conflict.</p>\n\n<p>If the user wants to log in a hundred times: let him do that. Every time he does, he gets a valid token. End of story. </p>\n\n<p>If a user doesn't exist, return a <code>404 Not Found</code> and if the login failed return <code>401 Unauthorized</code>. That's why they were invented: to signal, that a ressource isn't there and you are unauthorized to do that operation, you wanted.</p>\n\n<p>And only, when there is something <em>syntactically</em> wrong with a request you should answer with <code>400 Bad Request</code>. This is not about <em>semantics</em>. </p>\n\n<p>So, if I am asking you: »Do you live on the moon?« this is a <em>syntactically</em> correct question. Your answer »Can you repeat the question? - I did not understand, what you meant.« is misleading.</p>\n\n<p>That's why this</p>\n\n<pre><code> if (!WebSecurity.UserExists(model.UserName))\n return Request.CreateResponse(HttpStatusCode.BadRequest, \"User does not exist.\");\n</code></pre>\n\n<p>is wrong.</p>\n\n<p>If I ask you, whether you live on the moon, your answer should be yes or no.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-24T13:10:28.050",
"Id": "57921",
"ParentId": "25428",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T14:12:55.090",
"Id": "25428",
"Score": "3",
"Tags": [
"c#",
".net",
"mvc",
"api"
],
"Title": "REST-ish API Account Controller"
}
|
25428
|
<p>I just wrote the following javascript (jQeury loaded):</p>
<pre><code>var valid, ui;
try {
$.each(this._cache, function() {
$.each(this, function() {
$.each(this, function() {
if (this.label.toLowerCase() === valueLowerCase) {
valid = true;
ui = {item: $.extend({}, this) };
throw 'Control flow throw, please rethrow if accidently caught';
}
});
});
});
} catch(e) {}
</code></pre>
<p>My coworker suggested I rewrite this as follows:</p>
<pre><code>var valid, ui;
$.each(this._cache, function() {
$.each(this, function() {
$.each(this, function() {
if (this.label.toLowerCase() === valueLowerCase) {
valid = true;
ui = {item: $.extend({}, this) };
}
return !valid;
});
return !valid;
});
return !valid;
});
</code></pre>
<p>I think this is a valid case of using exceptions as control flow. Which way is the correct way to do this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T15:40:31.403",
"Id": "39430",
"Score": "4",
"body": "Exceptions should be used in exceptional circumstances, not in logic of the application. By exceptional circumstances, I mean they should only be used when something unexpected happens."
}
] |
[
{
"body": "<p>As Jef Vanzella mentioned, exceptions are for unexpected bad things, not for jumping out of control flow. Hence the second option is better, but it is still substandard code.</p>\n\n<p>Instead of using <code>this</code>, you should have a meaningful parameter name in your function declaration.</p>\n\n<p>Also, you could simply return the falsey <code>!ui</code> instead of <code>!valid</code>.</p>\n\n<p>Finally, not many people know that returning <code>false</code> stops the iteration, that deserves a comment.</p>\n\n<p>Now imagine that your data structure was <code>Cache -> Orders -> Shipments -> Items</code> then you could write:</p>\n\n<pre><code>var ui;\n\n//Returning false to each() will stop the iteration\n$.each(this._cache, function( order ) {\n $.each(order, function( shipment ) {\n $.each(shipment, function( item) {\n if (item.label.toLowerCase() === valueLowerCase) {\n ui = {item: $.extend({}, this) };\n }\n return !ui ;\n });\n return !ui ;\n });\n return !ui ;\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T15:20:31.057",
"Id": "38759",
"ParentId": "25432",
"Score": "3"
}
},
{
"body": "<p>I agree with <a href=\"https://codereview.stackexchange.com/a/38759/2634\">tomdemuyt</a> but I'd take a different approach altogether.</p>\n\n<p>Instead of iterating through objects with jQuery, I'd use <a href=\"http://underscorejs.org\" rel=\"nofollow noreferrer\">Underscore.js</a> and focus on <em>working with data</em>.<br>\nUndercore provides more convenience methods to filter and transform data than jQuery. </p>\n\n<p>There is also no rightward code drift if the data structure gets more complex in the future.</p>\n\n<p>Assuming <code>Cache -> Orders -> Shipments -> Items</code> data structure and that you iterate over object properties (and not arrays), it would be something like:</p>\n\n<pre><code>var orders = _.chain(this._cache).values(),\n shipments = orders.map(_.values).flatten(),\n items = shipments.map(_.values).flatten(),\n matchingItem,\n ui;\n\nmatchingItem = items.find(function (item) {\n return item.label.toLowerCase() === valueLowerCase;\n});\n\nif (matchingItem) {\n ui = { item: matchingItem.clone().value() };\n}\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/dU699/\" rel=\"nofollow noreferrer\">Run it on JSFiddle</a>.</p>\n\n<p>As tomdemuyt suggested, you don't need <code>valid</code> because you can check <code>ui</code>.</p>\n\n<p>The downside of this method is that although it will <em>not</em> run the check for every item, it still has to iterate over each order and shipment to gather their items into a single big array, so it is guaranteed to be slower.</p>\n\n<p>Still, this should not concern you, unless you have thousands of items—and from the point of maintenance I think this is simpler code to work with and extend. I'd prefer more readable code unless this really becomes the bottleneck.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T16:06:29.503",
"Id": "64715",
"Score": "1",
"body": "The only hiccup is that you process all items at all times with `.map()`, always giving worst case performance. Still, +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T16:11:25.303",
"Id": "64718",
"Score": "0",
"body": "@tomdemuyt Yeah, you're right."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T15:49:27.827",
"Id": "38761",
"ParentId": "25432",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T15:22:29.630",
"Id": "25432",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"exception-handling",
"jquery-ui"
],
"Title": "Exceptions for control flow"
}
|
25432
|
<p>I built a code piece that makes it easy to execute a set of <strong>sequential</strong> operations, that might depend on the same parameter value (passed across the execution) or might need a particular parameter.
There's also a possibility to manage an error from within the operations, by implementing <code>IReversible</code> interface. </p>
<p>This code example can be copy/pasted into a console app, so you can easily check the functionality.</p>
<p>So far, this is what I've done:</p>
<pre><code> class Program
{
static void Main(string[] args)
{
var transferenceInfo = new InterbankTranferenceInfo();
var orchestrator = new Orchestrator(new InternalDebitOperation(transferenceInfo),
new InterbankCreditOperation(),
new CommissionOperation());
orchestrator.Run();
}
}
public class InterbankTranferenceInfo : IParameter
{
public bool InternalDebitDone { get; set; }
public bool InterbankCreditDone { get; set; }
public bool CommissionDone { get; set; }
}
public class InternalDebitOperation : Operation<InterbankTranferenceInfo>, IOperation<InterbankTranferenceInfo>
{
public InternalDebitOperation(InterbankTranferenceInfo parameter)
: base(parameter)
{
}
public override InterbankTranferenceInfo Execute()
{
return new InterbankTranferenceInfo() { InternalDebitDone = true };
}
}
public class InterbankCreditOperation : Operation<InterbankTranferenceInfo>, IOperation<InterbankTranferenceInfo>
{
public override InterbankTranferenceInfo Execute()
{
Parameter.InterbankCreditDone = true;
return Parameter;
}
}
public class CommissionOperation : Operation<InterbankTranferenceInfo>, IReversible, IOperation<InterbankTranferenceInfo>
{
public override InterbankTranferenceInfo Execute()
{
Parameter.CommissionDone = true;
// Uncomment this code to test Reverse operation.
// throw new Exception("Test exception, it should trigger Reverse() method.");
return Parameter;
}
public void Reverse()
{
Parameter.CommissionDone = false;
}
}
public enum OperationStatus
{
Done,
Pending,
Reversed
}
public interface IParameter
{
}
public interface IReversible
{
void Reverse();
}
public interface IOperation<out T> : IInternalOperation<T> where T : IParameter
{
}
public interface IInternalOperation<out T> : IExecutableOperation<T>
{
bool GetParameterFromParentOperation { get; }
OperationStatus Status { get; set; }
IParameter Execute(IParameter parameter);
}
public interface IExecutableOperation<out T>
{
T Execute();
}
//[System.Diagnostics.DebuggerStepThroughAttribute()]
public abstract class Operation<T> : IInternalOperation<T> where T : IParameter
{
public T Parameter { get; private set; }
public bool GetParameterFromParentOperation { get { return this.Parameter == null; } }
public OperationStatus Status { get; set; }
public Operation()
{
Status = OperationStatus.Pending;
}
public Operation(IParameter parameter)
{
Status = OperationStatus.Pending;
this.Parameter = (T)parameter;
}
public abstract T Execute();
public virtual IParameter Execute(IParameter parameter)
{
this.Parameter = (T)parameter;
return this.Execute();
}
}
public class Orchestrator
{
public List<IOperation<IParameter>> Operations { get; private set; }
public Orchestrator(params IOperation<IParameter>[] operations)
{
this.Operations = new List<IOperation<IParameter>>();
foreach (var item in operations)
{
this.Operations.Add((IOperation<IParameter>)item);
}
}
public IParameter Run()
{
IParameter previousOperationResult = null;
foreach (var operation in this.Operations)
{
try
{
if (operation.GetParameterFromParentOperation)
previousOperationResult = operation.Execute(previousOperationResult);
else
previousOperationResult = operation.Execute();
operation.Status = OperationStatus.Done;
}
catch (Exception)
{
foreach (var o in this.Operations)
{
if (o is IReversible)
{
((IReversible)o).Reverse();
o.Status = OperationStatus.Reversed;
}
else
throw;
}
break;
}
}
return previousOperationResult;
}
}
</code></pre>
<p>Questions:</p>
<ol>
<li>What you think about it?</li>
<li>Am I reinventing the wheel? Is there any pattern or fwk that covers this functionality? It looks like command pattern with steroids. Or is it another pattern?</li>
<li>Do you see any possible future headache on this or have any suggestion about how to improve it?</li>
</ol>
<p>I don't like the implementation of both <code>Operation</code> and <code>IOperation</code> on concrete types, so feel free to correct me if there's a more elegant way of doing this covariant scenario.</p>
|
[] |
[
{
"body": "<p>It does not look like you ever reference <code>IExecutableOperation<T></code> or <code>IInternalOperation<T></code> directly, so I would take the YAGNI approach and roll them both into <code>IOperation<T></code>.</p>\n\n<p>With that done, <code>Operation<T></code> would implement <code>IOperation<T></code> directly, so you no longer have to explicitly mark <code>InternalDebitOperation</code>, <code>InterbankCreditOperation</code>, and <code>CommissionOperation</code> as implementing <code>IOperation<T></code>.</p>\n\n<p>Additional Comments/Concerns:</p>\n\n<ul>\n<li>There is the potential for InvalidCastExceptions when calling your <code>IParameter Execute (IParameter parameter)</code> overload, because you cast an IParameter to type T, which is a sub-type of IParameter, but there is nothing preventing you from passing a different IParameter implementation in which cannot be cast to T.</li>\n<li>See previous comment about your <code>Operation<T></code> constructor.</li>\n<li>The way in which Orchestrator is coded forces you to do everything in the context of IParameter. This somewhat defeats the purpose of making <code>Operation<T></code> generic, because you're having to box/unbox your parameter types between T and IParameter anyways. I would suggest either making Orchestrator generic as well. The alternative is making IOperation/Operation non-generic.</li>\n</ul>\n\n<p>With those comments in mind, I would make the following changes:</p>\n\n<pre><code> class Program\n {\n static void Main (string [] args)\n {\n var transferenceInfo = new InterbankTranferenceInfo ();\n\n var orchestrator = new Orchestrator<InterbankTranferenceInfo> (new InternalDebitOperation (transferenceInfo),\n new InterbankCreditOperation (),\n new CommissionOperation ());\n\n orchestrator.Run ();\n }\n }\n\n public class InterbankTranferenceInfo : IParameter\n {\n public bool InternalDebitDone { get; set; }\n\n public bool InterbankCreditDone { get; set; }\n\n public bool CommissionDone { get; set; }\n }\n\n public class InternalDebitOperation : Operation<InterbankTranferenceInfo>\n {\n public InternalDebitOperation (InterbankTranferenceInfo parameter)\n : base (parameter)\n {\n }\n\n public override InterbankTranferenceInfo Execute ()\n {\n return new InterbankTranferenceInfo () { InternalDebitDone = true };\n }\n }\n\n public class InterbankCreditOperation : Operation<InterbankTranferenceInfo>\n {\n public override InterbankTranferenceInfo Execute ()\n {\n Parameter.InterbankCreditDone = true;\n\n return Parameter;\n }\n }\n\n public class CommissionOperation : Operation<InterbankTranferenceInfo>, IReversible\n {\n public override InterbankTranferenceInfo Execute ()\n {\n Parameter.CommissionDone = true;\n\n // Uncomment this code to test Reverse operation.\n // throw new Exception(\"Test exception, it should trigger Reverse() method.\");\n\n return Parameter;\n }\n\n public void Reverse ()\n {\n Parameter.CommissionDone = false;\n }\n }\n\n public enum OperationStatus\n {\n Done,\n Pending,\n Reversed\n }\n\n public interface IParameter\n {\n }\n\n public interface IReversible\n {\n void Reverse ();\n }\n\n public interface IOperation<out T> where T : IParameter\n {\n bool GetParameterFromParentOperation { get; }\n\n OperationStatus Status { get; set; }\n\n T Execute (T parameter);\n\n T Execute ();\n }\n\n //[System.Diagnostics.DebuggerStepThroughAttribute()]\n public abstract class Operation<T> : IOperation<T> where T : IParameter\n {\n public T Parameter { get; private set; }\n\n public bool GetParameterFromParentOperation { get { return this.Parameter == null; } }\n\n public OperationStatus Status { get; set; }\n\n public Operation ()\n {\n Status = OperationStatus.Pending;\n }\n\n public Operation (T parameter)\n : this ()\n {\n this.Parameter = parameter;\n }\n\n public abstract T Execute ();\n\n public virtual T Execute (T parameter)\n {\n this.Parameter = parameter;\n return this.Execute ();\n }\n }\n\n public class Orchestrator<T> where T:IParameter\n {\n public List<IOperation<T>> Operations { get; private set; }\n\n public Orchestrator (params IOperation<T> [] operations)\n {\n this.Operations = new List<IOperation<T>> ();\n\n foreach (var item in operations)\n {\n this.Operations.Add (item);\n }\n }\n\n public T Run ()\n {\n T previousOperationResult = default (T);\n\n foreach (var operation in this.Operations)\n {\n try\n {\n if (operation.GetParameterFromParentOperation)\n previousOperationResult = operation.Execute (previousOperationResult);\n else \n previousOperationResult = operation.Execute ();\n\n operation.Status = OperationStatus.Done;\n }\n catch (Exception)\n {\n foreach (var o in this.Operations)\n {\n if (o is IReversible)\n {\n ((IReversible) o).Reverse ();\n o.Status = OperationStatus.Reversed;\n }\n else\n throw;\n }\n break;\n }\n }\n\n return previousOperationResult;\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T18:13:35.280",
"Id": "39432",
"Score": "0",
"body": "Thanks, but your code is not compiling. You can't do this: `T Execute(T parameter);`, setting the generic as a parameter type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T18:25:14.277",
"Id": "39434",
"Score": "0",
"body": "On the other hand, `IExecutableOperation<T>` or `IInternalOperation<T>` will be removed, thanks for noticing, their signature can be directly on `IOperation`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T18:38:02.297",
"Id": "39435",
"Score": "0",
"body": "Please explain me how can occur an `InvalidCastExceptions`, I don't see how can it happen, there's always a constraint clause to T to be a `IParameter`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T18:46:59.217",
"Id": "39436",
"Score": "0",
"body": "About: \"Orchestrator is coded forces you to do everything in the context of IParameter...\" It's that complex because of covariance, if you find any other way of doing it, let me know! Making non-generics operation would lead to a sort of anarchy when passing parameters between Operations, would be just `object` types and leave too much casting responsibility to concrete types."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T19:28:08.383",
"Id": "39443",
"Score": "0",
"body": "@Daniel How is `object` any worse than `IParameter`? And I think the amount of casting would be the same."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T20:10:27.757",
"Id": "39450",
"Score": "0",
"body": "@svick you're right, it would be the same actually (for `IParameter`, not for generic types as stands the item I replied). But I can't be sure parameter won't need a couple of common properties in the future, so let's just leave it there for a while. Thanks."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T17:56:35.437",
"Id": "25439",
"ParentId": "25435",
"Score": "2"
}
},
{
"body": "<p>First, some structural issues:</p>\n\n<ol>\n<li><p>I think the way you're using generics is completely wrong. The generic parameter <code>T</code> is almost useless <code>IInternalOperation<T></code> (since you're using <code>IParameter</code> there, not <code>T</code>). And if a class has a method <code>IParameter Execute(IParameter parameter)</code>, it means that method should accept any <code>IParameter</code>, which is not what you want.</p></li>\n<li><p><code>Orchestrator</code> works with <code>IParameter</code>, even if all the operations work with some specific subtype. I think <code>Orchestrator</code> should be generic too.</p></li>\n<li><p>Some of your operations don't work correctly if they are called with one overload of <code>Execute()</code>, the rest don't work correctly when called with the other overload. I think that you should have two different interfaces: one for the initial operation (with the parameterless overload of <code>Execute()</code>) and one for the rest of the operations (with the other overload). And <code>Orchestrator</code> should enforce this by taking a single initial operation and a collection of following operations.</p></li>\n<li><p>I think the marker interface <code>IParameter</code> is useless.</p></li>\n</ol>\n\n<p>With these modifications, your code could look something like:</p>\n\n<pre><code>public interface IOperationBase\n{\n OperationStatus Status { get; set; }\n}\n\npublic interface IOperation<T> : IOperationBase\n{\n void Execute(T parameter);\n}\n\npublic interface IInitialOperation<T> : IOperationBase\n{\n T Execute();\n}\n\npublic abstract class OperationBase<T> : IOperationBase\n{\n public T Parameter { get; protected set; }\n\n public OperationStatus Status { get; set; }\n\n protected OperationBase()\n {\n Status = OperationStatus.Pending;\n }\n}\n\npublic abstract class Operation<T> : OperationBase<T>, IOperation<T>\n{\n public void Execute(T parameter)\n {\n Parameter = parameter;\n ExecuteInternal();\n }\n\n protected abstract void ExecuteInternal();\n}\n\npublic abstract class InitialOperation<T> : OperationBase<T>, IInitialOperation<T>\n{\n protected InitialOperation(T parameter)\n {\n Parameter = parameter;\n }\n\n public abstract T Execute();\n}\n\npublic class Orchestrator<T>\n{\n public IInitialOperation<T> InitialOperation { get; private set; }\n\n public IOperation<T>[] Operations { get; private set; }\n\n public Orchestrator(\n IInitialOperation<T> initialOperation, params IOperation<T>[] operations)\n {\n InitialOperation = initialOperation;\n Operations = operations;\n }\n\n public T Run()\n {\n // omitted\n }\n}\n</code></pre>\n\n<p>One more thing regarding your implementation: the way you roll back the operations on exception doesn't make much sense to me. When rolling back, you usually:</p>\n\n<ul>\n<li>Roll back only the operations that actually succeeded (your code will try to roll back even operations that didn't actually run).</li>\n<li>Roll back the operations in reverse order: the last operation that ran first, the first operation last.</li>\n<li>Indicate to the caller that the whole operation failed. Either by rethrowing the exception after the rollback completes, or at least by returning <code>false</code> (and <code>true</code> on success).</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T20:54:12.040",
"Id": "39454",
"Score": "0",
"body": "About the roll backs, the only issue is to check if the operation was completed, and erroring out instead of the `break;` statement. I think the code already goes from the first to last operation to reverse. Thanks for the advice!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T20:59:15.643",
"Id": "39455",
"Score": "0",
"body": "Nice! I'll work a little on it, I'd like to remove that \"Initial Operation\" concept, will post back soon!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T21:39:18.013",
"Id": "39458",
"Score": "0",
"body": "Check the updated answer, I did a little modification in order to merge `IInitialOperation` and `IOperation`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T22:28:59.373",
"Id": "39465",
"Score": "0",
"body": "@Daniel Going from first to last is exactly the problem, I think it makes the most sense to go from last executed to first."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T04:11:21.440",
"Id": "39485",
"Score": "0",
"body": "Thanks, but in this case I have to undo the path in the order it was executed."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T20:31:33.837",
"Id": "25451",
"ParentId": "25435",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "25451",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T16:28:42.433",
"Id": "25435",
"Score": "3",
"Tags": [
"c#",
"design-patterns",
"generics",
"covariance"
],
"Title": "Sequential Execution: Orchestrator Pattern"
}
|
25435
|
<p>Below is the code I have written. I started yesterday with prime numbers and playing around with them. What the code does it determines the "prime gap" between primes numbers, prints them, then finds the gap between these numbers, prints, etc. It starts to create a very cool pattern <a href="https://math.stackexchange.com/questions/371434/has-anyone-found-a-pattern-in-prime-numbers">you can find some maths about it here</a> and see the pattern that it produces.</p>
<p>Anyways, I was wondering if there is a way to speed this puppy up!? I am not very good with optimization, this is probably my first Java optimization I've ever needed/wanted to do. </p>
<p>Originally I just hardcoded the first 150 primes into the program. Now I read the first 71k from a text file. I have been letting the implementation below run for about an hour and it has gotten to line 17. </p>
<p>The future of this I want to make a visualizer for this pattern. And figure out a way to scroll the TextArea over so it looks at the diagonal where the differences between numbers starts to breakdown to the pattern. If that made sense, probably not. Not much I say does.</p>
<pre><code>import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class PrimeSandbox
{
public static void main(String[] args) throws IOException
{
JTextArea screen = new JTextArea(5, 20);
Font font = new Font("Times New Roman", Font.BOLD, 8);
screen.setFont(font);
screen.setForeground(Color.BLUE);
JScrollPane scrollPane = new JScrollPane(screen);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(BorderLayout.CENTER, scrollPane);
//frame.pack();
frame.setLocation(0, 0);
frame.setSize(100, 100);
frame.setVisible(true);
frame.setAlwaysOnTop(true);
LinkedList<Integer> primesLL = new LinkedList<Integer>();
BufferedReader br = new BufferedReader(new FileReader("F:\\First100kPrimes.txt"));
try
{
String line = br.readLine();
while (line != null)
{
primesLL.add(Integer.decode(line));
line = br.readLine();
}
}
finally
{
br.close();
}
int lines = 0;
while(lines < 1000)
{
int size = primesLL.size();
LinkedList<Integer> tmp = new LinkedList<Integer>();
for(int i = 0; i < size; i++)
screen.append(" " + primesLL.get(i));
screen.append("\n");
screen.setCaretPosition(screen.getText().length());
for(int i = 0; i < size; i++)
{
if(i == 0)
tmp.add(0);
else
tmp.add(Math.abs(primesLL.get(i) - primesLL.get(i-1)));
}
primesLL.clear();
primesLL.addAll(tmp);
lines++;
//try {Thread.sleep(20);}
//catch(InterruptedException ex) {Thread.currentThread().interrupt();}
}
}
}
</code></pre>
<p><strong>EDIT:</strong> New code I've tried to optimize a little</p>
<pre><code>public class PrimeSandbox
{
public static void main(String[] args) throws IOException
{
JTextArea screen = new JTextArea(5, 20);
Font font = new Font("Times New Roman", Font.BOLD, 8);
screen.setFont(font);
screen.setForeground(Color.BLUE);
JScrollPane scrollPane = new JScrollPane(screen);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(BorderLayout.CENTER, scrollPane);
//frame.pack();
frame.setLocation(0, 0);
frame.setSize(100, 100);
frame.setVisible(true);
frame.setAlwaysOnTop(true);
LinkedList<Integer> primesLL = new LinkedList<Integer>();
BufferedReader br = new BufferedReader(new FileReader("F:\\First100kPrimes.txt"));
try
{
String line = br.readLine();
while (line != null)
{
primesLL.add(Integer.decode(line));
line = br.readLine();
}
}
finally
{
br.close();
}
int size = primesLL.size();
LinkedList<Integer> tmp = new LinkedList<Integer>();
for(int lines = 0; lines < 1000; lines++)
{
Arrays.toString(primesLL.toArray());
screen.append(Arrays.toString(primesLL.toArray()) + "\n");
screen.setCaretPosition(screen.getText().length());
tmp.add(0);
for(int i = 1; i < size; i++)
tmp.add(Math.abs(primesLL.get(i) - primesLL.get(i-1)));
primesLL.clear();
primesLL.addAll(tmp);
tmp.clear();
//try {Thread.sleep(20);}
//catch(InterruptedException ex) {Thread.currentThread().interrupt();}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Ok, so you do not need temporary List. You can change the code to reuse the same List, primesLL. Also I have changed the List to arrayList, since accessing elements by index is costly for LinkedList. Try this and see if it improves. </p>\n\n<pre><code>import java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.Font;\nimport java.io.BufferedReader;\nimport java.io.FileNotFoundException;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.LinkedList;\n\nimport javax.swing.JFrame;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTextArea;\n\npublic class PrimeSandbox \n{\n\npublic static void main(String[] args) throws IOException \n{\n JTextArea screen = new JTextArea(5, 20);\n Font font = new Font(\"Times New Roman\", Font.BOLD, 8);\n screen.setFont(font);\n screen.setForeground(Color.BLUE);\n JScrollPane scrollPane = new JScrollPane(screen); \n JFrame frame = new JFrame();\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setLayout(new BorderLayout());\n frame.add(BorderLayout.CENTER, scrollPane);\n //frame.pack();\n frame.setLocation(0, 0);\n frame.setSize(100, 100);\n frame.setVisible(true);\n frame.setAlwaysOnTop(true);\n\n ArrayList<Integer> primesLL = new ArrayList<Integer>();\n BufferedReader br = new BufferedReader(new FileReader(\"a.txt\"));\n try \n {\n String line = br.readLine();\n while (line != null) \n {\n primesLL.add(Integer.decode(line));\n line = br.readLine();\n }\n } \n finally \n {\n br.close();\n }\n\n int lines = 0;\n while(lines < 1000)\n {\n int size = primesLL.size();\n // LinkedList<Integer> tmp = new LinkedList<Integer>();\n\n for(int i = 0; i < size; i++)\n screen.append(\" \" + primesLL.get(i));\n screen.append(\"\\n\");\n screen.setCaretPosition(screen.getText().length());\n\n for(int i = size-1; i > 0; i--)\n {\n primesLL.set(i, Math.abs(primesLL.get(i) - primesLL.get(i-1)));\n }\n primesLL.set(0,0);\n // primesLL.clear();\n // primesLL.addAll(tmp);\n lines++;\n\n //try {Thread.sleep(20);}\n //catch(InterruptedException ex) {Thread.currentThread().interrupt();}\n }\n\n}\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T14:24:08.467",
"Id": "39524",
"Score": "0",
"body": "[primesLL.set(i, Math.abs(primesLL.get(i) - primesLL.get(i-1)));] This will cause an issue, on the first iteration you set element i to ([i]-[i-1]), then on the next iteration you set [i+1] = [i+1] - [i], and on our last iteration we changed [i], so [i+1] will be wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T17:45:55.947",
"Id": "39536",
"Score": "0",
"body": "No, that's why we are going backwards (take a look closely). you will set i with ([i]-[i-1]) and you no longer need the content of i, so the next iteration you set i-1 with [i-1]-[i-2] and you no longer need contents of i-1 and so on"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T08:33:48.470",
"Id": "25479",
"ParentId": "25436",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T16:45:52.360",
"Id": "25436",
"Score": "3",
"Tags": [
"java",
"optimization",
"primes",
"swing"
],
"Title": "Sierpinski gasket - patterns from primes"
}
|
25436
|
<p>I have a table with 'nested' inputs that need to be checked or unchecked when a button 'select all' is pressed. There are several levels that can be toggled with their respective 'select all' button. In my code I have a repetitive <code>.each()</code> statement where the second one tests if there are differing numbers of checked/unchecked inputs and if there are it overwrites what the first <code>.each()</code> statement did. How can I write the following code better?</p>
<pre><code>$(document).ready(function(){
$(".checkAll").click(function(e){
e.preventDefault();
var thisRow = $(this).parents("tr");
var thisRowNumber = parseInt(thisRow.attr("id").replace("row",""));
var thisLevel = parseInt(thisRow.children().first().attr("class").replace("textlevel",""));
var checked = 0;
var unchecked = 0;
$(".tablefull tr").each(function(){
if($(this).attr("class") !== "heading"){
r = parseInt($(this).attr("id").replace("row",""));
if(r > thisRowNumber){
n = parseInt($(this).children().first().attr("class").replace("textlevel",""));
if(n === thisLevel){
return false;
}
if(n > thisLevel){
$(this).find("input[name='ci_id']").prop("checked",function(index, oldAttr){
if(oldAttr){
checked++;
}
else {
unchecked++;
}
return !oldAttr;
});
}
}
}
});
if(checked > 0 && unchecked > 0){
$(".tablefull tr").each(function(){
if($(this).attr("class") !== "heading"){
r = parseInt($(this).attr("id").replace("row",""));
if(r > thisRowNumber){
n = parseInt($(this).children().first().attr("class").replace("textlevel",""));
if(n === thisLevel){
return false;
}
if(n > thisLevel){
$(this).find("input[name='ci_id']").prop("checked",true);
}
}
}
});
}
});
});
</code></pre>
<p>here's the working code in a fiddle: <a href="http://jsfiddle.net/KnU4X/1/" rel="nofollow">http://jsfiddle.net/KnU4X/1/</a></p>
<p>here's the code without my lengthy fix in a fiddle: <a href="http://jsfiddle.net/KnU4X/2/" rel="nofollow">http://jsfiddle.net/KnU4X/2/</a></p>
<p>To see the problem, click 'select all' with level 1, then 'select all' with level 2, then 'select all' with level 1 again. You will notice it unchecks everything except the level 2 which becomes checked.</p>
<p>Is there a way to remove all that seemingly redundant code and keep that functionality?</p>
|
[] |
[
{
"body": "<p>In general, you would have an easier time doing this if your \"nested rows\" were <em>actually</em> nested. However - that leads to a variety of other layout problems, etc.</p>\n\n<p>That said - here is a simpler way to accomplish what I think you're looking for:</p>\n\n<p><strong>jQuery code</strong>:</p>\n\n<pre><code>$(\".checkAll\").click(function (e) {\n e.preventDefault();\n\n // Find the row whose button was clicked.\n var $row = $(this).closest('tr');\n\n // Capture the associated \"level\" class.\n var cls = $row.children('td:first-child').attr('class');\n\n // Create a collection of rows, in which you can store the child-rows\n var $children = $row;\n\n // Start with the next row, and...\n var $current = $row.next();\n\n // ... for every subsequent row which is *not* on the same level as the\n // one you started with...\n while ($current.length && ($current.children('td:first-child').attr('class') !== cls)) {\n // Add the row to the collection.\n $children = $children.add($current);\n // Then move on to the next row.\n $current = $current.next();\n }\n\n // Capture all of the *checkboxes* within the matching rows\n var $checks = $($children).find('input[type=\"checkbox\"]');\n\n // If ALL checkboxes are checked, uncheck them.\n // Otherwise, check them all.\n if ($checks.length == $checks.filter(':checked').length)\n $checks.prop('checked', false);\n else\n $checks.prop('checked', true);\n});\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/TroyAlford/KnU4X/4/\" rel=\"nofollow\">Here is a working jsFiddle</a> showing the code in-action.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T18:48:26.823",
"Id": "25441",
"ParentId": "25440",
"Score": "2"
}
},
{
"body": "<p>Interesting scenario.</p>\n\n<p>First an foremost, you're making it harder for yourself by relying on the class name. This forced you to parse class name strings then parse the value to integers.</p>\n\n<p>Hence, I've simply added <code>data-level</code> attributes for each <code><tr></code>, signifying their levels. Now you have a value which you do not need to parse.</p>\n\n<p>That is all I've changed in the HTML (which probably means now your HTML has redundant things you can remove, I'll leave that to you)</p>\n\n<p>Next, is the script. Without the need to parse strings and values, you can focus on the logic. IMHO, the code logic is now much more readable and less distracting by all the string/value parsing you've been doing.</p>\n\n<p><strong>DEMO</strong>: <a href=\"http://jsfiddle.net/terryyounghk/vdEe8/\" rel=\"nofollow\">http://jsfiddle.net/terryyounghk/vdEe8/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T18:49:54.863",
"Id": "25442",
"ParentId": "25440",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "25441",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T18:27:04.543",
"Id": "25440",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "jquery checking nested input with repetitive code"
}
|
25440
|
<p>My goal is to have a reusable pattern for doing concurrent stream-processing in Go. </p>
<ul>
<li>The stream has to be closable from any node. </li>
<li>Errors should cleanly close the stream and forward the error to the consumer.</li>
<li>Should have a nice API</li>
</ul>
<p>Here's what I came up with: <a href="http://play.golang.org/p/DSIPmKiAst" rel="nofollow">http://play.golang.org/p/DSIPmKiAst</a></p>
<pre><code>package main
import (
"errors"
"log"
)
type Item struct {
val string
err error
}
type Stream struct {
in chan Item
close chan bool
}
func (s Stream) Close() {
// send the close signal
s.close <- true
// drain any remaining Item's from the stream
for _ = range s.in {
}
}
func NewWordStream(words []string) Stream {
s := Stream{make(chan Item), make(chan bool)}
go func() {
loop:
for _, w := range words {
select {
// if we get a close signal, break the loop and close the channel
case <-s.close:
break loop
// wrap the word in an Item and send it on the channel
case s.in <- Item{w, nil}:
continue
}
}
close(s.in)
}()
return s
}
func (s Stream) Map(fn func(string) (string, error)) Stream {
out := make(chan Item)
go func() {
erroring := false
for item := range s.in {
// ignore all items while erroring
if erroring {
continue
}
// if Item is an error, forward it, and start erroring
if item.err != nil {
erroring = true
out <- item
continue
}
// run the transformation function
val, err := fn(item.val)
// if the transformation returns an error, forward it and start erroring
if err != nil {
erroring = true
out <- Item{"", err}
continue
}
// everything went ok, forwarding transformed string
out <- Item{val, nil}
}
close(out)
}()
return Stream{out, s.close}
}
func (s Stream) Do(fn func(string) error) error {
var err error
for item := range s.in {
// when an error Item is recieved, save the error and close the stream
if item.err != nil {
err = item.err
s.Close()
continue
}
// otherwise invoke the callback with the item
if e := fn(item.val); e != nil {
err = e
s.Close()
continue
}
}
return err
}
func main() {
// stream items
words := []string{"this", "is", "pretty", "cool", "1", "2", "3"}
// producer
stream := NewWordStream(words)
// transformation function
wrap := func(s string) (string, error) {
if s == "cool" {
return "", errors.New("not cool")
}
return "<" + s + ">", nil
}
// consumer
show := func(w string) error {
log.Print(w, " ")
return nil
}
// do it!
if err := stream.Map(wrap).Do(show); err != nil {
log.Fatalf("Error: %s", err)
}
}
</code></pre>
<p>It'd appreciate any criticisms and suggestions for improvement. </p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T19:49:04.850",
"Id": "25447",
"Score": "2",
"Tags": [
"api",
"go",
"stream"
],
"Title": "Stream-chaining"
}
|
25447
|
<p>A few months ago, I wrote a query selector that seems to outperform the query selectors in the popular GP libraries by a pretty hefty margin. I'm wondering if I overlooked something. It seems odd that with all the manpower behind these other projects. It's this easy to come up with something that outperforms them.</p>
<p>The "trick" behind it is instead of parsing the query string every time, it will cache each query as a series of commands ("command pattern") to avoid parsing it again. Note that the results aren't cached, just the series of commands to be performed to get the results.</p>
<p>There are also some minor optimizations. For example, I assume that there isn't more than one <code>head</code>, <code>title</code>, or <code>body</code> tag in the document.</p>
<p>This supports CSS1 only (tag name, class name, id), but I think adding features from later CSS-es shouldn't affect the performance of the current code much at all, thanks to the "command-caching" design.</p>
<p>Have I overlooked something important? Is this fast because it's failing to do something critical? Is there something inherently wrong with this design, or is it possible the GP library authors have simply not considered this sort of design?</p>
<pre><code>/**
A simple, fast query selector.
@fileOverview
*/
/**
Perform a simple query selection.
@param {String} query
@param {Node} root
Optional root node, defaults to qs.global.document.
@returns {Array|NodeList}
DOM nodes matching the query.
@namespace The root qs namespace.
*/
function qs(query, root) {
var doc = root ? root.ownerDocument || root :
(root = qs.global.document);
return qs.run(qs.cache[query] || qs.compile(query), {
root: root,
doc: doc
}).nodes;
}
/**
A reference to the global object.
@type Object
*/
qs.global = (function () {
return this || [eval][0]('this');
}());
/**
Holds command arrays, keyed by query string.
@type Object
*/
qs.cache = {};
/**
Various regexen.
@type Object
@private
*/
qs.rx = {
singletons: /^(?:body|head|title)$/i,
className: /\.[^\s\.#]+/g,
id: /#[^\s\.#]+/g,
tagName: /^[^\s\.#]+/g,
lTrim: /^\s\s*/,
rTrim: /\s\s*$/,
comma: /\s*,\s*/,
space: /\s+/
};
/**
Check whether a DOM node has a css class.
@param {Node} node
@param {String} className
@returns {Boolean} true if success, else false.
*/
qs.hasClass = function (node, className) {
return (' ' + node.className + ' ')
.indexOf(' ' + className + ' ') > -1;
};
/**
@param {String} text
@returns {String}
*/
qs.trim = function (text) {
return text.replace(qs.rx.lTrim, '').replace(qs.rx.rTrim, '');
};
/**
Check a DOM node against a qs.Compound object.
@param {Node} node
The DOM node to check.
@param {qs.Compound} compound
An object constructed by qs.Compound, or an equivalent object.
@returns {Boolean} true if success, else false.
*/
qs.check = function (node, compound) {
var className, i = -1;
if ((compound.tagName && (compound.tagName !== node.tagName)) ||
(compound.id && (compound.id !== node.id)) ||
(!compound.className)) {
return false;
}
while ((className = compound.className[++i])) {
if (!qs.hasClass(node, className)) {
return false;
}
}
return true;
};
/**
Create an array of commands, store it in the cache, and return it.
@param {String} queryString
@returns {Array}
qs.Command objects to run for this queryString.
*/
qs.compile = function (queryString) {
var result = [], query = new qs.Query(queryString),
selectors = query.compounds,
selector = selectors[0],
compound, prevChain, i = -1,
isLast, isSingleton;
/* If the normalized query is already cached, create a new
reference to the command array in the cache using this
version of the queryString as the key.
*/
if (qs.cache[query]) {
return (qs.cache[queryString] = qs.cache[query]);
}
// FIXME: handle groups of selectors (recursive qs call)
// if (selectors.length > 1) { }
prevChain = 0;
while ((compound = selector[++i])) {
isLast = i === selector.length - 1;
isSingleton = qs.rx.singletons.test(compound.tagName);
if (compound.id || isSingleton || isLast) {
result = result.concat(qs.compoundToChain(
compound, selector.slice(prevChain, i)
));
prevChain = i + 1;
}
}
return (qs.cache[queryString] = qs.cache[query] = result);
};
/**
Called by qs.compile. Creates an array of commands from a
qs.Compound object.
@param {qs.Compound} compound
@param {Array} ancestorChecks
@returns {Array}
Array of command objects.
*/
qs.compoundToChain = function (compound, ancestorChecks) {
var result = [], hasId, hasAncestorChecks, className;
compound = compound.copy();
if (qs.rx.singletons.test(compound.tagName)) {
result.push({
fn: qs.cmd.getByTag,
args: [compound.tagName, true]
});
compound.tagName = false;
}
else if (compound.id) {
result.push({
fn: qs.cmd.getById,
args: [compound.id]
});
hasId = true;
compound.id = false;
}
else if (compound.className[0]) {
className = compound.className.shift();
result.push({
fn: qs.cmd.getByClass,
args: [className]
});
}
else if (compound.tagName) {
result.push({
fn: qs.cmd.getByTag,
args: [compound.tagName]
});
compound.tagName = false;
}
if (compound.id || compound.tagName ||
(compound.className && compound.className[0])) {
result.push({
fn: qs.cmd.filter,
args: [compound]
});
}
if (ancestorChecks.length) {
result.push({
fn: qs.cmd.checkAncestors,
args: ancestorChecks
});
hasAncestorChecks = true;
}
if (hasId) {
result.push({
fn: qs.cmd.checkIdRoot
});
}
return result;
};
/**
Run a set of commands in a given context.
@param {Array} commands
List of commands to run.
@param {Object} context
Shared object referenced by `this` in each command.
@returns {Object} context.
*/
qs.run = function (commands, context) {
var command, i = -1;
if (!context) {
context = {};
}
while ((command = commands[++i])) {
if (command.fn.apply(context, command.args)) {
return context;
}
}
return context;
};
/**
@namespace
Predefined commands for manipulating a collection of DOM nodes.
@description
*/
qs.cmd = {
/**
Get an element by id from the context document,
and set the context nodes to an array containing the result,
or an empty array.
@param {String} id
@return {Boolean}
true if no more commands should be processed, else false.
*/
getById: function (id) { // getById
var e = this.doc.getElementById(id);
this.nodes = e ? [e] : [];
return !e;
},
/**
Get a NodeList by class name from the context root,
and set the context nodes to the result.
@param {String} className
@return {Boolean}
true if no more commands should be processed, else false.
*/
getByClass: function (className) { // getByClass
this.nodes = this.root.getElementsByClassName(className);
return !this.nodes.length;
},
/**
Get a NodeList by tag name from the context root,
and set the context nodes to the result.
@param {String} tagName
@param {Boolean} setRoot
If true, set the context root to the first found node.
@return {Boolean}
true if no more commands should be processed, else false.
*/
getByTag: function (tagName, setRoot) { // getByTag
this.nodes = this.root.getElementsByTagName(tagName);
if (setRoot) {
this.root = this.nodes[0];
}
return !this.nodes.length;
},
/**
Filter the context nodes.
@param {qs.Compound} compound
@return {Boolean}
true if no more commands should be processed, else false.
*/
filter: function (compound) { // filter
var nodes = this.nodes, node, i = -1, result = [];
while ((node = nodes[++i])) {
if (qs.check(node, compound)) {
result.push(node);
}
}
this.nodes = result;
return !result.length;
},
/**
Check whether the context nodes' ancestors match a chain of
compound selectors.
@param {qs.Compound} compound...
One argument for each ancestor in the chain. The "oldest"
ancestor should be the first argument, and the "youngest"
should be the last.
@return {Boolean}
true if no more commands should be processed, else false.
*/
checkAncestors: function (/*...*/) { // checkAncestors
var root = this.root, nodes = this.nodes, node, result = [],
check, len = arguments.length, checkIndex = len, i = -1,
ancestor, topAncestor;
while ((node = nodes[++i])) {
ancestor = node;
check = arguments[--checkIndex];
while ((ancestor = ancestor.parentNode) &&
(ancestor !== root)) {
if (!qs.check(ancestor, check)) {
continue;
}
check = arguments[--checkIndex];
if (checkIndex < 0) {
topAncestor = ancestor;
result.push(node);
break;
}
}
checkIndex = len;
}
this.topAncestor = topAncestor;
this.nodes = result;
return !result.length;
},
/**
Check whether the context node is contained by the root node.
This command should be run if the *getById* command has been run.
It should run after any *filter* or *checkAncestors* commands
immediately following each *getById* command.
@return {Boolean}
true if no more commands should be processed, else false.
*/
checkIdRoot: function () { // checkIdRoot
var root = this.root,
node = this.topAncestor || this.nodes[0];
if (!root.ownerDocument) {
root = this.nodes[0];
return false;
}
while ((node = node.parentNode)) {
if (node === root) {
root = this.nodes[0];
return false;
}
}
return true;
}
};
/**
@class
Stores a compound selector in object form.
@see <a href="http://www.w3.org/TR/selectors4/#structure">
Selectors Level 4: Structure and Terminology
</a>
@param {String} text
Normalized compound selector text.
*/
qs.Compound = function (text) {
/**
CSS class to match.
@type String
*/
this.className = (text.match(qs.rx.className) || [])
.join('').substring(1).split('.');
/**
Tag name to match.
@type String
*/
this.tagName = ((text.match(qs.rx.tagName) || [])[0] || '')
.toUpperCase();
/**
Id attribute to match.
@type String
*/
this.id = ((text.match(qs.rx.id) || [])[0] || '')
.substring(1);
this.className.sort();
};
qs.Compound.prototype = {
/**
Create a plain object copy of the current object.
@returns {Object}
*/
copy: function () {
return {
id: this.id,
className: this.className.slice(),
tagName: this.tagName
};
},
/**
Get the normalized version of the compound selector.
@returns {String}
The normalized compound selector.
*/
toString: function () {
return this.normalized ||
(this.normalized = this.tagName +
(this.id ? '#' + this.id : '') +
(this.className[0] ? '.' + this.className.join('.') : ''));
}
};
/**
@class
Stores information about a query selector.
@constructor
@param {String} text
Query selector text.
*/
qs.Query = function (text) {
var compoundStrings = text.split(qs.rx.comma),
compound, compounds, i = -1, j,
original = text;
while ((text = compoundStrings[++i])) {
compounds = qs.trim(text).split(qs.rx.space);
j = -1;
while ((compound = compounds[++j])) {
compounds[j] = new qs.Compound(compound);
}
compoundStrings[i] = compounds;
}
compounds = compoundStrings;
/**
The original (non-normalized) query string.
@type String
*/
this.original = original;
/**
Compound selectors composing the query.
@type Array
*/
this.compounds = compounds.sort();
/**
Normalized version of the query.
@type String
*/
this.normalized = '';
};
/**
Get the normalized version of the original query selector.
@returns {String}
The normalized query selector.
*/
qs.Query.prototype.toString = function () {
if (this.normalized) {
return this.normalized;
}
var compounds = this.compounds, selector, i = -1, result = '';
while ((selector = compounds[++i])) {
result += (i ? ', ' : '') + selector.join(' ');
}
return (this.normalized = result);
};
</code></pre>
<p>Usage should look just like jQuery's <code>$</code> query selector; just use <code>qs</code> instead of <code>$</code>.</p>
<p>Please let me know if I've overlooked something, or if there are further improvements that can be made.</p>
<p><a href="http://jsperf.com/jquery-vs-dojo-vs-mootools-dom/135" rel="nofollow">Performance test vs GP libraries</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T22:23:07.990",
"Id": "39462",
"Score": "1",
"body": "It could be that the addition of the succeeding CSS revisions could have made libraries perform more complex parsing and additional filtering. Some libraries also use the native [`querySelectorAll`](https://developer.mozilla.org/en-US/docs/DOM/Document.querySelectorAll) if supported by the browser, which is a lot slower than your normal \"gather and filter\" method. Try adding up to CSS3 and check the performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T22:24:33.853",
"Id": "39463",
"Score": "0",
"body": "@JosephtheDreamer the thing is, it shouldn't affect the performance of queries *without* CSS3 stuff significantly at all due to the design... you'd have alternate versions of `qs.compoundToChain` and `qs.check`, and you'd only use them if you found certain symbols in the selector, otherwise the execution path should be pretty much identical, other than one extra `if`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T22:26:26.143",
"Id": "39464",
"Score": "0",
"body": "as for the internal qSA, this does seem to be faster in many cases, which also confuses me. I may add features from CSS2 and beyond, but generally I'm of the mindset that you shouldn't need complex queries like that in a properly designed web app... 99% of the time, class names, ids, and tag names should be enough."
}
] |
[
{
"body": "<p>My 2 cents,</p>\n\n<ul>\n<li>Well commented</li>\n<li>Naming is never confusing</li>\n<li>Quite readable</li>\n</ul>\n\n<p>for my edification\n* why <code>[eval][0]('this')</code> instead of <code>eval('this')</code>, to trick lint?</p>\n\n<p>As far as I can tell, your library is fast because you optimized for the test case. You ought to generate a DOM structure with a thousand elements and query each one ( rendering your cache useless ), will your library still be faster? Most JavaScript authors cache the lookups for efficiency and will not repeat queries unless the DOM changed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-06T21:25:34.190",
"Id": "60564",
"Score": "0",
"body": "The `eval` indirection was supposed to be a more linter-friendly version of `(1,eval)('this')`, but I found out later that some browser got this style of eval indirection wrong. Don't remember which one, may be fixed by now. http://stackoverflow.com/questions/9642491/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-06T21:33:37.450",
"Id": "60565",
"Score": "1",
"body": "It's not really optimized for the test case in particular, but it is optimized for cases where people use the same selector over and over, reason being, that's the kind of code I see people write a lot. I've tried it with larger documents and even disabling the \"command cache,\" it still outperforms others, but not by ridiculous margins like the ones in this test."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-03T00:20:07.553",
"Id": "208122",
"Score": "0",
"body": "Instead of `eval('this')`, why not `Function('return this')()`?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-06T14:03:23.983",
"Id": "36778",
"ParentId": "25452",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T21:48:06.107",
"Id": "25452",
"Score": "8",
"Tags": [
"javascript",
"performance",
"dom",
"query-selector"
],
"Title": "Very fast query selector"
}
|
25452
|
<p>I have either created something beautiful or something monstrous, and I'm not really sure which, and I don't know where else to turn but here. What I've done:</p>
<pre><code>var MyObject = function(opts) {
//init code, set vals, runs when 'new MyObject()' is called
}
MyObject.prototype = (function() {
//private helper functions
//scoping is a pain, but doable
function myPrivateFunction() {}
return {
publicFunc1: function() { /* uses myPrivateFunction() */ }
, publicFunc2: function() { /* uses myPrivateFunction() */ }
};
})();
MyObject.prototype.publicFunc3 = function() {}
MyObject.prototype.publicFunc4 = function() {}
MyObject.prototype.publicFuncEtc = function() {}
</code></pre>
<p>To my surprise, this works, and takes care of a pretty significant problem of creating reusable private functions for various public functions. Of course, I have to do some scoping for the <code>this</code> object, but I feel it's a small price to pay for being able to use private reusable functions. I left the other functions on the outside to avoid having to deal with scoping.</p>
<p>My question is: <strong>is this a code smell?</strong> and as a corollary, <strong>is there a better way to do this?</strong></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T22:37:31.810",
"Id": "39466",
"Score": "1",
"body": "`publicFunc3` can't see `myPrivateFunction`... sort of smells. And of course privates don't have a `this`, which sort of defeats OO design. Why not just wrap the whole thing in a IIFE and put the private stuff inside?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T22:39:36.053",
"Id": "39467",
"Score": "0",
"body": "yes.. that's because it doesn't need to. is that bad?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T22:40:53.213",
"Id": "39468",
"Score": "0",
"body": "It's probably not good... someone else working with the code will probably assume all public \"methods\" have access to all \"private\" ones. Personally, I think not worrying about trying to make things private makes life a lot easier when dealing with languages with no concept of private ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T22:41:43.200",
"Id": "39469",
"Score": "0",
"body": "that's a fair point."
}
] |
[
{
"body": "<p>The commenters pretty much said it all:</p>\n\n<ul>\n<li><code>publicFunc3</code> can't see <code>myPrivateFunction</code> <- not good</li>\n<li><p>I would declare <code>function() { /* uses myPrivateFunction() */ }</code> as a private function and then just return a pointer to it:</p>\n\n<pre><code>MyObject.prototype = (function() {\n //private helper functions\n //scoping is a pain, but doable\n function myPrivateFunction() {}\n function myPrivateFunction2() {/* uses myPrivateFunction() */ }\n function myPrivateFunction3() {/* uses myPrivateFunction() */ }\n\n return {\n publicFunc1: myPrivateFunction2\n , publicFunc2: myPrivateFunction3\n };\n})();\n</code></pre></li>\n<li>I know there is a \"comma first\" movement out there, but it looks silly to me</li>\n</ul>\n\n<p>Other than that, this code does not look monstrous to me, if it works for you, then why not.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T17:22:23.987",
"Id": "78328",
"Score": "0",
"body": "you should try going comma-first for a bit ;)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T01:40:49.910",
"Id": "44927",
"ParentId": "25454",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T22:07:48.617",
"Id": "25454",
"Score": "5",
"Tags": [
"javascript",
"design-patterns"
],
"Title": "Possibly mixing prototype and module pattern"
}
|
25454
|
<p>This works as intended, but was wondering if there is a more efficient way of coding this.</p>
<pre><code>if (window.location.href.indexOf('/search/') >= 0) {
switch ($.cookie("Layout")) {
case "Poster":
$("link:first").attr("href", "../css/list.css");
break;
case "Description":
$("link:first").attr("href", "../css/desc.css");
}
$(function () {
$(".Poster").click(function () {
$("link:first").attr("href", "../css/list.css");
$.cookie("Movie_Layout", "Poster", {
expires: 365,
path: '/media/search',
secure: true
});
$('.content-genre, .searchresults').hide().delay(75).fadeIn(275);
window.scrollTo(0, 0);
});
$(".Description").click(function () {
$("link:first").attr("href", "../css/desc.css");
$.cookie("Movie_Layout", "Description", {
expires: 365,
path: '/media/search',
secure: true
});
$('.content-genre, .searchresults').hide().delay(75).fadeIn(275);
window.scrollTo(0, 0);
});
});
} else {
switch ($.cookie("Layout")) {
case "Poster":
$("link:first").attr("href", "css/list.css");
break;
case "Description":
$("link:first").attr("href", "css/desc.css");
}
$(function () {
$(".Poster").click(function () {
$("link:first").attr("href", "css/list.css");
$.cookie("Movie_Layout", "Poster", {
expires: 365,
path: '/media',
secure: true
});
$('.content-genre, .searchresults').hide().delay(75).fadeIn(275);
window.scrollTo(0, 0);
});
$(".Description").click(function () {
$("link:first").attr("href", "css/desc.css");
$.cookie("Movie_Layout", "Description", {
expires: 365,
path: '/media',
secure: true
});
$('.content-genre, .searchresults').hide().delay(75).fadeIn(275);
window.scrollTo(0, 0);
});
});
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T23:16:58.560",
"Id": "39473",
"Score": "0",
"body": "well i guess both, but i wouldn't want to compromise execution time so that it looks nicer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T23:18:13.153",
"Id": "39474",
"Score": "0",
"body": "Ack, sorry, I deleted my comment thinking you weren't allowed to comment with only 1 rep. I asked if by \"efficient\" you meant code complexity or execution time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T00:43:08.807",
"Id": "39477",
"Score": "0",
"body": "Just to verify, you are reading 2 cookies right? \"Layout\" and \"Movie_Layout\"?"
}
] |
[
{
"body": "<p>This seems a bit simpler (<em>in terms of code repeating</em>)</p>\n\n<pre><code>var Layout = {\n 'Poster': {\n href: 'css/list.css'\n },\n 'Description': {\n href: 'css/desc.css'\n }\n};\n\nfunction setLink(file, pathFix) {\n $('link:first').attr('href', pathFix + file);\n}\n\n$(function () {\n var currentPathFix = '',\n initialLayout = $.cookie(\"Layout\");\n if (window.location.href.indexOf('/search/') >= 0) {\n currentPathFix = '../';\n }\n setLink(Layout( initialLayout ), currentPathFix );\n $.each(Layout, function (key, item) {\n $('.' + key).click(function () {\n setLink(item.href, currentPathFix);\n $.cookie(\"Movie_Layout\", key, {\n expires: 365,\n path: '/media/search',\n secure: true\n });\n $('.content-genre, .searchresults').hide().delay(75).fadeIn(275);\n window.scrollTo(0, 0);\n });\n });\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T23:13:41.263",
"Id": "25456",
"ParentId": "25455",
"Score": "4"
}
},
{
"body": "<p>As far as I understand your code, it's some cookie-based layout selector which runs during the loading of the page. I might be wrong, but the following code runs on that assumption, since you are placing <code>document.ready</code> handlers in the code.</p>\n\n<p>General tips:</p>\n\n<ul>\n<li>In JS, the double quote (<code>\"</code>) and single quote (<code>'</code>) mean the same, but I recommend using the single quote since its cleaner.</li>\n</ul>\n\n<p>As for code related notes, it's in the comments:</p>\n\n<pre><code>//Code that accesses the DOM is safer inside the `documentReady` handler\n$(function () {\n\n //The first major redundancy is the entire code based on the presence\n //of the `/search/` keyword, we factor that out into a variable\n var search = location.href.indexOf('/search/') >= 0;\n\n //The first difference between the search and non-search blocks is the\n //existence of the leading `../`. The `../` exists only when search exists\n var prefix = search ? '../' : '';\n\n //I found out that whatever code that refers to Poster and Description\n //have the same stylesheet names. We put them into this object for further\n //convenience\n var css = {\n 'Poster': 'list.css',\n 'Description': 'desc.css'\n };\n\n //The next difference is the existence of `/search in the cookie path.\n //We also factor out the cookie config into a single varuable up here\n //so we can easily change values rather than change them down there.\n var cookieConfig = {\n expires: 365,\n secure: true,\n path : '/media' + (search ? '/search' : '')\n };\n\n //Common practice for jQuery users is to cache static elements, especially\n //when they are used in handlers. This avoids your code from having jQuery\n //find them every time. This practice is only true for static elements.\n //This is not applicable some cases, like for example, you want to check \n //their existence on the DOM on button click.\n var firstLink = $('link:first');\n var content_search = $('.content-genre, .searchresults');\n\n //With everything factored out of the operations, what is left is the\n //common parts of the separate blocks of code, which we merge into one\n function handle(what) {\n //here, we use `what` which indicates if we are referring to Poster\n //or description. We use it as the key to determine which stylesheet\n //to use, and the value of the cookie to store.\n firstLink.attr('href', prefix + 'css/' + css[what]);\n $.cookie('Movie_Layout', what, cookieConfig);\n content_search.hide().delay(75).fadeIn(275);\n window.scrollTo(0, 0);\n }\n\n //So here we apply our css on load. You can see how the separation of\n //the parts fit.\n firstLink.attr('href', prefix + 'css/' + css[$.cookie('Layout')]);\n\n //We add our handlers for each element that requires a handler. If `.Poster`\n //and `.Description` refer to multiple elements, we can do delegation, where\n //a single handler is attached to the parent, instead of to each target\n $('#postersNearestParent').on('click', '.Poster', function () {\n //In here we call handle, where we indicate which to operate\n handle.call(this, 'Poster');\n });\n\n $('#descriptionsNearestParent').on('click', '.Description', function () {\n handle.call(this, 'Description');\n });\n\n});\n</code></pre>\n\n<p>Here's how short the code is without the comments. Still understandable, no?:</p>\n\n<pre><code>$(function () {\n var search = location.href.indexOf('/search/') >= 0;\n var prefix = search ? '../' : '';\n var css = {\n 'Poster': 'list.css',\n 'Description': 'desc.css'\n };\n var cookieConfig = {\n expires: 365,\n secure: true,\n path: '/media' + (search ? '/search' : '')\n };\n var firstLink = $('link:first');\n var content_search = $('.content-genre, .searchresults');\n\n function handle(what) {\n firstLink.attr('href', prefix + 'css/' + css[what]);\n $.cookie('Movie_Layout', what, cookieConfig);\n content_search.hide().delay(75).fadeIn(275);\n window.scrollTo(0, 0);\n }\n\n firstLink.attr('href', prefix + 'css/' + css[$.cookie('Layout')]);\n\n $('#postersNearestParent').on('click', '.Poster', function () {\n handle.call(this, 'Poster');\n });\n\n $('#descriptionsNearestParent').on('click', '.Description', function () {\n handle.call(this, 'Description');\n });\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T11:30:02.090",
"Id": "39512",
"Score": "0",
"body": "Thank-you for such a detailed description of your code! I've tried implementing your code into my page, and while it correctly defines the css for the page, when I click either the .Poster, or .Description buttons, it will not change the stylesheet."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T11:31:19.457",
"Id": "39513",
"Score": "0",
"body": "Also, .Poster, and .Description are a single element on the page."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T16:25:04.303",
"Id": "39528",
"Score": "0",
"body": "@Jrags87 My sample code uses delegation approach. you can change back to the non-delegated approach by changing the selectors `$('#postersNearestParent').on('click', '.Poster', function () {...` to `$('.Poster').on('click', function () {...`. Same goes for `.Description`. It also uses the [`jQuery.on`](http://api.jquery.com/on/) method, which only existed on jQuery 1.7"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T01:32:59.117",
"Id": "25460",
"ParentId": "25455",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "25456",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T23:03:45.190",
"Id": "25455",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "Movie search layout tweaks with cookie persistence"
}
|
25455
|
<p>I am trying to create a treenode structure based on a database table for a Dungeons and Dragons character creation program I am working on. I have come up with an incredibly confusing way to do it, but I am wondering if anyone can give me some better ideas on how to do this more efficiently. I have a tables called subfeats and feats. Subfeats contains all feats from the table feats that have subfeats. Really, all I want to do is create a parent/child treenode structure for all feats and their subfeats. Here is my code:</p>
<pre><code>foreach (DataRow subrow in ds.subfeats.Rows)
{
subfeatSet.Add(Convert.ToString(subrow[ds.subfeats.Columns.IndexOf("subfeat")]));
}
foreach (DataRow row in ds.feat.Rows)
{
TreeNode newNode = new TreeNode(Convert.ToString(row[ds.feat.Columns.IndexOf("name")]));
if (subfeatSet.Contains(newNode.Text))
{
// Do Nothing.
}
else
{
treeviewFeatsFeats.Nodes.Add(newNode);
foreach (DataRow subrow in ds.subfeats.Rows)
{
if (Convert.ToString(subrow[ds.subfeats.Columns.IndexOf("feat")]).Equals(newNode.Text))
{
TreeNode subTreeNode = new TreeNode(Convert.ToString(subrow[ds.subfeats.Columns.IndexOf("subfeat")]));
newNode.Nodes.Add(subTreeNode);
foreach (DataRow subsubrow in ds.subfeats.Rows)
{
if (Convert.ToString(subsubrow[ds.subfeats.Columns.IndexOf("feat")]).Equals(subTreeNode.Text))
{
TreeNode subsubTreeNode = new TreeNode(Convert.ToString(subsubrow[ds.subfeats.Columns.IndexOf("subfeat")]));
subTreeNode.Nodes.Add(subsubTreeNode);
}
}
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I like the use of white space and indentation, makes the code easy to read.</p>\n\n<p>I would start using <code>var</code> for your variable declarations. It keeps the code cleaner, and easier for your eyes to scan.</p>\n\n<p>Remove the <code>// Do Nothing</code> if statements. It is redundant and adds extra lines of code that are unneeded. This should work:</p>\n\n<pre><code>if (!subfeatSet.Contains(newNode.Text))\n{\n treeviewFeatsFeats.Nodes.Add(newNode);\n foreach (DataRow subrow in ds.subfeats.Rows)\n {\n\n ...\n}\n</code></pre>\n\n<p>I would also learn about linq, you can clean up most of your loops with linq. I would also look into moving some of the inner loops out into their own function. Moving to a function would remove some duplication you have in your code too.</p>\n\n<pre><code>private void ProcessNode(TreeNode parent, DataSet ds)\n{\n var index = ds.subfeats.Columns.IndexOf(\"feat\");\n foreach (var treeNode in (\n from row in ds.subfeats.Rows \n let nodeName = Convert.ToString(row[index])\n where rows.Contains(nodeName)\n select new TreeNode(nodeName)))\n {\n ProcessNode(treeNode, rows);\n parent.Add(treeNode); \n }\n}\n</code></pre>\n\n<p>Now your function looks like this:</p>\n\n<pre><code>var index = ds.feat.Columns.IndexOf(\"name\");\nforeach (var treeNode in (\n from row in ds.feat.Rows,\n let nodeName = Convert.ToString(row[index])\n where rows.Contains(nodeName)\n select new TreeNode(nodeName)))\n{\n ProcessNode(treeNode, ds);\n}\n</code></pre>\n\n<p>This is a start. I'm not happy with having to pass DataSet into the functions, but without fully understanding the data structure, I can't think of another way of doing it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T14:09:39.683",
"Id": "39523",
"Score": "0",
"body": "I would suggest to replace the '//Do nothing' with a continue: if (subfeatSet.Contains(newNode.Text)) continue; You save an indentation level for the rest of the code and the code is more readable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T16:06:01.650",
"Id": "39527",
"Score": "0",
"body": "Personally I would take the indentation over continue in this case because its only one level. And also, in my final code, the if statement was actually combined into the linq statement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T16:31:26.910",
"Id": "39529",
"Score": "0",
"body": "Thanks for the help! LINQ definitely seems like the way to go."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T02:23:48.333",
"Id": "25462",
"ParentId": "25459",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "25462",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T01:32:44.330",
"Id": "25459",
"Score": "3",
"Tags": [
"c#"
],
"Title": "Dynamic Treenode Creation"
}
|
25459
|
<p>I need somebody to review and polish my GUI code for my very very simple chat client. I haven't built any of the server sockets, so I'll do that later, but for now I just want people to tell me how crap my code is and how I can make it better. I'll post the full code below, but keep in mind that it is built to be as simple as possible and that some of it (like the stupid username system) could be temporary.</p>
<p>Something I want to know is how I would get the <code>messageBox</code> to extend the whole screen up to the button. If you full screen your window, you'll see what I mean. </p>
<p>MainGUI:</p>
<pre><code>package coltGUI;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
public class MainGUI {
MainGUI mainGUI;
JFrame newFrame = new JFrame("Colt Chat v0.1");
JButton sendMessage;
JTextField messageBox;
JTextArea chatBox;
JTextField usernameChooser;
JFrame preFrame;
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
MainGUI mainGUI = new MainGUI();
mainGUI.preDisplay();
}
public void preDisplay() {
newFrame.setVisible(false);
preFrame = new JFrame("Choose your username!(Colt chat v0.1");
usernameChooser = new JTextField();
JLabel chooseUsernameLabel = new JLabel("Pick a username:");
JButton enterServer = new JButton("Enter Chat Server");
JPanel prePanel = new JPanel(new GridBagLayout());
GridBagConstraints preRight = new GridBagConstraints();
preRight.anchor = GridBagConstraints.EAST;
GridBagConstraints preLeft = new GridBagConstraints();
preLeft.anchor = GridBagConstraints.WEST;
preRight.weightx = 2.0;
preRight.fill = GridBagConstraints.HORIZONTAL;
preRight.gridwidth = GridBagConstraints.REMAINDER;
prePanel.add(chooseUsernameLabel, preLeft);
prePanel.add(usernameChooser, preRight);
preFrame.add(BorderLayout.CENTER, prePanel);
preFrame.add(BorderLayout.SOUTH, enterServer);
preFrame.setVisible(true);
preFrame.setSize(300, 300);
enterServer.addActionListener(new enterServerButtonListener());
}
public void display() {
newFrame.setVisible(true);
JPanel southPanel = new JPanel();
newFrame.add(BorderLayout.SOUTH, southPanel);
southPanel.setBackground(Color.BLUE);
southPanel.setLayout(new GridBagLayout());
messageBox = new JTextField(30);
sendMessage = new JButton("Send Message");
chatBox = new JTextArea();
chatBox.setEditable(false);
newFrame.add(new JScrollPane(chatBox), BorderLayout.CENTER);
chatBox.setLineWrap(true);
GridBagConstraints left = new GridBagConstraints();
left.anchor = GridBagConstraints.WEST;
GridBagConstraints right = new GridBagConstraints();
right.anchor = GridBagConstraints.EAST;
right.weightx = 2.0;
southPanel.add(messageBox, left);
southPanel.add(sendMessage, right);
chatBox.setFont(new Font("Serif", Font.PLAIN, 15));
sendMessage.addActionListener(new sendMessageButtonListener());
newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
newFrame.setSize(470, 300);
}
class sendMessageButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (messageBox.getText().length() < 1) {
// do nothing
} else if (messageBox.getText().equals(".clear")) {
chatBox.setText("Cleared all messages\n");
messageBox.setText("");
} else {
chatBox.append("<" + username + ">: " + messageBox.getText() + "\n");
messageBox.setText("");
}
}
}
String username;
class enterServerButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
username = usernameChooser.getText();
if (username.length() < 1) {System.out.println("No!"); }
else {
preFrame.setVisible(false);
display();
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Your code was mostly good. Starting from the top of the program and working down, I'll list my changes.</p>\n<ul>\n<li><p>I added a global string with the application name, since you used it in more than one place. Now, you only have one string to change when you want to change the version number.</p>\n</li>\n<li><p>I put the Swing GUI code in the Event Dispatch thread (EDT) in the main method.</p>\n</li>\n<li><p>In the <code>preDisplay</code> method, I added some insets to make the display look nicer. I moved the <code>setVisible</code> method to the end.</p>\n</li>\n<li><p>In the display method, I added a main <code>JPanel</code>. I added an anchor and fill, as well as weights, to the left and right <code>GridBagConstants</code>. I added weights, which is the first time I've had to do so in a <code>GridBagLayout</code>. I was amazed at how much weight I had to give the left GBC to make the field fill my 22" monitor. I rearranged lines to group the component method calls together. I find that makes troubleshooting easier.</p>\n</li>\n<li><p>I added a focus method call to the <code>messageBox</code> so that the cursor would stay there to make typing easier for the user. For some reason, I couldn't get the <code>messageBox</code> focus when the <code>JFrame</code> first comes up.</p>\n</li>\n</ul>\n\n<pre><code>package coltGUI;\n\nimport java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.Font;\nimport java.awt.GridBagConstraints;\nimport java.awt.GridBagLayout;\nimport java.awt.Insets;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTextArea;\nimport javax.swing.JTextField;\nimport javax.swing.SwingUtilities;\nimport javax.swing.UIManager;\n\npublic class MainGUI {\n\n String appName = "Colt Chat v0.1";\n MainGUI mainGUI;\n JFrame newFrame = new JFrame(appName);\n JButton sendMessage;\n JTextField messageBox;\n JTextArea chatBox;\n JTextField usernameChooser;\n JFrame preFrame;\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n try {\n UIManager.setLookAndFeel(UIManager\n .getSystemLookAndFeelClassName());\n } catch (Exception e) {\n e.printStackTrace();\n }\n MainGUI mainGUI = new MainGUI();\n mainGUI.preDisplay();\n }\n });\n }\n\n public void preDisplay() {\n newFrame.setVisible(false);\n preFrame = new JFrame(appName);\n usernameChooser = new JTextField(15);\n JLabel chooseUsernameLabel = new JLabel("Pick a username:");\n JButton enterServer = new JButton("Enter Chat Server");\n enterServer.addActionListener(new enterServerButtonListener());\n JPanel prePanel = new JPanel(new GridBagLayout());\n\n GridBagConstraints preRight = new GridBagConstraints();\n preRight.insets = new Insets(0, 0, 0, 10);\n preRight.anchor = GridBagConstraints.EAST;\n GridBagConstraints preLeft = new GridBagConstraints();\n preLeft.anchor = GridBagConstraints.WEST;\n preLeft.insets = new Insets(0, 10, 0, 10);\n // preRight.weightx = 2.0;\n preRight.fill = GridBagConstraints.HORIZONTAL;\n preRight.gridwidth = GridBagConstraints.REMAINDER;\n\n prePanel.add(chooseUsernameLabel, preLeft);\n prePanel.add(usernameChooser, preRight);\n preFrame.add(prePanel, BorderLayout.CENTER);\n preFrame.add(enterServer, BorderLayout.SOUTH);\n preFrame.setSize(300, 300);\n preFrame.setVisible(true);\n\n }\n\n public void display() {\n JPanel mainPanel = new JPanel();\n mainPanel.setLayout(new BorderLayout());\n\n JPanel southPanel = new JPanel();\n southPanel.setBackground(Color.BLUE);\n southPanel.setLayout(new GridBagLayout());\n\n messageBox = new JTextField(30);\n messageBox.requestFocusInWindow();\n\n sendMessage = new JButton("Send Message");\n sendMessage.addActionListener(new sendMessageButtonListener());\n\n chatBox = new JTextArea();\n chatBox.setEditable(false);\n chatBox.setFont(new Font("Serif", Font.PLAIN, 15));\n chatBox.setLineWrap(true);\n\n mainPanel.add(new JScrollPane(chatBox), BorderLayout.CENTER);\n\n GridBagConstraints left = new GridBagConstraints();\n left.anchor = GridBagConstraints.LINE_START;\n left.fill = GridBagConstraints.HORIZONTAL;\n left.weightx = 512.0D;\n left.weighty = 1.0D;\n\n GridBagConstraints right = new GridBagConstraints();\n right.insets = new Insets(0, 10, 0, 0);\n right.anchor = GridBagConstraints.LINE_END;\n right.fill = GridBagConstraints.NONE;\n right.weightx = 1.0D;\n right.weighty = 1.0D;\n\n southPanel.add(messageBox, left);\n southPanel.add(sendMessage, right);\n\n mainPanel.add(BorderLayout.SOUTH, southPanel);\n\n newFrame.add(mainPanel);\n newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n newFrame.setSize(470, 300);\n newFrame.setVisible(true);\n }\n\n class sendMessageButtonListener implements ActionListener {\n public void actionPerformed(ActionEvent event) {\n if (messageBox.getText().length() < 1) {\n // do nothing\n } else if (messageBox.getText().equals(".clear")) {\n chatBox.setText("Cleared all messages\\n");\n messageBox.setText("");\n } else {\n chatBox.append("<" + username + ">: " + messageBox.getText()\n + "\\n");\n messageBox.setText("");\n }\n messageBox.requestFocusInWindow();\n }\n }\n\n String username;\n\n class enterServerButtonListener implements ActionListener {\n public void actionPerformed(ActionEvent event) {\n username = usernameChooser.getText();\n if (username.length() < 1) {\n System.out.println("No!");\n } else {\n preFrame.setVisible(false);\n display();\n }\n }\n\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T00:38:52.270",
"Id": "39550",
"Score": "0",
"body": "Thanks for the great answer, I appreciate it. I do have one question, though. What are insets? I've seen them before, but I don't really understand."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T01:05:04.193",
"Id": "39552",
"Score": "0",
"body": "Insets are inside margins, measured in pixels. I usually separate my left labels from my right fields with 10 pixels of space. I'll also put some space between the rows."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-15T05:00:54.327",
"Id": "315654",
"Score": "0",
"body": "thx for the code...:)\nbut there's a problem. When I actually copy this it gives me an error on the package coltGUI.\nI'm using NetBeans. could u please help me out with this??"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-04-25T16:44:13.207",
"Id": "25500",
"ParentId": "25461",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "25500",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T01:45:33.963",
"Id": "25461",
"Score": "1",
"Tags": [
"java",
"swing",
"gui"
],
"Title": "Simple chat room Swing GUI"
}
|
25461
|
<p>Let's say I have a key 'messages' that is usually a list, but might be None, or might not be present. So these are all valid inputs:</p>
<pre><code>{
'date': 'tuesday',
'messages': None,
}
{
'date': 'tuesday',
'messages': ['a', 'b'],
}
{
'date': 'tuesday',
}
</code></pre>
<p>If I want to retrieve 'messages' from the input, and iterate over them, I need to do something like this:</p>
<pre><code>messages = d.get('messages', []) # Check for key existence
if messages is None: # Check if key is there, but None
messages = []
for message in messages:
do_something()
</code></pre>
<p>That seems a little verbose for Python - is there a simpler way to write that?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T08:32:02.767",
"Id": "39495",
"Score": "1",
"body": "Consider using a `collections.defaultdict`."
}
] |
[
{
"body": "<p>You have to check for the existence of 'messages' AND the content of 'messages'. It's the same thing you have, but I would write it as:</p>\n\n<pre><code>if 'messages' in d and d['messages'] is not None:\n for m in d['messages']:\n do_something(m)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T06:15:21.057",
"Id": "25469",
"ParentId": "25465",
"Score": "2"
}
},
{
"body": "<pre><code>for message in d.get('messages') or ():\n do_something()\n</code></pre>\n\n<ul>\n<li><code>get</code> returns <code>None</code> by default for missing keys.</li>\n<li><code>a or b</code> evaluates to <code>b</code> when <code>bool(a) == False</code>. An empty list and <code>None</code> are examples of values that are false in a boolean context.</li>\n<li>Note that you cannot use this trick if you intend to modify the possibly empty list that is already in the dict. I'm using <code>()</code> instead of <code>[]</code> to guard against such mistakes. Also, CPython caches the empty tuple, so using it is slightly faster than constructing an empty list.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T06:50:07.027",
"Id": "53029",
"Score": "4",
"body": "Rollback: someone edited this to `for message in d.get('messages', ()):`. That would not, however, work when the value is `None`, like in the first example."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T06:28:23.827",
"Id": "25470",
"ParentId": "25465",
"Score": "15"
}
},
{
"body": "<p>First of all, I'm no python guy and I always favor readability over one-liners. If this happens regularly I would implement a get method which will return the default value not only for missing keys, but also for empty (or what ever required) values.</p>\n\n<p>In addition to that you maybe should have a look at the method that is generating your dictionary. Maybe you can just unify the message parameter at the place you store it and so you don't have to take care of this later?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T08:27:51.727",
"Id": "25478",
"ParentId": "25465",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "25470",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T02:54:02.610",
"Id": "25465",
"Score": "15",
"Tags": [
"python",
"hash-map"
],
"Title": "Set a default if key not in a dictionary, *or* value is None"
}
|
25465
|
<p>I have the library that I have found to be very useful when creating dynamic content rich web applications. I call it DO.js. It allows me to create entire DOM structures inside of Javascript in a similar manner that HTML markup should look. Additionally, it does it all without writing any HTML strings. It uses a hierarchy of embedded functions and objects to create the DOM structure. Please see my site below for examples.</p>
<p>My question is, is this a good way of doing this? I can and I have (the website below is created in this fashion) created whole websites using this method. I made it so that I could easily load and display large amounts of data pulled via ajax and where each bit of data will have events and variables attached. Of course, this is hard and tacky to do using normal HTML.</p>
<p>I kinda created documentation for it. However, I am not very good with documentation(or writing in general.) </p>
<p>What should/could be done better? What would be the best programming practices in this case? Anykind of critique would be awesome.</p>
<p>Thanks </p>
<p><a href="http://hurdevan.com/#!Home/Projects/DO.js" rel="nofollow">http://hurdevan.com/#!Home/Projects/DO.js</a></p>
<p>Please note that the website does not work at all in IE due to a Hashbang.js bug. And, I don't care about IE. </p>
<p>Code Examples:</p>
<p>Simple Example</p>
<pre><code>with(DO.dom)
{
div({parentElement:document.body},
span(b('Hello World!'))
);
}
</code></pre>
<p>An example using events and such:</p>
<pre><code>var win = {};
with(DO.dom)
{
win.root = div({parentElement:document.body,style:'border:1px solid black;width:200px;height:200px;position:fixed;'},
win.bar = div({style:'height:20px;text-align:center;background-color:#333333;color:white;cursor:pointer;',
onmousedown:DO.Func(true,function(eve,winobj)
{
window.onmousemove = winobj.bar.onmousemove;
window.onmouseup = winobj.bar.onmouseup;
winobj.offsetX = winobj.root.offsetLeft - eve.x;
winobj.offsetY = winobj.root.offsetTop - eve.y;
winobj.activeDrag = true;
},win),
onmouseup:DO.Func(true,function(eve,winobj)
{
window.onmousemove = false;
window.onmouseup = false;
winobj.activeDrag = false;
},win),
onmousemove:DO.Func(true,function(eve,winobj)
{
if(!winobj.activeDrag)return false;
winobj.root.style.position="fixed";
winobj.root.style.left = (eve.x + winobj.offsetX)+"px";
winobj.root.style.top = (eve.y + winobj.offsetY)+"px";
},win)
},'Move Window'),
win.body = div(
div(b('First Name:'),
win.firstName = input({type:'text'})
),
div(b('Last Name:'),
win.lastName = input({type:'text'})
),
div(b('Email:'),
win.email = input({type:'text'})
),
input({type:'submit',onclick:DO.Func(function(winobj)
{
alert("First Name:"+winobj.firstName.value +"\n"+"Last Name:"+winobj.lastName.value +"\n"+"Email:"+winobj.email.value +"\n");
},win)}),
"This window was created with DO.dom"
)
);
}
</code></pre>
<p>Another example that allows the DOM structure to be child/parent aware.</p>
<pre><code>with(DO.dom)
{
var foo =div({parentElement:document.body},
div({nid:'inputElements';},
input({nid:'firstName'}),
input({nid:'lastName'}),
input({nid:'email'})
)
);
}
foo.inputElements.firstName.value = 'Hello';
foo.inputElements.lastName.value = 'Word';
foo.inputElements.email.value = 'hello@world.com';
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T09:25:41.210",
"Id": "39500",
"Score": "0",
"body": "Please include the code in your question, we shouldn't have to follow five different links to see it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T19:10:38.070",
"Id": "39541",
"Score": "0",
"body": "https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/with <- might wanna read that before anyone sees this ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T20:25:06.720",
"Id": "39544",
"Score": "0",
"body": "I agree. But I have never had any issue. Additionally, could make $ = DO.dom and do $.div($.b('hello world')); \nI have used both."
}
] |
[
{
"body": "<p>A more typical approach these days, if you <em>have to</em> create a lot of DOM objects in javascript, is to use a templating system, such as <a href=\"http://mustache.github.io/\" rel=\"nofollow\">Mustache</a> (see also <a href=\"http://icanhazjs.com/\" rel=\"nofollow\">iCanHazjs</a>), and thus translate javascript objects into HTML. \nThe advantages are <strong>readable javascript</strong> and <strong>optimised DOM object creation</strong>. The disadvantage of this vs. your library is that this doesn't deal with the event binding.</p>\n\n<p>Your library certainly seems powerful, but I would say that this might be very hard to read if you have are creating a lot of DOM objects.<br>\nWhat you'd end up with is a lot of .js code that essentially replicates an HTML document fragment, but with less readability. </p>\n\n<p>This is the advantage of using HTML templates; that you can read the HTML structure easily, but in the javascript code, you don't have more than a line or two of code that does the DOM element creation. Also, templating systems generally build DOM objects in an efficient manner.</p>\n\n<p>Also, I'd look into something like <a href=\"https://github.com/hafriedlander/jquery.entwine\" rel=\"nofollow\">jQuery entwine</a> as a possibility for easy-to-read event binding.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-27T17:47:48.217",
"Id": "39605",
"Score": "0",
"body": "Was this supposed to be a code review?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T10:56:12.893",
"Id": "39633",
"Score": "0",
"body": "Fair comment, I was answering too much on StackOverflow and hadn't adapted my answer style. I was answering the question here from OP: \"My question is, is this a good way of doing this?\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T19:27:15.963",
"Id": "39638",
"Score": "0",
"body": "Thanks for the answer. Readability can be a problem if said person did a sloppy job writing the code. It is definitely something that should not be abused. However, I believe use can be found when multiple elements have to later be readdressed(post creation) for updating.\n\nThe traditional methods of pulling elements from the dom are insufficient in large quantities. DO.dom allows for hundreds of elements to be organized in an object oriented fashion. This allows for smaller lookup time during runtime. \nOr, is there a better way of looking up tons of elements?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-27T11:46:24.647",
"Id": "25561",
"ParentId": "25475",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "25561",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T19:37:21.900",
"Id": "25475",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "DO.dom: Creating large DOM structures in Javascript"
}
|
25475
|
<p>I have a multi dimensional array like this:</p>
<pre><code>[0] =>
['batch_id'] => '1'
['some_stuff'] => 'values'
[0] =>
['unit_id'] => '12'
['some_stuff'] => 'values'
[1] =>
['unit_id'] => '41'
['some_stuff'] => 'values'
</code></pre>
<p>This comes from an external API, so I have no control over the original formatting of the array.</p>
<p>What would be the preferred (least overhead) way to take all the 'unit_id' and 'batch_id' fields, remove them from the group of values about the item, and assign that value to the item's key?</p>
<p>What I've tried (and works, but I want to find something cleaner):</p>
<pre><code>public function fixArray($batches) {
$batchfix = array();
foreach($batches as $batch) {
$unitfix = $array;
$batch_temp = $batch;
array_shift(array_shift($batch_temp)); // Get rid of id details
foreach($batch_temp as $unit)
$unittemp = $unit;
array_shift($unittemp);
$unitfix[$unit['unit_id']] = $unittemp;
$batchfix[$batch['batch_id']] = $batch;
}
return $batchfix;
}
</code></pre>
<p>Any suggestions?</p>
|
[] |
[
{
"body": "<p>I suppose the result you want to have is this:</p>\n\n<pre><code> Array\n (\n [1] => Array\n (\n [stuff] => values\n [units] => Array\n (\n [12] => Array\n (\n [stuff] => values\n )\n [41] => Array\n (\n [stuff] => values\n )\n )\n )\n )\n</code></pre>\n\n<p>In this case you can use the code:</p>\n\n<pre><code> public function fixArray($originalBatches) {\n $batches = array();\n foreach($originalBatches as $batch) {\n $units = array();\n $batch_id = $batch['batch_id'];\n unset($batch['batch_id']);\n foreach ($batch as $key => $value) {\n if (is_numeric($key) && !empty($value['unit_id'])) {\n $units[$value['unit_id']] = array_slice($value, 1);\n unset($batch[$key]);\n }\n }\n $batches[$batch_id] = array_merge($batch, array('units' => $units));\n }\n return $batches;\n }\n</code></pre>\n\n<p>Still the use of the 2 foreach is not a very good practice. You can change the code accordingly to use array_walk. This would be much faster.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T13:12:50.807",
"Id": "25477",
"ParentId": "25476",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-24T11:43:07.467",
"Id": "25476",
"Score": "1",
"Tags": [
"php",
"recursion"
],
"Title": "Assign value of nested array as array key"
}
|
25476
|
<p>I'm taking a scripting language course with no prior scripting language or Linux experience, though I've taken classes in VB, Java, and C++. Our first assignment is to write a script that will traverse the directory tree of the location the script is run from and rename the files according to some predetermined rules. In this case, directories are to have spaces, \", and any .hxx or .cxx extensions removed. Files get the same treatment except their extensions are changed to .h or .cpp respectively. Also, the script isn't supposed to actually change the file names, just produce a file with the commands to do so, mine are bash commands in the form of mv 'old file name' 'old_file_name'.</p>
<pre><code>#!/usr/bin/perl -w
use Cwd;
use File::Find;
use strict;
my $file = "output.txt";
my $dir = getcwd;
# Creates file to print output to, Die with error message if we can't open it
open my $fh, '>>', $file
or die "$file: $!\n";
# traverse the directory tree
find(\&process_files, $dir);
# creates a file of bash rename scripts
sub process_files
{
my $s1 = $_;
if (-f)
{
$s1 =~ s/\s/_/g;
$s1 =~ s/\"//g;
$s1 =~ s/\.cxx/\.cpp/g;
$s1 =~ s/\.hxx/\.h/g;
print $fh "mv '" , $_ , "' " , $s1 , "\n";
print "mv '" , $_ , "' " , $s1 , "\n";
}
if (-d)
{
$s1 =~ s/\s/_/g;
$s1 =~ s/\"//g;
$s1 =~ s/\.(cxx|hxx)//g;
print $fh "mv '" , $_ , "' " , $s1 , "\n";
print "mv '" , $_ , "' " , $s1 , "\n";
}
}
close $fh;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-27T11:54:45.537",
"Id": "39597",
"Score": "0",
"body": "Not what you were asking, but be aware of the linux command `rename` ([see here](http://en.wikipedia.org/wiki/Util-linux), or [here for windows](http://gnuwin32.sourceforge.net/packages/util-linux-ng.htm)) which allows you to rename files using perl regexes."
}
] |
[
{
"body": "<p>It seems correct to me except these lines:</p>\n\n<pre><code>$s1 =~ s/\\.cxx/\\.cpp/g;\n$s1 =~ s/\\.hxx/\\.h/g;\n$s1 =~ s/\\.(cxx|hxx)//g;\n</code></pre>\n\n<p>There're no needs to do the substitution <strong>g</strong> lobal and also you need to anchor the regex at the end:</p>\n\n<pre><code>$s1 =~ s/\\.cxx$/.cpp/;\n$s1 =~ s/\\.hxx$/.h/;\n$s1 =~ s/\\.(cxx|hxx)$//;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T09:15:01.323",
"Id": "25481",
"ParentId": "25480",
"Score": "3"
}
},
{
"body": "<p>This is a great script you have (special thanks for using <code>File::Find</code>)!</p>\n\n<p>There are a few, mostly stylistic issues I have with your code:</p>\n\n<h3><code>use warnings</code></h3>\n\n<p>I see you have the <code>-w</code> flag on the shebang line, but <code>use warnings</code> is more flexible. It has <em>lexical</em> scope, so you can deactivate warnings in a scope by <code>no warnings</code>, which sometimes is useful. In any way, it is a good habit to start.</p>\n\n<h3>The Unix Way: Writing Pluggable Programs</h3>\n\n<p>Much of the power of Unix comes from the little programs you can pipe together to transform data (see <a href=\"https://en.wikipedia.org/wiki/Unix_philosophy\" rel=\"nofollow\">Unix Philosophy</a>, esp <em>“Write Programs that work together”</em>). They all have in common that they accept input on STDIN, and (mostly) print to STDOUT. The user can then take that output and display it, write it to a file, or pass it to another program.</p>\n\n<p>However, you print to both a file (in append mode! tell me a scenario where that is useful, and <code>cat</code> can't help), and STDOUT. The latter is enough. If the user wants the output on the screen, he does</p>\n\n<pre><code>$ /path/to/script\n</code></pre>\n\n<p>If he wants it in a file</p>\n\n<pre><code>$ /path/to/script > output.sh\n</code></pre>\n\n<p>If he wants both, the <code>tee</code> command is useful:</p>\n\n<pre><code>$ /path/to/script | tee output.sh # option -a for append mode possible\n</code></pre>\n\n<p>Your script basically duplicates <code>tee</code> functionality, this is unneccessary.</p>\n\n<p>If you <em>want</em> the user to see certain output, regardless of output redirection, print to <code>STDERR</code> (this is what <code>warn</code> and <code>die</code> do).</p>\n\n<p>Your script starts searching in the current working directory. This is a good default, but giving a start dir as command line option would be really sweet:</p>\n\n<pre><code>$ /path/to/script ~/look/.here\n</code></pre>\n\n<p>All we need for that is</p>\n\n<pre><code>my $dir = @ARGV ? shift() : getcwd();\n</code></pre>\n\n<h3>Duplicate code? Consider refactoring.</h3>\n\n<p>I would write your <code>process_files</code> like</p>\n\n<pre><code>sub process_files {\n my $name = $_;\n # normalize name\n $name =~ s/\\s/_/g;\n $name =~ s/\"//g;\n # changes depending on type\n if (-f) {\n # normalize C++ extensions\n $name =~ s/\\.cxx\\z/.cpp/;\n $name =~ s/\\.hxx\\z/.h/;\n } elsif (-d) {\n # remove C++ extensions\n $name =~ s/\\.[ch]xx\\z//;\n } else {\n return; # unknown type? Ignore, leave sub\n }\n return if $name eq $_; # don't print mv command if there are no changes\n # common: print mv command\n print \"mv -T '$_' $name\\n\";\n}\n</code></pre>\n\n<p>It is a bit silly to refactor such little code, but I think it better conveys what we are doing. E.g. the name normalization is common. Inside the substitutions, I removed unneccessary escaping. The second half of a substitution has the semantics of a double-quoted string, so the period doesn't have to be escaped. As a personal preference, I tend to use <code>\\z</code> (end of string) rather than <code>$</code>, (end of… whatever, depends on regex flags).</p>\n\n<p>While you can pass multiple arguments to <code>print</code>, which will be concatenated automatically, you could also use the wonderful string interpolation Perl has—I find the above command more readable this way. Esp. when writing code that writes other code, clarity is a security feature.</p>\n\n<h3>Close</h3>\n\n<p>When a Perl process exits, remaining open filehandles are automatically closed. Lexical filehandles (as you are using), are closed as soon as their reference count drops to zero (i.e. when they go out of scope). So manual closing is generally useless except for following two cases:</p>\n\n<ul>\n<li>You're using exotic buffering, and want to flush the buffer before closing</li>\n<li>Your filehandle is actually connected to another process. The return value of <code>close</code> will indicate if the attached processed exited abnormaly.</li>\n</ul>\n\n<p>… of which none apply here.</p>\n\n<h3>“Funny edge cases to destroy your program” or: Non-Stylistic Problems</h3>\n\n<p>When we are already talking about security: If I were paranoid, I'd worry about filenames that contain single quotes, and other fun like semicolons, or <code>';rm -rf * ;</code>, which is a valid filename for Linux. To mitigate these issues, one could</p>\n\n<pre><code>use String::ShellQuote;\nmy $secure_orig_name = shell_quote $_;\nmy $secure_new_name = shell_quote $name;\nprint \"mv -T $secure_orig_name $secure_new_name\\n\";\n</code></pre>\n\n<p>but one could just as well assume that C++ source directories only contain sane filenames.</p>\n\n<p>The <code>-T</code> flag for <code>mv</code> uses the second argument as the target name. Otherwise, it will check if there is a directory with that name, and move the file there. E.g.</p>\n\n<pre><code># ./foo\n# ./bar/\n$ mv foo bar\n# ./bar/\n# ./bar/foo\n</code></pre>\n\n<p>but</p>\n\n<pre><code># ./foo\n# ./bar/\n$ mv -T foo bar\nmv: cannot overwrite directory `bar' with non-directory\n</code></pre>\n\n<p>which I'd rather prefer.</p>\n\n<p>But it still isn't perfect. What if we rename a directory, but also some of its contents? Then the resulting <code>mv</code> command will try to rename a file whose path doesn't exists any more. The solution is to use the <code>finddepth</code> function instead of <code>find</code>, to process the contents of a directory <em>before</em> the directory itself is passed to your callback.</p>\n\n<p>But it still won't work: <code>File::Find</code> will <code>chdir</code> into the currently inspected directory, so when we would run the <code>mv</code> commands, we'd be in the wrong working directory. But it's easy to sprinkle the code with <code>cd</code>s.</p>\n\n<pre><code>use Cwd qw/abs_path/\nmy $dir = abs_path($dir);\nmy $cwd = $dir;\n...;\nsub process_files {\n # Inject cd wherever neccessary\n my $abs_path = abs_path($File::Find::dir);\n if ($cwd ne $abs_path) {\n $cwd = $abs_path;\n my $secure_cwd = shell_quote $abs_path;\n print \"cd $secure_cwd\\n\";\n }\n ...;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T14:11:22.753",
"Id": "25492",
"ParentId": "25480",
"Score": "3"
}
},
{
"body": "<p>There is a book called Perl Best Practices by Damian Conway that suggests some things to change: </p>\n\n<p>Always use parentheses with functions (except builtins), even when they take no parameters: </p>\n\n<pre><code>my $dir = getcwd();\n</code></pre>\n\n<p>While / may be the historical standard, things like {} with natural matches are often better: </p>\n\n<pre><code> $name =~ s{\\s}{_}g;\n $name =~ s{\\\"}{}g;\n $name =~ s{[.]cxx\\z}{.cpp};\n $name =~ s{[.]hxx\\z}{.h};\n $name =~ s{[.](?:cxx|hxx)\\z}{};\n $name =~ s{[.][ch]xx\\z}{};\n</code></pre>\n\n<p>This also helps with Leaning Toothpick Syndrome, e.g. s/\\s/// -- where it can get confusing as to what is a delimiter, what is an escape character, and what is part of the pattern. Contrast with s{\\s}{/}. </p>\n\n<p>Use non-capturing parentheses (?:) rather than using () when just grouping. Of course in this case, you only need to alternate a single character. A character class is better for that than grouped alternation. Thus <code>[ch]xx</code> is better than <code>(?:cxx|hxx)</code></p>\n\n<p>If matching a single character, a character class like <code>[.]</code> is often more readable than an escaped character like <code>\\.</code></p>\n\n<p>I also followed M42's suggestions but used the more specific \\z (end of string) rather than the $ (end of line). </p>\n\n<p>Always use a FILEHANDLE with print statements. This avoids the accidental consumption of a variable as a file handle. E.g. </p>\n\n<pre><code>print STDOUT qq{mv -T '$original' $name\\n};\n</code></pre>\n\n<p>Obviously assumes that you assign $_ to $original and rename $s1 to $name. Assigning $_ before using it is one of Conway's things. It leads to more readable code if you pick a better name than $_ for the new variable. </p>\n\n<p>Use the more flexible qq{} over \"\", etc. </p>\n\n<p>Note: I don't take Conway as gospel. He likes half-cuddled else clauses and I prefer mine fully cuddled. And I dropped his mandatory regex modifiers msx (at least most of the time). But some of his ideas make sense on their own. I probably forgot some that would apply. It's been a while since I read the book. Anyway, following Conway will usually produce more readable and maintainable Perl code than just winging it. Even just reading Conway and thinking about what you want to incorporate can help. Perl has so many possible bad practices that it is easy to get committed to them before you realize their downfalls. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-12T22:14:15.833",
"Id": "66441",
"ParentId": "25480",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "25492",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T08:46:46.777",
"Id": "25480",
"Score": "1",
"Tags": [
"file-system",
"perl"
],
"Title": "Perl script to rename files in a directory tree"
}
|
25480
|
<p>We had a requirement to remove the port number from the <code>Request.Url.AbsoluteUr</code> <strong>i.e</strong></p>
<p><strong>Actual:</strong></p>
<blockquote>
<p><code>https://mysitename:443/Home/Index</code></p>
</blockquote>
<p><strong>Expected:</strong></p>
<blockquote>
<p><code>https://mysitename/Home/Index</code></p>
</blockquote>
<p>The code I used for this is</p>
<pre><code> string newUrl = context.Request.Url.AbsoluteUri.Replace(":" + context.Request.Url.Port, string.Empty);
</code></pre>
<p>This is working fine. but I'm eager to know is there any better way to do this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T11:28:59.540",
"Id": "39511",
"Score": "0",
"body": "What if you have URL like `https://mysitename:443/Home/Index:443`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T12:05:38.643",
"Id": "39515",
"Score": "0",
"body": "I believe Request.Url.AbsoluteUri return Url in the format mentioned above."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T12:57:29.160",
"Id": "39520",
"Score": "0",
"body": "It does, but if you have an URL where the port part is by chance repeated in the body of the URL, your code won't work correctly."
}
] |
[
{
"body": "<p>Use UriBuilder and set Port to -1</p>\n\n<pre><code>Uri oldUri = new Uri(\"http://myhost:443/Home/Index\");\nUriBuilder builder = new UriBuilder(oldUri);\nbuilder.Port = -1;\nUri newUri = builder.Uri;\n</code></pre>\n\n<p>In case you want to remove the port part only when it is default, e.g. 80 for <code>http</code> and 443 for <code>https</code>, use snippet below (credit goes to <a href=\"https://codereview.stackexchange.com/users/14423/chris\">Chris</a> for the idea)</p>\n\n<pre><code>static Uri RemovePortIfDefault(Uri uri) {\n if (uri.IsDefaultPort && uri.Port != -1) {\n UriBuilder builder = new UriBuilder(uri);\n builder.Port = -1;\n return builder.Uri;\n }\n else return uri;\n}\n</code></pre>\n\n<blockquote>\n <p>If the Port property is set to a value of -1, this indicates that the default port value for the protocol scheme will be used to connect to the host.</p>\n</blockquote>\n\n<p>See: <a href=\"https://msdn.microsoft.com/en-us/library/system.uribuilder.port(v=vs.110).aspx#Remarks\" rel=\"nofollow noreferrer\"><code>UriBuilder.Port Property</code></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-28T14:08:07.877",
"Id": "237295",
"Score": "1",
"body": "This will remove ANY port, not only 'default' 443 :( Chris's answer is much better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-01T11:38:14.323",
"Id": "237817",
"Score": "0",
"body": "@Dmitry Yes, that might be the case but also depends on what you need. If you follow the OP code, so my code just do exactly the same as OP code does, which is removing ANY port. However, if you want to just remove port number when it is the standard port number, so Chris answer is the correct one, though I cannot find anywhere in the document that it will always omit standard port number."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-13T12:36:26.613",
"Id": "368579",
"Score": "2",
"body": "You can use `if (uriBuilder.Uri.IsDefaultPort){uriBuilder.Port = -1;}` to only get rid of it when its default."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T11:28:44.840",
"Id": "25486",
"ParentId": "25485",
"Score": "15"
}
},
{
"body": "<p>I have witnessed the UriBuilder .port = -1 fix elsewhere. Frankly guys, it is a hack that really isn't a good production ready solution. </p>\n\n<p>The right solution here is to use UriBuilder as follows.</p>\n\n<pre><code>var uri = new UriBuilder(baseUri);\nstring newUrl = uri.Uri.ToString();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-24T20:54:30.740",
"Id": "129293",
"Score": "3",
"body": "I disagree. Setting the port to -1 to suppress it is well documented in the framework and should be considered production-ready. See MSDN: http://msdn.microsoft.com/en-us/library/system.uribuilder.port%28v=vs.100%29.aspx. Also, if you are passing a UriBuilder object around, the eventual user of it may want to call .ToString() on it rather than .Uri.ToString(), and that would again include the redundant port information."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-18T01:20:13.900",
"Id": "134517",
"Score": "0",
"body": "Agreed as well. The documentation does show it to be. Just wonder why on earth they wouldn't use a CONST value for that thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-18T17:17:55.177",
"Id": "134688",
"Score": "0",
"body": "Yeah, not sure why they didn't make a const or enum for that as they usually do."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-26T17:41:40.387",
"Id": "45427",
"ParentId": "25485",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "25486",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T10:58:34.807",
"Id": "25485",
"Score": "9",
"Tags": [
"c#",
"asp.net",
"asp.net-mvc-4",
"url"
],
"Title": "Truncate port number from absolute Uri"
}
|
25485
|
<p>I am currently trying to implement a very simple MVC framework as a way of helping me understand how they work. My base controller class has 2 properties, a model and a view. All controllers have a generic view class property however only certain controllers have a model. </p>
<p>I needed a way of obtaining the name of the child controller class in the base controller class so that in the constructor I can check to see if a model class exists and instantiate one if so. I think I have come up with a solution using late static binding. I do not fully understand the concept, but as far as I can tell, if used in a parent class the static keyword refers to the child class.</p>
<p>I also implemented a function className() in the controller class which uses the 'this' keyword to get the name of the current class. This function is then called with the static keyword resulting in the name of the child class being obtained.</p>
<p>Below is the code for the Controller class. All models are titled controllerName_model.</p>
<pre><code>/**
* Base controller class, creates a generic view class and a model class (if one exists for the child class) for the controller.
*/
class Controller
{
public $view;
public $model;
public function __construct()
{
//Create a new genereic view object
$this->view = new View();
//Use late static binding to get the name of the child class extending this base class
$name = static::className();
//Create the path to the related model (if it exists)
$path = 'models/' . $name . '_model.php';
//If the model exists then require the file and create a new model object and store in $this->model
if(file_exists($path)) {
require $path;
$modelName = $name . '_Model';
$this->model = new $modelName();
}
}
/**
* This class returns the name of each class that extends this base controller class. It is used in the
* constructor with late static binding to get the name of the child class so that a model can be created if one exists.
*/
public function className() {
return get_class($this);
}
}
</code></pre>
<p>As far as I can tell this method is working but I am not confident that it is correct or that it is the best way of doing this. If anyone knows of any other ways of doing this or can point out any flaws in this approach I would be extremely grateful. Thanks.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T12:29:39.080",
"Id": "39518",
"Score": "0",
"body": "`get_class($this);` But \"that in the constructor I can check to see if a model class exists and instantiate one if so\" makes no sense"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T14:26:10.510",
"Id": "39525",
"Score": "0",
"body": "Basically I need the name of the child controller within the main Controller class. Once I have the name of the controller I can then check if there is a related model class. The model classes are named the same as the controller but with _Model after the name, e.g. there is a controller class called Dashboard, and the corresponding model is Dashboard_Model. If the model exists I create a new model class and assign it to the $model property of the controller class."
}
] |
[
{
"body": "<p>Looks fine to me; though somethings to think about. Do you need to run get_class? Or might it be better to have a model variable in the child class</p>\n\n<pre><code>class Blog extends Controller\n{\n private $modelClass = 'Blog';\n}\n</code></pre>\n\n<p>The overhead of get_class might be small, but probably more than a variable; but this way also give you the ability of being able to use the same model with multiple controllers if you need to. Granted you could just inherit with the models too, but that would mean 2 includes instead of one.</p>\n\n<p>If you don't go that route, consider some validation, string tidying or consistency in your model/file names.</p>\n\n<pre><code>$path = 'models/' . $name . '_model.php';\n</code></pre>\n\n<p>will likely equal <code>Blog_model.php</code> but your class is <code>Blog_Model</code> see the mixing of cases; consider <code>Blog_Model.php</code> or doing a <code>strtolower($name)</code>. This might seem minor, but different Operating Systems handle case differently and I have been bitten by this exact issue.</p>\n\n<p>I noticed you are doing a <code>require</code> rather than a <code>require_once</code> which could lead you to have <code>cannot re-declare class</code> errors. if require_once isn't for you consider </p>\n\n<pre><code>if(!class_exists($modelName))\n</code></pre>\n\n<p>This might seems abstract at the moment, but when I came to upgrade an admin system for a custom CMS I found it really handy for the admin Controllers to wrap the frontend wesbites controllers, and adding a little checking could greatly increase your flexibility further down the road.</p>\n\n<p>If you haven't done already check out <code>__autoload</code> <a href=\"http://php.net/manual/en/language.oop5.autoload.php\" rel=\"nofollow\">http://php.net/manual/en/language.oop5.autoload.php</a> if might be more overhead, but it is just so handy I really miss it on legacy projects.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T15:43:52.270",
"Id": "25533",
"ParentId": "25488",
"Score": "1"
}
},
{
"body": "<p>First of all, none of <em>so-called</em> "mvc frameworks" in php actually implement MVC or any other MVC-inspired design pattern. Instead they attempt to mimic Rails (which is primarily a rapid prototyping framework).</p>\n<p>The other thing that you seem to be unaware of is that model in proper MVC is not a class or an object. Model is a layer, that contains all of the business logic. It is one of the two major layers in MVC. Other being the presentation layer, which contains view, controller, templates and some other types of structures.</p>\n<ul>\n<li>for more details on the subject: read <a href=\"http://martinfowler.com/eaaDev/uiArchs.html\" rel=\"nofollow noreferrer\">GUI Architectures</a> by <em>Martin Fowler</em>,</li>\n<li>to see how it might apply to PHP project, take a look at <a href=\"https://stackoverflow.com/a/5864000/727208\">this</a> answer.</li>\n</ul>\n<br>\n<h3>.. now the "review part"</h3>\n<ul>\n<li><p>avoid the use of <code>public</code> attributes for objects. This breaks the encapsulation. If you expect to extend the class, then instead you should use <code>protected</code> visibility.</p>\n</li>\n<li><p>constructors should not do any "work". If you put complicated logic in constructors, it makes it harder to test you code. Instead, if there is some code that must be executed before the instance is released in "general population", you should use builders or factories for that.</p>\n</li>\n<li><p>do not instantiate objects in the constructors. This too makes it harder to test or even recognize the source of bugs. Instead you should pass the required instance in the constructor. This practice is called "<a href=\"http://www.martinfowler.com/articles/injection.html\" rel=\"nofollow noreferrer\">dependency injection</a>"</p>\n</li>\n<li><p>if you read <a href=\"https://en.wikipedia.org/wiki/Model_view_controller\" rel=\"nofollow noreferrer\">wiki</a> article on MVC, you will notice, that loading class files is not one of controller's responsibilities. This task instead should be done by an autoloader. I would recommend for you to explore the use of <a href=\"http://php.net/manual/en/function.spl-autoload-register.php\" rel=\"nofollow noreferrer\"><code>spl_autload_register()</code></a>. For simplified implementation example you can take a look at <a href=\"https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md\" rel=\"nofollow noreferrer\">PSR-0</a> ... though, do not take it as gospel.</p>\n</li>\n</ul>\n<br>\n<h3>As for the application design ..</h3>\n<p>I already mentioned above, but lemme reiterate: the controllers in MVC have quite precise responsibilities. They handle the user input. In web applications every change in the site is a direct result of user's action.</p>\n<p>These controller alter the state of model layer, usually by employing services, which isolate the business logic from presentation layer. Controllers do not acquire data from model layer.</p>\n<p>That part is done by view instances. Each view instance is responsible for all of the UI logic in the page that you see (if it is sending HTML as response .. there are exceptions). It assembles the the response from multiple templates based on data that it acquired from model layer. The controller have almost no contact with views. The most that controllers do is alter the type of response that view produces (switching from html to json or xml).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T08:36:14.993",
"Id": "25609",
"ParentId": "25488",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T12:27:46.553",
"Id": "25488",
"Score": "2",
"Tags": [
"php",
"mvc"
],
"Title": "What is the best way to get the child class name for use in a parent class"
}
|
25488
|
A stream is a series of data elements (characters, bytes or complex packets) which can be accessed or made accessible in a serial fashion. Random access is not possible.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T12:31:21.637",
"Id": "25490",
"Score": "0",
"Tags": null,
"Title": null
}
|
25490
|
<p>Is there a better way to write the JS for this? I'm asking because I read from somewhere that using <code>.hover</code> isn't recommended. Also, if I move the mouse in and out of the box really fast, the box fades in and out the exact number of times I entered/left the box. How do I prevent this?</p>
<p><a href="http://jsfiddle.net/byB6L/55/" rel="nofollow noreferrer">jsFiddle</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(".project-mask").hover(
function() {
$(".thumbnail").fadeOut(300);
$(".description").fadeIn(300);
},
function() {
$(".thumbnail").fadeIn(300);
$(".description").fadeOut(300);
}
);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.project-mask { height:260px;position:relative;width:260px }
.thumbnail, .description { position:absolute;width:100% }</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<article class="project">
<div class="project-mask">
<div class="thumbnail">
<img src="http://dummyimage.com/260x260/000/fff" height="260" width="260" />
</div>
<div class="description">
<p>blah blah blah</p>
</div>
</div>
</article></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>This type of functionality is what <a href=\"http://api.jquery.com/hover/\" rel=\"nofollow\"><code>.hover()</code></a> was designed for. I wouldn't recommend using anything else. As far as avoiding building up a queue of events when hovering, jQuery has the <a href=\"http://api.jquery.com/stop/\" rel=\"nofollow\"><code>.stop()</code></a> method for that very reason.</p>\n\n<pre><code>$(\".project-mask\").hover(\n function() {\n $(\".thumbnail\").stop(true, true).fadeOut(300);\n $(\".description\").stop(true, true).fadeIn(300);\n },\n function() {\n $(\".thumbnail\").stop(true, true).fadeIn(300);\n $(\".description\").stop(true, true).fadeOut(300); \n }\n); \n</code></pre>\n\n<p>Here is a <a href=\"http://jsfiddle.net/bplumb/byB6L/56/\" rel=\"nofollow\"><strong>fiddle</strong></a> </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T15:24:27.323",
"Id": "25496",
"ParentId": "25491",
"Score": "1"
}
},
{
"body": "<p>This might work too. At least you should traverse!</p>\n\n<pre><code>$(\".project-mask\").hover(function() {\n $(this).find(\".thumbnail, .description\").stop(true, true).fadeToggle(300);\n}); \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T11:00:22.150",
"Id": "27193",
"ParentId": "25491",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "25496",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T13:02:45.777",
"Id": "25491",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"html",
"css"
],
"Title": ".hover() for fading effect"
}
|
25491
|
<p>I am achieving a hover state per continent through:</p>
<pre><code>var continentId =""
function getID(continentId){
jQuery.each(mapObject.mapData.paths, function(i, val) {
if (val.continent == continentId){
continentCodes[i] = "#3e9d01";
mapObject.series.regions[0].setValues(continentCodes);
}
});
}
function removeGetID(continentId){
jQuery.each(mapObject.mapData.paths, function(i, val) {
if (val.continent == continentId){
continentCodes[i] = "#128da7";
mapObject.series.regions[0].setValues(continentCodes);
}
});
}
//LIST COUNTRIES & CONTINENTS TEMP
jQuery('.continentLink').hover(function(e) {
continentId = this.id;
getID(continentId);
}, function(){
removeGetID(continentId);
});
</code></pre>
<p>Is there any way to shorten this so that I don't have to have multiple <code>each</code> statements? I'm really trying to learn to write efficient code.</p>
<p>Here's the full code if it helps: <a href="http://jsfiddle.net/dawidvdh/EpGep/10/" rel="nofollow">JSFIDDLE</a></p>
<pre><code>jQuery(function(){
//JSON MARKERS
var markers = [{latLng: [-34.033333300000000000, 23.066666700000040000], name: 'Knysna', info:'its got a lake...'},
{latLng: [-33.924868500000000000, 18.424055299999963000], name: 'Cape Town', info:'its nice...'}];
//JSON MARKERS
//JSON STYLING
var markerStyle = {initial: {fill: '#F8E23B',stroke: '#383f47'}};
var regionStyling = {initial: {fill: '#128da7'},hover: {fill: "#A0D1DC"}};
//JSON STYLING
//GLOBAL VARIABLES
var countryList = "", continentList = "";
var resultsDup = {};
var continentCodes = {};
//GLOBAL VARIABLES
//INIT MAP PLUGIN
jQuery('#world-map').vectorMap({
map: 'world_mill_en',
normalizeFunction: 'polynomial',
markerStyle:markerStyle,
regionStyle:regionStyling,
backgroundColor: '#383f47',
series: {regions: [{values: {},attribute: 'fill'}]},
markers: markers,
onRegionClick:function (event, code){
jQuery('#world-map').vectorMap('set', 'focus', code);
},
onMarkerClick: function(events, index){
jQuery('#infobox').html(markers[index].name);
}
});
//INIT MAP PLUGIN
var mapObject = jQuery('#world-map').vectorMap('get', 'mapObject');
//LIST COUNTRIES & CONTINENTS
jQuery.each(mapObject.mapData.paths, function(i, val) {
countryList += '<li><a id='+i+' class="countryLink">'+val.name+'</a></li>';
//remove duplicate continents
var resultsList = val.continent;
if (resultsDup[resultsList]) {
jQuery(this).remove();
}else{
resultsDup[resultsList] = true;
continentList += '<li><a id='+val.continent+' class="continentLink">'+val.continent+'</a></li>';
}
//remove duplicate continents
});
//display countries
jQuery('#countryList').html(countryList);
//display continents
jQuery('#continentList').html(continentList);
var continentId =""
function getID(continentId){
jQuery.each(mapObject.mapData.paths, function(i, val) {
if (val.continent == continentId){
continentCodes[i] = "#3e9d01";
mapObject.series.regions[0].setValues(continentCodes);
}
});
}
function removeGetID(continentId){
jQuery.each(mapObject.mapData.paths, function(i, val) {
if (val.continent == continentId){
continentCodes[i] = "#128da7";
mapObject.series.regions[0].setValues(continentCodes);
}
});
}
//LIST COUNTRIES & CONTINENTS TEMP
jQuery('.continentLink').hover(function(e) {
continentId = this.id;
getID(continentId);
}, function(){
removeGetID(continentId);
});
//Zoom to Country Function
jQuery('.countryLink').click(function(e) {
jQuery('#world-map').vectorMap('set', 'focus', this.id);
});
//Continent Hover function
});
</code></pre>
|
[] |
[
{
"body": "<p>You are looking to remove the copy pasted code, to make it more DRY.</p>\n\n<p>Beyond that, it seems that really whether you <code>getID</code> or <code>removeGetID</code>, you set a number of ID's and then update <code>mapObject</code>. Furthermore, it seems that you do not need to update mapObject within the loop, which is slow.</p>\n\n<p>I would counter-propose</p>\n\n<pre><code>var helpfullyNamedConstant1 = '#3e9d01';\nvar helpfullyNamedConstant2 = '#128da7';\n\nfunction setContinentCodes(continentId, continentCodesValue ){\n jQuery.each(mapObject.mapData.paths, function(i, val) {\n if (val.continent == continentId){\n continentCodes[i] = continentCodesValue ;\n }\n });\n mapObject.series.regions[0].setValues(continentCodes);\n}\n\njQuery('.continentLink').hover(function(e) {\n setContinentCodes(this.id, helpfullyNamedConstant1);\n}, function(){\n setContinentCodes(this.id, helpfullyNamedConstant2);\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T16:21:03.263",
"Id": "39227",
"ParentId": "25493",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "39227",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T14:15:46.523",
"Id": "25493",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "Jvector Map add/remove function shorten code"
}
|
25493
|
<p>I'm now developing an instant messaging system but I'm a little confused: I can't decide which approach I have to choose!</p>
<p>I want you to tell me what is good/bad with this programming approach. One friend of mine said it's difficult to read, but it works.</p>
<pre><code>/*! | (c) 2012, 2013 by Bellashh*/
/// <reference path="jquery-2.0.0-vsdoc.js" />
$(document).ready(function () {
var ChatProvider = {
"Friends": [],
"People": [],
"Conferences": [],
"UI": {},
"Utils": {
"functions": {
"alert": function (str) {
alert(str);
} /*ChatProvider.Utils.functions.alert*/ ,
"addFriend": function (friend) {
ChatProvider.Friends.push(friend);
alert(ChatProvider.Friends.pop().Names);
} /*ChatProvider.Utils.functions.addFriend*/ ,
} /*ChatProvider.Utils.functions*/ ,
"events": {} /*ChatProvider.Utils.events*/ ,
"settings": {
} /*ChatProvider.Utils.settings*/
}
} //var ChatProvider
ChatProvider.Utils.functions.addFriend({
"Names": "bellash"
});
}); //$(document).ready
</code></pre>
<p>P.S: for visibility sake, I added some space between line separating objects' properties.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T16:37:03.590",
"Id": "39530",
"Score": "0",
"body": "Quick question, from a user's (not developer's) point of view: How do we access `Friends`, `People` and `Conferences`? Do we get them through a function or do we access the arrays directly?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T18:34:17.903",
"Id": "39540",
"Score": "2",
"body": "Is this the real code you want reviewed, or some kind of example? I ask because `addFriend` pushes something onto the `Friends` array and then immediately pops it back off, which makes no sense, and the `alert` function seems contrived; it just wraps `window.alert`. In other words, it wouldn't do much good to review this code, as the code doesn't do anything useful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T11:23:34.020",
"Id": "39656",
"Score": "0",
"body": "Dagg It is only an example. But I wonder if this is the best approach of coding in javascript instead of creating(bubling) separated functions in a .js file, my approach is good because it avoids conflicts between js file: am I wrong ?\n@JosephtheDreamer for example, to access the Friends array, you just need to write ChatProvider.Friends[index] ..."
}
] |
[
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li>drop <code>functions</code>, it is too long and it's obvious that <code>alert</code> in <code>ChatProvider.utils.alert()</code> is a function. Furthermore, specifically for <code>alert</code>, that should be under <code>UI</code> in my mind</li>\n<li>Your functions are all over the place, I would think that adding a friend would be <code>ChatProvider.friends.add()</code> but you put it in <code>ChatProvider.Utils.functions.addFriend()</code></li>\n<li>You treat your object as 1 singleton, what if you need more than 1 instance ?</li>\n<li>Maybe you are from a Java background, but namespacing the way you approach it should be avoided</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T18:02:15.297",
"Id": "42685",
"ParentId": "25495",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "42685",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T15:13:47.863",
"Id": "25495",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "Instant messaging system"
}
|
25495
|
<p>I create this class method to Enter Selected Items Form CheckboxList to associated resource I use ADO.net & store Proc to insert data can someone help me to improve it and make to so clean instead of my Hacks BTW I use Microsoft Enterprise Lib</p>
<pre><code>public static void Insert(List<int> listSkills, int rID)
{
var connection = ConfigurationManager.ConnectionStrings["SiteSqlServer"];
Database objDB = new SqlDatabase(connection.ConnectionString);
//int val = 0;
using (DbCommand cmd = objDB.GetStoredProcCommand("Insert_Skills_Resources"))
{
foreach (var s in listSkills)
{
try
{
objDB.AddInParameter(cmd, "@SkillID", DbType.Int32, s);
objDB.AddInParameter(cmd, "@ResourceID", DbType.Int32, rID);
objDB.ExecuteNonQuery(cmd);
cmd.Parameters.Clear();
}
catch (Exception ex)
{
throw ex;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T16:48:13.547",
"Id": "39531",
"Score": "0",
"body": "Any reason why you're not using some ORM?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T17:42:27.067",
"Id": "39535",
"Score": "0",
"body": "because I don't know how to use EF"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T08:06:46.287",
"Id": "39711",
"Score": "0",
"body": "@a_Elnajjar I updated my answer with some important info about the parameter name i.e. using `Database.BuildParameterName` to create it."
}
] |
[
{
"body": "<pre><code>catch (Exception ex)\n{\n throw ex;\n}\n</code></pre>\n\n<p>This code doesn't make any sense. If you want to rethrow an exception, use just <code>throw;</code>, so that the stack trace is not reset. But if that's all you do in your <code>catch</code> block, then there is no reason to use <code>try</code>-<code>catch</code>, you should just remove it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T16:50:47.073",
"Id": "25501",
"ParentId": "25497",
"Score": "1"
}
},
{
"body": "<p>If you are using the Enterprise Library it is often better to set up a default connection in the configuration file:</p>\n\n<pre><code><configuration>\n <configSections>\n <section name=\"dataConfiguration\" \n type=\"Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings,\n Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, \n Culture=neutral, PublicKeyToken=null\" \n requirePermission=\"false\"/>\n </configSections>\n\n <dataConfiguration defaultDatabase=\"SiteSqlServer\" />\n\n <!-- Rest of your settings here, including your SiteSqlServer connection string -->\n</configuration>\n</code></pre>\n\n<p>Now you don't need to look up the connection string - you can rely on the Enterprise library to get it for you:</p>\n\n<pre><code>public static void Insert(IEnumerble<int> skills, int resourceId)\n{\n // No dependency on SQL anymore - the connection string is found\n // from the dataConfiguration section in your config file. If you change\n // to another (supported) provider, you don't need to change this code.\n Database db = DatabaseFactory.CreateDatabase();\n\n // Add in your schema to the stored proc name (I've assumed dbo).\n using (var cmd = db.GetStoredProcCommand(\"dbo.Insert_Skills_Resources\"))\n {\n // This method populates the parameters collection of the DbCommand\n // by interrogating the database about the command.\n db.DiscoverParameters(cmd);\n\n // As the parameters are now known, we can just set the value of \n // them directly, no need specify direction or type etc.\n cmd.Parameters[\"ResourceID\"].Value = resourceId;\n\n foreach (var skill in skills)\n {\n cmd.Parameters[\"SkillID\"].Value = skill;\n db.ExecuteNonQuery(cmd);\n // Don't need to clear the parameters now.\n }\n // <Pointless try catch removed.>\n }\n} \n</code></pre>\n\n<p>EDIT:</p>\n\n<p>Sorry, it's been a year or more since I used the Enterprise Library I can't remember whether you need the @ at the start of the parameter name or not - it might be <code>cmd.Parameters[\"@SkillID\"]</code>.</p>\n\n<p>EDIT 2:</p>\n\n<p>I remembered why I couldn't remember if you need the @ or not (if that makes sense). You do need the @ BUT, you should use the <code>Database.BuildParameterName</code> method to create the parameter in the format the current provider expects - for sql server this is an @ symbol before the parameter name.</p>\n\n<p>This is how you should do it:</p>\n\n<pre><code>cmd.Parameters[db.BuildParameterName(\"ResourceID\")].Value = resourceId;\n</code></pre>\n\n<p>With this final correction the code is actually ignorant of the provider!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T10:07:55.657",
"Id": "25610",
"ParentId": "25497",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "25610",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T15:50:38.410",
"Id": "25497",
"Score": "1",
"Tags": [
"c#",
"asp.net"
],
"Title": "Insert Selected item in listbox using Ado.net and stor proc"
}
|
25497
|
<p>I have a simple Java model Class called Person which have a constructor that receives a JSONObject. In that constructor I get the values from the JSONObject and put in my instance variables. This is just a simple question but which way is best?</p>
<pre><code>public Person(JSONObject personJsonObject) {
// Without setter
this.name = personJsonObject.getString("name");
// With setter passing String
setName(personJsonObject.getString("name"));
// With setter passing JSONObject
setName(personJsonObject);
}
</code></pre>
<p>And when my setter isn't just a simple attribution but a evaluation, which one should I use?</p>
<pre><code>public Person(JSONObject personJsonObject) {
// Without setter
this.fullName = personJsonObject.getString("name") + personJsonObject.getString("lastName");
// With setter passing String
setFullName(personJsonObject.getString("name"), personJsonObject.getString("lastName"));
// With setter passing JSONObject
setFullName(personJsonObject);
// Or should I put this logic in the getFullName method? The caveat is if there is a huge calculation in the getter method. It wouldn't be efficient.
}
</code></pre>
<p>Thanks for your answer.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T17:58:19.950",
"Id": "39569",
"Score": "0",
"body": "This is a lot about your preference.\nWhat did you choose initially?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T18:02:13.267",
"Id": "39570",
"Score": "0",
"body": "If there is evaluation, I prefer your suggestion:\n`setFullName(personJsonObject);`\n\nIf you are going to evaluate, accept only what you need, unless it ruins the 'legibility' of the code."
}
] |
[
{
"body": "<p>If you have setter methods (<code>setName</code>, <code>setFullName</code>) in your class, then your constructor should call the setter methods.</p>\n\n<pre><code>setName(personJsonObject.getString(\"name\"));\n</code></pre>\n\n<p>If you don't have setter methods in your class (your class is immutable), then your constructor should perform the evaluation.</p>\n\n<pre><code>this.name = personJsonObject.getString(\"name\");\n</code></pre>\n\n<p>You should only pass to a method what it needs. In this case, your <code>setName</code> method takes a String as a parameter, which is what the method needs. If your method needs 3 or more values from the <code>personJsonObject</code> (arbitrary rule of mine), then you would pass the <code>personJsonObject</code> to the method.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T18:52:22.923",
"Id": "25505",
"ParentId": "25502",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "25505",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T17:07:55.313",
"Id": "25502",
"Score": "1",
"Tags": [
"java",
"constructor"
],
"Title": "Java constructor should use setter?"
}
|
25502
|
<p>This is a function I just wrote that tries to condense a set of strings into grouped lines. It actually works, but looks ugly. Is there a better way to achieve the same thing?</p>
<p><strong>Take 4</strong> <em>filtering empty strings first and dropping the <code>if line</code> on the final <code>yield</code></em></p>
<pre><code>def mergeToLines(strings, length=40, sep=" "):
strs = (st for st in sorted(strings, key=len, reverse=True) if st)
line = strs.next()
for s in strs:
if (len(line) + len(s) + len(sep)) >= length:
yield line
line = s
else:
line += sep + s
yield line
</code></pre>
<p>The idea is that it takes a bunch of strings, and combines them into lines about as long as <code>lineLength</code>. Each line has one or more of the original strings in it, but how many isn't clear until I actually get to slotting them in. Also, note that if a single entry in the list is longer than <code>lineLength</code>, it's still added as its own line (dropping elements is not an option here).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T06:36:57.987",
"Id": "39557",
"Score": "1",
"body": "In take 3, `if line:` is redundant unless you have empty strings in `strings`. If you do have empty strings, you probably should filter out all of them earlier on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T13:46:25.347",
"Id": "39576",
"Score": "0",
"body": "@JanneKarila - good point."
}
] |
[
{
"body": "<p><strong>RECURSIVE SOLUTION:</strong>\n<em>NOTE: it assumes that the input <code>strings</code> is already sorted. You could sort this at every call of the function, but this seems like unnecessary overhead.</em></p>\n\n<pre><code>def recursiveMerge(strings=[], current_line='', line_length=40, result=[]):\n \"\"\" Gather groups of strings into a line length of approx. 40 \"\"\"\n\n # base case\n if not strings:\n result.append(current_line)\n return result\n\n else:\n next_line = strings.pop(0)\n\n # if current_line + next_line < line_length, add them\n # otherwise append current_line to result\n if len(current_line + next_line) < line_length:\n current_line = ' '.join([current_line, next_line]).lstrip(' ') \n else:\n result.append(current_line)\n current_line = next_line\n\n # recursively call function\n return recursiveMerge(strings, current_line = current_line, result=result)\n</code></pre>\n\n<p><strong>ITERATIVE SOLUTION:</strong></p>\n\n<pre><code>def myMerge(strings, line_length=40, res=[]):\n \"\"\" Gather groups of strings into a line length of approx. 40 \"\"\"\n\n # sort the list of string by len\n strings = sorted(strings, key=len, reverse=True)\n\n # loop through the group of strings, until all have been used\n current_line = strings.pop(0)\n while strings:\n next_line = strings.pop(0)\n\n # if current_line + next_line shorter than line_length, add them\n # otherwise, append current_line to the result\n\n if len(current_line + next_line) < line_length:\n current_line = ' '.join([current_line, next_line])\n else:\n res.append(current_line)\n current_line = next_line\n\n # add any remaining lines to result \n res.append(current_line)\n\n return res\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T00:59:42.410",
"Id": "39551",
"Score": "1",
"body": "l_len should be line_length, no?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T23:04:40.167",
"Id": "25512",
"ParentId": "25508",
"Score": "3"
}
},
{
"body": "<p>Your code isn't so ugly, guys :) But I can write it better</p>\n\n<pre><code>def cool_merger(strings, line_len=40, sep=\" \"):\n ss = list(sorted(strings, key=len, reverse=True))\n return [line for line in [(lambda n, s: s if n+1 < len(ss) and (len(s) + len(ss[n+1]) >= line_len) else (ss.__setitem__(n+1, sep.join((str(ss[n]), str(ss[n+1]))))) if len(ss) > n+1 else ss[n] )(n, s) if len(s) < line_len else s for n, s in enumerate(ss)] if line != None]\n</code></pre>\n\n<p>(<em>joke</em>)</p>\n\n<p>By the way, works fast.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T00:19:54.530",
"Id": "39549",
"Score": "2",
"body": "+1 for it being crazy short! Very nice. Wouldn't want to be your team-mate who had to maintain it though :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T06:53:28.653",
"Id": "39558",
"Score": "0",
"body": "@NickBurns Thanks :) Surely it's written not for production but just for fun. Maintainability should be on the first place."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T23:49:33.950",
"Id": "25515",
"ParentId": "25508",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "25512",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T20:54:11.293",
"Id": "25508",
"Score": "4",
"Tags": [
"python",
"iteration"
],
"Title": "Python line condenser function"
}
|
25508
|
<p>This method allows for the execution of parameterized commands within a DAL class, and I tried to make it as reusable as possible. It works well but it feels a bit verbose to me. Is there a way to simplify this or is it good as is?</p>
<pre><code>/// <summary>
/// Retrieves records from the specified data source.
/// </summary>
/// <param name="query">The command to be executed.</param>
/// <param name="dataSrc">The data source to use for the command.</param>
/// <param name="parameters">Optional parameters for a parameterized command.</param>
/// <returns>A System.Data.DataTable containing the returned records.</returns>
public static DataTable GetRecords(string query, DelConnection dataSrc, params SqlParameter[] parameters)
{
if (query == "") throw new ArgumentException("No command provided.", "query");
string conString = Dal.GetConnectionString(dataSrc);
using (SqlConnection con = new SqlConnection(conString))
using (SqlCommand cmd = new SqlCommand(query, con))
{
// Add parameters to command
foreach (SqlParameter p in parameters)
{
cmd.Parameters.Add(p);
}
// Fill data table
DataTable data = new DataTable();
using (SqlDataAdapter adap = new SqlDataAdapter(cmd))
{
adap.Fill(data);
}
return data;
}
} //// End GetRecords()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T21:52:33.347",
"Id": "39546",
"Score": "1",
"body": "Is there a requirement to have to have parameters?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T22:14:26.120",
"Id": "39547",
"Score": "5",
"body": "Why are you returning `null` when the result is empty? It just makes the code that works with the result more complicated (it always has to check for `null`), more error prone (what if your forget to check for `null`?) and doesn't actually give you anything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T22:19:15.790",
"Id": "39548",
"Score": "0",
"body": "Not a requirement but definitely a possibility."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T13:25:00.430",
"Id": "39572",
"Score": "0",
"body": "What is a `DelConnection`? I can't find it on Google. Is it an enum like `Development`, `Test`, `Production` etc?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T13:28:53.260",
"Id": "39574",
"Score": "0",
"body": "@abuzittingillifirca: Yes, it's a custom enum that identifies the data source. The DAL is currently translating it into the underlying connection string."
}
] |
[
{
"body": "<p>Why is it static?</p>\n\n<p>First off, I would remove the check for no parameters. You've already checked that it is not null, if somebody passes in an empty list, the <code>foreach</code> for parameters will just be ignored.</p>\n\n<p>As svick said, I would not return a null value if no results are found. This complicates code on the calling side because you have to check for null before you work with it. Same principle as the parameters. If I have a <code>foreach</code> on an empty list, my code within the foreach would not be called.</p>\n\n<p>I would change <code>conString == \"\"</code> to <code>string.IsNullOrEmpty(constring)</code> I would do the same thing for query, because most people will pass an empty string before they pass a space string. If you think space will be a problem, do both.</p>\n\n<p>I would change this <code>DataTable data = new DataTable();</code> to use var <code>var data = new DataTable();</code> It makes the code easier to scan quickly.</p>\n\n<p>If you insist on returning null for empty sets, change <code>(data.Rows.Count > 0)</code> to <code>(data.Rows.Any())</code>. I think it makes the code much easier to read because it says exactly what you are looking for.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T23:19:49.683",
"Id": "25513",
"ParentId": "25509",
"Score": "2"
}
},
{
"body": "<p>I would suggest few improvements:</p>\n\n<ol>\n<li><strong>Validate all parameters as early as possible</strong>. In your method, the validation of <code>parameters</code> collection is not early enough. This is not really about performance because 99.9% of the time there should be no exception thrown, but it is about grouping the validation logic together</li>\n<li><strong>Make it an extension method</strong>. You can easily make this an extension method of <code>DelConnection</code> and then simplify your code at call site like <code>dataSrc.GetRecords(\"some query here\")</code></li>\n<li><strong>Consider return empty result instead of null value</strong>. Especially when you meant to return empty result. My rule of thumb is that <em>every method that returns some kind of collection should not return null at all</em>.</li>\n<li><strong>Using <code>params</code> instead of concrete-type collection</strong>. Instead of using <code>SqlParameterCollection</code>, you can use <code>params SqlParameter[] parameters</code> instead. This will make it more convenient to call this method.</li>\n</ol>\n\n<p>For the verbosity, your code is not verbose at all in my opinion. It is as short as it should be.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T13:33:09.343",
"Id": "39575",
"Score": "0",
"body": "Thanks to everyone for their input. I accepted tia's answer but really used bits from everyone's response. I'll update the question to show the changes I made."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T05:51:30.120",
"Id": "25518",
"ParentId": "25509",
"Score": "1"
}
},
{
"body": "<p>1: This method is public - are you expecting to use it outside of your Data Access Layer? The method signature includes a <code>SqlParameterCollection</code>... Now all of your calling code has to know that you're using SQL underneath.</p>\n\n<p>2: This code smells:</p>\n\n<pre><code>string conString = Dal.GetConnectionString(dataSrc);\nif (conString == \"\") throw new ArgumentException(\"Invalid connection source provided.\", \"dataSrc\");\n</code></pre>\n\n<p>You have a class called Dal responsible for getting connection strings. This seems like more of a configuration thing - I think the class should be renamed to something more descriptive.</p>\n\n<p>I also think that the GetConnectionString method should throw an exception if there isn't a connection string for the data source - it shouldn't be the responsibility of this method. </p>\n\n<p>3: As others have said, don't return null - return an empty collection for no results.</p>\n\n<p>4: Check for empty strings consistently. I.e. don't mix <code>== \"\"</code> and <code>string.IsNullOrWhiteSpace</code> - always use one of the methods on string.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T09:28:59.880",
"Id": "25519",
"ParentId": "25509",
"Score": "2"
}
},
{
"body": "<ol>\n<li>If you say that this method should be as reusable as possible then I assume that it will be used throughout the program. Then why it takes SqlParameterCollection parameter? All non DAL classes should not know such details. List(Of string, object) is enough for parameters.</li>\n<li>DelConnection parameter. Your DAL implementation should encapsulate all logic related to DB connections. So if you have one connection string than remove this parameter and acquire connection in this method directly. If you have multiple connection strings than your business layer classes should know only connection string names and pass it to your method. </li>\n<li>You use provider specific classes for connection and command. Why not use base classes (or interfaces) as DbConnection, DbCommand and specify DB provider in your connection string?</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T12:41:44.280",
"Id": "25527",
"ParentId": "25509",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "25518",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T21:11:03.633",
"Id": "25509",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Proper way to execute parameterized commands within a method"
}
|
25509
|
<p>original code example</p>
<pre><code>if (var1 == null) {
String msg = "var 1 is null";
logger.log(msg);
throw new CustomException(msg);
}
if (var2 == null) {
String msg = "var 2 is null";
logger.log(msg);
throw new CustomException(msg);
}
if (var3 == null) {
String msg = "var 3 is null";
logger.log(msg);
throw new CustomException(msg);
}
return var3.toString(); // ok
</code></pre>
<p>new code</p>
<pre><code>if (var1 == null) {
logMessageAndThrowException("var 1 is null");
}
if (var2 == null) {
logMessageAndThrowException("var 2 is null");
}
if (var3 == null) {
logMessageAndThrowException("var 3 is null");
}
return var3.toString(); // NetBeans warn me here for a NPE
void logMessageAndThrowException(String msg) throws CustomException {
logger.log(msg);
throw new CustomException(msg);
}
</code></pre>
<p>Is this a bad practice or NetBeans just are not able to understand the code?</p>
|
[] |
[
{
"body": "<p>The second version removes some duplication, so it's better, but usually you should choose one of logging and rethrowing. Frameworks/appservers usually catch and log uncatched exceptions so you will have two (or more) entries for the same exception it the log file which makes debugging hard.</p>\n\n<blockquote>\n <p>Log the exception only once!</p>\n \n <p>One of the common pain points that I have noticed is logging and\n rethrowing an exception. As a result, the log files contains the same\n exceptions several times on several stack levels.</p>\n</blockquote>\n\n<p>Author: <a href=\"https://softwareengineering.stackexchange.com/a/112625/36726\">Nayaki</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T11:17:20.537",
"Id": "39564",
"Score": "1",
"body": "youre right... the best thing is probably only throw the exception and let it be logged somewhere else"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T14:23:14.303",
"Id": "39578",
"Score": "0",
"body": "+1 for palacsint. First, in the spirit of \"separation of concerns\", have a separate entity for logging and another separate one for exception throwing. Also, the logging and message throwing invocation could be invoked from inside a loop with the argument's number as parameter."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T10:44:27.910",
"Id": "25522",
"ParentId": "25520",
"Score": "3"
}
},
{
"body": "<pre><code>if (var3 == null) {\n logMessageAndThrowException(\"var 3 is null\");\n}\nreturn var3.toString(); // NetBeans warn me here for a NPE\n</code></pre>\n\n<p>Netbeans probably does not look into the method. Netbeans does not know from the name, what a human will read. So Netbeans sees an if statement, no direct return or throw and assumes that it could happen to execute <code>return var3.toString();</code></p>\n\n<p>In general for arguments checking:</p>\n\n<ul>\n<li>I would avoid custom exceptions, use runtime exceptions</li>\n<li>I would only check arguments if they are used as a state variable for later usage. If not, it is completely fine to get a direct NullPointer exception. Because the results are the same: I will get a notice about the variable unexpectedly being null at the moment.</li>\n<li>I would use a wrapper/proxy method like:</li>\n</ul>\n\n<p>#</p>\n\n<pre><code>public static <T> T notNull(final T value) {\n if (value == null) //you could add more logic here, like logging\n throw new IllegalArgumentException(\"Value is null\");\n return value;\n}\npublic static <T> T notNull(final T value, final String message) {\n if (value == null)\n throw new IllegalArgumentException(\"Value is null, \" + message);\n return value;\n}\n</code></pre>\n\n<p>to write such code:</p>\n\n<pre><code>this.variable = notNull(variable);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-27T14:54:12.267",
"Id": "25563",
"ParentId": "25520",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "25522",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T09:56:23.773",
"Id": "25520",
"Score": "1",
"Tags": [
"java",
"logging"
],
"Title": "Encapsulating logging and throwing exceptions into a method. Bad practice?"
}
|
25520
|
<p>I have often read about how important clear and efficient code is. Also often people talk and write about 'beautiful' code. Some hints and critic from experienced developers for the following code would be extremely helpful to me. Another question that I often ask myself is about list comprehensions: I feel that in the first specific code (about prime palindromes), especially the second function that verifies palindrome characteristics could be expressed on one line in a list comprehension - how would that work, and would it even be an advantage of some sort?</p>
<p>The code calculates all the prime palindromes from 0 to 1000 and prints the largest.</p>
<pre><code>#My solution to codeval challenge Prime Palindrome. AUTHOR: S.Spiess
#initial count
counting_list = [x for x in range(0,1001)]
#prime number check. make list prime_list containing only primes from 0 to 1000
def prime_check(a_list):
prime_list = []
for k in a_list:
count = 2.0
d_test = 0
while count < k:
if k % count == 0:
d_test += 1
count += 1
else:
count += 1
if d_test < 1 and k > 1:
prime_list.append(k)
return prime_list
#check prime numbers from previous function for palindrome characteristic. append in new list.
def palindrome_check(num_list):
palindrome_list = []
for i in num_list:
temp = str(i)
if temp == temp[::-1]:
palindrome_list.append(i)
return palindrome_list
#print biggest palindrome prime from 0 to 1000
print max(palindrome_check(prime_check(counting_list)))
</code></pre>
<p>Here is another sample of code I wrote. It contains two functions that can change the base of a number.</p>
<pre><code>def to_mod20(any_num):
a_list = []
if any_num < 20 and any_num >= 1:
a_list.append(int(any_num))
while any_num >= 20:
a_list.append(any_num % 20)
if any_num / 20 < 20:
a_list.append(any_num / 20)
any_num = any_num / 20
#invert list for proper output
return a_list[::-1]
def decimal_mod20(any_dec):
count = 0
a_list = []
while any_dec < 1 and count < 4:
a_list.append(int(any_dec * 17.0))
any_dec = any_dec * 17.0 - int(any_dec * 17.0)
count += 1
#print any_dec
return a_list
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>The list comprehension <code>[x for x in range(0,1001)]</code> is redundant, as <code>range</code> already returns a list in Python 2. In Python 3 one can use <code>list(range(1001))</code></li>\n<li>Write a <a href=\"http://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\">docstring</a> instead of a comment to describe a function.</li>\n<li>Why is <code>count</code> a <code>float</code> (2.0) in <code>prime_check</code>? Should be an <code>int</code>.</li>\n<li>Prefer <code>for</code> loops to <code>while</code> loops when they do the same thing. Eg. use <code>for count in xrange(2, k)</code> in <code>prime_check</code>.</li>\n<li><code>if any_num < 20 and any_num >= 1:</code> can be written as <code>if 1 <= any_num < 20:</code></li>\n<li>You may want to look for more efficient algorithms for generating primes.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T09:55:58.990",
"Id": "39652",
"Score": "0",
"body": "Good to know.. very helpful points! Unfortunately I cannot vote up yet due to missing reputation."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T17:01:51.923",
"Id": "25537",
"ParentId": "25521",
"Score": "5"
}
},
{
"body": "<p>Very few things occur to me here:</p>\n\n<ul>\n<li><p><a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8</a>, the Python Style Guide and <a href=\"http://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow\">PEP 257</a>, Python Docstring Conventions. The comments you wrote above functions should become docstrings instead.</p></li>\n<li><p><code>[x for x in range(0,1001)]</code> is the same as <code>list(range(0, 1001))</code> which is the same as <code>range(0, 1001)</code>. That is, until you actually follow my last point, where the behaviour of <code>range()</code> rather follows that of <code>xrange()</code>.</p></li>\n<li><p>You are passing along lists, which implies building them, using them and then throwing them away. In some cases, using generator expressions would be more efficient.</p></li>\n<li><p>You are building a list of palindrome primes of which you then print the maximum. Since the input array is sorted, isn't the output array sorted, too, so that the last one is the maximum? BTW: This lacks a check whether that list is empty! At least formally, since 1 is prime and a palindrome.</p></li>\n<li><p>Last point: Use Python 3! ;)</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T09:56:17.600",
"Id": "39653",
"Score": "0",
"body": "Thanks for your advice. Unfortunately I cannot vote up yet due to missing reputation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-08T02:05:16.733",
"Id": "99282",
"Score": "0",
"body": "Most mathematicians would say that 1 is neither prime nor composite."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T17:05:44.060",
"Id": "25538",
"ParentId": "25521",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "25537",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T10:18:21.683",
"Id": "25521",
"Score": "5",
"Tags": [
"python",
"primes",
"palindrome"
],
"Title": "Calculating all prime palindromes from 0 to 1000 and printing the largest"
}
|
25521
|
<p>I have a class which is responsible for waiting until a message is added to a message list and then sending it off to get processed.</p>
<ul>
<li><code>withdrawMessages</code> waits for a message. I wait for a total of 2 minutes for a message to appear. I do this to keep the connection alive on my browser.</li>
<li><code>depositMessage</code> adds a message to the message list.</li>
</ul>
<p>The process flow I am aiming for is:</p>
<ul>
<li><p>Deposit a message into the list</p></li>
<li><p>Wait is notified and the whole list gets passed to the processor object (<code>IUpdater</code>) </p></li>
</ul>
<p>If <code>processMessages</code> is about to get executed and a new message is added to the list I want to make sure this new message is also sent when calling <code>responseUpdater.sendResponse</code></p>
<p>I need it to be thread-safe so when <code>responseUpdater.sendResponse(messageList);</code> is actually getting processed, then nothing else can be added to the list. It needs to wait until <code>sendResponse</code> is completed before adding it.</p>
<p><code>sendResponse</code> basically sends the list to browser then the browser sends back a request to call <code>withdrawMessages</code>. So if a new message is added when <code>sendResponse</code> is getting executed, it has to wait until <code>withdrawMessages</code> is called again. At that point it will process the messages.</p>
<pre><code>public class MessagePusher {
private static final int TWO_MINUTE_WAIT = 120 * 1000;
private volatile boolean notified = false;
private final ArrayList<String> messageList = new ArrayList<String>();
private void waitOnMessages(int duration) throws InterruptedException {
messageList.wait(duration);
}
private void notifyWaitingThreads() {
if (messageList.size() > 0) {
notified = true;
this.messageList.notify();
}
}
public void depositMessage(String message) {
synchronized (this.messageList) {
this.messageList.add(message);
notifyWaitingThreads();
}
}
//IUpdater just processes the messages
public void withdrawMessages(IUpdater updater) {
boolean processRequired = false;
synchronized (messageList) {
//gets lock
boolean timeout = false;
try {
//releases lock
waitOnMessages(TWO_MINUTE_WAIT);
//gets lock again
if ((!notified)) {
timeout = true;
}
} catch (InterruptedException e) {
ShipsLog.out.asWarning("Unexpected exception! Nested exception is:\n" + e);
}
if (notified || timeout) {
notified = false;
processRequired = true;
}
}
if (processRequired) {
processMessages(updater);
}
}
public void processMessages(IUpdater responseUpdater) {
synchronized (messageList) {
responseUpdater.sendResponse(messageList);
messageList.clear();
}
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>It looks like you only have one lock, so you can't have deadlock; but for future reference, you can add deadlock detection to the program, see for example <a href=\"http://meteatamel.wordpress.com/2012/03/21/deadlock-detection-in-java/\" rel=\"nofollow\">this blog post</a> but there are many other options available.</p></li>\n<li><p>You may want to replace the arraylist with a <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html\" rel=\"nofollow\">ConcurrentLinkedQueue</a>, this will let you remove the synchronized block from <code>depositMessage</code> and may let you remove the synchronized block from <code>withdrawMessages</code> and <code>processMessages</code> depending on how <code>responseUpdater.sendReponse</code> is implemented. In general, try to use lock-free data structures when possible - they generally scale better, and you can't heave deadlock if you don't have any locks.</p></li>\n<li><p><a href=\"https://www.research.ibm.com/haifa/projects/verification/contest/index.html\" rel=\"nofollow\">ConTest</a> is a tool for detecting multithreading problems e.g. race conditions. <a href=\"http://javapathfinder.sourceforge.net/\" rel=\"nofollow\">Java Pathfinder</a> is a much more heavyweight approach to this.</p></li>\n<li><p>For a large project, you may want to use a library like <a href=\"http://akka.io/\" rel=\"nofollow\">Akka</a> or <a href=\"http://docs.oracle.com/javaee/1.3/jms/tutorial/\" rel=\"nofollow\">JMS</a> to manage concurrency.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T01:20:58.150",
"Id": "25524",
"ParentId": "25523",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T22:24:12.793",
"Id": "25523",
"Score": "1",
"Tags": [
"java",
"multithreading",
"thread-safety"
],
"Title": "Sending messages for processing"
}
|
25523
|
<p>I usually find the .js files to be quite messy and the truth is that mine are even worse than the average as, being soft, I'm not the sharpest tool neither at jQuery nor JavaScript.</p>
<p>I would really appreciate if someone could give me a heads up about improving the readability (and point me bad practices) of this code. I would try to have them into account for other .js files.</p>
<pre><code>$(function () {
$('form').on("click", "div.toggler", function () {
$(this).next().slideToggle(300);
});
$('a.edit').click(function (e) {
var clickedElement = $(this).parent();
var url = $('#editForm').data('amp-url');
$.get(url, { id: parseInt($(this).attr('id')) }, function (result) {
$("#editForm").html(result);
// Display edit form just below the "item" clicked
if ($("#editForm").is(":visible")) {
$('#editForm').slideToggle(300, function() {
$("#editForm").appendTo(clickedElement);
$('#editForm').slideToggle(300);
});
} else {
$("#editForm").appendTo(clickedElement);
$('#editForm').slideToggle(300);
}
}, "html");
e.preventDefault();
});
// Hide edit form when click outside it
$(document).mouseup(function (e) {
if ($('#editForm').is(":visible")) {
var container = $("#editForm");
if (container.has(e.target).length === 0) {
container.slideUp(300);
}
}
});
(function (a) {
jQuery.fn.screencenter = function () {
this.css("position", "absolute");
this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
return this;
};
})(jQuery);
});
</code></pre>
<p>By the way, I have seen <a href="https://stackoverflow.com/questions/14754619/jquery-ajax-success-callback-function-definition">here</a> that deferred objects seems cleaner (apart of other considerations). I couldn't make it work, though.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T12:13:04.320",
"Id": "39566",
"Score": "1",
"body": "How do you organize your code in other languages? Don't you put the code in semantically named files?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T12:42:59.223",
"Id": "39567",
"Score": "0",
"body": "Yes, this is in a separate file with the name of controller (which doesn't have many views, just a main one and a partial for the moment): Documents.js"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T13:25:54.853",
"Id": "39573",
"Score": "1",
"body": "You could start by not leaning on jQuery to find that \"editForm\" element a zillion times over the course of your script. `$('#editForm')` is ugly as all get out. `editForm` is not. Write `var editForm = $('#editForm')` once (or better yet, a crystal clear `document.getElementById('editForm')`), use `editForm` from there on out, your code is looking cleaner and running faster already. `$(this).attr('id')` is slow and ugly, `this.id` is not, and so on... rinse and repeat."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T14:02:10.347",
"Id": "39577",
"Score": "0",
"body": "Can't vote up as in stack overflow both of your comments. Agreed that is a big improvement Dagg, but I wonder as I need to wrap these DOM object in a jquery one it's better at most do something like var editForm = $(document.GetElementById('editForm')) almost top of the file, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T07:49:56.110",
"Id": "39622",
"Score": "0",
"body": "Voting up turned out to be a privilege I just got"
}
] |
[
{
"body": "<p>As Dagg said in his comment, try to cache things as much as possible - I haven't tested this code but you could do something like this:</p>\n\n<pre><code>(function ($, window) {\n // Do stuff when the DOM is ready.\n $(function () {\n\n $('form').on(\"click\", \"div.toggler\", function () {\n $(this).next().slideToggle(300);\n });\n\n $('a.edit').click(function (e) {\n var clickedElement = $(this).parent(),\n editForm = $('#editForm'), // cache the edit form element.\n url = editForm.data('amp-url');\n\n $.get(url, {\n id: parseInt(this.id, 10) // Always specify the radix parameter\n }, function (result) {\n editForm.html(result);\n\n // Display edit form just below the \"item\" clicked\n if (editForm.is(\":visible\")) {\n editForm.slideToggle(300, function () {\n editForm.appendTo(clickedElement);\n editForm.slideToggle(300);\n });\n } else {\n editForm.appendTo(clickedElement);\n editForm.slideToggle(300);\n }\n },\n \"html\");\n e.preventDefault();\n });\n\n // Hide edit form when click outside it \n $(document).mouseup(function (e) {\n var container = $(\"#editForm\");\n if (container.is(\":visible\")) {\n if (container.has(e.target).length === 0) {\n container.slideUp(300);\n }\n }\n });\n });\n\n // Add the screen center function to jQuery.\n $.fn.screencenter = function () {\n var w = $(window);\n this.css(\"position\", \"absolute\");\n this.css(\"top\", ((w.height() - this.outerHeight()) / 2) + w.scrollTop() + \"px\");\n this.css(\"left\", ((w.width() - this.outerWidth()) / 2) + w.scrollLeft() + \"px\");\n return this;\n };\n}(jQuery, window));\n</code></pre>\n\n<p>This avoids having to hit the DOM each time, for example, you had $('window') four times... It's much better to get it once and store it in a variable.</p>\n\n<p>I've also wrapped everything in an IIFE (Immediately Invoked Function Expression).</p>\n\n<p>I'm not sure what you were trying to do here: </p>\n\n<pre><code>(function (a) {\n // code omitted.\n})(jQuery);\n</code></pre>\n\n<p>But effectively you are passing the <code>jQuery</code> object into a function aliased as a. Then you are not using <code>a</code> but the <code>jQuery</code> object anyway - a bit pointless.</p>\n\n<p><strong>Edit:</strong>\nRegarding the deferred object question:</p>\n\n<pre><code>var idToSend = 10;\nvar request = $.get(url, {\n id: idToSend\n});\n\n// Assign handlers for events (can also chain):\nrequest.done(function (result) {\n // Code for success. \n}).fail(function (result) {\n // Code for fail\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-27T11:57:37.193",
"Id": "39598",
"Score": "0",
"body": "Thanks RobH, big improvement. As a minor point I declared editForm (now editContainer) inside the IIFE so I can access it both in the ajax call and the function for hiding the form. After almost two years working as C# developer I don't know how to deal properly with .js and I find that even much more senior people than me don't neither, in my environment at least I feel we're just patching things via solutions posted in the web. I'm trying to spend time on javascript and its libraries, hopefully I will be able to structure my knowledge on that. Will try now the deferred object stuff."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T10:10:43.857",
"Id": "39654",
"Score": "0",
"body": "@mitomed Yeah I know what you mean. I'm predominantly a C# developer (in SharePoint actually) but really like JavaScript. I recommend you ready JavaScript: The Good Parts by Douglas Crockford. It's an amazing book and gives a great insight into how good JavaScript actually is!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T15:57:17.410",
"Id": "25535",
"ParentId": "25526",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "25535",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T11:43:26.750",
"Id": "25526",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "JQuery code to toggle an edit form"
}
|
25526
|
<p>I'm trying to update my website's code to HTML5's semantic and structural elements, but I'm not very sure with the <code>section</code>s and <code>article</code> element.</p>
<p>Here's the structure of my page:</p>
<pre><code><body>
<header id="heaven" style="background-image: url(" ./images/header/2.png ");"></header>
<nav id="outer-nav" style="position: absolute; top: 0px;"></nav>
<div id="main" style="position: relative; top: 332px; background-image: url(" ./images/background/1.png ");">
<div id="sidebar-container">
<aside class="sidebar-menu-left"></aside>
<aside class="sidebar-menu-right"></aside>
<div id="content">
<div class="textblock">
<form action="user_login.php" method="post"></form>
<div class="newornament"></div>
<form action="user_register.php" method="post"></form>
<div class="info"></div>
</div>
</div>
<footer id="disclaimer"></footer>
</div>
</div>
</body>
</code></pre>
<p></p>
<p>Should I turn the <code>main div</code> and/or the <code>content div</code> into a section, and should the <code><div class="textblock"></code> be the article, or should I put each of the <code><form></code> in an article?</p>
<p>Any other hints about the structure are also welcome.</p>
<p>You can take a look at the whole page <a href="http://habbo-heaven.de/" rel="nofollow">here</a>.</p>
|
[] |
[
{
"body": "<p>When in doubt about which element to use, always refer to the spec. It will tell you exactly where and when it is appropriate to each element(s).</p>\n\n<p>For a section here's is what the MDN spec has to say:</p>\n\n<blockquote>\n <p>The HTML Section Element (<code><section></code>) represents a generic section of a\n document, i.e., a thematic grouping of content, typically with a\n heading.</p>\n \n <p>Usage notes:</p>\n \n <p>If it makes sense to separately syndicate the content of a \n element, use an <code><article></code> element instead. Do not use the \n element as a generic container; this is what <code><div></code> is for, especially\n when the sectioning is only for styling purposes. A rule of thumb is\n that a section should logically appear in the outline of a document.</p>\n</blockquote>\n\n<p>In other words, if you have content that is related and goes together, put them in a section. Example is a heading section. Do this as long as you have actual content that will go in the element and you're not just using it to style your page.</p>\n\n<p>Now for the article element:</p>\n\n<blockquote>\n <p>The HTML <code><article></code> Element represents a self-contained composition in\n a document, page, application, or site, which is intended to be\n independently distributable or reusable, e.g., in syndication. This\n could be a forum post, a magazine or newspaper article, a blog entry,\n a user-submitted comment, an interactive widget or gadget, or any\n other independent item of content.</p>\n \n <p>Usage notes:</p>\n \n <p>When an <code><article></code> element is nested, the inner element represents an\n article related to the outer element. For example, the comments of a\n blog post can be <code><article></code> elements nested in the <code><article></code>\n representing the blog post. Author information of an <code><article></code> element\n can be provided through the <code><address></code> element, but it doesn't apply to\n nested <code><article></code> elements. The publication date and time of an\n <code><article></code> element can be described using the <code>pubdate</code> attribute of a\n <code><time></code> element.</p>\n</blockquote>\n\n<p>OK so use an article when you have stuff that goes with your site but is independent from the rest of the page. If you use an article element within another element, that article element's content should be related to the parent element's content/stuff.</p>\n\n<p>From what I can tell your <code><div class=\"main\"></code> it for styling and positioning, so it should remain a <code><div></code>. You got that sidebar <code><aside></code> element well, and the content inside is should be in the <code><aside></code> element itself, or if you have content that is groupable and related, then a <code><section></code> element inside that would be appropriate as well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T15:27:53.883",
"Id": "39580",
"Score": "0",
"body": "so ive changed the content div to a section but now the question is should i put a article element around each of the forms and if i do so should i the delete the textblock div and use the css style of the textblock at the article element?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T15:52:41.027",
"Id": "39581",
"Score": "0",
"body": "I would suggest a section element containing both forms. And yes apply the textblock styles to that section."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T14:44:18.380",
"Id": "25532",
"ParentId": "25528",
"Score": "1"
}
},
{
"body": "<p>You can’t decide which sectioning elements to use without taking the actual content into consideration. So the following is meant for the home page of <a href=\"http://www.habbo-heaven.de/\" rel=\"nofollow\">http://www.habbo-heaven.de/</a> (sub pages might differ!).</p>\n\n<p>Your <code>header</code> (<code>#outer-nav</code>) is fine. It contains the <code>h1</code> for the whole site. Therefore it is a child of <code>body</code> (and no other sectioning element).</p>\n\n<p>Your <code>nav</code> (<code>#outer-nav</code>) is fine. It contains the site-wide navigation, therefore it is a child of <code>body</code> (and no other sectioning element).\nYou could use a <code>ul</code> for the links, though.</p>\n\n<p>Using <code>aside</code> is fine. It contains content related to the whole page. Therefore it is a child of <code>body</code> (and no other sectioning element). However, your use of the headings inside of it is not correct for your content. The first heading inside the <code>aside</code> will be the (only!) heading of that sectioning element. But you use several <code>h1</code> and, assuming that my understanding of your content is correct, there should be no top heading for all the blocks in the sidebars, because semantically they are all on the same level. There would be 2 possible solutions:</p>\n\n<ul>\n<li><p>use one <code>aside</code> for all blocks and use <code>section</code> elements for each block (if you need containers for styling, use <code>div</code> elements around the <code>aside</code> elements)</p>\n\n<pre><code><aside>\n <!-- <div class=\"sidebar-menu-left\"> -->\n <section>\n <h1>Zuletzt gesetzte Gebote</h1>\n </section>\n <section>\n <h1>Zuletzt hinzugefügte Möbel</h1>\n </section>\n <!-- </div> -->\n <!-- <div class=\"sidebar-menu-right\"> -->\n <section>\n <h1>Top Trader</h1>\n </section>\n <section>\n <h1>Neusten User</h1>\n </section>\n <section>\n <h1>Zuletzt hinzugefügte Angebote</h1>\n </section>\n <!-- </div> -->\n</aside>\n</code></pre></li>\n<li><p>use a separate <code>aside</code> for every block in the sidebar</p>\n\n<pre><code><!-- <div class=\"sidebar-menu-left\"> -->\n<aside>\n <h1>Zuletzt gesetzte Gebote</h1>\n</aside>\n<aside>\n <h1>Zuletzt hinzugefügte Möbel</h1>\n</aside>\n<!-- </div> -->\n<!-- <div class=\"sidebar-menu-right\"> -->\n<aside>\n <h1>Top Trader</h1>\n</aside>\n<aside>\n <h1>Neusten User</h1>\n</aside>\n<aside>\n <h1>Zuletzt hinzugefügte Angebote</h1>\n</aside>\n<!-- </div> -->\n</code></pre></li>\n</ul>\n\n<p>Note that these two variants don’t generate the same document outline. The first variant will open another heading level for the <code>aside</code>, even if you don’t specify a heading explicitly. In the second variant all <code>aside</code> headings will be on the same (top) level as e.g. the main content. I’d prefer the first variant with one <code>aside</code> as container, because it doesn’t clutter the document outline and all your sidebar blocks are related content-wise anyway. If possible, find a suitable heading (you could hide it visually), like \"Recent activity\" or similar.</p>\n\n<p>For the two forms you <em>could</em> use an <code>article</code> element for each (as you already do on the live site). <code>section</code> would work, too, of course. And it would also be possible to use no sectioning element at all (just headings), because you marked up all other content appropriately (<code>header</code>, <code>footer</code>, <code>aside</code>), so it’s clear what the main content is. For this content (just these two forms), it’s mostly a question of taste.</p>\n\n<p>Your <code>footer</code> (<code>#disclaimer</code>) is fine. It contains the footer for the whole page/site, not only for the main content. Therefore it is a child of <code>body</code> (and no other sectioning element).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-27T23:43:32.330",
"Id": "25573",
"ParentId": "25528",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T13:42:06.863",
"Id": "25528",
"Score": "2",
"Tags": [
"html",
"html5"
],
"Title": "Update HTML4 to new HTML5 Semantic/Structural Elements"
}
|
25528
|
<p>I have a list in Prolog like this: </p>
<pre><code>Puzzle = [ A1, A2, A3,
B1, B2, B3,
C1, C2, C3 ].
</code></pre>
<p>And I want every variable in the list to be a number in the range of 1 to 9.
Currently I'm doing this like so:</p>
<pre><code>between(1,9, A1),
between(1,9, A2),
% ...
between(1,9, C3).
</code></pre>
<p>Even though this works, it's already pretty ugly even for the only 9 numbers I have so far. However I will have to expand my list to contain at least 81 numbers at first (<code>A1</code> till <code>I9</code>), and even 405 in the end. </p>
<p>I would rather not 'write' 405 lines of code just to limit the range of the numbers in the list, but since I'm new to Prolog, I don't know how I can improve this.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T14:35:30.167",
"Id": "39579",
"Score": "0",
"body": "Before moving on, I would strongly advise you to actually try to learn the language. What you are asking here is _very_ basic and fundamental to using the language."
}
] |
[
{
"body": "<p>Once you will have to hardcode your list to include all the variables from A1 to I9. Then you can iterate through it:</p>\n\n<pre><code>foreach(X, Your_list) do between(1, 9, X).\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T14:30:12.957",
"Id": "25531",
"ParentId": "25529",
"Score": "1"
}
},
{
"body": "<p>In SWI-Prolog you can simply do:</p>\n\n<pre><code>?- numlist(1,9,Puzzle).\nPuzzle = [1, 2, 3, 4, 5, 6, 7, 8, 9].\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-12T18:20:55.087",
"Id": "49554",
"ParentId": "25529",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "25531",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T14:21:01.743",
"Id": "25529",
"Score": "1",
"Tags": [
"prolog"
],
"Title": "Range of all variables in List in Prolog"
}
|
25529
|
<p>I would like to hear your feedback on the link below that lets users add a link to a website. I read that <code>javascript:void(0)</code> is <a href="https://stackoverflow.com/questions/134845/href-attribute-for-javascript-links-or-javascriptvoid0">suggested</a> instead of a <code>#</code> for the <code><a href=""</code> attribute. Is this still the best practice?</p>
<pre><code><a href="javascript:void(0)" onclick="window.open('https://www.example.com/add?url='+encodeURIComponent(window.location)+'&text='+encodeURIComponent(document.title))" title="Add link">Add Link</a>
</code></pre>
|
[] |
[
{
"body": "<p>First of all, <a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/void\" rel=\"nofollow\">void</a> is an operator, not a function. The parentheses are extraneous; it should be written as <code>void 0</code>.</p>\n\n<p><code>href=\"#\"</code> should be avoided for the reasons given in the answer you linked; people will forget to cancel the event and the page will jump to the top when users click the link, or worse, if the page uses a <code>base</code> tag, the page will navigate somewhere else.</p>\n\n<p>Most people will tell you to avoid putting JavaScript in tag attributes at all, instead binding events to the element later on, once the page has been loaded, or binding the event to a parent element and delegating.</p>\n\n<p>If you're going to use an inline <code>onclick</code> attribute anyway, and there's nothing appropriate to put in the <code>href</code> attribute, I'd consider not making it a link at all. Make it a <code>button</code> or some other kind of element, possibly styled to look like a hyperlink.</p>\n\n<p>As a final note, <code>GET</code> requests <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html\" rel=\"nofollow\">should be safe and idempotent</a>, meaning following a link or visiting a URL should not cause changes on your server / in your database. <code>https://www.example.com/add?...</code> looks suspiciously like it breaks that rule; you may be in a world of trouble if spiders start crawling those links. Making a <code>POST</code> request, for example by submitting a form, would be the proper way to handle this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T18:50:05.440",
"Id": "25542",
"ParentId": "25540",
"Score": "4"
}
},
{
"body": "<p>I suggest you take the <code>addEventListener</code>/<code>attachEvent</code> approach instead of using inline scripts. They are much cleaner and upholds separation of concerns. <a href=\"https://codereview.stackexchange.com/a/23308/11919\">Here's a simple patch</a> which makes it crossbrowser.</p>\n\n<pre><code>//assuming NS is an object, your namespace\nNS.addEL = (function binding(){\n if(window.addEventListener){\n return function addEventListener(el, ev, handler){\n el.addEventListener(ev, handler);\n }\n } else if(window.attachEvent) {\n return function attachEvent(el, ev, handler){\n el.attachEvent('on' + ev, handler);\n }\n } else {\n return function(){/*not supported for some reason*/}\n }\n}());\n</code></pre>\n\n<p>Using the said patch, you can have a cleaner HTML. Using <code>#</code> is a safeguard that prevents the link to point to nowhere, but the page jumps up. This will be your \"last line of defense\" from going somewhere.</p>\n\n<pre><code><a href=\"#\" id=\"link\" title=\"Add link\">Add Link</a>\n</code></pre>\n\n<p>And the JS that goes with it, we use our patch. Our main defense against the link moving the page away is <a href=\"https://developer.mozilla.org/en-US/docs/DOM/event.preventDefault\" rel=\"nofollow noreferrer\"><code>event.preventDefault</code></a>. </p>\n\n<p>Another way is returning false after the entire operation. This prevents eveything, and I mean <em>everything</em> that happens after it. It's link calling <code>event.preventDefault()</code> and <a href=\"https://developer.mozilla.org/en-US/docs/DOM/event.stopPropagation\" rel=\"nofollow noreferrer\"><code>event.stopPropagation</code></a>. You may be doing some delegation, so this might not be advisable.</p>\n\n<p>I suggest using <code>href=\"#\"</code> and <code>event.preventDefault</code> to stop the link from going somewhere.</p>\n\n<pre><code>var link = document.getElementById('link');\n\nNS.addEL(link,'click',function(event){\n\n //prevent the link from moving us away\n event.preventDefault();\n\n window.open('https://www.example.com/add?url='+encodeURIComponent(window.location)+'&text='+encodeURIComponent(document.title))\n\n //one way to prevent default, but stops propagation and everything else\n return false;\n});\n</code></pre>\n\n<p>If this is some tracker code, which displays nothing on the opened window, I suggest you route this to an iframe instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T19:11:14.237",
"Id": "25545",
"ParentId": "25540",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T17:31:16.993",
"Id": "25540",
"Score": "1",
"Tags": [
"javascript",
"html"
],
"Title": "Submitting the current webpage to a bookmarking site"
}
|
25540
|
<p>I am trying to code <a href="http://en.wikipedia.org/wiki/Battleship_%28game%29" rel="nofollow">Battleship</a>. It should be a text one-player game against computer where computer and human player take turns in shooting at opponent's ships. I decided to start implementation with this part: <em>A human types target coordinates and computer answers if a ship has been hit or even if it has been sunk. Ship positions are fixed (predefined in the program).</em> For some time I wondered how to represent game plan and ships to get this working as smoothly as possible. This is what I have put together:</p>
<pre><code>class GamePlan:
DIMX = 10
DIMY = 10
SHIP_MISS = 0
SHIP_HIT = 1
SHIP_DEAD = 2
SHIP_COUNTS = {
2: 1,
3: 1,
}
def __init__(self):
self.ships = [
[(1,1), (1,2)],
[(5,6), (5,7), (5,8)],
]
def hit(self, target):
hit_ship = None
hit_ship_index = None
for i, ship in enumerate(self.ships):
if target in ship:
ship.pop(ship.index(target))
hit_ship = ship
hit_ship_index = i
if hit_ship == []:
self.ships.pop(hit_ship_index)
return self.SHIP_DEAD
if hit_ship:
return self.SHIP_HIT
return self.SHIP_MISS
def main():
game_plan = GamePlan()
while True:
raw_coords = raw_input('Enter coords: ')
str_coords = raw_coords.split()
coords = tuple([int(c) for c in str_coords])
if len(coords) != 2:
print 'Bad input'
continue
result = game_plan.hit(coords)
if result == GamePlan.SHIP_DEAD:
print 'Ship dead'
if result == GamePlan.SHIP_HIT:
print 'Ship hit'
if result == GamePlan.SHIP_MISS:
print 'Missed'
if __name__ == "__main__":
main()
</code></pre>
<p><strong>EDIT:</strong> <code>GamePlan</code> should be probably called <code>Board</code> as answer of Janne Karila suggests. Just to clarify what I meant by that name with my flawed English.</p>
<p>There are a few things I am unsure about:</p>
<ol>
<li><p>Is it correct that <code>GamePlan</code> processes shooting (in the method <code>hit</code>)? </p></li>
<li><p>Is <code>hit</code> a good name for that method or should it be something like <code>process_hit</code>? Because <code>GamePlan</code> is being hit, it is not hitting anything. Is <code>hit</code> still good in such case? This is probably my biggest concern.</p></li>
<li><p>Should ships be represented as objects of a class <code>Ship</code> instead?</p></li>
<li><p>Is <code>GamePlan</code> a good thing to have or is it useless? I mean I could make class AI that directly owns <code>ships</code> but I am not sure where stuff like <code>SHIP_COUNTS</code> would go then. I have also planned that I will use <code>GamePlan</code> to generate ship positions (hence <code>SHIP_COUNTS</code> and <code>DIMX</code>, <code>DIMY</code> which are unused atm) but plan generation could also easily go to AI, I guess.</p></li>
<li><p>Is there anything else that is wrong?</p></li>
</ol>
|
[] |
[
{
"body": "<p>Perhaps <code>GamePlan</code> would better be named eg. <code>Board</code>? English is not my mother tongue, but AFAIK game plan == strategy.</p>\n\n<p>1,3,4: The ships are static, they just occupy some space on the board. However, a ship object would be aware which squares belong to the ship, and perhaps should be responsible to determine if it has been sunk.</p>\n\n<p>2: <code>hit</code> is perfect; in OOP the object is often the object also in grammatical sense. Think of <code>file.close()</code>.</p>\n\n<p>5: If the player hits the same coordinates twice, you'll report a miss, which is wrong.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T20:11:48.993",
"Id": "39587",
"Score": "0",
"body": "Thank you! Especially for that point 2. I was thinking many hours about that (feeling stupid that I think about something like that) and couldn't even quite formulate what I was thinking about. Now I can thanks to your remark about grammatical sense:). Specifically, whether programmatic objects are objects of operation when a method is called upon them or if they are subjects and method names should reflect it. I program for pretty long time but today my head got messy."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-27T14:31:00.810",
"Id": "39600",
"Score": "0",
"body": "at 5.: Well this what I wanted. It is miss because that part of ship is already destroyed. Is it played differently?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-27T19:41:13.420",
"Id": "39606",
"Score": "0",
"body": "@clime I would imagine that the ship remains floating until it sinks. Of course, it's a mistake on player's part to hit the same spot again, as it gives no new information."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T19:56:55.287",
"Id": "25547",
"ParentId": "25541",
"Score": "2"
}
},
{
"body": "<ol>\n<li><p>I think it is good idea to have method hit inside GamePlan because you don't plan to use it in other place then GamePlan I assume.</p></li>\n<li><p>You have chosen good name for method hit. 'Simple is better then complex'.</p></li>\n<li><p>If you plan continue develop game you suppose to put ship into separated class it will be easier to operate when code will grow.</p></li>\n<li><p>PlanGame is good idea to have. It helps separate game code from future Menu for example.\nWhat you can do change PlanGame to GameController. The GameController could manage all objects and get orders to do such as .hit(), .create_ship(), .restart() etc. Also this will let you create Plan or Map which will be managed by GameController also.</p></li>\n<li><p>I cannot see any docstrings. Remember that we read code more often then write.</p></li>\n</ol>\n\n<p>Your result codes are good but you can enhance them:</p>\n\n<pre><code>SHIP_MISS = 0\nSHIP_HIT = 1\nSHIP_DEAD = 2\n\nRESULTS = {SHIP_MISS: 'Missed',\n SHIP_HIT: 'Hit',\n SHIP_DEAD: 'Dead'}\n</code></pre>\n\n<p>And now you can do:</p>\n\n<pre><code>if result == GamePlan.SHIP_DEAD:\n print GamePlan.RESULTS[SHIP_DEAD]\nif result == GamePlan.SHIP_HIT:\n print GamePlan.RESULTS[SHIP_HIT]\nif result == GamePlan.SHIP_MISS:\n print GamePlan.RESULTS[SHIP_MISS]\n</code></pre>\n\n<p>or even:</p>\n\n<pre><code>print GamePlan.RESULTS[result]\n</code></pre>\n\n<p>This is closing for changes and opening for improvements try do that as much as possible.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T20:27:47.327",
"Id": "39588",
"Score": "0",
"body": "Thank you. That dictionary in 5. is cool. And GameController is very interesting idea in 4."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T20:17:33.573",
"Id": "25549",
"ParentId": "25541",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "25547",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T18:28:20.937",
"Id": "25541",
"Score": "6",
"Tags": [
"python",
"battleship"
],
"Title": "Designing a simple Battleship game in Python"
}
|
25541
|
<p>Please help make this code more cleaner. It's a part of window procedure that notifies my renderer <em>before</em> client area of window resized.</p>
<p>I need to check two combinations of bit blags: some of them must be set, and some must be not. How to do it without bunch of temp variables? (and probably calculate only 2 possible states and only once, not every call)</p>
<p>Thanks!</p>
<pre><code>LRESULT CALLBACK MSWindow::Impl::WndProc( HWND hWnd, uint msg, WPARAM wParam, LPARAM lParam )
{
switch( msg )
{
// ...
// WM_WINDOWPOSCHANGING is sent just about window position, size or order changed.
case WM_WINDOWPOSCHANGING:
{
const WINDOWPOS* wp = ((WINDOWPOS*)lParam);
const auto& flags = wp->flags;
const bool NOCOPYBITS = (flags & SWP_NOCOPYBITS) > 0;
const bool NOSIZE = (flags & SWP_NOSIZE) > 0;
const bool FRAMECHANGED = (flags & SWP_FRAMECHANGED) > 0;
const bool NOOWNERZORDER = (flags & SWP_NOOWNERZORDER) > 0;
const bool NOZORDER = (flags & SWP_NOZORDER) > 0;
const bool NOACTIVATE = (flags & SWP_NOACTIVATE) > 0;
const bool SHOWWINDOW = (flags & SWP_SHOWWINDOW) > 0;
const bool IsResizingAboutToEnd = !(NOSIZE) && NOOWNERZORDER && NOZORDER && (!NOACTIVATE);
const bool IsGoingToMaximizeOrRestore = FRAMECHANGED && (!NOACTIVATE) && (!NOCOPYBITS) && (!SHOWWINDOW);
if ( IsGoingToMaximizeOrRestore || IsResizingAboutToEnd )
{
Resize(Point(wp->cx, wp->cy));
}
break;
}
// .....
}
</code></pre>
|
[] |
[
{
"body": "<p>You first need to select the bits in the flag you want to test by ANDing them with a mask containing all the bits. </p>\n\n<p>This will zero all the bits that aren't being tested.</p>\n\n<p>You then just need to check the value of the bits you want so the masks and values are:</p>\n\n<pre><code>const UINT EndMask = NOSIZE | NOOWNERZORDER | NOZORDER | NOACTIVATE;\nconst UINT MaxRestoreMask = FRAMECHANGED | NOACTIVATE | NOCOPYBITS | SHOWWINDOW;\nconst UINT EndValue = NOOWNERZORDER | NOZORDER;\nconst UINT MaxRestoreValue = FRAMECHANGED;\n</code></pre>\n\n<p>The test then becomes:</p>\n\n<pre><code>if ((flags & EndMask) == EndValue || (flags & MaxRestoreMask) == MaxRestoreValue)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T21:33:58.293",
"Id": "25552",
"ParentId": "25543",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "25552",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T18:55:35.930",
"Id": "25543",
"Score": "2",
"Tags": [
"c++",
"bitwise"
],
"Title": "Simplify bit flags checking code"
}
|
25543
|
<p>I want to retrieve id and name per skill. It works but is it well done? I would like to stay with minidom but all advices will be appreciated.</p>
<pre><code># This is only part of XML that interesting me:
# <skill>
# <id>14</id>
# <skill>
# <name>C++</name>
# </skill>
# </skill>
# <skill>
# <id>15</id>
# <skill>
# <name>Java</name>
# </skill>
# </skill>
skills = document.getElementsByTagName('skill')
for skill in skills:
try:
id_ = skill.getElementsByTagName('id')[0].firstChild.nodeValue
name = skill.getElementsByTagName('name')[0].firstChild.nodeValue
my_object.create(name=name.strip(),
id=id_.strip())
except IndexError:
pass
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T21:27:55.170",
"Id": "39591",
"Score": "0",
"body": "Your xml doesn't seem to match your code (and is also not well formed)."
}
] |
[
{
"body": "<p>This is probably as good as you can get with minidom.</p>\n<p>However, consider ditching minidom--it's really only there when you <em>absolutely, postively</em> need some kind of DOM api and only have the standard library. Note the <a href=\"http://docs.python.org/2/library/xml.dom.minidom.html\" rel=\"nofollow noreferrer\">documentation for minidom</a>.</p>\n<blockquote>\n<p>Users who are not already proficient with the DOM should consider using the xml.etree.ElementTree module for their XML processing instead</p>\n<p>Warning: The xml.dom.minidom module is not secure against maliciously constructed data. If you need to parse untrusted or unauthenticated data see XML vulnerabilities.</p>\n</blockquote>\n<p>XML in Python is almost always processed with the <a href=\"http://docs.python.org/2/library/xml.etree.elementtree.html\" rel=\"nofollow noreferrer\">ElementTree</a> interface, not a DOM interface. There are many implementations of ElementTree including xml.etree.ElementTree (pure Python, in stdlib) and xml.etree.cElementTree (CPython, in stdlib), and lxml (third-party all-singing, all-dancing xml processing library that uses libxml2).</p>\n<p>Here is how I would do this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>try:\n # On Python 2.x, use the faster C implementation if available\n from xml.etree import cElementTree as ET\nexcept ImportError:\n # pure-python fallback\n # In Python3 just use this, not the one above:\n # Python3 will automatically choose the fastest implementation available.\n from xml.etree import ElementTree as ET\n\nxmlstr = """<root>\n<skill>\n <id>14</id>\n <name>C++</name>\n </skill>\n <skill>\n <id>15</id>\n <name>Java</name>\n </skill>\n</root>"""\n\nroot = ET.fromstring(xmlstr)\n\ndef get_subelem_texts(elem, subelems):\n """Return {subelem: textval,...} or None if any subelems are missing (present but empty is ok)"""\n attrs = {}\n for sa in skillattrs:\n textval = skill.findtext(sa)\n if textval is None:\n return None\n attrs[sa] = textval.strip()\n return attrs\n\n\nskillattrs = 'id name'.split()\n\nfor skill in root.find('skill'):\n args = get_subelem_texts(skill, skillattrs)\n if args is not None:\n my_object.create(**args)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T21:54:14.563",
"Id": "25553",
"ParentId": "25544",
"Score": "2"
}
},
{
"body": "<p>In the sample code you provided, there are skill outer and inner tag names. The way you loop over them triggers to <code>IndexError</code> exceptions that you simply ignore.</p>\n\n<p>Usually we handle exceptions in order to do something meaningful and concrete, not to ignore them. A way to avoid this dilemma is to simply avoid triggering those exceptions (especially that in practice you may have more elements than what you provided). So this is the way you could improve the code on this point:</p>\n\n<pre><code>>>> from xml.dom import minidom\n>>> xml_string = '<top><skill><id>14</id><skill><name>C++</name></skill></skill><skill><id>15</id><skill><name>Java</name></skill></skill></top>'\n>>> xml_dom = minidom.parseString(xml_string)\n>>> ids = xml_dom.getElementsByTagName('id')\n>>> names = xml_dom.getElementsByTagName('name')\n>>> language_ids = [ids[i].firstChild.data for i in range(len(ids))]\n>>> language_names = [names[i].firstChild.data for i in range(len(names))]\n>>> language_ids_with_names = dict(zip(language_ids, language_names))\n>>> language_ids_with_names\n{u'15': u'Java', u'14': u'C++'}\n</code></pre>\n\n<p>Note that I added a root element called <code>top</code> for the XML string you provided, otherwise I can not parse it.</p>\n\n<p>I do not see a reason why to change the library for this code. Many people ask to use <code>minidom</code> alternatives but there are many situations where <code>minidom</code> is effective and useful and I used it many times professionally.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-25T09:31:14.773",
"Id": "192897",
"ParentId": "25544",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "25553",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T18:59:07.863",
"Id": "25544",
"Score": "2",
"Tags": [
"python",
"xml"
],
"Title": "Parsing XML with double nested tags using mindom"
}
|
25544
|
<p>This is a basic sorting function written in jQuery that moves items in the DOM around to create empty spaces for a droppable(). Since there is so much going on in a droppable over event, i'd love some feedback on how this could be done better. </p>
<p><strong>This is all in a function called on the over event of the droppable()</strong></p>
<p>I have an array of empty spots</p>
<pre><code> var emptyHolders = [];
$('.pipeline-holder').each(function(){
if($(this).hasClass('holder-empty')){
var eid = $(this).attr('id');
emptyHolders.push(eid.substring(14));
}
});
</code></pre>
<p>cid is the droppable element that you're over top of, so I find the next open slot using </p>
<pre><code> for (var i = 0; i < emptyHolders.length; i++) {
var currentEmpty = emptyHolders[i];
if (currentEmpty > cid) {
nextEmpty = currentEmpty;
i = emptyHolders.length;
} else {
prevEmpty = parseInt(currentEmpty);
}
}
</code></pre>
<p>If there is a an empty slot further down the list, I use a for loop to loop through moving the items around the DOM to make the space needed to drop the element.</p>
<pre><code> if (nextEmpty != null) {
var moveMe = nextEmpty -1;
for (var i = moveMe; i >= cid; i--) {
var nextcount = i + 1;
var me = $('#pipeline-rank-' + i);
var next = $('#pipeline-rank-' + i).parents('.pipeline-rank-row').next().find('.pipeline-holder');
var pid = $('#pipeline-rank-' + i).find('.content-wrapper').attr('id');
next.append($('#pipeline-rank-' + i).find('.content-wrapper'));
next.removeClass('holder-empty');
next.siblings('.remember-my-position-hover').html(pid);
}
$('#pipeline-rank-' + cid).addClass('holder-empty');
}
</code></pre>
<p>If there is not one further down the list, I do the same thing in reverse to check if there is a spot above the droppable to push items up into.</p>
<p>It's usable here: <a href="http://jsfiddle.net/mstefanko/LEjf8/9/" rel="nofollow">http://jsfiddle.net/mstefanko/LEjf8/9/</a></p>
<p>Any thoughts are extremely appreciated!</p>
|
[] |
[
{
"body": "<p>Here you have some general thoughts:</p>\n\n<ol>\n<li><p>First of all, cache jQuery elements (<code>var $this = $(this);</code> instead of multiple executions of <code>$(this)</code>). <a href=\"http://jsfiddle.net/tomalec/pXPdS/1/\" rel=\"nofollow\">http://jsfiddle.net/tomalec/pXPdS/1/</a></p></li>\n<li><p>You can also chain jQuery methods, it simplifies codes, and helps with above.</p></li>\n<li><p>To reduce amount of code you can use <code>toggleClass</code> instead of <code>addClass</code> <code>removeClass</code>.<a href=\"http://jsfiddle.net/tomalec/pXPdS/2/\" rel=\"nofollow\">http://jsfiddle.net/tomalec/pXPdS/2/</a></p></li>\n<li><p>Instead of selecting <code>$('#rankDrag')</code> in <code>start</code> callback you can use reference given in arguments <code>ui.helper</code>\n<a href=\"http://jsfiddle.net/tomalec/pXPdS/3/\" rel=\"nofollow\">http://jsfiddle.net/tomalec/pXPdS/3/</a></p></li>\n<li><p>To get id of empty/not empty holder ids, in my opinion, <code>.map</code> is more readable than <code>.each</code>. Moreover, you can move that function outside <code>rearrange</code> to avoid re-declaring it every time.</p>\n\n<pre><code>function getTruncatedId(index, element){\n return element.id.substring(14);\n}\n\nfunction rearrange(dropid) {\n //..\n emptyHolders = holders.filter('.holder-empty').map(getTruncatedId);\n isRanked = holders.filter(':not(.holder-empty)').map(getTruncatedId);\n //..\n}\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/tomalec/pXPdS/4/\" rel=\"nofollow\">http://jsfiddle.net/tomalec/pXPdS/4/</a></p></li>\n<li><p>Pass dropped element to <code>rearrange</code>, so you will not have to traverse through DOM again:</p>\n\n<pre><code>rearrange( $(this).attr('id') );//dropId = $(this).attr('id');\n//..\nisEmpty = $('#'+dropId).hasClass('holder-empty');\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/tomalec/pXPdS/5/\" rel=\"nofollow\">http://jsfiddle.net/tomalec/pXPdS/5/</a></p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T17:14:26.543",
"Id": "25625",
"ParentId": "25546",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "25625",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T19:30:35.857",
"Id": "25546",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"jquery-ui"
],
"Title": "Jquery sortable style function"
}
|
25546
|
<p>This is the first time I've written a class in Java to do encryption using AES. Since security is involved I would love it if someone could take a look at it and let me know if anything is wrong with my implementation. Additionally, any feedback about shortcuts I could have taken or sloppy processes I've used would be greatly appreciated!</p>
<pre><code>import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
public class Encrypt {
private Cipher encryptCipher;
private SecretKey key;
private IvParameterSpec iv;
private byte[] clearText;
/**
* Encrypts data using AES-128
* @param clearText The data to be encrypted
*/
public Encrypt(String clearText) {
//Generate the IV and key
this.iv = new IvParameterSpec(this.generateIv());
this.key = this.generateKey();
//Create an AES cipher in CBC mode using PKCS5 padding
try {
this.encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
try {
this.encryptCipher.init(Cipher.ENCRYPT_MODE, this.key, this.iv);
}
catch(InvalidKeyException ex) {
Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex);
}
catch(InvalidAlgorithmParameterException ex) {
Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex);
}
}
catch(NoSuchAlgorithmException ex) {
Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex);
}
catch(NoSuchPaddingException ex) {
Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex);
}
//Convert the clear text passed by the user into bytes
try {
this.clearText = clearText.getBytes("UTF-16");
}
catch(UnsupportedEncodingException ex) {
Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Generates a random IV to be used in the encryption process
* @return The IV's byte representation
*/
private byte[] generateIv() {
SecureRandom random = new SecureRandom();
byte[] ivBytes = new byte[16];
random.nextBytes(ivBytes);
return ivBytes;
}
/**
* Generates a secret key to be used in the encryption process
* @return The secret key
*/
private SecretKey generateKey() {
KeyGenerator keygen;
try {
//Java normally doesn't support 256-bit key sizes without an extra installation so stick with a 128-bit key
keygen = KeyGenerator.getInstance("AES");
keygen.init(128);
SecretKey aesKey = keygen.generateKey();
return aesKey;
}
catch(NoSuchAlgorithmException ex) {
Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
/**
* Encrypts the data passed during instantiation of this object
* @return The byte representation of the encrypted data
*/
public byte[] encrypt() {
try {
return this.encryptCipher.doFinal(this.clearText);
}
catch(IllegalBlockSizeException ex) {
Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
catch(BadPaddingException ex) {
Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-27T15:36:24.350",
"Id": "39603",
"Score": "0",
"body": "My first suggestion is to make refactor a little bit your constructor. Start by making a Method `getCipherInstance()` put your try catches in that method. Then make another method `initializeCipher()` This will make your constructor easier to read. As for your random IV generator you might want to consider a lesson from how Mifare Desfire passes enciphered data. You basically start with a IV of 0x00 and have a key that is known elsewhere. In the end hacking is much more difficult."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-02T21:00:40.773",
"Id": "39894",
"Score": "0",
"body": "Thanks, good idea. I've refactored a little bit and moved a lot of the work that was being done in the constructor into separate methods."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-04T05:52:34.040",
"Id": "60134",
"Score": "0",
"body": "If you have found a good solution/answer to your question then you should consider adding an answer here. It will be beneficial to everyone. Self-answering you question is valid, and encouraged."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-03T13:39:21.027",
"Id": "112494",
"Score": "0",
"body": "One thing I wanted to point out is that I did NOT use a fixed IV with 0x00 bytes. I'm not sure why anyone suggests using a constant IV as it defeats the entire purpose of an IV. The IV is supposed to be random for each encryption operation, no?"
}
] |
[
{
"body": "<p>Here's my final implementation with the changes based on @Robert Snyder's comment:</p>\n\n<blockquote>\n <p>My first suggestion is to make refactor a little bit your constructor.\n Start by making a Method <code>getCipherInstance()</code> put your try catches in\n that method. Then make another method <code>initializeCipher()</code> This will\n make your constructor easier to read. As for your random IV generator\n you might want to consider a lesson from how Mifare Desfire passes\n enciphered data. You basically start with a IV of 0x00 and have a key\n that is known elsewhere. In the end hacking is much more difficult.</p>\n</blockquote>\n\n<pre><code>import com.sun.org.apache.xml.internal.security.utils.Base64;\nimport java.io.UnsupportedEncodingException;\nimport java.security.InvalidAlgorithmParameterException;\nimport java.security.InvalidKeyException;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.SecureRandom;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport javax.crypto.BadPaddingException;\nimport javax.crypto.Cipher;\nimport javax.crypto.IllegalBlockSizeException;\nimport javax.crypto.KeyGenerator;\nimport javax.crypto.NoSuchPaddingException;\nimport javax.crypto.SecretKey;\nimport javax.crypto.spec.IvParameterSpec;\n\npublic class Encrypt {\n\n private Cipher encryptCipher;\n private SecretKey key;\n private IvParameterSpec iv;\n\n private byte[] clearText;\n private byte[] encryptedText;\n\n /**\n * Encrypts data using AES-128\n * @param clearText The data to be encrypted\n */\n public Encrypt(String clearText) {\n\n //Generate the IV and key\n this.iv = new IvParameterSpec(this.generateIv());\n this.key = this.generateKey();\n this.encryptCipher = createCipher();\n this.clearText = this.convertClearText(clearText);\n this.encryptedText = this.encrypt();\n }\n\n /**\n * Converts the clear text passed by the user to an array of bytes\n * @param clearText The clear text passed by the user\n * @return The byte representation of the clear text\n */\n private byte[] convertClearText(String clearText) {\n\n //Convert the clear text passed by the user into bytes\n try {\n return clearText.getBytes(\"UTF-8\");\n }\n catch(UnsupportedEncodingException ex) {\n Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex);\n return null;\n }\n }\n\n /**\n * Creates an AES cipher using CBC mode with PKCS5 padding\n * @return The cipher used to encrypt data\n */\n private Cipher createCipher() {\n\n //Create an AES cipher in CBC mode using PKCS5 padding\n try {\n Cipher cipher = Cipher.getInstance(\"AES/CBC/PKCS5Padding\");\n cipher.init(Cipher.ENCRYPT_MODE, this.key, this.iv);\n return cipher;\n }\n catch(NoSuchAlgorithmException ex) {\n Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex);\n return null;\n }\n catch(NoSuchPaddingException ex) {\n Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex);\n return null;\n }\n catch(InvalidKeyException ex) {\n Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex);\n return null;\n }\n catch(InvalidAlgorithmParameterException ex) {\n Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex);\n return null;\n }\n }\n\n /**\n * Generates a random IV to be used in the encryption process\n * @return The IV's byte representation\n */\n private byte[] generateIv() {\n SecureRandom random = new SecureRandom();\n byte[] ivBytes = new byte[16];\n random.nextBytes(ivBytes);\n return ivBytes;\n }\n\n /**\n * Generates a secret key to be used in the encryption process\n * @return The secret key\n */\n private SecretKey generateKey() {\n KeyGenerator keygen;\n try {\n\n //Java normally doesn't support 256-bit key sizes without an extra installation so stick with a 128-bit key\n keygen = KeyGenerator.getInstance(\"AES\");\n keygen.init(128);\n SecretKey aesKey = keygen.generateKey();\n return aesKey;\n }\n catch(NoSuchAlgorithmException ex) {\n Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex);\n return null;\n }\n }\n\n /**\n * Returns the initialization vector\n * @return The randomly generated IV\n */\n public IvParameterSpec getIv() {\n return this.iv;\n }\n\n /**\n * Returns the key used for encryption\n * @return The randomly generated secret key\n */\n public SecretKey getKey() {\n return this.key;\n }\n\n /**\n * Encrypts the data passed during instantiation of this object\n * @return The byte representation of the encrypted data\n */\n public final byte[] encrypt() {\n try {\n return this.encryptCipher.doFinal(this.clearText);\n }\n catch(IllegalBlockSizeException ex) {\n Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex);\n return null;\n }\n catch(BadPaddingException ex) {\n Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex);\n return null;\n }\n }\n\n /**\n * Returns the encrypted text as a base64 encoded string\n * @return The encrypted base64 encoded string\n */\n @Override\n public String toString() {\n return Base64.encode(encryptedText);\n }\n\n}\n</code></pre>\n\n<p>Here is the most recent version of the class. One of the suggestions was to set the IV to 0x00 which I did not do. Someone correct me if I'm wrong but I'm almost positive that it is critical to have random data for the IV for each encryption operation. I've done what others have suggested and bubbled the exceptions up. The constructor has also been cleaned up quite a bit and there's now a <code>toString()</code> method that returns the data as a base64 encoded string. </p>\n\n<pre><code>import org.apache.commons.codec.binary.Base64;\nimport java.io.UnsupportedEncodingException;\nimport java.security.InvalidAlgorithmParameterException;\nimport java.security.InvalidKeyException;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.SecureRandom;\nimport javax.crypto.BadPaddingException;\nimport javax.crypto.Cipher;\nimport javax.crypto.IllegalBlockSizeException;\nimport javax.crypto.KeyGenerator;\nimport javax.crypto.NoSuchPaddingException;\nimport javax.crypto.SecretKey;\nimport javax.crypto.spec.IvParameterSpec;\n\npublic final class Encrypt {\n\n private Cipher encryptCipher;\n private SecretKey key;\n private IvParameterSpec iv;\n\n private byte[] clearText;\n private byte[] encryptedText;\n\n /**\n * Encrypts data using AES-128\n *\n * @param clearText The data to be encrypted\n * @throws java.security.NoSuchAlgorithmException\n * @throws javax.crypto.NoSuchPaddingException\n * @throws java.security.InvalidKeyException\n * @throws javax.crypto.BadPaddingException\n * @throws java.security.InvalidAlgorithmParameterException\n * @throws javax.crypto.IllegalBlockSizeException\n * @throws java.io.UnsupportedEncodingException\n */\n public Encrypt(String clearText) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException {\n\n //Generate the IV and key\n this.iv = new IvParameterSpec(this.generateIv());\n this.key = this.generateKey();\n this.encryptCipher = createCipher();\n this.clearText = this.convertClearText(clearText);\n this.encryptedText = this.encrypt();\n }\n\n /**\n * Converts the clear text passed by the user to an array of bytes\n *\n * @param clearText The clear text passed by the user\n * @return The byte representation of the clear text\n */\n private byte[] convertClearText(String clearText) throws UnsupportedEncodingException {\n\n //Convert the clear text passed by the user into bytes\n return clearText.getBytes(\"UTF-8\");\n }\n\n /**\n * Creates an AES cipher using CBC mode with PKCS5 padding\n *\n * @return The cipher used to encrypt data\n */\n private Cipher createCipher() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {\n\n //Create an AES cipher in CBC mode using PKCS5 padding\n Cipher cipher = Cipher.getInstance(\"AES/CBC/PKCS5Padding\");\n cipher.init(Cipher.ENCRYPT_MODE, this.key, this.iv);\n return cipher;\n }\n\n /**\n * Generates a random IV to be used in the encryption process\n *\n * @return The IV's byte representation\n */\n private byte[] generateIv() {\n SecureRandom random = new SecureRandom();\n byte[] ivBytes = new byte[16];\n random.nextBytes(ivBytes);\n return ivBytes;\n }\n\n /**\n * Generates a secret key to be used in the encryption process\n *\n * @return The secret key\n */\n private SecretKey generateKey() throws NoSuchAlgorithmException {\n KeyGenerator keygen;\n\n //Java normally doesn't support 256-bit key sizes without an extra installation so stick with a 128-bit key\n keygen = KeyGenerator.getInstance(\"AES\");\n keygen.init(128);\n SecretKey aesKey = keygen.generateKey();\n return aesKey;\n\n }\n\n /**\n * Returns the initialization vector\n *\n * @return The randomly generated IV\n */\n public IvParameterSpec getIv() {\n return this.iv;\n }\n\n /**\n * Returns the key used for encryption\n *\n * @return The randomly generated secret key\n */\n public SecretKey getKey() {\n return this.key;\n }\n\n /**\n * Encrypts the data passed during instantiation of this object\n *\n * @return The byte representation of the encrypted data\n */\n private byte[] encrypt() throws IllegalBlockSizeException, BadPaddingException {\n return this.encryptCipher.doFinal(this.clearText);\n\n }\n\n /**\n * Returns the encrypted text as a base64 encoded string\n *\n * @return The encrypted base64 encoded string\n */\n @Override\n public String toString() {\n return Base64.encodeBase64String(encryptedText);\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-04T14:24:57.633",
"Id": "36640",
"ParentId": "25548",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "36640",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T20:02:35.310",
"Id": "25548",
"Score": "10",
"Tags": [
"java",
"cryptography"
],
"Title": "AES-128 encryption class"
}
|
25548
|
<p>The code checks many more conditions like the one below. I was thinking to memoize it, but I can't think about how (writers block). How else could I optimize this? I know it seems silly, but my code is spending the majority of the time in the function.</p>
<pre><code>def has_three(p, board):
"""Checks if player p has three in a row"""
# For every position on the board
for i in xrange(6):
for j in xrange(7):
if board[i][j] == p:
if i<=2 and board[i+1][j]==p and board[i+2][j]==p and board[i+3][j]==0:
return True
if i>=3 and board[i-1][j]==p and board[i-2][j]==p and board[i-3][j]==0:
return True
if j<=3 and board[i][j+1]==p and board[i][j+2]==p and board[i][j+3]==0:
return True
if j>=3 and board[i][j-1]==p and board[i][j-2]==p and board[i][j-3]==0:
return True
if i<=2 and j<=3 and board[i+1][j+1]==p and board[i+2][j+2]==p and board[i+3][j+3]==0:
return True
if i<=2 and j>=3 and board[i+1][j-1]==p and board[i+2][j-2]==p and board[i+3][j-3]==0:
return True
if i>=3 and j<=3 and board[i-1][j+1]==p and board[i-2][j+2]==p and board[i-3][j+3]==0:
return True
if i>=3 and j>=3 and board[i-1][j-1]==p and board[i-2][j-2]==p and board[i-3][j-3]==0:
return True
return False
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T21:13:37.580",
"Id": "39589",
"Score": "4",
"body": "Can you post the entire function and some input and expected output? Also, what the function is supposed to do?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T22:23:15.770",
"Id": "39592",
"Score": "0",
"body": "Can there be more than two players?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T22:32:40.573",
"Id": "39593",
"Score": "0",
"body": "nope, only two. and i'll call them 1 and 2"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-27T08:46:34.553",
"Id": "39596",
"Score": "2",
"body": "A board of 7x6 looks like \"Connect Four\", except that you check not 4 but 3 connected cells (\"Connect Three\"?). Is that what you are trying to do?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T09:25:49.897",
"Id": "39627",
"Score": "0",
"body": "Even not knowing the game, I wonder if the checks for `==0` are correct here."
}
] |
[
{
"body": "<p>We really need to know more about the game to help you properly. Also, why is your program spending so much time in this function? (Are you doing some kind of lookahead, with this function being part of the evaluation?)</p>\n\n<p>If this is a game like <a href=\"http://en.wikipedia.org/wiki/Gomoku\" rel=\"nofollow\">gomoku</a>, where players take turns, and in each turn a player places one piece on the board, and the first player to get <em>n</em> in a line wins, then the only way that the board can have a winning line is if that line includes the piece that was just played. Hence there's no point looking at other points in the board.</p>\n\n<p>So in this case you'd write something like this:</p>\n\n<pre><code>DIRECTIONS = [(1,0),(1,1),(0,1),(-1,1)]\n\ndef legal_position(i, j, board):\n \"\"\"Return True if position (i, j) is a legal position on 'board'.\"\"\"\n return 0 <= i < len(board) and 0 <= j < len(board[0])\n\ndef winning_move(player, move, board, n = 3):\n \"\"\"Return True if 'move' is part of a line of length 'n' or longer for 'player'.\"\"\"\n for di, dj in DIRECTIONS:\n line = 0\n for sign in (-1, 1):\n i, j = move\n while legal_position(i, j, board) and board[i][j] == player:\n i += sign * di\n j += sign * dj\n line += 1\n if line > n: # move was counted twice\n return True\n return False\n</code></pre>\n\n<p>But without understanding the rules of your game, it's impossible for me to know if this approach makes any sense.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T23:04:36.970",
"Id": "25554",
"ParentId": "25550",
"Score": "1"
}
},
{
"body": "<p>You can reduce the number of comparisons if you just loop through rows, columns and diagonals, and count the consecutive <code>p</code>'s as you go along.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T09:29:26.353",
"Id": "25586",
"ParentId": "25550",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T21:10:59.193",
"Id": "25550",
"Score": "2",
"Tags": [
"python",
"performance"
],
"Title": "Checking a board to see if a player has three in a row"
}
|
25550
|
<p>I recently made <a href="http://ucsd.edu/timeline/" rel="nofollow noreferrer">this campus timeline</a> for my university. When viewing the timeline on a mobile device (not a tablet), the navbar changes so that you can jump to the previous or next decade by clicking one of the arrows.</p>
<p>I'm concerned about the performance of the animation. I'm using a Samsung Galaxy S3 (one of the most powerful Android phones out) but it's still extremely sluggish in both Chrome and Dolphin browser. How can I make it faster? The code that controls the jump and animation can be viewed here:</p>
<pre><code>$timeline.find(".dec-banner").on("click", "a", function(event) { // bring user to previous or next decade if clicked on in the decade header
var $navlink = $(this).attr("href");
if ($(this).parent().hasClass("decade-jump-prev")) {
$("html,body").stop(true, true).animate({scrollTop: $($navlink).offset().top-43},"fast");
}
if ($(this).parent().hasClass("decade-jump-next")) {
$("html,body").stop(true, true).animate({scrollTop: $($navlink).offset().top},"fast");
}
event.preventDefault();
});
</code></pre>
<p>Is this animation hardware accelerated? If not, can I somehow force it to be?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-29T23:11:53.877",
"Id": "180596",
"Score": "0",
"body": "Randomly stumbled across this very old question of mine and now I can tell the past version of me and anyone else reading that jQuery's animate is extraordinarily inefficient and that I should have used something like Greensock to handle the animation."
}
] |
[
{
"body": "<pre><code>//html and body don't change in the lifetime of the page, no sense fetching them everytime\n//thus we move it out of the handler into a static scope\nvar html_body = $('html,body');\n\n//Use the context parameter and keep your code short. It acts like `find`.\n//I suggest you delegate at a lower parent so bubbling won't travel that far.\n//If `.dec-banner` is unique in the page, consider assigning it an `id` instead\n//so we can directly access it, rather than find some `class` under some node\n//Lastly, you can be more specific rather than listening for events on `a` elements\n//that way, the handler won't execute on any `a` element under `.dec-banner`\n$('.dec-banner', $timeline).on('click', 'a', function (event) {\n\n //for values that get used more than once, especially if they require DOM fetching\n //cache their values in variables. In this case, `$(this)` and parent gets used more than once\n var $this = $(this);\n var navlink = $($this.attr('href'));\n var parent = $this.parent();\n\n //we check for the existence of these classes to determine the fix\n var prev = parent.hasClass('decade-jump-prev');\n var next = parent.hasClass('decade-jump-next');\n\n event.preventDefault();\n\n //evaluate if they are prev and next once, rather than twice\n //we can't use the *return early* approach for avoiding indention\n //since propagation might be used\n if (prev || next) {\n\n //within this block, we assume that the links are either prev or next\n //if not prev, then it should be next\n\n html_body.stop(true, true).animate({\n //we adjust the fix depending on the existence of prev and next\n //if prev, we use 43, otherwise 0\n scrollTop: navlink.offset().top - (prev ? 43 : 0)\n }, 'fast');\n }\n\n\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T18:41:25.397",
"Id": "39687",
"Score": "0",
"body": "this is fantastic! thank you very much. i'm in the beginning stages of learning javascript/jquery so this was extremely helpful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-27T20:32:33.270",
"Id": "25571",
"ParentId": "25555",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "25571",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-26T23:07:54.077",
"Id": "25555",
"Score": "2",
"Tags": [
"javascript",
"performance",
"jquery",
"html",
"animation"
],
"Title": "Timeline animations"
}
|
25555
|
<p>I'm putting together a little application and it requires about 6 <code>if</code> statements to verify actions, here's the code I'm using:</p>
<pre><code>if($player[0]['value'] == $server->clean_attr($row['attr1'])) {
if($player[1]['value'] == $server->clean_attr($row['attr2'])) {
if($player[2]['value'] == $server->clean_attr($row['attr3'])) {
if($player[3]['value'] == $server->clean_attr($row['attr4'])) {
if($player[4]['value'] == $server->clean_attr($row['attr5'])) {
if($player[5]['value'] == $server->clean_attr($row['attr6'])) {
//perform action here
}
}
}
}
}
}
</code></pre>
<p>How could I improve such code so it doesn't require all these <code>if</code> statements? They seem pretty messy.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T20:22:31.320",
"Id": "39640",
"Score": "0",
"body": "I'd change your attr names if you can for readability"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-26T21:28:04.593",
"Id": "193730",
"Score": "2",
"body": "This post is off-topic for two reasons: it is unclear what this code is doing, and the code is hypothetical (\"`//perform action here`\")"
}
] |
[
{
"body": "<p>You could separate the array checks and the conditional: create a walker and store the result of a failed comparison in a separate container. Then check just that stored value:</p>\n\n<h3>Walker</h3>\n\n<pre><code>function walk_players( &$player, $key, $context )\n{\n $server = $context['server'];\n $row_attr = $context['row'][ 'attr' . $key + 1 ];\n\n passed( $player[ $key ][ 'value'] === $server->clean_attr( $row_attr ) );\n}\n</code></pre>\n\n<h3>Storage</h3>\n\n<pre><code>function passed( $test = NULL )\n{\n static $pass = FALSE;\n\n if ( NULL === $test )\n return $pass;\n\n if ( FALSE === $test )\n $pass = $test;\n}\n</code></pre>\n\n<h3>Cleaned code</h3>\n\n<pre><code>$context = array (\n 'row' => $row,\n 'server' => $server\n);\n\narray_walk( $player, 'walk_players', $context );\n\nif ( passed() )\n{\n // do something\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-27T08:09:36.217",
"Id": "25557",
"ParentId": "25556",
"Score": "1"
}
},
{
"body": "<p>Assuming the attribute names are truly <code>attr1</code> through <code>attr5</code>, this is nice and terse.</p>\n\n<pre><code>$allEqual = true;\nfor ($i = 0; $i <= 5; $i++) {\n if ($player[$i]['value'] != $server->clean_attr($row['attr' . ($i + 1)]) {\n $allEqual = false;\n break;\n }\n}\n\nif ($allEqual) {\n // ...\n}\n</code></pre>\n\n<p>It doesn't take much tweaking to have a more varied set of attribute names.</p>\n\n<pre><code>$attrs = array('one', 'two', 'three', 'four', 'five');\n$allEqual = true;\nfor ($attrs as $player => $attr) {\n if ($player[$player]['value'] != $server->clean_attr($row[$attr]) {\n // ... the rest is identical ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-27T10:14:32.040",
"Id": "25558",
"ParentId": "25556",
"Score": "6"
}
},
{
"body": "<p>Since PHP 5.5 you have the function <a href=\"http://www.php.net/manual/de/function.array-column.php\" rel=\"nofollow\"><code>array_column</code></a>. This function could be used like this:</p>\n\n<pre><code>$values = arra_column($player,'value');\n\nforeach($values as $i => $value){\n //stop checking further values\n if($value !== $server->clean_attr($row['attr'.$i+1]) return false;\n //perform action here\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-26T22:55:49.993",
"Id": "193740",
"Score": "1",
"body": "Please explain how this recommendation is helpful to the user, and provide more information regarding the code that you have displayed."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T08:02:50.903",
"Id": "33052",
"ParentId": "25556",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "25558",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-27T05:40:47.910",
"Id": "25556",
"Score": "-4",
"Tags": [
"php"
],
"Title": "Too much nesting"
}
|
25556
|
<p>I have the following C++ program:</p>
<pre><code>#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
void printVector (std::vector<int>& vec)
{
for (int a = 0; a < vec.size(); a++)
std::cout << (char)vec[a] << ", ";
}
int main ()
{
const std::string HANGMAN[] = {"\n------+",
"\n |\n |\n |\n |\n |\n------+",
"\n ---+\n |\n |\n |\n |\n |\n------+",
"\n ---+\n | |\n |\n |\n |\n |\n------+",
"\n ---+\n | |\n O |\n |\n |\n |\n------+",
"\n ---+\n | |\n O |\n | |\n |\n |\n------+",
"\n ---+\n | |\n O |\n /| |\n |\n |\n------+",
"\n ----\n | |\n O |\n /|\\ |\n |\n |\n-------",
"\n ----\n | |\n O |\n /|\\ |\n / |\n |\n-------",
"\n ----\n | |\n O |\n /|\\ |\n / \\ |\n |\n-------"};
const std::string WORDS[] = {"zigzagging", "wigwagging", "grogginess", "beekeeping", "mummifying",
"fluffiness", "fulfilling", "shabinness", "revivified", "kobnobbing",
"beekeepers", "wheeziness", "shagginess", "sleeveless", "parallaxes",
"woolliness", "chumminess", "skyjacking", "grubbiness", "wobbliness",
"feebleness", "jaywalking", "alkalizing", "blabbering", "overjoying"};
srand(time(0));
std::string compWord = WORDS[rand() % 25];
char compHiddenWord[] = "----------";
int hangmanPos = 0;
std::vector<int> guessed;
char userGuess;
bool letterCorrect;
while (hangmanPos != 9)
{
std::cout << "\nThis is your hangman:\n" << HANGMAN[hangmanPos] <<
"\n\nThese are the letters you've already guessed:\n\n";
printVector(guessed);
std::cout << "\n\nThis is my word:\n\n" << compHiddenWord <<
"\n\nGuess a letter: ";
std::cin >> userGuess;
guessed.push_back(userGuess);
letterCorrect = false;
for (int a = 0; a < compWord.size(); a++)
if (compWord[a] == userGuess)
{
if (letterCorrect == false)
{
std::cout << userGuess << " is in my word!\n\n\n";
letterCorrect = true;
}
compHiddenWord[a] = userGuess;
}
if (letterCorrect == false)
{
std::cout << "Oops! " << userGuess << " is not in my word.";
hangmanPos++;
}
else
for (int a = 0; a < compWord.size(); a++)
if (compWord == compHiddenWord)
{
std::cout << "Well done, " << compWord << " was my word!";
return 0;
}
}
std::cout << "\nOh Dear! Looks like you've been hanged. My word was actually " << compWord << ".";
}
</code></pre>
<p>Which is supposed to replicate the classic game of hangman visually. Is the code fully optimized? Is there an other way I could improve it?</p>
|
[] |
[
{
"body": "<p>I'm by far no expert, and I might be wrong on some of my statements, so take them as a basis for discussion. Anyway, I am trying to learn about code quality in C++ myself, so I'm giving it a shot.</p>\n\n<ol>\n<li><code>printVector</code> should take the argument as const-ref, because the vector is not supposed to be changed in the function call.</li>\n<li>Consider using an iterator to loop through the vector in <code>printVector</code>. However, in a small-scale program like this I don't see this as a big issue. In larger programs, it might help you to make a function more general. And thanks to C++11's <code>auto</code>, it will be very readable -- even more so if you use a range-based <code>for</code> loop.</li>\n<li>You're using the <code>vector<int></code> <code>guessed</code> to store the <code>char</code>s from <code>userGuess</code>. Why not a <code>vector<char></code> to store <code>char</code>? Would also make the type cast to <code>(char)</code> in <code>printVector</code> unnecessary.</li>\n<li>Also you're mixing C-arrays and STL's <code>std::vector</code>, C-strings (<code>char *</code>) and <code>std::string</code>. Try to stick to the STL versions throughout. If you are using a C++11 capable compiler, you can even initialize the std::vector the same way as you're doing with the C-array now.</li>\n<li>You are using curly braces <code>{}</code> in <code>for</code> loops and <code>if/else</code> statements only when absolutely required. Most style guides encourage using braces for every <code>for/if/else</code> block, or at most allow omitting them for one-line \"blocks\". The reason is readability (you can always expect to find a <code>}</code> where a longer block ends) and editability (It's easy to forget adding the braces when adding a line to the supposed <code>for/if/else</code> block).</li>\n<li>It doesn't look like idiomatic C++ to compare a bool variable with <code>==</code> as in <code>if(letterCorrect == false)</code>. You should use something like <code>if (! letterCorrect)</code> instead.</li>\n<li>You should add a <code>return 0;</code> statement when the user is hanged. As far as I know it isn't required for the <code>main</code> function, but as you're already returning with <code>return 0;</code> when the user guesses the word, you should also do so at the end of the function.</li>\n<li>The condition <code>if (compWord == compHiddenWord)</code> is wrong. You're looping over the array elements, but then you're comparing the pointer to the <code>0th</code> element of the array to the std::string, instead of comparing the array elements. If you follow my suggestion above and change compHiddenWord to std::string, then you can omit the loop and simply write <code>if(compWord == compHiddenWord)</code> (Edit: As I learned, it also works correctly for comparisons of char* and std::string, so I deleted my example for by-character comparison)</li>\n<li>You're using <code>a</code> as a loop index. While this isn't wrong, C++ programmers would typically use <code>i</code> or <code>j</code> for this purpose. </li>\n<li>Edit: Your hangman array goes from 0 to 9 -- but in the <code>while</code> loop you never reach the 9 thanks to the <code>hangManPos != 9</code> condition. Therefore, you will never print the completely hanged hangman.</li>\n</ol>\n\n<p>Let me know what you think!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T15:57:22.943",
"Id": "25594",
"ParentId": "25562",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-27T12:12:16.360",
"Id": "25562",
"Score": "5",
"Tags": [
"c++",
"optimization",
"game",
"hangman"
],
"Title": "Code Review for Hangman in C++"
}
|
25562
|
<p>In MS excel, a date is also represented as a numeric value, with 1-Jan-1900 as the first day. Also in VBA there are dateAdd and dateDiff functions. dateAdd adds a given unit (day, month quarter or a year) to a date. dateDiff returs the difference between the numeric values of two dates. I have written a scheme code in DrRacket to implement these operations. In my code, all dates are represented in the form of a list where the format is (list month day year). date-hash function returs the numeric value of a date. dateAdd and dateDiff do the addition and subtraction. Note: - It is assumed that the user will supply valid dates(i.e I have not checked what happens when user gives values like '(2 31 1999) for a date). </p>
<pre><code>#lang racket
;;List of dates in a normal year and a leap year
(define normal-year-days '((1 31) (2 28) (3 31) (4 30) (5 31) (6 30) (7 31) (8 31) (9 30) (10 31) (11 30) (12 31)))
(define leap-year-days '((1 31) (2 29) (3 31) (4 30) (5 31) (6 30) (7 31) (8 31) (9 30) (10 31) (11 30) (12 31)))
;;all dates are in the form of a list--(list month day year)
;;Contract: month-part:date:number
;;Purpose: To find the month part of a date
;;Example: (month-part '(12 31 2000)) should produce 12
;;Definition:
(define (month-part dt)
(car dt))
;;Contract: day-part:date:number
;;Purpose: To find the day part of a date
;;Example: (day-part '(12 31 2000)) should produce 31
;;Definition:
(define (day-part dt)
(car (cdr dt)))
;;Contract: year-part:date:number
;;Purpose: To find the year part of a date
;;Example: (year-part '(12 31 2000)) should produce 2000
;;Definition:
(define (year-part dt)
(car (cdr (cdr dt))))
;;Contract: is-leap?:number:boolean
;;Purpose: To find whether a year is leap
;;Example: (is-leap? 2000) should produce #t,
;; : (is-leap? 1900) should produce #f
;;Definition:
(define is-leap?
(lambda (yyyy)
(cond ((not (= (remainder yyyy 4) 0)) #f)
(else
(if (= (remainder yyyy 400) 0)
#t
(not (= (remainder yyyy 100) 0)))))))
;;Contract: find-days-from-list:number list:number
;;Purpose: To fetch the no of days in a month from the two lists defined above
;;Example: (find-days-from-list 2 normal-year-days) should produce 28
;;Definition:
(define (find-days-from-list m days-list)
(if (= m (car (car days-list)))
(car (cdr (car days-list)))
(find-days-from-list m (cdr days-list))))
;;Contract: days-in-mon:number number:number
;;Purpose: To fetch the no of days in the given month of the given year
;;Example: (days-in-mon 2 2000) should produce 29
;;Definition:
(define (days-in-mon m y)
(if (is-leap? y)
(find-days-from-list m leap-year-days)
(find-days-from-list m normal-year-days)))
;;Contract: days-in-year:number:number
;;Purpose: To fetch the no of days in the given year
;;Example: (days-in-year 2000) should produce 366
;;Definition:
(define (days-in-year y)
(if (is-leap? y)
366
365))
;;Contract: date-hash:date :number
;;Purpose: To convert a date to a number (i.e number of days since 1-Jan-1900)
;;Example: (date-hash '(1 1 1900)) should produce 1,
;; : (date-hash '(12 31 2000)) should produce 36890
;;Definition:
(define (date-hash dt)
(let ((dd (day-part dt))
(mm (month-part dt))
(yyyy (year-part dt)))
(letrec ((iter (lambda (m d y hash)
(if (= y yyyy)
(if (= m mm)
(if (= d dd)
hash
(iter m (+ 1 d) y (+ 1 hash)))
(iter (+ 1 m) d y (+ (days-in-mon m y) hash)))
(iter m d (+ y 1) (+ (days-in-year y) hash))))))
(iter 1 1 1900 1))))
;;Contract: increment-date:date :date
;;Purpose: To find the next date
;;Example: (increment-date '(1 1 1903)) should produce '(1 2 1903),
;; : (increment-date '(12 31 2000)) should produce '(1 1 2001)
;;Definition:
(define (increment-date dt)
(let ((day (day-part dt))
(month (month-part dt))
(year (year-part dt)))
(cond ((and (= month 12) (= day 31)) (cons 1 (cons 1 (cons (+ 1 year) '()))))
((last-date-of-month? month day year) (cons (+ 1 month) (cons 1 (cons year '()))))
(else (cons month (cons (+ 1 day) (cons year '())))))))
;;Contract: last-date-of-month?:number number number :boolean
;;Purpose: To determine whether a given date is the last day of the month
;;Example: (last-date-of-month? 2 29 2000) should produce #t,
;; : (last-date-of-month? 2 28 2000) should produce #f
;;Definition:
(define (last-date-of-month? m d y)
(if (is-leap? y)
(= d (find-days-from-list m leap-year-days))
(= d (find-days-from-list m normal-year-days))))
;;Contract: dateAdd:symbol(either 'd, 'm, or 'y) number date:date
;;Purpose: To add given number of days, months or years(unit * multiplier) to a date
;;Example: (dateAdd 'd 3 '(2 29 2000)) should produce '(3 3 2000),
;; : (dateAdd 'm 7 '(7 31 1999)) should produce '(2 29 2000)
;; : (dateAdd 'm 7 '(7 28 1999)) should produce '(2 28 2000)
;; : (dateAdd 'y 2 '(2 29 2000)) should produce '(2 28 2002)
;;Definition:
(define (dateAdd unit multiplier prev-date)
(cond ((equal? unit 'd) (add-days multiplier prev-date))
((equal? unit 'm) (add-month-or-year multiplier prev-date 'm))
((equal? unit 'y) (add-month-or-year multiplier prev-date 'y))
(else (error "symbol not identified"))))
;;Contract: add-days:number date:date
;;Purpose: To add given number of days (multiplier) to a date
;;Example: (add-days 3 '(2 29 2000)) should produce '(3 3 2000))
;;Definition:
(define (add-days mult dt)
(if (= mult 0)
dt
(add-days (- mult 1) (increment-date dt))))
;;Contract: add-month-or-year:number date symbol(either 'm or 'y):date
;;Purpose: To add given number of months or year (multiplier) to a date
;;Example: (add-month-or-year 3 '(11 31 1999) 'm) should produce '(2 29 2000))
;; : (add-month-or-year 3 '(3 31 1999) 'm) should produce '(6 30 1999))
;; : (add-month-or-year 3 '(2 28 1997) '9) should produce '(2 28 2000))
;;Definition:
(define (add-month-or-year mult dt unit)
(let* ((month-sum (+ mult (month-part dt)))
(next-year
(if (equal? unit 'm)
(+ (quotient month-sum 12) (year-part dt))
(+ mult (year-part dt))))
(next-month
(if (equal? unit 'm)
(remainder month-sum 12)
(month-part dt)))
(next-day (day-part dt))
(last-day-of-next-month (days-in-mon next-month next-year)))
(if (> next-day last-day-of-next-month)
(cons next-month (cons last-day-of-next-month (cons next-year '())))
(cons next-month (cons next-day (cons next-year '()))))))
;;Contract: dateDiff :date date: number
;;Purpose: To find the number of days between two days(date1 - date 2, the least expected date is '(1 1 1900))
;;Example: (dateDiff '(2 29 2000) '(6 15 1965)) 12677
(define (dateDiff dt1 dt2)
(- (date-hash dt1) (date-hash dt2)))
</code></pre>
|
[] |
[
{
"body": "<p>I don’t have many or deep comments, but since there aren’t any answers yet, here are mine, for what they’re worth.</p>\n\n<p>You have a lot of chains of calls to car and cdr. I would tend to use the c*r shortcuts instead. And when possible, I’d use first, second, third, etc. instead. e.g. Instead of...</p>\n\n<pre><code>(define (year-part dt)\n (car (cdr (cdr dt))))\n</code></pre>\n\n<p>...I would have written...</p>\n\n<pre><code>(define year-part caddr)\n</code></pre>\n\n<p>...or...</p>\n\n<pre><code>(define year-part third)\n</code></pre>\n\n<p>Also, when you just need an alias for an existing function, you can use define to create one rather than wrapping it in another function. (I didn’t test that with Racket, but I use it in other Schemes, and I’m pretty sure I’ve done it in Racket too.)</p>\n\n<p>Likewise, you use chains of cons where I would’ve used the list function or quasiquotation. e.g. Instead of…</p>\n\n<pre><code>(cons 1 (cons 1 (cons (+ 1 year) '())))\n</code></pre>\n\n<p>…I would’ve written…</p>\n\n<pre><code>(list 1 1 (+ 1 year))\n</code></pre>\n\n<p>...or...</p>\n\n<pre><code>`(1 1 ,(+ 1 year))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T15:08:08.287",
"Id": "29650",
"ParentId": "25566",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-27T17:29:42.383",
"Id": "25566",
"Score": "0",
"Tags": [
"scheme",
"datetime"
],
"Title": "Numeric Value for a Date, dateAdd and dateDiff"
}
|
25566
|
<p>I've been working in PHP since almost three years ago. In this time I built a framework as base for my projects.</p>
<p>I want it to be improved, and which other best option there are that use StackExchange?, so I decided to post this here.</p>
<p>The framework is hosted in GitHub:
<a href="https://github.com/CPedrini/Delos" rel="nofollow">https://github.com/CPedrini/Delos</a></p>
<p><strong>Now, the problem:</strong>
I think that there is a mess in the Input class, particularly in how the base's query string is parsed, I have problems to make a definitely decision of how manage URI's parameters.</p>
<p>I've created a <code>.htaccess</code>, which rewrites the URI like this:</p>
<p><strong>From this:</strong> <code>127.0.0.1/home/initialize/param1:value1/param2:value2</code></p>
<p><strong>To this:</strong> <code>127.0.0.1/index.php?p=home/initialize/param1:value1/param2:value2</code></p>
<p>Obviously, this is not needed, it's just a fancy stuff. If <code>mod_rewrite</code> is disabled then all the links on the web must be changed to the rewritten form.</p>
<p>So, in input class constructor the query string <code>p</code> is parsed.</p>
<p>I explode the $_GET['p'] var with separation slashes and delete empty values.</p>
<p>Then if first value doesn't contain a <code>:</code> char I store it in <code>$_GET['section']</code> var, it will be the control to be instantiated.</p>
<p>Then, if section was there, in the second exploded value, if there isn't a <code>:</code> char then this is the method of the control to be called. I store it in <code>$_GET['method']</code>.</p>
<p>Finally, all the others stripped vars are parsed and stripped with the <code>:</code> char. In the previous example, to this:</p>
<pre><code>$_GET['param1'] = value1
</code></pre>
<p>Do you guys think that it's uniform? What changes do you suggest?</p>
<p><strong>EDIT:</strong> Added code in question.</p>
<pre><code>$a = explode('/', $_GET['p']);
foreach ($a as $key => $value) {
if($value == ''){
unset($a[$key]);
}
}
$b = 0;
if(isset($a[0]) && !strstr($a[0],':')){
$_GET['section'] = $this->security->sanitize($a[0]);
$b+=1;
if(isset($a[1]) && !strstr($a[1],':')){
$_GET['method'] = $this->security->sanitize($a[1]);
$b+=1;
}
}
if(isset($a[$b])){
for($b = $b; $b < count($a); $b ++){
if(!strstr($a[$b],'method') && !strstr($a[$b],'section')){
$c = explode(':',$a[$b]);
$_GET[$this->security->sanitize($c[0])] = isset($c[1]) ? $this->security->sanitize($c[1]) : '';
}
}
}
unset($_GET['p']);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-27T20:50:50.667",
"Id": "39610",
"Score": "0",
"body": "Sorry, but a whole library is too much for us to review. Per the [FAQ], you need to include the code you want reviewed in your question (not just link to it). And it should be a reasonable amount of code. You also might want to have a look at this meta question: [How to get feedback on whole projects](http://meta.codereview.stackexchange.com/q/704/2041)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-03T14:00:17.790",
"Id": "39906",
"Score": "0",
"body": "\"*Do you guys think that it's uniform?*\" By *uniform*, do you mean *consistent*?"
}
] |
[
{
"body": "<p>Instead of this block:</p>\n\n<pre><code>foreach ($a as $key => $value) {\n if($value == ''){\n unset($a[$key]);\n }\n}\n</code></pre>\n\n<p>You could simply use <a href=\"http://fr2.php.net/array_filter\" rel=\"nofollow\"><code>array_filter()</code></a> without the second parameter:</p>\n\n<pre><code>$a = array_filter($a);\n</code></pre>\n\n<p>And also your method <a href=\"https://github.com/CPedrini/Delos/blob/master/system/core/Security.php#L14\" rel=\"nofollow\"><code>system/core/Security::sanitize</code></a>\n(I suppose that would be <code>$this->security->sanitize</code> in your code above):</p>\n\n<ul>\n<li><code>strip_tags</code> does simply nothing after <code>htmlspecialchars</code>, because all the tags like <code><b></code> got replaced with <code>&lt;b&gt;</code>.</li>\n<li>If that should secure you from cross site scripting it's definitely applied at the wrong place. You should only escape the html tags before outputting them, not directly after retrieving them, because some methods (like HTML parsers) would then parse the string wrongly.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-03T14:16:38.410",
"Id": "25768",
"ParentId": "25567",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-27T18:15:01.800",
"Id": "25567",
"Score": "2",
"Tags": [
"php",
"mvc"
],
"Title": "Delos MVC PHP Framework"
}
|
25567
|
<p>This application is a "Student Registration System" using JDBC with Oracle as part of our school project. It works as it stands right now.</p>
<p>Questions:</p>
<ol>
<li>What is a better way to structure the project? Why?</li>
<li>Any 'crimes' committed in the code?</li>
</ol>
<p>Details:</p>
<ul>
<li>I've decided to make the interface as a web service/page instead of a swing application.</li>
<li>I'm using Tomcat 7.0, jTable.org jquery based table, JSP, Java.</li>
</ul>
<p>The current files in the project:</p>
<ul>
<li>DBInterface.java</li>
<li>StudentInterface.java</li>
<li>Students.java - Acts as the model interfacing with the database using JDBC</li>
<li>StudentsAjax.jsp - Acts as the view providing data and services to the HTML client
index.html</li>
</ul>
<p>Important parts of the files:</p>
<p><strong><code>DBInterface</code></strong></p>
<pre><code>package models;
public interface DBInterface {
static final String dburl = "jdbc:oracle:thin:@";
static final String dbuser = "xxx";
static final String dbpass = "xxx";
}
</code></pre>
<p><strong><code>StudentInterface</code></strong></p>
<pre><code>package models;
import java.util.List;
import org.json.JSONObject;
public interface StudentsInterface extends DBInterface {
public int createStudent(String sid, String firstName, String lastName, String status, double gpa, String email);
public List<JSONObject> retrieveStudent(String sid);
...........
}
</code></pre>
<p><strong><code>Students</code></strong></p>
<pre><code>package models;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import oracle.jdbc.OracleTypes;
import oracle.jdbc.pool.OracleDataSource;
import org.json.JSONObject;
public class Students implements StudentsInterface {
/*
* Method creates a Student entry into the table.
* @Returns 1 if successfull. 0 otherwise.
* (non-Javadoc)
* @see models.StudentsInterface#createStudent(java.lang.String, java.lang.String, java.lang.String, java.lang.String, int, java.lang.String)
*/
@Override
public int createStudent(String sid, String firstName, String lastName, String status, double gpa, String email) {
int retVal = 0;
try {
// Connection to Oracle server
OracleDataSource ds = new oracle.jdbc.pool.OracleDataSource();
ds.setURL(dburl);
Connection conn = ds.getConnection(dbuser, dbpass);
//Insert
PreparedStatement insert = conn.prepareStatement("INSERT into students VALUES(?,?,?,?,?,?)");
// Input other values
insert.setString(1, sid);
insert.setString(2, firstName);
insert.setString(3, lastName);
insert.setString(4, status);
insert.setDouble(5, gpa);
insert.setString(6, email);
// execute the update
insert.executeUpdate();
// close the result set, statement, and the connection
conn.close();
retVal = 1;
} catch (SQLException ex) {
System.out.println("\n*** SQLException caught ***\n");
} catch (Exception e) {
System.out.println("\n*** other Exception caught ***\n");
}
return retVal;
}
//--------------------------------------
@Override
public List<JSONObject> retrieveStudent(String sid) {
List<JSONObject> t = new ArrayList<JSONObject>();
try {
// Connection to Oracle server
OracleDataSource ds = new oracle.jdbc.pool.OracleDataSource();
ds.setURL(dburl);
Connection conn = ds.getConnection(dbuser, dbpass);
// Query
Statement stmt = conn.createStatement();
System.out.println("\n*** Executing");
String query = "SELECT * FROM students";
if(!sid.equals("ALL"))
query += " WHERE sid = '" + sid + "' ";
// Save result
ResultSet rset;
rset = stmt.executeQuery(query);
System.out.println("\n*** Done");
// determine the number of columns in each row of the result set
ResultSetMetaData rsetMeta = rset.getMetaData();
int columnCount = rsetMeta.getColumnCount();
System.out.println("\n*** Retrieved Student Count is
//insert result into a List
while (rset.next()) {
JSONObject e = new JSONObject();
//loop through columns
for (int i = 1; i <= columnCount; i++) {
String key = rsetMeta.getColumnName(i);
String value = rset.getString(i);
//Convert First char to upper case
key = key.toLowerCase();
key =toString(key.charAt(0)).toUpperCase()+key.substring(1);
e.put(key,value);
}
t.add(e);
}
// close the result set, statement, and the connection
rset.close();
stmt.close();
conn.close();
} catch (SQLException ex) {
System.out.println("\n*** SQLException caught ***\n");
} catch (Exception e) {
System.out.println("\n*** other Exception caught ***\n");
}
return t;
}
....
....
....
}
</code></pre>
<p><strong><code>StudentsAjax</code></strong></p>
<pre><code><%@page import="org.json.JSONObject"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="application/json; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="models.*" %>
<% String incomingAction = (String)request.getParameter("action"); %>
<%
StudentsInterface si = new Students();
JSONObject cover = new JSONObject();
//Decide what to perform based on incoming action.
//-------------------- LIST
if(incomingAction.equals("list")) {
//Prepare JSON output
cover.put("Result","OK");
cover.put("Records", listStudents("ALL"));
}
else //-------------------- CREATE
if(incomingAction.equals("create")) {
//Retrieve result
int reply = si.createStudent(
(String)request.getParameter("Sid")
,(String)request.getParameter("Firstname")
,(String)request.getParameter("Lastname")
,(String)request.getParameter("Status")
,(String)request.getParameter("Email")
);
//Prepare JSON output
cover.put("Result","OK");
cover.put("Record", listStudents((String)request.getParameter("Sid")).get(0) );
}
else //-------------------- UPDATE
.....
.....
.....
//Output in the JSON format.
out.println(cover.toString());
%>
<%!
// -------------------------------- Functions
List<JSONObject> listStudents(String id) {
StudentsInterface si = new Students();
List<JSONObject> t;
//Retrieve result
if(id.equals("ALL")) {
t = si.showAllStudents();
}
else {
t = si.retrieveStudent(id);
}
return t;
}
</code></pre>
|
[] |
[
{
"body": "<p>The first 'crime' is a <a href=\"http://en.wikipedia.org/wiki/SQL_injection\" rel=\"nofollow\">SQL injection</a> vulnerability. You are using a <code>PreparedStatement</code> when inserting, which is great. You avoided the problem there. But this is a problem:</p>\n\n<pre><code>String query = \"SELECT * FROM students\";\nif(!sid.equals(\"ALL\")) \n query += \" WHERE sid = '\" + sid + \"' \";\n</code></pre>\n\n<p>If the <code>sid</code> parameter comes from outside the system (as it does above), it can be anything, including a maliciously crafted string that could cause damage to the system. The simple solution is to build the query using parameter placeholders and use a <code>PreparedStatement</code> here as well.</p>\n\n<pre><code>String query = \"SELECT * FROM students\";\nif(!sid.equals(\"ALL\")) \n query += \" WHERE sid = ?\";\n</code></pre>\n\n<hr>\n\n<p>The second 'crime' is the unsafe closing of database resources. Each resource should be closed in a <code>finally</code> block to ensure that it is properly released, even in the event that an exception occurs while working with the resource.</p>\n\n<p>For example, given this code:</p>\n\n<pre><code>Connection conn = ds.getConnection(dbuser, dbpass);\n// do some work using the connection (what if an exception occurs here?)\nconn.close();\n</code></pre>\n\n<p>The connection will not be closed if an exception occurs between opening and closing the connection. To ensure the connection is always closed, use something like this:</p>\n\n<pre><code>Connection conn = ds.getConnection(dbuser, dbpass);\ntry {\n // do some work using the connection\n}\nfinally {\n conn.close(); // this will be called even if an exception occurs in the try block\n}\n</code></pre>\n\n<p>If you are using Java 7, check out the <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow\">try-with-resources</a> statement. The above code can be simplified to this:</p>\n\n<pre><code>try (Connection conn = ds.getConnection(dbuser, dbpass)) {\n // do some work using the connection\n} // connection will automatically be closed here\n</code></pre>\n\n<p>This also goes for prepared statements, result sets, and any other type of resource that might need to be closed/released.</p>\n\n<hr>\n\n<p><code>createStudent</code> is declared to return an <code>int</code> of 1 if successful, 0 otherwise. It seems like a <code>boolean</code> would better represent the possible outcomes. Having said that, it might be even better to throw an exception in the event of failure.</p>\n\n<hr>\n\n<p>The <code>retrieveStudent</code> function is confusing. The name and argument imply that it will retrieve a single student by an sid, but the return type implies it will return multiple. It is not obvious that you can call it in a 'special' way to get all students. I would recommend splitting this into 2 separate functions:</p>\n\n<pre><code>public JSONObject retrieveStudent(String sid) { ... }\npublic List<JSONObject> retrieveStudents() { ... }\n</code></pre>\n\n<hr>\n\n<p>JSP files are generally used for presentation and very limited logic. It is more common to put request handling logic in a servlet (or controller in a MVC framework), then render the presentation using a JSP. In this case, there really is no presentation, so all of that code could be in a servlet.</p>\n\n<hr>\n\n<p>You should not need to cast the <code>request.getParameter()</code> calls to a <code>String</code>. They are already declared to return a <code>String</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T23:26:05.267",
"Id": "40304",
"Score": "0",
"body": "Thanks Joe for Pointing out the security issue and commenting on the general coding standards ! mucha gracis !"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T14:36:04.583",
"Id": "25593",
"ParentId": "25572",
"Score": "2"
}
},
{
"body": "<ol>\n<li>Follow layered architecture. <a href=\"http://www.cmjackson.net/2010/01/18/mvc-and-n-layer-architecture/\" rel=\"nofollow\">Read about Model-View-Controller pattern.</a> (This should eliminate most of your design issues so I won't specify each one of them here)</li>\n<li>Externalize environment specific entries like dburl, dbuser and dbpassword by <a href=\"http://tomcat.apache.org/tomcat-7.0-doc/jndi-datasource-examples-howto.html\" rel=\"nofollow\">creating a JDBC DataSource in tomcat. You should also pool database connections.</a> This should eliminate the need for <code>DBInterface</code>.</li>\n<li>Use Checked (like StudentNotFoundException etc.) and Unchecked exceptions. Here are the <a href=\"http://www.javapractices.com/topic/TopicAction.do?Id=129\" rel=\"nofollow\">guidelines</a>.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T23:26:48.397",
"Id": "40305",
"Score": "0",
"body": "Thanks Pangea for commenting on and pointing out good resources for improving the design of the system."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T20:34:42.133",
"Id": "25597",
"ParentId": "25572",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "25597",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-27T23:24:03.510",
"Id": "25572",
"Score": "4",
"Tags": [
"java",
"jdbc"
],
"Title": "Student Registration System"
}
|
25572
|
<p>I wanted to wrap the <a href="https://github.com/tulskiy/jkeymaster" rel="nofollow">jkeymaster</a> library in a Clojure wrapper (for my own use, but perhaps also to save others some time). I'm just learning Clojure so I'm still not quite sure what "idiomatic libraries/APIs" look like. In Ruby, I would have created an object with methods, but in one of the clojure books they recommended letting users manage state themselves, so I have function that creates a provider, and this provider must then be passed to the register function.</p>
<p>Here's first an example of usage:</p>
<pre><code>(ns keymaster.core
(:require [keymaster.keymaster :as km]))
(defn -main
"I don't do a whole lot ... yet."
[& args]
(km/register (km/provider) "control shift 1" #(println "hi")))
</code></pre>
<p>And here is the full text of the "library".</p>
<pre><code>(ns keymaster.keymaster
(:gen-class)
(:use (com.tulskiy.keymaster.common)))
(defn provider []
"Gets and initiates a keymaster provider, which must be passed to register to register shortcuts"
(let [provider (com.tulskiy.keymaster.common.Provider/getCurrentProvider true)]
(.init provider)
provider))
(defn- conv-keystroke [x]
"Takes keystroke in the form \"control shift 1\" and returns a Keystroke class"
(javax.swing.KeyStroke/getKeyStroke x))
(defn- conv-listener [f]
"Takes a function with one argument, which will get passed the keycode, and creates a listener
Todo: How to accept a function with or without a parameter to accept hotKey?"
(proxy [com.tulskiy.keymaster.common.HotKeyListener] [] (onHotKey [hotKey] (f))))
(defn register
[provider shortcut listener]
"Registers a shortcut on provider, which will trigger listener (with one argument)"
(let [k (conv-keystroke shortcut)
l (conv-listener listener)]
(.register provider k l)))
</code></pre>
<p>In addition to any general style feedback, both about the coding, and the design of the API, I'm also wondering if there is any way to have conv-listener accept either a 0 or 1-arity function. Right now I made the choice of accepting a 0-arity function, but if someone wanted to pass a 1-arity function, where the first argument would be the name of the keycode called (<code>hotKey</code>), which I would call with <code>(f hotKey)</code>, I would have to rewrite... Possible to allow both? (1-arity is inconvenient for anonymous functions where we really don't need it - which I suspect is most of the time, since we can bind different hotkeys to different listeners).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T02:13:43.513",
"Id": "39701",
"Score": "0",
"body": "I rewrote slightly to have provider instead return a (partial register provider), which the user can then use to register a new key directly, thus exposing only one function to the user. http://github.com/houshuang/keymaster-clj - still interested in feedback"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-02T02:53:32.513",
"Id": "39842",
"Score": "0",
"body": "Got a nice GitHub pull request (another form of code review), and a substantially nicer function is now available - also as a Clojar. But still happy to receive feedback here."
}
] |
[
{
"body": "<p>As a wrapper goes I think this looks fine. The feedback I do have is that I wouldn't use <code>let</code> as often as you do and would use the <a href=\"https://clojuredocs.org/clojure.core/-%3E\" rel=\"nofollow\">treading macro</a> <code>(-> ...)</code> instead. </p>\n\n<p>For example:</p>\n\n<pre><code>(-> (com.tulskiy.keymaster.common.Provider/getCurrentProvider true)\n .init)\n</code></pre>\n\n<p>does the same as </p>\n\n<pre><code>(let [provider (com.tulskiy.keymaster.common.Provider/getCurrentProvider true)]\n (.init provider)\n provider)\n</code></pre>\n\n<p>and it's easier to read and shorter. You could also do it this way:</p>\n\n<pre><code>(.init (com.tulskiy.keymaster.common.Provider/getCurrentProvider true))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-20T16:58:45.917",
"Id": "94190",
"ParentId": "25575",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T01:27:16.537",
"Id": "25575",
"Score": "4",
"Tags": [
"clojure"
],
"Title": "API wrapper for Clojure"
}
|
25575
|
<p>I am working on a program in which 10000 random non-repeating numbers are selectively sorted into ascending order"</p>
<pre><code>import java.util.Random;
public class Sorting {
public static void main (String[] args){
//Here, we initiate an array with the integers
//1 through 10,000 in order.
Random rgen = new Random();
int[] intArray = new int[10000];
for (int i=0; i<10000; i++) {
intArray[i] = i+1;
}
//Here, we randomize the positions.
for (int i=0; i<10000; i++) {
int randomPosition = rgen.nextInt(10000);
int temp = intArray[i];
intArray[i] = intArray[randomPosition];
intArray[randomPosition] = temp;
}
//Here, we check for the maximum in the
//unsorted section of the list.
int max;
for (int i=9999; i>=0; i--) {
max = i;
for (int j=i-1; j>=0; j--)
if (intArray[j]>intArray[max]) {
max = j;
}
//Here, we swap the positions of the
//maximum and the last value in the
//unsorted section of the list.
if (max != i) {
int tmp = intArray[i];
intArray[i] = intArray[max];
intArray[max] = tmp;
}
}
//Here, we output the result.
for (int k=0; k<10000; k++) {
System.out.println(intArray[k]);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I tested it and it works as it should. I would only like to remark a couple of things. </p>\n\n<p>You may want to split your long commented function into shorter ones:</p>\n\n<ul>\n<li><p><code>static int[] InitArray(int length){...}</code></p></li>\n<li><p><code>static int[] SelectionSort(int[]arr){...}</code></p></li>\n<li><p><code>static void Swap(int[]arr, int i, int j){...}</code></p></li>\n<li><p>print the result in the <code>main()</code>, as you do know.</p></li>\n</ul>\n\n<p>This makes your code easier to read and easier to reuse.</p>\n\n<p>Another thing I'd remove is the <code>if(max != i)</code>. I'd rather make the swap every time. If you look carefully, there's small chance that you do this operation unnecessarily, and when you do do it, it won't harm you. </p>\n\n<p>Note: If you keep doing the swap as you do now, you won't have any problem by removing the <code>if</code>. However, if you modify it to make the swap without a temp variable, it might go wrong.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T12:31:26.263",
"Id": "25589",
"ParentId": "25576",
"Score": "5"
}
},
{
"body": "<p>Your code for finding the maximum of an array is wrong. It should be</p>\n\n<pre><code>int maxIndex = 0;\nfor(int k = 1; k < intArray.length; k++)\n if(intArray[k] > intArray[maxIndex])\n maxIndex = k;\n</code></pre>\n\n<p>Additionally, you will have to run the sorting code <code>intArray.length</code> times if you want the array to be truly sorted. This type of sort takes <code>O(n^2)</code> time, as opposed to <code>O(nlogn)</code> of quicksort.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T17:11:14.580",
"Id": "39636",
"Score": "0",
"body": "I tried doing that code but I mess up on the swapping."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T20:19:15.087",
"Id": "39639",
"Score": "0",
"body": "@FernandoMartinez How so? What is happening with the swapping?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-28T02:19:41.793",
"Id": "74172",
"Score": "1",
"body": "2 things - the code is not wrong.... why do you think it is? But -1 vote applied for saying the code should not have correct Braces!!! Will remove -1 when `{ ... }` braces are added to `for` and `if` blocks.... will add +1 if you identify why the original code is broken."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T01:52:58.390",
"Id": "25592",
"ParentId": "25576",
"Score": "4"
}
},
{
"body": "<p><strong>Comments</strong></p>\n\n<p>You're adding a bunch of comments almost everywhere in your code. Let see see what does your comments say about your code.</p>\n\n<pre><code>//Here, we initiate an array with the integers\n//1 through 10,000 in order.\nRandom rgen = new Random();\nint[] intArray = new int[10000];\nfor (int i=0; i<10000; i++) {\n intArray[i] = i+1;\n}\n</code></pre>\n\n<p>Your comments is saying exactly what your code is doing. In fact, I don't really need your comment to know what you're doing. A for-each loop is really common and storing integer in an array is nothing new in the programming world. So is a comment a good way to convey that ? I think not.</p>\n\n<p>I could go through each of your comment and say the same thing, but what your comment really tell to me is that this specific piece of code have a specific function. So if you have take the time to explain what this specific piece of code, why not encapsulate it in a function. The method signature of the previous code block could look like this : <code>public static int[] populateArrayFrom1To10000()</code></p>\n\n<p><strong>Magic Number</strong></p>\n\n<p>You have hard coded 10000 almost everywhere in your code. What if you want to change it to 50000 to test something? You would need to change each occurrence of the number to the new one. One good thing to do is to extract the number to a constant and use this variable instead of \"hard-coding\" it. </p>\n\n<p>Be aware that refactoring your method in different functions will do something like that. You will have a parameter for each of your functions and will minimize the occurrence of the magic number. </p>\n\n<p><em>Minor note</em> </p>\n\n<pre><code> for (int i=0; i<10000; i++) {\n intArray[i] = i+1;\n }\n</code></pre>\n\n<p>I would re-write this loop for this one :</p>\n\n<pre><code> for (int i=1; i=<10000; i++) {\n intArray[i] = i;\n }\n</code></pre>\n\n<p>This is minor, but I find it more clear that you're going through every number and assign it to the array. There is no meaning in doing <code>i + 1</code> as you don't really need to add 1 to <code>i</code> if you change your loop to actually go to <code>10000</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T23:23:04.613",
"Id": "42994",
"ParentId": "25576",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-04-28T02:01:58.780",
"Id": "25576",
"Score": "6",
"Tags": [
"java",
"sorting",
"random"
],
"Title": "Sorting random non-repeating numbers"
}
|
25576
|
<p>I have not completed this but want to make my own template library for wrapping the Win32 API to make it compatible with std::string/std::wstring... Here's a sample of what I've worked with so far. </p>
<p>My questions are:</p>
<ol>
<li>Is this a good idea? </li>
<li>Is it acceptable to undefine Windows API macros (e.g. <code>#undef GetWindowText</code>)?</li>
<li>Is there perhaps a better way to do this besides changing the name scheme (e.g. <code>getWindowText</code> or <code>GetWindowString</code> as opposded to <code>GetWindowText</code>)? I prefer not to change the names.</li>
</ol>
<p>Note: Please don't provide answers like "why don't you just use WTL?" or "just use MFC". I prefer to deal directly with the Windows API; I just want to make it easier to work with <code>std::basic_string</code>. </p>
<p><strong>Implementation</strong></p>
<pre><code>#ifdef _WINUSER_
#undef GetWindowTextLength
template<typename _T> int GetWindowTextLength(HWND hWnd);
template<> int GetWindowTextLength<wchar_t>(HWND hWnd) { return ::GetWindowTextLengthW(hWnd); }
template<> int GetWindowTextLength<char>(HWND hWnd) { return ::GetWindowTextLengthA(hWnd); }
#undef GetWindowText
template<typename _T> std::basic_string<_T> GetWindowText(HWND hWnd);
template<> std::basic_string<wchar_t> GetWindowText(HWND hWnd)
{
std::size_t len = GetWindowTextLength<wchar_t>(hWnd)+1;
std::vector<wchar_t> buffer(len);
::GetWindowTextW(hWnd, buffer.data(), len);
return std::basic_string<wchar_t>(buffer.begin(), buffer.end());
}
template<> std::basic_string<char> GetWindowText(HWND hWnd)
{
std::size_t len = GetWindowTextLength<char>(hWnd)+1;
std::vector<char> buffer(len);
::GetWindowTextA(hWnd, buffer.data(), len);
return std::basic_string<char>(buffer.begin(), buffer.end());
}
#endif//_WINUSER_
</code></pre>
<p><strong>Example Usage</strong></p>
<pre><code>std::basic_string<TCHAR> text = GetWindowText(hWnd);
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n<p>I have not completed this but want to make my own template library for wrapping the Win32 API to make it compatible with std::string/std::wstring...</p>\n<p>Is this a good idea?</p>\n</blockquote>\n<p>If you have the time to do that as an exercise, probably (there should be <em>a lot</em> of effort involved).</p>\n<p>If you want to create a library for future use with an intentional name clash, probably no.</p>\n<blockquote>\n<p>Is it acceptable to undefine Windows API macros (e.g. #undef GetWindowText)?</p>\n</blockquote>\n<p>Not really. If you are careful about it, you can make it work, but these macros can change, their implementation can change depending on where MS wants to take their API in the future and what is behind them may change. You are better off writing your library so that there are no name clashes with MS's macro names.</p>\n<blockquote>\n<p>Is there perhaps a better way to do this besides changing the name scheme (e.g. getWindowText or GetWindowString as opposded to GetWindowText)? I prefer not to change the names.</p>\n</blockquote>\n<p>No. You are better off using new names. Seeing the old names in code would make me (as a client of your lib) assume they have the same semantics, parameters and behavior as the WinAPI defines (macros and all). I would assume the names belong to WinAPI and look automatically to MSDN documentation if I had questions (as in, not in your library's documentation).</p>\n<p>Using the same name would create confusion for other people using your code, for you as a developer (consider what happens when you have an error due to a macro name accidentally included where you define your API: you'd have errors caused by name clash in macro expansion, when you don't want the macro defined. For you it would be (almost) easy to fix, as you know the problem. Consider what happens though, when a client of your code writes:</p>\n<pre><code>#include <yourcode.h> // undefines macros and defines your interface\n#include <windows.h> // redefines macros and causes errors\n</code></pre>\n<p>This is an error that is easy to make for client code (especially for someone not familiar with the implementation details/constraints of your library) and it is something that you cannot enforce in your library code (you actually could, if you issue <code>#error</code> directives in your includes but that is as brittle as the whole concept - MS changes some implementation details and you have to update your code).</p>\n<p>Also consider that your library would have to be complete from the start - if you only implement wrappers for what you need and discover you need a new API, you'd have to define a wrapper to use it - you will be unable to simply include the WinAPI headers and using it from there (as doing so would cause macro expansion clashes).</p>\n<blockquote>\n<p>I prefer to deal directly with the Windows API; I just want to make it easier to work with std::basic_string.</p>\n</blockquote>\n<p>Nothing is stopping you from wrapping the calls. Just don't undefine WinAPI function access macros and replace them with functions (using undefined macro names). You'd introduce a naming/include limitation in client code that would be hard to get around to in specific cases, and would only work with ugly workarounds in client code or by requiring modifications to your library).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T22:27:08.190",
"Id": "39815",
"Score": "0",
"body": "+1 Including the `Windows.h` header after my library was definitely something I hadn't thought about."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T14:40:57.800",
"Id": "25618",
"ParentId": "25581",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "25618",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T04:40:09.853",
"Id": "25581",
"Score": "3",
"Tags": [
"c++",
"template",
"windows",
"winapi"
],
"Title": "std::string/std::wstring template wrapper for Win32 API"
}
|
25581
|
<p>I'm a bit confused if saving the information to session code below, belongs in the controller action as shown below or should it be part of my Model? </p>
<p>I would add that I have other controller methods that will read this session value later.</p>
<pre><code>public ActionResult AddFriend(FriendsContext viewModel)
{
if (!ModelState.IsValid)
{
return View(viewModel);
}
// Start - Confused if the code block below belongs in Controller?
Friend friend = new Friend();
friend.FirstName = viewModel.FirstName;
friend.LastName = viewModel.LastName;
friend.Email = viewModel.UserEmail;
httpContext.Session["latest-friend"] = friend;
// End Confusion
return RedirectToAction("Home");
}
</code></pre>
<p>I thought about adding a static utility class in my Model which does something like below, but it just seems stupid to add 2 lines of code in another file.</p>
<pre><code>public static void SaveLatestFriend(Friend friend, HttpContextBase httpContext)
{
httpContext.Session["latest-friend"] = friend;
}
public static Friend GetLatestFriend(HttpContextBase httpContext)
{
return httpContext.Session["latest-friend"] as Friend;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T08:47:53.373",
"Id": "39624",
"Score": "1",
"body": "Why are you asking this twice? http://stackoverflow.com/questions/16260442/mvc-does-putting-data-in-cache-or-session-belong-in-controller"
}
] |
[
{
"body": "<h2>Yes</h2>\n\n<p>Yes it belong s to the controller. If you are interacting with HTTP... stuff then you should do it in your MVC tier in your N-tier application stack. If you would put this thing in the model then it would be in your business logic and then you would have a hard dependency on the HttpContext which is bad becouse what would happen if you would create a WCF service endpoint for your business logic?</p>\n\n<p>MVC tier is just an public service interface which is communication with the users on HTTP channel nothing more. If you don't have an N-tier design in your app then you should get start to clean up your solution and put things were they belong.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T08:42:08.250",
"Id": "25584",
"ParentId": "25583",
"Score": "0"
}
},
{
"body": "<p>This is something I always get confused with as well!!</p>\n\n<p>I would probably think it's fine where it is but if you were considering moving it I might suggest using an interface and injecting that into the controller. That way it doesn't matter where the latest friend information is persisted and the controller remains separate from this concern.</p>\n\n<p>Although this might be overkill for your situation and example of this in use might be:</p>\n\n<pre><code>public interface IFriendProvider\n{\n Friend GetLatest();\n void SaveLatest(Friend friend);\n}\n</code></pre>\n\n<p>Your controller action might then become:</p>\n\n<pre><code>public ActionResult AddFriend(FriendsContext viewModel)\n {\n if (!ModelState.IsValid)\n { \n return View(viewModel);\n }\n\n // where _friendProvider has been supplied through the controller constructor\n // using DI (See Ninject or Unity for example)\n _friendProvider.SaveLatest(new Friend()\n {\n FirstName = viewModel.FirstName;\n LastName = viewModel.LastName;\n Email = viewModel.UserEmail; \n }); \n}\n</code></pre>\n\n<p>Your implementation of the friendProvider would be something like:</p>\n\n<pre><code>public class SessionFriendProvider : IFriendProvider\n{\n private readonly HttpContext __httpContext;\n\n // or instead of Context maybe the session object itself?\n public SessionFriendProvider(HttpContextBase context)\n {\n __httpContext = context;\n }\n\n public void SaveLatest(Friend friend)\n {\n _httpContext.Session[\"latest-friend\"] = friend;\n }\n\n public Friend GetLatest() \n {\n return _httpContext.Session[\"latest-friend\"] ?? new Friend();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T20:41:28.833",
"Id": "25598",
"ParentId": "25583",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T08:21:10.257",
"Id": "25583",
"Score": "1",
"Tags": [
"c#",
"asp.net-mvc",
"session"
],
"Title": "Saving data to a session"
}
|
25583
|
<p>How would you write this jQuery code cleaner and better? I'm a beginner.</p>
<pre><code>$.extend({
misTip : function($tipSettings) {
$tip = $tipSettings.tip ? $tipSettings.tip : '';
$closeTime = $tipSettings.closeTime ? $tipSettings.closeTime : 1500;
$refresh = $tipSettings.refresh;
delete $tipSettings.msg;
delete $tipSettings.closeTime;
delete $tipSettings.refresh;
//dialog ui tip
var tpl = '';
tpl += '<div style="padding:5px 20px">';
tpl += '<p style="font-size:14px;padding-top:10px;"><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span><span class="ajaxMsg">' + $tip + '</span></p>';
tpl += '</div>';
var $defaultTipSettings = {
title : 'notice',
slow : 'slide',
width : 320,
open : function (event, ui) {
$(this).bind("keypress",function(event){
$(this).dialog('close');
});
$dialog = $(this);
setTimeout(function(){
$dialog.dialog('close');
if ($refresh) {
_refresh();
}
}, $closeTime);
}
}
var $tipSettings = $.extend($defaultTipSettings, $tipSettings);
$(tpl).dialog($tipSettings);
}
});
</code></pre>
|
[] |
[
{
"body": "<p>You are using several global variables in the code, which should be local.</p>\n\n<p>You are prefixing variable names with <code>$</code> for no apparent reason, that only makes the code harder to read.</p>\n\n<p>You can use the <code>||</code> operator instead of the conditional operator to check for missing values.</p>\n\n<p>You are using the variable <code>_refresh</code> in the code, I assume that it should be the variable that you defined instead.</p>\n\n<pre><code>$.extend({\n misTip : function(tipSettings) {\n var tip = tipSettings.tip || '';\n var closeTime = tipSettings.closeTime || 1500;\n var refresh = tipSettings.refresh;\n\n delete tipSettings.msg;\n delete tipSettings.closeTime;\n delete tipSettings.refresh;\n\n //dialog ui tip\n var tpl =\n '<div style=\"padding:5px 20px\">' +\n '<p style=\"font-size:14px;padding-top:10px;\"><span class=\"ui-icon ui-icon-alert\" style=\"float:left; margin:0 7px 20px 0;\"></span><span class=\"ajaxMsg\">' + tip + '</span></p>' +\n '</div>';\n\n var defaultTipSettings = {\n title : 'notice',\n slow : 'slide',\n width : 320,\n open : function (event, ui) {\n $(this).bind(\"keypress\",function(){\n $(this).dialog('close');\n });\n var dialog = $(this);\n setTimeout(function(){\n dialog.dialog('close');\n if (refresh) {\n refresh();\n }\n }, closeTime);\n }\n }\n var settings = $.extend(defaultTipSettings, tipSettings);\n $(tpl).dialog(settings);\n }\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T14:13:02.480",
"Id": "25590",
"ParentId": "25585",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "25590",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T09:14:43.780",
"Id": "25585",
"Score": "-1",
"Tags": [
"javascript",
"beginner",
"jquery-ui"
],
"Title": "Tip dialog jQuery plugin"
}
|
25585
|
<p>The function <code>func(int m,int n)</code> outputs (for m = 3, n = 5):</p>
<pre><code>3
34
345
34
3
</code></pre>
<p>I came up with this code:</p>
<pre><code>void func(int m,int n)
{
for(int i=1;i<n-m+2;i++)
{ int k=i;
int j=m;
while(k>0)
{
System.out.print(j);
k--;j++;
}
System.out.println("");
}
for(int i=n-m;i>0;i--)
{ int k=i;
int j=m;
while(k>0)
{
System.out.print(j);
k--;j++;
}
System.out.println("");
}
}
</code></pre>
<p>Is there an alternate, better way to do it? Can it be more efficient?</p>
|
[] |
[
{
"body": "<p>You can do it recursively:</p>\n\n<pre><code>void func(int m,int n) {\n if (m == n) {\n System.out.println(m);\n } else {\n func(m, n - 1);\n for (int i = m; i <= n; i++) {\n System.out.print(i);\n }\n System.out.println(\"\");\n func(m, n - 1);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T11:09:28.567",
"Id": "25588",
"ParentId": "25587",
"Score": "4"
}
},
{
"body": "<p>Dividing the work over some helper methods with explaining names helps making the code more readable and reduces <a href=\"http://en.wikipedia.org/wiki/Cyclomatic_complexity\" rel=\"nofollow\">cyclometic complexity</a> per method.</p>\n\n<p>Use a <code>StringBuilder</code> to compose the result String, as this anbles building the String non sequentially.</p>\n\n<p>Separate the building logic from the output logic, they are two different responsibilities (reasons for change).</p>\n\n<p>I've kept the method name <code>func</code> but I suggest you choose a more meaningful name.</p>\n\n<pre><code>private static final String DOUBLE_NEWLINE = \"\\n\\n\";\n\npublic void func(int m, int n) {\n System.out.println(buildFuncString(m, n));\n}\n\nprivate String buildFuncString(int m, int n) {\n String fullEnumeration = enumerateFromTo(m, n);\n StringBuilder builder = new StringBuilder(fullEnumeration);\n for (int i = n - m; i > 0; i--) {\n String substring = fullEnumeration.substring(0, i);\n builder.insert(0, DOUBLE_NEWLINE).insert(0, substring);\n builder.append(DOUBLE_NEWLINE).append(substring);\n }\n return builder.toString();\n}\n\nprivate String enumerateFromTo(int m, int n) {\n StringBuilder builder = new StringBuilder();\n for (int i = m; i <= n; i++) {\n builder.append(i);\n }\n return builder.toString();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T07:05:07.043",
"Id": "25607",
"ParentId": "25587",
"Score": "2"
}
},
{
"body": "<p>I'll try solve it using a stack. (I've renamed your function 'func' to 'printWithStack' )</p>\n\n<pre><code>void printWithStack(int m, int n) {\n\n Stack<Integer> integerStack= new Stack<Integer>();\n\n // Go uphill, print up to m = n\n for( int i=m ; i<=n; i ++) { \n if(i <= n) integerStack.push(i); \n print(integerStack); \n }\n\n // Go downhill, print until the stack is empty \n while(!integerStack.isEmpty()) {\n integerStack.pop();\n print(integerStack);\n }\n}\n\n/**\n * Print all the element of the given stack on a line\n */\nvoid print(Stack<Integer> stackToPrint) {\n if(!stackToPrint.isEmpty()) {\n for(Integer element : stackToPrint) System.out.print(element);\n System.out.println();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T08:29:21.940",
"Id": "25608",
"ParentId": "25587",
"Score": "2"
}
},
{
"body": "<p>The recursive looks the cleanest. To extend the normal loop approaches:</p>\n\n<pre><code>public static void printNumbersTriangle(final int start, final int end) {\n if (!(start <= end))\n throw new IllegalArgumentException(\"Start not <= end. Start: \" + start + \", end: \" + end);\n int position = start;\n int modifier = 1;\n while (position >= start) {\n printAllNumbersFromStartUntilEndExclusive(start, position);\n position += modifier;\n if (position == end)\n modifier = -1;\n }\n}\n\npublic static void printAllNumbersFromStartUntilEndExclusive(final int start, final int end) {\n for (int i = start; i <= end; i++)\n System.out.print(i);\n System.out.println();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T21:40:38.520",
"Id": "25663",
"ParentId": "25587",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T09:50:56.760",
"Id": "25587",
"Score": "3",
"Tags": [
"java",
"performance",
"formatting"
],
"Title": "Number pyramid in Java"
}
|
25587
|
<p>I've been teaching myself Ruby this weekend. First of all, I am aware that there is a built-in sort function. I've written this code strictly as an exercise.</p>
<p>I have background primarily in C# and Javascript, so this is a change of pace for me.</p>
<p>If you are a seasoned professional with a lot of Ruby experience, my code will probably make your hair stand on end, so please advise me how to do this the right way in case I'm ever sitting next to you writing Ruby code.</p>
<p>The code appears to work, but I'll bet that the convention that I'm used to using is not the best way to get things done in Ruby.</p>
<pre><code>class Array
@@swap = lambda {|a, i0, i1|
x = a[i0]
a[i0] = a[i1]
a[i1] = x
# puts "Swapping elements at position #{i0} and #{i1}"
# puts a.inspect()
}
@@recurse = lambda {|a, iStart, iEnd|
# puts "iStart = #{iStart}, iEnd = #{iEnd}, a=#{a.inspect()}"
# base case
return if (iStart == iEnd)
pivot = a[iEnd]
i = iStart # iterator to count over the array
j = iStart # the index of the last element less than the pivot
while i < iEnd
if a[i] < pivot
@@swap.call(a, i, j)
j += 1
end #if
i += 1
end #while
# Put the pivot element after the last element less than the pivot element
@@swap.call(a, j, iEnd)
# Recurse over the elements less than the pivot and the elements greater than the pivot
thread0 = Thread.new() { @@recurse.call(a, iStart, j - 1) if j != iStart }
.join()
thread1 = Thread.new() { @@recurse.call(a, j + 1, iEnd) if j != iEnd }
.join()
}
def quickSort()
@@recurse.call(self, 0, self.length() - 1)
end #quickSort
end
a = []
i = 0
until i === 1000
a.push(i)
i += 1
end
a.shuffle()
a.quickSort()
errorFound = false
i = 0
until i === 1000
errorFound = true unless (i === a[i])
i += 1
end
puts 'All sorted' unless errorFound
puts 'Error' if errorFound
</code></pre>
|
[] |
[
{
"body": "<p>Here's my two cents on this.</p>\n\n<ul>\n<li><p>For starters, swapping two elements can be expressed in ruby this way :</p>\n\n<pre><code>a, b = b, a\n</code></pre></li>\n<li><p>Instead of : </p>\n\n<pre><code>a = []\ni = 0\nuntil i === 1000\n a.push(i)\n i += 1\nend \n</code></pre>\n\n<p>use a range and cast it into an array:</p>\n\n<pre><code>a = (0..1000).to_a\n</code></pre></li>\n<li><p>Instead of : </p>\n\n<pre><code>errorFound = false\ni = 0\nuntil i === 1000\n errorFound = true unless (i === a[i])\n i += 1\nend\n</code></pre>\n\n<p>do this : </p>\n\n<pre><code>error_found = a.each_with_index.any? {|value, index| value != index}\n</code></pre></li>\n<li><p>Be aware that threads in ruby <a href=\"http://www.ruby-forum.com/topic/216913\" rel=\"nofollow\">aren't always 'real' threads</a></p></li>\n<li><p>The use of class variables is somewhat shuned by ruby developpers because these variables are shared between the class and its descendants, which leads to nasty bugs when you are not aware of this property. Class-level instance variables are preferred, and some have implemented mechanisms for <a href=\"http://apidock.com/rails/Class/class_attribute\" rel=\"nofollow\">\"real\", inheritable class variables</a> </p></li>\n<li><p>In general, learn by heart all methods from the <a href=\"http://ruby-doc.org/core-2.0/Enumerable.html\" rel=\"nofollow\">Enumerable Module</a>. These are really handy and expressive, and any class just needs to implement an <code>each</code> method to fully benefit from its iterative goodness... In the end, ruby devs tend to prefer iterators over loops, except for some special cases (in place modification messing with indexes, etc.). </p></li>\n<li><p>Use blocks / procs / lambdas. Blocks are just plain awesome and any idiomatic ruby script is bound to be riddled with them. Coding with closures / anonymous functions can be hard to grasp at first, but it's really rewarding. That said, I don't really get why you want to use procs in this case (i.e. for \"recurse\"). A class (\"static\") method would be suitable here. </p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T22:11:49.163",
"Id": "25602",
"ParentId": "25596",
"Score": "4"
}
},
{
"body": "<p>What m_x said, plus Some stylistic suggestions:</p>\n\n<p>For long blocks (like your lamba initialisations) do ... end are usually preferred for readability to curly braces (though some would beg to differ).</p>\n\n<p>Comments documenting methods are usually put before the method (<a href=\"http://www.caliban.org/ruby/rubyguide.shtml#comments\" rel=\"nofollow\">makes auto-documentation tools happy</a>)</p>\n\n<p>It's arguably preferable to just define method functionality inside a method definition instead of a separate object (i.e. a lambda). If you want to define the instance specific version of the method in terms of the general version, you can do something like:</p>\n\n<pre><code>class Array\n def self.quicksort a, iStart=0, iEnd=nil\n iEnd ||= a.length-1\n ...\n end\n\n def quicksort\n self.class.quicksort self\n end\nend\n</code></pre>\n\n<p>Also </p>\n\n<pre><code>i = iStart\nwhile i < iEnd\n ...\n i += 1\nend\n</code></pre>\n\n<p>can be:</p>\n\n<pre><code>iStart.upto(iEnd-1) do |i|\n ...\nend\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>(iStart...iEnd).each do |i|\n ...\nend\n</code></pre>\n\n<p>Unnecessary brackets in method calls are unnecessary (and bad feng shui). </p>\n\n<p>Finally it is acceptable and arguably neater when attaching a <em>short</em> method call to the tail of a block to keep it on the same line i.e. <code>thread = Thread.new {...}.join</code>. This can improve readability a lot in some instances: <code>read_books = book_shelf.each_book.map { |book| book.read if book.cover.is_pretty? }.compact</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T17:13:03.520",
"Id": "39682",
"Score": "0",
"body": "+1, although i do prefer using brackets in method signatures and calls, with one space on each side : `example.execute( self )`. I find it easier to spot arguments when scanning terse lines of code, and all in all there's many situations where you must use them anyway. That said, it's purely a matter of taste, and sometimes it justs feels more natural not to use brackets. YMMV"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T13:39:22.060",
"Id": "25616",
"ParentId": "25596",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T20:10:08.603",
"Id": "25596",
"Score": "1",
"Tags": [
"ruby",
"sorting",
"quick-sort"
],
"Title": "Quicksort in Ruby!"
}
|
25596
|
<p>This is a simple packet sniffer that turns on LEDs when there's network activity. It works by picking up filters in a configuration file and listen for activity in those filters. When there's a captured packet, it sets a bit in a bit-mask that corresponds to the filter index in the config file. Then, once all the filters have been polled, it sends the bit-mask to an LED device ( in this case, an Arduino ) and the lights turn on. </p>
<p>I'm just looking for suggestions or any sort of feedback on the code. All comments are welcome.</p>
<pre><code>#include "main.h"
int close_signal = 0;
int main( int argc, char * argv[] ){
struct filter_node * head = 0;
FILE * led_device = 0;
FILE * config_file = 0;
char * line_buffer = 0;
char errbuf[ PCAP_ERRBUF_SIZE ];
char * dev = 0;
bpf_u_int32 maskp;
bpf_u_int32 netp;
unsigned int led_mask = 0;
printf( "Starting %s..\n", argv[ 0 ] );
/* Daemonize */ {
pid_t p_id = fork( ); // start in new process
if( p_id < 0 ){
printf( "Couldn't start %s\n", argv[ 0 ] );
return -1;
}
else if( p_id > 0 ) return 0;
if( setsid( ) < 0 ){ // disconnect from terminal
if( errno != EPERM ){ // EPERM == already disconnected
printf( "Couldn't start %s\n", argv[ 0 ] );
return -1;
}
}
int i = 0; // close standard io
for( ; i < 3; i++ ) close( i );
// only keep stdout, redirected to a file
if( open( NULL_DEVICE, O_RDONLY ) < 0 ) return -1;
if( open( OUTPUT_FILE, O_WRONLY | O_CREAT | O_TRUNC ) < 0 ) return -1;
if( open( NULL_DEVICE, O_WRONLY ) < 0 ) return -1;
// sets 'close' to true so that a cleanup
// can occur before process exits
if( signal( SIGTERM, exit_handler ) == SIG_ERR ){
printf( "Error creating exit handler!\n" );
return -1;
}
}
printf( "%s is daemonized\nInitializing packet sniffers..\n", argv[ 0 ] );
led_device = fopen( LED_DEVICE, "rw+" );
if( !led_device ){
printf( "Error opening %s\n", LED_DEVICE );
return -1;
}
config_file = fopen( CONFIG_FILE, "r+" );
if( !config_file ){
printf( "Error opening %s\n", CONFIG_FILE );
fclose( led_device );
return -1;
}
struct filter_node * temp = 0;
int i = 0;
// for reading lines of the config file
line_buffer = malloc( LINE_BUFFER_SIZE );
if( !line_buffer ){
printf( "Couldn't allocate memory for %s\n", argv[ 0 ] );
fclose( config_file );
fclose( led_device );
}
// look up netmask of the network
if( pcap_lookupnet( 0, &netp, &maskp, errbuf ) < 0 ){
printf( "Error looking up netmask: %s\n", errbuf );
return -1;
}
// each line of the file represents a network filter
for( ; fgets( line_buffer, LINE_BUFFER_SIZE, config_file ); i++ ){
printf( "Starting sniffer %d for %s", i, line_buffer );
// create node in linked list
temp = malloc( sizeof( struct filter_node ) );
if( !temp ){
printf( "Couldn't allocate memory!\n" );
continue;
}
// create a handle for each filter
temp->cap_handle = pcap_open_live( 0, BUFSIZ, 1, -1, errbuf );
if( !temp->cap_handle ){
printf( "pcap_open_live(): %s\n" , errbuf );
free( temp );
continue;
}
// compile filter
if( pcap_compile( temp->cap_handle, &temp->fp, line_buffer, 0, netp ) < 0 ){
printf( "Error compiling expression: %s", line_buffer );
pcap_close( temp->cap_handle );
free( temp );
continue;
}
// assign filter to handle
if( pcap_setfilter( temp->cap_handle, &temp->fp ) < 0 ){
printf( "Error setting filter: %s", line_buffer );
pcap_close( temp->cap_handle );
pcap_freecode( &temp->fp );
free( temp );
continue;
}
// set to non blocking calls
// this is so that each filter can be checked
// in the same instance of time
if( pcap_setnonblock( temp->cap_handle, 1, errbuf ) < 0 ){
printf( "Error setting Non-block mode: %s\n", errbuf );
pcap_close( temp->cap_handle );
pcap_freecode( &temp->fp );
free( temp );
continue;
}
temp->index = i; // assign the index of the node
temp->next = head; // add to filter list
head = temp; // set head of filter list
}
fclose( config_file ); // no longer need config file
free( line_buffer ); // no longer need line buffer
while( !close_signal ){ // main loop, stopped by signal handler
for( temp = head, led_mask = 0; temp; temp = temp->next ){ // traverse filter list
if( pcap_dispatch( temp->cap_handle, // acknowledge all packets
-1,
capture_callback,
( u_char * ) &temp->index ) > 0 )
led_mask |= ( 1 << temp->index ); // set bit index in led_mask
}
if( led_mask ){ // when all filters have been polled, send the led mask to device
if( fwrite( &led_mask, 1, 1, led_device ) > 0 ) fflush( led_device );
}
}
// the program was signaled
// close the led device
fclose( led_device );
// free filter, capture handle, and memory of
// all nodes in the filter list
while( head ){
printf( "Closing sniffer %d\n", head->index );
pcap_freecode( &head->fp );
temp = head->next;
free( head );
head = temp;
}
// confirm program has closed correctly
printf( "%s closed\n", argv[ 0 ] );
return 0;
}
void capture_callback( u_char * index, const struct pcap_pkthdr* pkthdr, const u_char * packet ){
// nothing to be done here
}
void exit_handler( int sig ){
close_signal = 1; // closes main loop
}
</code></pre>
<p>And if anyone is interested, the entire project is on <a href="https://code.google.com/p/th-arduino-network-status/" rel="nofollow">Google Code</a>.</p>
|
[] |
[
{
"body": "<p>Your code looks nice and compiles cleanly (once I filled in the blanks). I\nhave a few comments, the main one being your lack of functions. Putting\neverything in main is not practicable beyond a certain size and you have\nexceeded that size. Various functions should be extracted from main,\nincluding at least the daemonize code, creating each filter node and the main\nloop. So main might look something like (simplified):</p>\n\n<pre><code> daemonize();\n head = configure_filter_chain();\n if (head) {\n int led = open_led();\n while (!close_signal) {\n filter(head, led);\n }\n }\n</code></pre>\n\n<p>Some detailed comments:</p>\n\n<ul>\n<li><p>use <code>perror</code> to print errors where <code>errno</code> has been set. This prints to\nstderr, not stdout, so you will need to open a descriptor for that.</p></li>\n<li><p>do you need to open descriptors for unused stdin/stderr (or stdin/stdout -\nsee previous point)? Are they used? If not why not just fclose(stdin)?</p></li>\n<li><p>it is better to open resources only when you need them. For example you\nopened a file on the LED device long before it is needed.</p></li>\n<li><p>why use buffered i/o on the LED? Wouldn't unbuffered (ie open/write) be\nmore suitable than buffered (fopen/fwrite/fflush)?</p></li>\n<li><p>the content of your big for-loop has a few issues. For a start, it should\nprobably be a function. Also, you allocate memory before it is needed, and\nhence have to free it at several points. And your error recovery (closing\nresources obtained) is duplicated. Something like the following would be\nneater, where <code>create_node</code> allocates a new node and adds it to the linked\nlist:</p>\n\n<pre><code>static void create_filter_node(const char *line, bpf_u_int32 netp, struct filter_node **head)\n{\n char errbuf[PCAP_ERRBUF_SIZE];\n struct bpf_program fp;\n int compiled = -1;\n\n pcap_t *handle = pcap_open_live(0, BUFSIZ, 1, -1, errbuf);\n if (!handle){\n fprintf(stderr, \"...\" , errbuf);\n }\n else if ((compiled = pcap_compile(handle, &fp, line, 0, netp)) < 0){\n fprintf(stderr, \"...\" , line);\n }\n else if (pcap_setfilter(handle, &fp) < 0){\n fprintf(stderr, \"...\" , line);\n }\n else if (pcap_setnonblock(handle, 1, errbuf) < 0){\n fprintf(stderr, \"...\" , errbuf);\n }\n else if (create_node(handle, fp, i, head)) {\n return; // ie. Success!\n }\n\n if (handle) {\n pcap_close(handle);\n }\n if (compiled == 0) {\n pcap_freecode(&fp);\n }\n}\n</code></pre>\n\n<p>Some people use <code>goto</code> statements to handle this sort of clean-up, instead\nof the if-else-if chain. In this case that seems unnecessary.</p></li>\n</ul>\n\n<p>And some pedantic comments</p>\n\n<ul>\n<li><p>Adding spaces inside brackets is unusual. It is more normal to write <code>if (condition)</code>\nrather than <code>if( condition )</code></p></li>\n<li><p><code>dev</code> is unused</p></li>\n<li><p>on failure it is normal to return EXIT_FAILURE (from stdlib) not -1</p></li>\n<li><p>define loop variables in the for-loop if possible, so <code>for (int i=0; ...)</code></p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T19:11:28.837",
"Id": "39688",
"Score": "0",
"body": "thanks! I'll be going through your points as I rewrite the code. When I finish editing the source, should I edit this question for more review? or, should I post a new review?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T19:24:43.683",
"Id": "39690",
"Score": "0",
"body": "Personally I'd post a new review to keep it separate. You are more likely to get a follow-up review that way I expect. But the choice is yours :-) BTW, you are likely to get other reviews here, so perhaps wait to see what others have to say before taking my advice as gospel."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T13:23:52.353",
"Id": "25614",
"ParentId": "25600",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "25614",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T21:22:41.263",
"Id": "25600",
"Score": "3",
"Tags": [
"c",
"linux",
"networking"
],
"Title": "lightweight packet sniffer review"
}
|
25600
|
<p>I'd like anyone here to help me clean up my code. It's about calculating men's risk of getting coronary heart disease. <a href="https://gist.github.com/akosijiji/57d0da84b24ea9f6dd0e" rel="nofollow">Here's the link to my method</a>.</p>
<pre><code>private void calculateForMen(){
// TODO
// For Men
// 20–34 years: Minus 9 points.
// 35–39 years: Minus 4 points.
// 40–44 years: 0 points.
// 45–49 years: 3 points.
// 50–54 years: 6 points.
// 55–59 years: 8 points.
// 60–64 years: 10 points.
// 65–69 years: 11 points.
// 70–74 years: 12 points.
// 75–79 years: 13 points.
// TODO Men Age 20-34
if( strAge.equals("20 to 34") ){ // Minus 7 points
// First point
points = points - 9;
// Second point
if( strTotalCholesterol.equals("160 to 199") ){// 4 points
points = points + 4;
}
else if( strTotalCholesterol.equals("200 to 239") ){ // 8 points
points = points + 7;
}
else if( strTotalCholesterol.equals("240 to 279") ){ // 11 points
points += 9;
}
else if( strTotalCholesterol.equals("280 or greater") ){ // 13 points
points += 11;
}
// Third point
if( strHDL.equals("60 or greater") ) // Minus 1 point
{
points -= 1;
}
else if( strHDL.equals("40 to 49") ){ // 1 point
points += 1;
}
else if( strHDL.equals("Less than 40") ){ // 2 points
points += 2;
}
// Fourth point
if( strSBP.equals("130 to 139") ){ // 2 points
points += 1;
}
else if( strSBP.equals("140 to 159") ){ // 3 points
points += 1;
}
else if( strSBP.equals("160 or greater") ){ // 4 points
points += 2;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T11:39:46.937",
"Id": "39657",
"Score": "0",
"body": "Longest single method EVER! So first thing you need to look up is how to use methods / refactor. Second your indention levels are a bit out of sync. That is first glance. I'll edit a little bit and post a answer in a second"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T12:04:28.027",
"Id": "39661",
"Score": "0",
"body": "Your repeat yourself very frequently. There are a few easy ways around this, one is to make a interface for each gender/age group. That interface will have the strings `strSBP`, `strSmoker` etc and it will have methods such as `GetSBPPoints()` `GetSmokerPoints` etc. Then in your main method you make a instantiate a new class based on the age and gender then call the methods to get the points. Once you get your points then display your message."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T12:05:24.500",
"Id": "39662",
"Score": "0",
"body": "Another way around this is to put in a few parameters in those methods to calculate the Points so that it can do the math to adjust the returned points."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T12:13:56.980",
"Id": "39663",
"Score": "0",
"body": "Hello can you show me how to implement those? Thanks I really need your help because I'm new to java programming."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T12:35:27.870",
"Id": "39665",
"Score": "0",
"body": "Please paste the code into the question as per the FAQ, otherwise I'll have to close the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T12:42:52.003",
"Id": "39667",
"Score": "0",
"body": "@WinstonEwert my codes are very long so I just pasted it in gist."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T13:08:45.117",
"Id": "39668",
"Score": "0",
"body": "@neknekmouh, I don't care how long it is. You have to post it into the question. If it can't fit post a sample of it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T13:10:38.627",
"Id": "39669",
"Score": "0",
"body": "@WinstonEwert I posted the code as per your request..."
}
] |
[
{
"body": "<p>So I'm not going to show you what a interface is (since I am at work) but I can show you a small blurb of what i'm talking about. Note that the number I put into this are not meant to be accurate, they are just to get you started.</p>\n\n<pre><code>interface Patient\n{\n int getAgePoints();\n int getChloresterolPoints(String chlor);\n int getHDLPoints(String hdl);\n int getSBPPoints(String sbp);\n int getSmokerPoints(String smoker);\n}\nclass UnkownPatient implements Patient\n{\n public UnkownPatient()\n {\n }\n @Override\n public int getChloresterolPoints(String chlor)\n {\n return 0;\n }\n\n @Override\n public int getHDLPoints(String hdl)\n {\n return 0;\n }\n\n @Override\n public int getSBPPoints(String sbp)\n {\n return 0;\n }\n\n @Override\n public int getSmokerPoints(String smoker)\n {\n return 0;\n }\n\n @Override\n public int getAgePoints()\n {\n return 0;\n }\n\n}\nclass PatientMan20to34 implements Patient\n{\n public PatientMan20to34()\n {\n }\n\n @Override\n public int getAgePoints()\n {\n return -9;\n }\n\n @Override\n public int getChloresterolPoints(String chlor)\n {\n switch (chlor)\n {\n case \"160 to 199\":\n return 4;\n case \"200 to 239\":\n return 7;\n case \"240 to 279\":\n return 9;\n case \"280 or greater\":\n return 11;\n default:\n return 0;\n }\n }\n\n @Override\n public int getHDLPoints(String hdl)\n {\n // Third point\n switch (hdl)\n {\n case \"60 or greater\":\n return -1;\n case \"40 to 49\":\n return 1;\n case \"Less than 40\":\n return 2;\n default:\n return 0;\n }\n }\n\n @Override\n public int getSBPPoints(String sbp)\n {\n switch (sbp)\n {\n case \"130 to 139\":\n return 1;\n case \"140 to 159\":\n return 1;\n case \"160 or greater\":\n return 2;\n default:\n return 0;\n }\n }\n\n @Override\n public int getSmokerPoints(String smoker)\n {\n if (smoker.equals(\"Yes\"))\n {\n return 8;\n }\n else\n {\n return 0;\n }\n }\n}\n</code></pre>\n\n<p>then to work it now you have the following</p>\n\n<pre><code>public CoronaryHeart()\n{\n String strAge = \"20 to 34\";\n String strTotalChloresterol = \"240 to 279\";\n String strHDL = \"30 to 49\";\n String strSBP = \"140 to 159\";\n String strIsSmoker = \"No\";\n\n Patient p = new UnkownPatient();\n switch(strAge)\n {\n case \"20 to 34\":\n p = new PatientMan20to34();\n }\n\n int points = p.getAgePoints();\n points += p.getChloresterolPoints(strTotalChloresterol);\n points += p.getHDLPoints(strHDL);\n points += p.getSBPPoints(strSBP);\n points += p.getSmokerPoints(strIsSmoker);\n\n DisplayAlterBasedOnPoints(points);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T13:52:15.633",
"Id": "25617",
"ParentId": "25611",
"Score": "1"
}
},
{
"body": "<p>Each of your if blocks are very similar. You basically the same thing in each if block. This a sign that you've got the conditionally at the wrong level. Instead of writing code that does:</p>\n\n<ol>\n<li>If age category 1\n<ol>\n<li>Add points for age</li>\n<li>Add points for cholestoral</li>\n<li>etc</li>\n</ol></li>\n<li>If age category 2\n<ol>\n<li>Add points for age</li>\n<li>Add points for cholestoral</li>\n<li>etc</li>\n</ol></li>\n<li>etc</li>\n</ol>\n\n<p>Write it like this:</p>\n\n<ol>\n<li>Add points for age\n<ol>\n<li>Handle age category 1</li>\n<li>Handle age category 2</li>\n<li>etc</li>\n</ol></li>\n<li>Add points for cholestoral\n<ol>\n<li>Handle age category 1</li>\n<li>Handle age category 2</li>\n<li>etc</li>\n</ol></li>\n<li>etc</li>\n</ol>\n\n<p>So adding the age points should look something like:</p>\n\n<pre><code>if( strAge.equals(\"20 to 34\") ){ // Minus 7 points\n points = points - 9;\n}\nelse if( strAge.equals(\"35 to 39\") ){\n points = points - 4;\n}\nelse if( strAge.equals(\"35 to 39\") ){\n points = points - 4;\n}\nelse if( strAge.equals(\"40 to 44\") ){\n points += 0;\n} \nelse if( strAge.equals(\"45 to 49\") ){\n points += 3;\n}\nelse if( strAge.equals(\"50 to 54\") ){\n points += 6;\n}\nelse if( strAge.equals(\"55 to 59\") ){\n points += 8;\n}\nelse if( strAge.equals(\"60 to 64\") ){\n points += 10;\n}\nelse if( strAge.equals(\"65 to 69\") ){\n points += 11;\n}\nelse if( strAge.equals(\"70 to 74\") ){\n points += 12;\n}\nelse if( strAge.equals(\"75 to 79\") ){\n points += 13;\n}\n</code></pre>\n\n<p>But doesn't that repeat the <code>.equals</code> way too much? Yes. But the repetition here is much simpler and easier to deal with then what you had before. So we prefer this. Once we have this we can simplify it.</p>\n\n<p>The next key is to use data not code. That is, make lists of things and look them up rather then putting them in code. </p>\n\n<pre><code>static String [] ageCategories = {\"20 to 34\", \"35 to 39\", \"40 to 44\", \"45 to 49\", \"50 to 54\", \"55 to 59\", \"60 to 64\", \"64 to 69\", \"70 to 74\", \"75 to 79\"}\nstatic int agePoints = {-9, -4, -4, 0, 3, 6, 8, 10, 11, 12, 13};\n\npoints += agePoints[Arrays.asList(ageCategories).indexOf(strAge)];\n</code></pre>\n\n<p>This looks up the age level and the points by looking in the arrays. No ifs required. You should basically not need to use any if statements whatsoever in this particular code. You should rewrite it to fetch everything out of arrays like this.</p>\n\n<p>As the number of age ranges increases, it may be easier to work with a map because each point adjustment is matched up to its corresponding age range.</p>\n\n<pre><code>static final Map<String, Integer> pointsByAgeRange = new HashMap<>() {{\n put(\"20 to 34\", -9);\n put(\"35 to 39\", -4);\n ...\n put(\"75 to 79\", 13);\n}};\n\npoints += pointsByAgeRange.get(strAge); // assumes range is in map\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T17:43:37.110",
"Id": "39684",
"Score": "0",
"body": "Use a `Map<String, Integer>` instead of the paired arrays."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T17:47:09.877",
"Id": "39685",
"Score": "0",
"body": "@DavidHarkness, good thought. But I don't do Java enough to know the syntax. Is there a way to do a map literal? Feel free to edit my answer to show the better way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T19:21:39.713",
"Id": "39689",
"Score": "0",
"body": "Sadly, Java doesn't yet have a map literal, but the anonymous subclass trick I included comes pretty close."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T19:33:50.913",
"Id": "39691",
"Score": "0",
"body": "Thanks! It's a good trick to know when I'm called upon to use Java in the future."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T06:01:04.877",
"Id": "39706",
"Score": "0",
"body": "David and Winston Map<String, Integer> is fit for this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T13:19:54.827",
"Id": "39724",
"Score": "0",
"body": "@neknekmouh, what?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T14:55:28.793",
"Id": "25619",
"ParentId": "25611",
"Score": "3"
}
},
{
"body": "<p>The following is just a refactor of your code. I haven't touched anything in the design, although I believe you should. You may start with Snyder answer. </p>\n\n<p>Now, read your code and notice that you have the same code in several places in the same method. This should ring a bell, the most likely is that you copy pasted. Everytime you copy paste code, you should wait and think, because is extremely likely you will do better with that code in a separate method. That been said, this is your method:</p>\n\n<pre><code>private void calculateForMen(){\n\n // TODO Men Age 20-34\n if( strAge.equals(\"20 to 34\") ){ // Minus 7 points\n\n // First point\n points = points - 9;\n\n // Second point\n points += Cholesterol(strTotalCholesterol, 1); \n }\n // TODO Men Age 35-39\n else if( strAge.equals(\"35 to 39\") ){\n\n // First point\n points = points - 4;\n\n // Second point\n points += Cholesterol(strTotalCholesterol, 1);\n }\n // TODO Men Age 40-44\n else if( strAge.equals(\"40 to 44\") ){\n\n // First point\n points += 0;\n\n // Second point\n points += Cholesterol(strTotalCholesterol, 2); \n }\n // TODO Men Age 45-49\n else if( strAge.equals(\"45 to 49\") ){\n\n // First point\n points += 3;\n\n // Second point\n points += Cholesterol(strTotalCholesterol, 2);\n }\n // TODO Men Age 50-54\n else if( strAge.equals(\"50 to 54\") ){\n // First point\n points += 6;\n\n // Second point\n points += Cholesterol(strTotalCholesterol, 3);\n\n }\n // TODO Men Age 55-59\n else if( strAge.equals(\"55 to 59\") ){\n\n // First point \n points += 8;\n\n // Second point\n points += Cholesterol(strTotalCholesterol, 3);\n\n }\n // TODO Men Age 60-64\n else if( strAge.equals(\"60 to 64\") ){\n\n // First point \n points += 10;\n\n // Second point\n points += Cholesterol(strTotalCholesterol, 4); \n }\n // TODO Men Age 65-69\n else if( strAge.equals(\"65 to 69\") ){\n\n // First point\n points += 11;\n\n // Second point\n points += Cholesterol(strTotalCholesterol, 4);\n\n }\n // TODO Men Age 70-74\n else if( strAge.equals(\"70 to 74\") ){\n\n // First point\n points += 12;\n\n // Second point\n points += Cholesterol(strTotalCholesterol, 5); \n\n }\n // TODO Men Age 75-79\n else if( strAge.equals(\"75 to 79\") ){\n\n // First point\n points += 13;\n\n // Second point\n points += Cholesterol(strTotalCholesterol, 5); \n }\n\n // Third point\n points += HDL(strHDL);\n // Fourth point\n points += SBP(strSBP);\n // Fifth point\n points += Smoker(strSmoker);\n\n totalPoints = points;\n strTotalPoints = String.valueOf(totalPoints);\n DisplayMaleAlert(points); \n}\n</code></pre>\n\n<p>The auxiliary methods are as follows:</p>\n\n<pre><code>private void DisplayMaleAlert(int points)\n{\nif(totalPoints < 0){\n displayMaleAlertLessThanOne();\n}\nelse if(totalPoints >= 0 && totalPoints <= 4){\n displayMaleAlertOnePercent();\n}\nelse if(totalPoints >= 5 && totalPoints <= 6){\n displayMaleAlertTwoPercent();\n}\nelse if(totalPoints == 7){\n displayMaleAlertThreePercent();\n}\nelse if(totalPoints == 8){\n displayMaleAlertFourPercent();\n}\nelse if(totalPoints == 9){\n displayMaleAlertFivePercent();\n}\nelse if(totalPoints == 10){\n displayMaleAlertSixPercent();\n}\nelse if(totalPoints == 11){\n displayMaleAlertEightPercent();\n}\nelse if(totalPoints == 12){\n displayMaleAlertTenPercent();\n}\nelse if(totalPoints == 13){\n displayMaleAlertTwelvePercent();\n}\nelse if(totalPoints == 14){\n displayMaleAlertSixteenPercent();\n}\nelse if(totalPoints == 15){\n displayMaleAlertTwentyPercent();\n}\nelse if(totalPoints == 16){\n displayMaleAlertTwentyFivePercent();\n}\nelse if(totalPoints >= 17){\n displayMaleAlertThirtyPercent();\n}\n}\n\n private int Cholesterol(string strTotalCholesterol, int ageGroup)\n {\nif(ageGroup == 1)\n return Cholesterol1(strTotalCholesterol);\nif(ageGroup == 2)\n return Cholesterol1(strTotalCholesterol);\nif(ageGroup == 3)\n return Cholesterol1(strTotalCholesterol);\nif(ageGroup == 4)\n return Cholesterol1(strTotalCholesterol);\nif(ageGroup == 5)\n return Cholesterol1(strTotalCholesterol);\n }\n\n private int Cholesterol1(string strTotalCholesterol)\n {\nif( strTotalCholesterol.equals(\"160 to 199\") ){// 4 points\n points = points + 4;\n}\nelse if( strTotalCholesterol.equals(\"200 to 239\") ){ // 8 points\n points = points + 7;\n}\nelse if( strTotalCholesterol.equals(\"240 to 279\") ){ // 11 points\n points += 9;\n}\nelse if( strTotalCholesterol.equals(\"280 or greater\") ){ // 13 points\n points += 11;\n}\n }\n\n private int Cholesterol2(string strTotalCholesterol)\n {\nif( strTotalCholesterol.equals(\"160 to 199\") ){ // 3 points\n points += 3;\n}\nelse if( strTotalCholesterol.equals(\"200 to 239\")){ // 6 points\n points += 5;\n}\nelse if( strTotalCholesterol.equals(\"240 to 279\")){ // 8 points\n points += 6;\n}\nelse if( strTotalCholesterol.equals(\"280 or greater\") ){ // 10 points\n points += 8;\n}\n }\n\nprivate int Cholesterol3(string strTotalCholesterol)\n{\nif( strTotalCholesterol.equals(\"160 to 199\") ){ // 2 points\n points += 2;\n}\nelse if( strTotalCholesterol.equals(\"200 to 239\")){ // 4 points\n points += 3;\n}\nelse if( strTotalCholesterol.equals(\"240 to 279\")){ // 5 points\n points += 4;\n}\nelse if( strTotalCholesterol.equals(\"280 or greater\") ){ // 7 points\n points += 5;\n} \n }\n\nprivate int Cholesterol4(string strTotalCholesterol)\n{\nif( strTotalCholesterol.equals(\"160 to 199\") ){ // 1 points\n points += 1;\n}\nelse if( strTotalCholesterol.equals(\"200 to 239\")){ // 2 points\n points += 1;\n}\nelse if( strTotalCholesterol.equals(\"240 to 279\")){ // 3 points\n points += 2;\n}\nelse if( strTotalCholesterol.equals(\"280 or greater\") ){ // 4 points\n points += 3;\n}\n}\nprivate int Cholesterol5(string strTotalCholesterol)\n{\nif( strTotalCholesterol.equals(\"240 to 279\")){ // 2 points\n points += 1;\n}\nelse if( strTotalCholesterol.equals(\"280 or greater\") ){ // 2 points\n points += 1;\n}\n}\n\nprivate int HDL(string strHDL)\n{\nif( strHDL.equals(\"60 or greater\") ) // Minus 1 point\n{\n points -= 1;\n}\nelse if( strHDL.equals(\"40 to 49\") ){ // 1 point\n points += 1;\n}\nelse if( strHDL.equals(\"Less than 40\") ){ // 2 points\n points += 2;\n}\n\n}\n\nprivate int SBP(string strSBP)\n{\nif( strSBP.equals(\"130 to 139\") ){ // 2 points\n points += 1;\n}\nelse if( strSBP.equals(\"140 to 159\") ){ // 3 points\n points += 1;\n}\nelse if( strSBP.equals(\"160 or greater\") ){ // 4 points\n points += 2;\n}\n}\n\nprivate int Smoker(string strSmoker)\n{\nif(strIsSmoker.equals(\"Yes\")){\n points += 1; \n}\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T18:18:10.627",
"Id": "25629",
"ParentId": "25611",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T11:05:03.743",
"Id": "25611",
"Score": "2",
"Tags": [
"java",
"beginner",
"android"
],
"Title": "Calculating men's risk of getting coronary heart disease"
}
|
25611
|
<p>I am working with an application that will have sub forms. The primary form opens above the system tray, and on mouse-over, secondary windows will open right next to the primary. When I use the <code>Me.location = New Point ()</code> and then assign the point, it works great… until I change PC's and the user has a different screen resolution. </p>
<p>I was thinking of something like this: </p>
<pre class="lang-vb prettyprint-override"><code>Dim intX As Integer = Screen.PrimaryScreen.Bounds.Width
Dim intY As Integer = Screen.PrimaryScreen.Bounds.Height
Dim errMsg As String = "An Error has occured. Please close the app and contact Jeremy." + Environment.NewLine + "Error 101: Missing Resolution " + Str(intX) + " x " + Str(intY) + "."
MsgBox(errMsg, vbCritical)
Select Case intX
Case "1920"
If intY = "1200" Then
'Me.Location = New Point
Else
MsgBox(errMsg, vbCritical)
End If
Case "1650"
If intY = "1200" Then
'Me.Location = New Point
MsgBox(errMsg, vbCritical)
Else
MsgBox(errMsg, vbCritical)
End If
Case "1440"
If intY = "900" Then
'Me.Location = New Point
Else
MsgBox(errMsg, vbCritical)
End If
Case "1280"
Select Case intY
Case "1024"
'Me.Location = New Point
Case "960"
'Me.Location = New Point
Case "800"
'Me.Location = New Point
Case "768"
'Me.Location = New Point
Case Else
MsgBox(errMsg, vbCritical)
End Select
End Select
</code></pre>
<p>But I am confident there is a cleaner, faster way to determine the screen resolution and decide placement of the secondary windows. </p>
|
[] |
[
{
"body": "<p>Why don't you simply subtract the width and height of your form from the value obtained by the Screen class?</p>\n\n<pre><code>Dim intX As Integer = Screen.PrimaryScreen.Bounds.Width\nDim intY As Integer = Screen.PrimaryScreen.Bounds.Height\n\nSecondForm.Location = new Point(intX - SecondForm.Width, intY - SecondForm.Height)\n</code></pre>\n\n<p>also, to keep in consideration the effective area available for your forms (exluding the app bar) you could use the <code>Screen.PrimaryScreen.WorkingArea</code> property instead of Bounds</p>\n\n<p>If the position of the second form should be dinamically calculated from the position of the first form, then you need to use the location of the first form and adding its width to place the second one</p>\n\n<pre><code>SecondForm.Location = new Point(FirstForm.Location.X + FirstForm.Width, FirstForm.Location.Y)\n</code></pre>\n\n<p><strong>REMEMBER.</strong> To set a custom location for a form it is necessary to set also the property <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.form.startposition%28v=vs.100%29.aspx\" rel=\"nofollow\">Form.StartPosition</a> to FormStartPosition.Manual</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa984420%28v=VS.71%29.aspx\" rel=\"nofollow\">Some introductory docs on Form Location here</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T00:08:14.437",
"Id": "39658",
"Score": "0",
"body": "much nicer. Can you elaborate on what it means? I have used this code, or very similar to open the initial window, but I dont fully understand what is going on here. And to prevent me from needing to ask more questions from just copying and pasting the code, I would like to understand it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T00:11:21.313",
"Id": "39659",
"Score": "1",
"body": "Well, knowing your limits on the X/Y axys you stay inside the screen subtracting the width and height of your form. Of course, if the position of the second form should be dinamically calculated from the position of the first form, then you need to use the location of the first form and adding its width to place the second one"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T11:43:52.230",
"Id": "39660",
"Score": "0",
"body": "@Steve Do not ask users to accept answers, it is considered noise and will be deleted (and further action may be taken). Do not do this again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T12:28:59.337",
"Id": "39664",
"Score": "0",
"body": "@casperOne could you point me to the relevant discussion about this, thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T12:38:06.313",
"Id": "39666",
"Score": "0",
"body": "It's in the [documentation for the privileges on commments](http://stackoverflow.com/privileges/comment). See \"when should I comment\". None of your comments fall into that category. Also see the section about \"when shouldn't I comment\", specifically \"Discussion of community behavior or site policies\"."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-28T00:03:35.113",
"Id": "25613",
"ParentId": "25612",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-27T23:59:57.730",
"Id": "25612",
"Score": "2",
"Tags": [
"vb.net"
],
"Title": "Screen resolution"
}
|
25612
|
<p>Is there a way of writing this correctly working query more efficiently? I'm asking only to learn LINQ better:</p>
<pre><code> var cpuInfo = edgeLPs
.GroupBy(k => k.CPU.ID, e => e.CPU)
.ToDictionary(k => k.Key, v => new
{
LogicalProcs = v.First().LogicalProcessorsCount,
Cores = v.First().Cores.Count,
SMT = v.First().SMT
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T14:38:34.797",
"Id": "39672",
"Score": "0",
"body": "What is the type of `edgeLPs`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T16:06:42.263",
"Id": "39674",
"Score": "0",
"body": "It's List<CustomType>. The type comprises a set of 5 other custom types, of which CPU and LogicalProcessor are two."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T16:07:45.893",
"Id": "39675",
"Score": "0",
"body": "My point with this question is that I'm pulling First() three times. This is the part that looks inefficient to me."
}
] |
[
{
"body": "<p>First, the usual disclaimer about performance: most of the time, you shouldn't worry much about it. If you find that your code is too slow, you should measure to find out which part is causing the slowdown and improve that. Trying to make code that's not performance critical more efficient is often a waste of your time.</p>\n\n<p>In your specific case, I don't think the calls to <code>First()</code> would hurt your performance. But I would understand if you wanted to fix that to make your code more <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">DRY</a>. To do that, you could use <code>Select()</code>:</p>\n\n<pre><code>var cpuInfo = edgeLPs\n .GroupBy(e => e.CPU.ID, e => e.CPU)\n .Select(g => new { id = g.Key, cpu = g.First() })\n .ToDictionary(g => g.id, g => new\n {\n LogicalProcs = g.cpu.LogicalProcessorsCount,\n Cores = g.cpu.Cores.Count,\n SMT = g.cpu.SMT\n });\n</code></pre>\n\n<p>Though the change from <code>.First()</code> to something like <code>.cpu</code> isn't actually much of an improvement.</p>\n\n<p>Also, I think that using <code>First()</code> like this can be a sign of faulty logic. If you know that there will be always at most one CPU with a given ID, then you should use <code>Single()</code> instead, or, in your case, simply use <code>ToDictionary()</code> without the preceding <code>GroupBy()</code>. If there can be multiple CPUs with the same ID, i think you should figure out what to do with the rest of them, and not simply ignore all but the first one.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T02:55:50.267",
"Id": "39703",
"Score": "0",
"body": "Thanks @svick. In this case, \"LogicalProcs\", \"Cores\", and \"SMT\" is identical for each instance (CPU.ID), so First() is fine. I did feel this is not ideal, but it seems there is no other way to do it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T17:00:21.233",
"Id": "25624",
"ParentId": "25615",
"Score": "3"
}
},
{
"body": "<p>What are you looking for when you say 'efficient'? There are certainly ways to optimize the performance of the query, which likely exclude LINQ and depend on the nature of your input set.</p>\n\n<p>But if you're just looking for a concise and readable way of expressing the logic, what you have is pretty good. I would modify it slightly to use a temp variable when creating the final dictionary value:</p>\n\n<pre><code>var cpuInfo = edgeLPs\n .GroupBy(k => k.CPU.ID, e => e.CPU)\n .ToDictionary(k => k.Key, v => \n {\n var cpu = v.First();\n return new\n {\n LogicalProcs = cpu.LogicalProcessorsCount,\n Cores = cpu.Cores.Count,\n SMT = cpu.SMT\n };\n });\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T02:08:25.447",
"Id": "39699",
"Score": "0",
"body": "Although it certainly gets the job done, I'd say using `return` within queries is a a bad approach. You're making the queries look less functional and more procedural. Using return statements within lambdas should be reserved for callbacks or other uses of the sort."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T20:43:34.030",
"Id": "25635",
"ParentId": "25615",
"Score": "1"
}
},
{
"body": "<p>I'd write it so you project your result within the grouping. Then when mapping to the dictionary, you can just take the first item in the group. That way, you can save yourself a few calls and have an overall cleaner looking query.</p>\n\n<pre><code>var cpuInfo = edgeLPs\n .GroupBy(e => e.CPU.ID, e => new\n {\n LogicalProcs = e.CPU.LogicalProcessorsCount,\n Cores = e.CPU.Cores.Count,\n SMT = e.CPU.SMT,\n })\n .ToDictionary(g => g.Key, g => g.First());\n</code></pre>\n\n<hr>\n\n<p>On a stylistic note, you should name your lambda parameters after the object they represent, not after what the entire lambda is supposed to represent.</p>\n\n<p>Judging by the names you chose in the method calls, you used <code>k</code> for key, <code>e</code> for element, and <code>v</code> for value. These would be poor names and would be prone to confusion for other developers.</p>\n\n<p>In the <code>GroupBy()</code> call, I would name the lambda parameter either <code>edgeLP</code> (or whatever is more appropriate) or simply <code>e</code> as the parameter represents the <code>edgeLP</code> that you are grouping. The <code>ToDictionary()</code> call is operating on <code>IGrouping<></code> objects so I tend to use <code>g</code> in that case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T02:50:55.807",
"Id": "39702",
"Score": "0",
"body": "Thanks @Jeff. This is perfect, and helps me understand LINQ better."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T02:27:36.880",
"Id": "25639",
"ParentId": "25615",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "25639",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T13:32:15.263",
"Id": "25615",
"Score": "5",
"Tags": [
"c#",
"linq"
],
"Title": "LINQ Group query - simplifying"
}
|
25615
|
<p>As the question states: have I missed some obvious security vulnerabilities in this code? Particularly interested in XSS...</p>
<p>I'm trying to create something more robust that <a href="http://php.net/manual/en/function.strip-tags.php" rel="nofollow">strip_tags</a>, but simpler than <a href="http://htmlpurifier.org/" rel="nofollow">HTML Purifier</a> which just feels like overkill.</p>
<pre><code>class StripTags {
private $tags;
private $dom;
function __construct($html, $tags = null) {
// Setup tags
$this->setTags($tags);
//Initialise document using provided HTML
$doc = new DOMDocument();
@$doc->loadHTML($html); //suppress invalid HTML warnings
$doc_elem = $doc->documentElement;
$this->traverseAndRemove($doc_elem);
// Store DOM for processing in __toString()
$this->dom = $doc;
}
public function __toString() {
// Remove unwanted DOCTYPE etc
$str = $this->dom->saveHTML();
$str = str_replace('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">', "", $str);
$str = preg_replace("/^<html><body>/", "", trim($str));
$str = preg_replace("/<\/body><\/html>$/", "", trim($str));
return $str;
}
private function setTags($t) {
if (empty($t) or !is_array($t)) {
$this->tags = array("html", "body", "p", "span", "div", "img", "b", "i", "em", "strong", "h1", "h2", "h3", "h4", "a", "pre");
} else {
$this->tags = $t;
}
if (!in_array("html",$this->tags)) {
$this->tags[] = "html";
}
if (!in_array("body",$this->tags)) {
$this->tags[] = "body";
}
}
private function traverseAndRemove(&$elem) {
// Check node type, attributes and child nodes
// Reset child/attribute loops if one is removed
if ($elem->nodeType === XML_ELEMENT_NODE) {
$tagName = $elem->tagName;
if (!in_array($tagName, $this->tags)) {
// Remove any elements in the tags array and stop processing it
$elem->parentNode->removeChild($elem);
return;
}
// Check attributes for Javascript events and src/hrefs with javascript too...
if ($elem->hasAttributes()) {
$attrs = $elem->attributes;
for ($i=0,$max=$attrs->length; $i<$max; $i++) {
$name = $attrs->item($i)->name;
if (in_array($name, array("onload", "onclick","onmouseover","onmousemove","onmousehover","onmousedown","onmouseup", "onunload"))) {
$elem->removeAttribute($name);
$max--;
$i--;
}
if (in_array($name,array("src", "href")) and preg_match("/^javascript:/i", $attrs->item($i)->value)) {
$elem->removeAttribute($name);
$max--;
$i--;
}
}
}
}
// Check all child nodes too
if ($elem->hasChildNodes()) {
$children = $elem->childNodes;
for ($i=0, $max=$children->length; $i<$max; $i++) {
$this->traverseAndRemove($children->item($i));
if ($children->length < $max) {
$i -= ($max - $children->length);
$max = $children->length;
}
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T16:10:47.727",
"Id": "39676",
"Score": "2",
"body": "Are you attempting to allow users to input a limited subset of tags? if not, the best solution is to throw out everything you've written for sanitizing input, and just make sure the output is encoded."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T10:45:19.733",
"Id": "39715",
"Score": "0",
"body": "Yes, sorry, it's to sanitize input from a WYSIWYG editor... we need the customer to be able to have some HTML, but not all"
}
] |
[
{
"body": "<p>It would help if you explained exactly why you think this approach is more robust than using strip_tags. It will certainly be likely to be a lot slower.</p>\n\n<p>From a quick inspection it doesn't seem to filter CSS behaviours nor data URIs.</p>\n\n<p>If it were me I'd be building on to strip_tags rather than trying to start from scratch.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T11:52:13.670",
"Id": "39759",
"Score": "0",
"body": "strip_tags doesn't validate the HTML, nor can it alter any attributes, which I'd like to be able to do in order to make the \"sanitizing\" process more robust. How would you build on top of strip_tags instead of starting from scratch?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T23:00:33.333",
"Id": "25664",
"ParentId": "25620",
"Score": "2"
}
},
{
"body": "<p>Problem is trying to blacklist stuff is really hard.</p>\n\n<p>Why did you miss <code>ontouchstart</code>? What about all the other touch events?</p>\n\n<p>What about <code>onfocus</code>?</p>\n\n<p>Why <code>onmouseover</code> but not <code>onmouseleave</code>?</p>\n\n<p>What about <code>onerror</code> on a malformed <code>img</code> tag?</p>\n\n<p>What about when a tab is in the middle of <code>javascript</code>?</p>\n\n<p>What about when that tab looks like <code>&#x09;</code>?</p>\n\n<p>What about when instead <code>&#x0A;</code> is in there?</p>\n\n<p>Did you know an image tag doesn't need a 'src'?</p>\n\n<p>Did you forget about lowsrc? What about DYNSRC?</p>\n\n<p>What if the src is encoded in UTF8 code points?</p>\n\n<p>What if the HTML is malformed? (e.g. <code><img \"\"\"><script>alert(\"hi\")</script>\"></code>)</p>\n\n<p><strong>You will lose trying to do this!</strong></p>\n\n<p><a href=\"https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet\" rel=\"nofollow\">https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet</a> is a great resource, but even that will miss things that are less common.</p>\n\n<p>Be very restrictive, use a good library that covers this, or rethink how you might allow entry.</p>\n\n<p>Markdown for instance + some custom work to allow extra bits and bobs might be a better choice. Look at how this input box works as an example.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-30T08:33:39.240",
"Id": "27958",
"ParentId": "25620",
"Score": "2"
}
},
{
"body": "<p>Blacklisting unwanted content is a fundamentally flawed approach. The only safe way to defend against XSS attacks is by using white listing.</p>\n\n<p>In other words, define what kind of content you'll allow and delete everything else.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-30T08:44:40.133",
"Id": "27959",
"ParentId": "25620",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T15:11:42.537",
"Id": "25620",
"Score": "3",
"Tags": [
"php",
"html",
"parsing"
],
"Title": "Have I missed some obvious XSS vulnerabilities?"
}
|
25620
|
<p>Say I have a code snippet like this </p>
<pre><code> if(string.Compare(isStandardFlag,"STANDARD",true)==0)
{
hearingID = centreSession.standardID;
centreSession.standardOutcomeID
= disciplineSvc.SaveResultA(hearingID,OffenceID, Outcome);
centreSession.standardOutcomeNoteID
= disciplineSvc.SaveResultB(hearingID, txt1.Text, "ResultHearing");
}
else{
hearingID = centreSession.noneStandardID;
centreSession.noneStandardHearingOutcomeID
= disciplineSvc.SaveResultA(hearingID,OffenceID, Outcome);
centreSession.noneStandardHearingOutcomeNoteID
= disciplineSvc.SaveResultB(hearingID, txt1.Text, , "ResultHearing");
}
</code></pre>
<p>You can see the 'if' and 'else' do the same thing but just assign the result to different variables.</p>
<p>Is there a pattern I can refer to refactor the code? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T16:35:17.417",
"Id": "39680",
"Score": "0",
"body": "What is the reason that you need to save the results in different properties?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T16:40:27.530",
"Id": "39681",
"Score": "0",
"body": "@JeffVanzella it is a usercontrol been used in 2 different places on the same screen, the logic is very similar. I need 2 places to store their results."
}
] |
[
{
"body": "<p>First, it looks like the <code>ID</code>, <code>OutcomeID</code> and <code>OutcomeNoteID</code> belong together, so I think it it makes sense to extract them into a separate class (though my naming of it is just a guess):</p>\n\n<pre><code>class Hearing\n{\n public int ID { get; private set; }\n\n public int OutcomeID { get; private set; }\n\n public int OutcomeNoteID { get; private set; }\n\n public Hearing(int id)\n {\n ID = id;\n }\n\n public void SetOutcome(int outcomeId, int outcomeNoteId)\n {\n OutcomeID = outcomeId;\n OutcomeNoteID = outcomeNoteId;\n }\n}\n</code></pre>\n\n<p>With that, your code could be changed to something like:</p>\n\n<pre><code>Hearing hearing;\nif (string.Equals(isStandardFlag, \"STANDARD\", StringComparison.InvariantCultureIgnoreCase))\n hearing = centreSession.StandardHearing;\nelse\n hearing = centreSession.NonStandardHearing;\n\nhearing.SetOutcome(\n disciplineSvc.SaveResultA(hearing.ID, OffenceID, Outcome),\n disciplineSvc.SaveResultB(hearing.ID, txt1.Text, \"ResultHearing\"));\n</code></pre>\n\n<p>Some additional notes:</p>\n\n<ol>\n<li>I have also changed <code>string.Compare() == 0</code> to <code>string.Equals()</code>, because I think it expresses the intent better.</li>\n<li>Some of the names are quite bad (e.g. <code>txt1</code> or <code>SaveResultA</code>), you should improve those.</li>\n<li>Dealing with ids a lot is not very object-oriented. I think it would make more sense to deal directly with <code>Outcome</code> and <code>OutcomeNote</code> objects, not just their ids.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T16:40:36.930",
"Id": "25623",
"ParentId": "25621",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "25623",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T15:38:08.467",
"Id": "25621",
"Score": "1",
"Tags": [
"c#",
"design-patterns"
],
"Title": "It there a pattern used to process a same function but assign the result to a different variable regarding to a different condition?"
}
|
25621
|
<p>I have two pieces of they which do almost the same thing. They both return the most common base class of two types. They differ in two aspect:</p>
<ol>
<li>If one of the arguments is <code>null</code>, code A returns <code>null</code> and code B returns <code>object</code>.</li>
<li>If one of the arguments is an interface type, code A returns <code>null</code> and code B returns <code>object</code>.</li>
</ol>
<p>My two questions for you:</p>
<ol>
<li>Which code is more readable?</li>
<li><p>When it comes down to those differences, should the code:</p>
<p>a. return <code>null</code>.<br>
b. return <code>object</code>.<br>
c. throw an exception?</p></li>
</ol>
<p><strong>Code A:</strong></p>
<pre><code> /// <summary>
/// Returns the most common type of two types.
/// If no common type can be found, null is returned.
/// </summary>
static public Type GetCommonBaseClass(Type a, Type b)
{
if ((a == null) || (b ==null))
return null;
if (a.IsInterface || b.IsInterface)
return null;
if (a.IsAssignableFrom(b))
return a;
while (true)
{
if (b.IsAssignableFrom(a))
return b;
b = b.BaseType;
}
}
/// <summary>
/// Returns the most common type of one or more types.
/// If no common type can be found, null is returned.
/// </summary>
static public Type GetCommonBaseClass(params Type[] types)
{
if ((types == null) || (types.Length == 0))
return null;
Type type = types[0];
for (int i = 0; i < types.Length; i++)
type = GetCommonBaseClass(type, types[i]);
return type;
}
</code></pre>
<p><strong>Code B:</strong></p>
<pre><code> /// <summary> Finds the most derived common base class of all the provided types, or System.Object if there is no common base class </summary>
public static Type CommonBaseClass(params Type[] types)
{
if(ReferenceEquals(types,null)) return typeof(object);
types = types.Where(x => !ReferenceEquals(x,null)).Distinct().ToArray();
switch (types.Length)
{
case 0: return typeof(object);
case 1: return types[0].IsInterface ? typeof(object): types[0];
default:
IEnumerable<IEnumerable<Type>> hierarchies = types.Select(ClassHierarchy).OrderBy(x => x.Count());
Queue<Type> smallest = new Queue<Type>(hierarchies.First().Reverse());
hierarchies = hierarchies.Skip(1);
do
{
int maxPossible = smallest.Count;
hierarchies = hierarchies.Select(each => each.Take(maxPossible));
Type candidate = smallest.Dequeue();
if (hierarchies.All(each => each.Last() == candidate))
return candidate;
} while (smallest.Count > 1);
return typeof(object);
}
}
///<summary>Gets the class hierarchy of the provided type, in order of derivation, e.g. : (System.Object,CustomBaseType,CustomConcreteType,...), or the singleton of System.Object type if the provided type is an interface or null </summary>
public static IEnumerable<Type> ClassHierarchy(this Type type)
{
if (type == null || type.IsInterface) type = typeof(object);
var stack = new Stack<Type>();
do
{
stack.Push(type);
type = type.BaseType;
} while (type != null);
return stack;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T20:15:57.370",
"Id": "39692",
"Score": "0",
"body": "I definitely find the first option more readable"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T20:36:12.030",
"Id": "39693",
"Score": "1",
"body": "`object` is the base for everything, so I don't know why you *wouldn't* want to return it if there's nothing more specific."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-14T20:19:49.197",
"Id": "304772",
"Score": "0",
"body": "I agree with @Bobson. In A, when `if (a.IsInterface || b.IsInterface)` is hit, you should be returning `typeof(object)` (or some other reference to the object type). As mentioned, it is the base of *every* object in the .NET Framework."
}
] |
[
{
"body": "<p>Which is more readable is quite a subjective question, however if you ask me I choose the first option. There's however something that bothers me more. You should never allow a potential exception to propagate in your code (this is returning null, you'll find yourself asking again if x is null, and what if you forget once???). You should handle this null value responsible or throw an ArgumentNullException(). A good approach as I see it could be returning object, since nearly everything in C# inherits from object, as you do in your second choice. You can read more <a href=\"https://stackoverflow.com/questions/254461/net-how-do-you-get-the-type-of-a-null-object\">here</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T18:58:38.723",
"Id": "25631",
"ParentId": "25628",
"Score": "1"
}
},
{
"body": "<p>I think that code A is quite a lot simpler, so it's also more readable. It's quite clear what <code>GetCommonBaseClass(Type a, Type b)</code> is supposed to do and <code>GetCommonBaseClass(params Type[] types)</code> is also quite straightforward.\nOn the other hand, <code>CommonBaseClass(params Type[] types)</code> in Code B is much more complicated, it's hard to see what's actually going on in all that code.</p>\n\n<p>Also, in code A, <code>GetCommonBaseClass(params Type[] types)</code> could be simplified even more by using something like <code>types.Aggregate(GetCommonBaseClass)</code>.</p>\n\n<p>Regarding the edge cases, I think that, <code>null</code> inputs should cause an <code>ArgumentNullException</code> to be thrown. (Or not, if <code>null</code> is really a valid value.) With interfaces, I think the correct behavior depends on your requirements. If you don't know, I think the safest choice is to throw an exception. It's trivial to allow interfaces later on, if that's needed. On the other hand, adding a restriction could cause a issues with older code that uses your method.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T20:22:47.017",
"Id": "39738",
"Score": "0",
"body": "+1. The only way returning `object` given null parameter(s) makes sense is if, by design, you never return `object` for 2 \"objective\" parameters. After all what class does not derive from `object`? ... I hope you have good documentation!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T19:08:50.427",
"Id": "25632",
"ParentId": "25628",
"Score": "3"
}
},
{
"body": "<ol>\n<li><code>A</code> is more readable obviously.</li>\n<li>In case of interface type, the method should return null. In case of null parameter, the method should throw exception.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T16:51:21.513",
"Id": "25659",
"ParentId": "25628",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T18:07:28.170",
"Id": "25628",
"Score": "3",
"Tags": [
"c#",
"functional-programming"
],
"Title": "GetCommonBaseClass: Readabiliy and Functionality"
}
|
25628
|
<p>i need to create a cache class to avoid making the same calculations more than needed. My idea was something really basic like</p>
<pre><code>class transient_cache {
static private $cache = array();
static public function get_value( array $obj, $key ) {
// $obj is an array( $object, $method )
$classname = get_class( $obj[0] );
$method = $obj[1];
if( ! isset( self::$cache[$classname] ) ) {
self::$cache[$classname] = array();
}
if( ! isset( self::$cache[$classname][$method] ) ) {
self::$cache[$classname][$method] = array();
}
if( ! isset( self::$cache[$classname][$method][$key] ) ) {
self::$cache[$classname][$method][$key] = call_user_func( $obj );
}
return self::$cache[$classname][$method][$key];
}
}
</code></pre>
<p>Do you think this approach is correct or would you suggest something better?</p>
|
[] |
[
{
"body": "<p>I would say that there isn't a correct or incorrect way of achieving this. Everyones requirements differ.</p>\n\n<p>You probably want to expand this out, there's a lot going on in the one static method you have in that class. Whilst I don't have anything against mediator patterns, I would probably combine a number of patterns to build a powerful caching class, as well as utilising magic methods (I know some people are averse to this).</p>\n\n<p>I need to note the below is a lot more complicated and would benefit from some refactoring to be stored against the actual method rather than a key.</p>\n\n<pre><code>class Cache {\n\n /**\n * Cached objects\n * @static array\n */\n private static $cache = array();\n\n /**\n * Per instance class name\n * @var string\n */\n private $call;\n\n /**\n * Per instance method name\n * @static array\n */\n private $method;\n\n /**\n * Construct the class and build cache array if not set\n * @param string $method\n * @param string $class\n * @param string $key \n */\n public function __construct($method, $class, $key)\n {\n if ( ! isset(static::$cache[$class] )\n static::$cache[$class] = array();\n\n if ( ! isset(static::$cache[$class][$method] )\n static::$cache[$class][$method] = array();\n\n // Set the class for this instance\n $this->call = $class;\n\n // Set the method for this instance\n $this->method= $method;\n\n // Set the key for the cache\n $this->key = $key;\n }\n\n /**\n * Get the cached value\n * @return mixed Cached value\n */\n public function get()\n {\n return $this->{$this->key};\n }\n\n /**\n * Get magic method to return the key\n * @param string $key\n */\n public function __get($key)\n {\n if (isset(static::$cache[$this->call][$this->method][$key]))\n return static::$cache[$this->call][$this->method][$key];\n\n return static::$cache[$this->call][$this->method][$key] = call_user_func(array($this->call, $this->method));\n }\n\n /**\n * Call static magic method, catches all statically called methods\n * and builds an instance of the cache class using a reflector\n * @param $method\n * @param $args \n */\n public static function __callStatic($method, $args)\n {\n $method = str_replace(__CLASS__ . '::', '', $method);\n\n $ref = new ReflectionClass(__CLASS__);\n\n $inst = $ref->newInstanceArgs($args);\n\n return $inst->get();\n }\n</code></pre>\n\n<p>}</p>\n\n<p>Usage</p>\n\n<pre><code>$result = Cache::{method}({class}, {key};\n</code></pre>\n\n<p>To retrieve say a user object from the User class with method <code>get_user</code>;</p>\n\n<pre><code>$user = Cache::get_user('User', 'user_object');\n</code></pre>\n\n<p>The main advantage to this is that the class can be extended easily using other design patterns such as a Facade that further simplifies the class API. It can also be added to easily with further methods within the class body itself rather than by a pure static call. The class can also be instantiated with the <code>new</code> keyword providing the ability to create separate cache instances that utilise the same static properties and methods.</p>\n\n<p>I need to add this class is very much a prototype that I thought of when I saw your class above. I love cacheing stuff in general and providing standardised interfaces for it is always a great thing to do across all applications you write.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-04T15:42:17.387",
"Id": "39953",
"Score": "0",
"body": "Ah shame :( Though WP functions on PHP > 5.3 just fine... You could however create a static make method that calls an anonymous private method using __call(). I believe that was implemented prior to 5.2.6"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-03T09:07:11.097",
"Id": "25761",
"ParentId": "25630",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T18:54:08.517",
"Id": "25630",
"Score": "2",
"Tags": [
"php",
"design-patterns",
"cache"
],
"Title": "How to create a simple stateless cache class in PHP"
}
|
25630
|
<p>I am new to Ruby and would like some help with re-factoring my code.</p>
<pre><code>class Beam
def initialize
puts "Please specify span of beam"
@span = gets.chomp.to_f
puts "How many number of point loads do you want?"
@pointLoadNos = gets.chomp.to_i
@pointLoad = Array.new(@pointLoadNos)
@pointLoadDistFromLeft = Array.new(@pointLoadNos)
@pointLoadDistFromRight = Array.new(@pointLoadNos)
@magnitude = Array.new(@pointLoadNos)
@reaction = Array.new(2,0)
end
def setValues
count = 0
while count < @pointLoadNos
puts "At what dist should point load #{count+1} be placed from left?"
@pointLoadDistFromLeft[count] = gets.chomp.to_f
if @pointLoadDistFromLeft[count] > @span
puts "Dist of Point Load #{count+1} From Left should be less than span length of beam"
else
puts "Magnitude of point load #{count+1} should be?"
@magnitude[count] = gets.chomp.to_f
@pointLoadDistFromRight[count] = (@span - @pointLoadDistFromLeft[count])
count += 1
end
end
end
def calReactions
i = 0
while i < @pointLoadNos
@reaction[0] += (@pointLoadDistFromLeft[i]*@magnitude[i])/@span
@reaction[1] += (@pointLoadDistFromRight[i]*@magnitude[i])/@span
i += 1
end
puts "Reaction at Left: #{@reaction[0]}"
puts "Reaction at Left: #{@reaction[1]}"
end
end
beam = Beam.new
beam.setValues
beam.calReactions
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T21:53:55.850",
"Id": "39694",
"Score": "3",
"body": "For future reference, please give some background/context on what your code's supposed to accomplish. Yes, we can glean it from reading the code, but a simple \"This class models a beam (as in a bridge or building) and calculates the forces exerted at its ends by an arbitrary number of point loads. It prompts the user for input values.\" would help a lot."
}
] |
[
{
"body": "<p>I would write something like:</p>\n\n<pre><code>class Beam\n def prompt msg\n # a bit kung-fu, sorry\n puts msg while gets.strip!.empty?\n yield $_\n end\n def initialize \n @span = prompt \"Please specify span of beam\", &:to_f\n @pointLoadNos = prompt \"How many number of point loads do you want?\", &:to_i\n @pointLoad = []\n @pointLoadDistFromLeft = []\n @pointLoadDistFromRight = []\n @magnitude = []\n end\n def setValues\n @pointLoadNos.times do |count|\n while 0 > @pointLoadDistFromRight[count] = @span - @pointLoadDistFromLeft[count] =\n prompt(\"At what dist should point load #{count + 1} be placed from left?\", &:to_f)\n puts \"Dist of Point Load #{count + 1} From Left should be less than span length of beam\"\n end\n @magnitude[count] = prompt \"Magnitude of point load #{count + 1} should be?\", &:to_f\n end\n end\n def calReactions\n @reaction = [0, 0]\n @magnitude.zip(@pointLoadDistFromLeft, @pointLoadDistFromRight) do |mag, left, right|\n @reaction[0] += (left * mag) / @span\n @reaction[1] += (right * mag) / @span\n end\n puts \"Reaction at Left: #{@reaction[0]}\"\n puts \"Reaction at Right: #{@reaction[1]}\"\n end\nend\n\nbeam = Beam.new\nbeam.setValues\nbeam.calReactions\n</code></pre>\n\n<p>See <a href=\"http://ruby.about.com/od/beginningruby/a/Block-Parameters-And-Yielding.htm\" rel=\"nofollow\">this</a> and <a href=\"http://www.potstuck.com/2011/08/06/ruby-symbols-instead-of-blocks/\" rel=\"nofollow\">this</a> - when you pass a block, you don't have to catch it into argument, but can just use Ruby's keyword <code>yield</code>. Also instead of describing a block as a proc, you can use <code>&:method</code> notation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T01:04:15.797",
"Id": "25637",
"ParentId": "25633",
"Score": "2"
}
},
{
"body": "<p>First of all, you should <strong>not</strong> get user input from inside your <code>Beam</code> class. This ties it to the console and makes automated testing more difficult. A layered architecture is more suitable : </p>\n\n<pre><code># The Beam class is only concerned by business logic.\n# Notice how the logic and workflow are clear and readable,\n# and how easy you it would be to write tests for it.\n# \nclass Beam\n\n attr_reader :span\n\n def initialize( span )\n @span = span.to_f\n @load_points = {}\n end\n\n def add_load_point( distance, magnitude )\n distance, magnitude = distance.to_f, magnitude.to_f\n if distance < 0 || distance > span || @load_points[distance]\n raise ArgumentError, 'invalid load point' \n end\n @load_points[distance] = magnitude\n end \n\n def reactions\n @load_points.inject( left: 0, right: 0 ) do |hash, (distance, magnitude)|\n hash[:left] += distance * magnitude / span\n hash[:right] += (span - distance) * magnitude / span\n hash\n end\n end\n\nend\n\n\n# this module is an interface between your class and the user\n# via the console. Notice that this module (could be a class,\n# does not matter) is only concerned about asking questions,\n# adapting user input to feed the Beam class interface, and \n# formatting output.\n# \nmodule BeamConsole\n\n # here we chose to move all questions to the user to methods,\n # and name these methods with an exclamation mark at the end\n #\n def self.invoke\n beam = Beam.new( span? )\n begin\n beam.add_load_point( distance?, magnitude? )\n rescue ArgumentError => e\n puts \"Invalid parameters for load point. Please retry.\" ; retry \n end while more? \n format_reactions( beam.reactions )\n end\n\n private #=================================================================== \n\n # adapted from @nakilon's answer, tail-recursive variant\n def self.prompt( msg )\n output = gets.strip!\n return output unless output.empty? \n prompt( msg )\n end\n\n def self.span?\n prompt( 'Please specify span of beam' ).to_f\n end\n\n def self.more?\n answer = prompt( 'Do you want to add points ? (y/n)' )\n answer = prompt( 'please answer by y or n' ) unless answer =~ /^[y|n]$/\n answer == 'y'\n end\n\n def self.distance?\n prompt( 'At what distance should the point be placed from left?' ).to_f\n end\n\n def self.magnitude?\n prompt( 'Magnitude should be?' ).to_f\n end\n\n def self.format_reactions( reactions )\n puts \"Reaction on the left is : %.4f\" % reactions[:left]\n puts \"Reaction on the right is : %.4f\" % reactions[:right]\n end\nend\n</code></pre>\n\n<p>This may seem overkill, but separating concerns is the core of OOP. With this approach, you'll end up with a <code>Beam</code> class devoid of any responsability concerning user interaction, and that's a good thing : you want your class to perform business logic before anything else. </p>\n\n<p>This way, your code will be more readable (no logic riddled with prompts), so more maintainable, but also more <em>reusable</em>. Imagine that one day you want to allow users to perform calculations from a web page : you could not reuse your <code>Beam</code> class if it is tied to the console, but you could if you separated responsibilities. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T16:49:18.963",
"Id": "25658",
"ParentId": "25633",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T19:44:07.897",
"Id": "25633",
"Score": "1",
"Tags": [
"beginner",
"ruby",
"physics"
],
"Title": "Calculating reactions to load on a beam"
}
|
25633
|
<p>So for practice with Javascript, I wrote this lightweight widget factory which is similar in functionality (okay, that's a bit of a stretch) to jQuery's UI Widget factory. I was hoping I could get some pointers as far as idiom usage and also if there are any glaring problems with the below code. </p>
<pre><code>var _CreateWidget = function(namespace, implementation) {
_Widget = {
_create: function() {},
_destroy: function() {},
_set: function() {},
_get: function() {},
options: {},
context: undefined,
namespace: namespace,
apply: function(element) {
this.context = element;
element[namespace] = this;
this._create();
}
};
for (var item in implementation) {
if (implementation.hasOwnProperty(item)) {
_Widget[item] = implementation[item];
}
}
return _Widget;
}
Widget = function(namespace, implementation) {
return function(element) {
var instance = _CreateWidget(namespace, implementation);
instance.apply(element);
return instance
};
}
</code></pre>
<p>An example widget would be defined as follows:</p>
<pre><code>//Example widget
Page = Widget("page", {
_create: function() {
//initialization code here
},
_destroy: function() {
},
_set: function() {
},
_get: function() {
},
request: function() {
//custom function
},
options: {
url: ''
}
});
</code></pre>
<p>And the widget would be applied to an element like so:</p>
<pre><code>myElement = document.getElementById("myUniqueId");
appliedPageReference = Page(myElement);
myElement.page.request(); //One way to call the custom request() function;
appliedPageReference.request(); //Another way to call the custom request() function;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T08:15:31.963",
"Id": "39712",
"Score": "0",
"body": "You're missing the `var` keyword in several places."
}
] |
[
{
"body": "<ul>\n<li><p>Although DOM elements can be used like normal JavaScript objects, I'd avoid attaching JavaScript other than handlers. The problem is when they form <a href=\"https://stackoverflow.com/q/1493453/575527\">circular references</a>. In browser garbage collectors, they won't collect garbage if something still references them. If you accidentally form circular references, this will lead to memory leaks (unfreed memory)</p>\n\n<p><a href=\"https://stackoverflow.com/a/10004655/575527\">jQuery avoids this by creating objects in an internal cache</a> and assigns an ID to the element. That way, you are assigning a primitive to the element, not an object. This is how jQuery collects and manages event handlers, data attributes, and others.</p>\n\n<p>So a general tip is: <em>What is from JavaScript, stays in JavaScript. (And not cross over to the DOM)</em></p></li>\n<li><p>In jQuery's case, the functions are not actually attached to the element. That's the purpose of the \"jQuery object\". In a gist, a jQuery object is just an <a href=\"https://www.inkling.com/read/javascript-definitive-guide-david-flanagan-6th/chapter-7/array-like-objects\" rel=\"nofollow noreferrer\">array-like object</a> (let's call it \"pseudo-array\" from this point on), that contains DOM elements. The prototype of the jQuery object is where the functions live. These functions operate on each value in the collection.</p>\n\n<p>Executing a function in a jQuery object is not like this:</p>\n\n<pre><code>someElement.doSomething();\n</code></pre>\n\n<p>But rather, something like this:</p>\n\n<pre><code>collectionOfStuff.forEach(function(DOMElement,i,arr){\n //do something for each in the collection\n});\n</code></pre></li>\n<li><p><code>Widget</code> in your code is some function that manufactures \"widget templates\" which are used to bind to your elements. Rather than having <code>Widget</code> return the template, why not make <code>Widget</code> your namespace. You can then create a function that attaches to the namespace. </p>\n\n<p>It would be synonymous to doing <code>jQuery.fn.extend(function(){...})</code></p>\n\n<pre><code>//define widget\nWidget.defineWidget('Page',function(){\n\n //local stuff, aka \"private\"\n var privateVar = 'foo';\n function privateFn(){...}\n\n //anything attached to `this` is \"public\"\n //we will execute this function, providing an object as `this`\n this.publicVar = 'bar';\n this.publicFn = function(){...}\n\n});\n\n//access widget\nvar reference = Widget.Page(bindingTarget);\n</code></pre>\n\n<p><code>defineWidget</code> define a creator function into the namespace that uses the widget definition to build instances, something like:</p>\n\n<pre><code>Widget.defineWidget = function(name,fn){\n\n //store\n wigetCache[name] = fn;\n\n //attach to namespace\n Widget[name] = function(){\n\n //BaseClass could be some constructor with prototype containing\n //all functions that widgets should have\n var instance = new BaseClass();\n\n //run the instance through the definition to attach the internals\n return fn.call(instance);\n } \n}\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T04:04:08.093",
"Id": "25641",
"ParentId": "25640",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "25641",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T03:09:33.770",
"Id": "25640",
"Score": "0",
"Tags": [
"javascript",
"jquery-ui"
],
"Title": "Roll your own widget factory"
}
|
25640
|
<p>I chanced upon this code written by the Solution Architect for an MS CRM project and I am lost for words. Am I going crazy or is this code OK?</p>
<pre><code>string returnedOptionSetStringValue=string.Empty;
int returnedInt = 0;
Utils.RetrieveOptionSetLabelOrValue(CRMAccess.xrmService, Contact.EntityLogicalName, "new_status", optionSetValue.Value, string.Empty, ref returnedOptionSetStringValue, ref returnedInt, CRMAccess.tracerService);
</code></pre>
<p>The method within the Utils class is as follows</p>
<pre><code>public static void RetrieveOptionSetLabelOrValue(IOrganizationService CrmWebService, string EntityName, string AttributeName, int OptionSetValue, string optionSetText, ref string returnedText, ref int returnedNumber, ITracingService tracerService)
{
string returnLabel = string.Empty;
tracerService.Trace("starting in function ");
OptionMetadataCollection optionsSetLabels = null;
tracerService.Trace("in retrieve option set label with values:" + OptionSetValue + " and text " + optionSetText);
optionsSetLabels = RetrieveOptionSetMetaDataCollection(ref CrmWebService, EntityName, AttributeName);
foreach (OptionMetadata optionMetdaData in optionsSetLabels)
{
tracerService.Trace("now in loop with " + optionMetdaData.Label.UserLocalizedLabel.Label + " and " + optionMetdaData.Value.Value);
//we have number we need text from optionset
if (OptionSetValue != 0)
{
if (optionMetdaData.Value == OptionSetValue)
{
returnedText = optionMetdaData.Label.UserLocalizedLabel.Label;
break;
}
}
//we have text we need number from optionset
else if (optionSetText != String.Empty)
{
if (optionMetdaData.Label.UserLocalizedLabel.Label == optionSetText)
{
returnedNumber = optionMetdaData.Value.Value;
break;
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T09:57:36.987",
"Id": "39713",
"Score": "0",
"body": "I wouldn't say it's bad practice or bad code exactly - it's just not idiomatic for C#. This kind of code would be very familiar for someone who came from a C++/COM/Win32 background."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T10:01:16.983",
"Id": "39714",
"Score": "0",
"body": "@MattDavey But, why would someone use `ref` for a method like this. Honestly, I have not seen a proper real use for `ref`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T12:22:37.297",
"Id": "39720",
"Score": "1",
"body": "If you didn't write this code, then I think this question is off-topic here, per the [FAQ]."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T12:38:32.327",
"Id": "39721",
"Score": "0",
"body": "@svick Strictly per the rules, I agree that this may be off-topic here, but the question contains code and it is actual code from a project rather than pseudo-code or example code and I want the code to be good code and to the best of my knowledge the code works and I want feedback about any / all facets of the code. So, 5 out of 6 questions are answered with an Yes. There are similar questions in this site for instance - http://codereview.stackexchange.com/questions/23134/is-this-code-as-weird-as-i-think-it-is/23135#23135 and plenty others. Personally, I do not think it is off-topic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T13:56:19.173",
"Id": "39725",
"Score": "0",
"body": "@Kanini check out System.Int32.TryParse for a \"proper real\" use for a ref parameter. There are many reasons to pass a parameter by reference. But like I said, this is not considered idiomatic in C#, and to someone who *only* knows C# it may appear strange or wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T19:33:00.823",
"Id": "39736",
"Score": "0",
"body": "@MattDavey `System.Int32.TryParse` uses an `out` parameter not a `ref` parameter. The way the method in the question is implemented is not great because the semantics of an `out` parameter make more sense but cant be used because 50% of the time you want to be able to pass in a value so have to use `ref`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T08:15:10.210",
"Id": "39748",
"Score": "0",
"body": "@RobH there's not a whole lot of difference between ref and out parameters - it's a distinction that only C# makes afaik. The semantics of passing by reference are the crux of the question here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T10:23:54.550",
"Id": "39750",
"Score": "0",
"body": "@MattDavey well we are talking about C# and it is a distinction in the language. I think Homero Barbosa does a good job of explaining legitimate uses of `ref` in [his answer](http://codereview.stackexchange.com/a/25675/22816)"
}
] |
[
{
"body": "<p>This is done when you want to catch any modifications inside the method you'r calling. </p>\n\n<p>returnedInt is a value type, so he pass it as a <a href=\"http://msdn.microsoft.com/en-us/library/14akc2c7.aspx\" rel=\"nofollow\">ref</a>erence to ensure the above.\nreturnedOptionSetStringValue is a reference type but the reference to the string is passed by value, so, the same.</p>\n\n<p>Is it a good practice? I don't think so, especially since the method is void. Instead you could return the string and pass the int as an <a href=\"http://msdn.microsoft.com/en-us/library/t3c3bfhx%28v=vs.80%29.aspx\" rel=\"nofollow\">out</a> param. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T08:04:44.283",
"Id": "39710",
"Score": "0",
"body": "Thanks! Yes, I understand why the ref and passing it as a reference. But is it not better to have two separate methods one returning a string (pass the int) and the other returning an int (pass the string)? Of course, having one method with void and your suggestion will ensure that there is only one method and is better. +1 for that!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T12:58:07.170",
"Id": "39723",
"Score": "0",
"body": "OK then. I didn't suggest you should keep the void method, au contraire, you should return something, since you are already implicitly returning two values. In the other hand, this type of practice is pretty common in C++ as svick said, you shouldn't need to look to much before you find a boolean method \"returning\" someting else, so you can catch it if true. So theorically one method should do one thing, but in practice sometimes is \"better\" this kind of thing. Just do it right. And for me, right is what I answer above."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T14:09:37.153",
"Id": "39726",
"Score": "0",
"body": "Ah, I see! Sorry, I could not quite understand what you meant by \"you shouldn't need to look to much before you find a boolean method \"returning\" something else so you acn catch it if true\". Care to elaborate?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T16:15:32.350",
"Id": "39730",
"Score": "0",
"body": "what I mean is that is pretty common to find something like bool Func(param) and in other method ask if(Func(param))/*do something with param*/"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T07:32:33.203",
"Id": "25645",
"ParentId": "25644",
"Score": "2"
}
},
{
"body": "<p>Methods should only <em>do</em> one thing - in your example I think you should have seperate methods: <code>GetOptionSetLabel</code> and <code>GetOptionSetValue</code>.</p>\n\n<p>I'm always wary of public static void methods as well. I would expect something more like this (tracing code ommitted):</p>\n\n<pre><code>public class YourSensibleClassName\n{\n private IOrganizationService organizationService;\n\n // Constructor injection with a DI framework?\n public YourSensibleClassName(IOrganizationService service)\n {\n this.organizationService = service;\n } \n\n public int GetOptionSetValue(\n string entityName, \n string attributeName, \n string optionSetText, \n ITracingService tracerService)\n {\n var optionSetLabels = GetOptionSetLabels(entityName, attributeName);\n\n var result = optionSetLabels\n .FirstOrDefault(\n label => label.Label.UserLocalizedLabel.Label.Equals(optionSetText));\n\n if (result == null) \n {\n throw new Exception(\n string.Format(\n \"No value exists for the specifed optionSetText {0}\", \n optionSetText));\n }\n\n return result;\n }\n\n public string GetOptionSetText(\n string entityName, \n string attributeName, \n int optionSetValue, \n ITracingService tracerService)\n {\n // Code to get the text from the value\n }\n\n private OptionMetadataCollection GetOptionSetLabels(\n string entityName, \n string attributeName)\n {\n // Code to get the OptionMetadataCollection and this method needs refactoring too:\n // RetrieveOptionSetMetaDataCollection(ref this.organisationService, entityName, attributeName);\n }\n}\n</code></pre>\n\n<p>I'd expect this to be called like:</p>\n\n<pre><code>YourSensibleClassName c = new YourSensibleClassName(CRMAccess.xrmService);\n\nvar optionSetValue = c.GetOptionSetValue(\n Contact.EntityLogicalName, \n \"new_status\", \n \"the option set text\", \n CRMAccess.tracerService);\n</code></pre>\n\n<p>Judging by similar code I've seen written by people, I would think that your Solution Architect comes from a VB6 and before background and hasn't quite made the transition to C#. I'd also be worried by the lack of consistency with parameter names (both camel and Pascal case used), not using built in methods (e.g. using <code>== string.Empty</code> instead of <code>string.IsNullOrEmpty(string)</code>), using a foreach loop when Linq offers a much shorter and clearer way of achieving the goal (although internally doing roughly the same thing) and a clear obsession with ref parameters.</p>\n\n<p>Just to add, one particular dev who coded like this created a method which required over 20 arrays passed by reference... It still makes me shudder.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T08:56:33.027",
"Id": "25647",
"ParentId": "25644",
"Score": "2"
}
},
{
"body": "<p>To answer your question, to me this is an illegitimate use of <code>ref</code> on a value type parameter.</p>\n\n<p>Here's why:</p>\n\n<p>1) Legit usages of <code>ref</code> are when you need to keep track the value of <code>ref</code> parameter or when passing the value is expensive. e.g. when using recursion to traverse a tree and you need to keep track of its depth.</p>\n\n<pre><code>Node<T> FindNode(T root, int nodeValue, ref int depth);\n</code></pre>\n\n<p>2) The code by the Solution Architect looks confusing and weird because it should be using <code>out</code> parameters instead (not to mention that it smells and looks like it deserves some refactoring).</p>\n\n<p>Unlike <code>ref</code> params, <code>out</code> params need not be initialized prior being passed; which is why <code>returnedOptionSetStringValue</code> and <code>returnedInt</code> are being initialized.</p>\n\n<p>For further reading:\n<a href=\"http://msdn.microsoft.com/en-us/library/t3c3bfhx(v=vs.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/t3c3bfhx(v=vs.80).aspx</a>\n<a href=\"https://stackoverflow.com/questions/1516876/when-to-use-ref-vs-out\">https://stackoverflow.com/questions/1516876/when-to-use-ref-vs-out</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T05:56:30.440",
"Id": "25675",
"ParentId": "25644",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "25675",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T07:10:13.777",
"Id": "25644",
"Score": "4",
"Tags": [
"c#"
],
"Title": "Using ref for value types"
}
|
25644
|
<p>I want to efficiently (few intermediate objects) and neatly (few lines and easy to read) filter an array, removing <em>and returning</em> rejected items. So like a call to delete_if except instead of returning the remaining items, returning the deleted items.</p>
<p>Here's some code that works:</p>
<pre><code>ary = (0..9).to_a
odds = ary.select {|i| i%2==1 }
ary -= odds
</code></pre>
<p>or:</p>
<pre><code>ary = (0..9).to_a
(_,ary),(_,odds) = ary.group_by {|i| i.odd? }.sort {|a,b| a[0] ? 1 : -1 }
</code></pre>
<p>But I can't help but think there should be a better way...</p>
<p>Ideally something more like: <code>odds = ary.delete_and_return(&:odd?)</code></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T11:22:23.827",
"Id": "39718",
"Score": "0",
"body": "`deleted = ary - ary.select(&:someproc)` seems totally fine to me"
}
] |
[
{
"body": "<p>it is <a href=\"http://ruby-doc.org/core-2.0/Array.html#method-i-delete_if\" rel=\"nofollow\">built-in</a> : </p>\n\n<pre><code>ary.delete_if( &:odd? )\n</code></pre>\n\n<p><strong>EDIT</strong></p>\n\n<p>Sorry, misread your question. You can do this :</p>\n\n<pre><code>deleted = ary.select( &:odd? ).tap{|odd| ary -= odd }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T12:22:07.607",
"Id": "39719",
"Score": "0",
"body": "as a side note, it is sad that `Enumerable#drop` does not provide this functionality : it would accept a block, drop _n or all_ elements where the block returns true, and return the dropped elements. I wish I knew C better to patch it..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T12:07:33.047",
"Id": "25649",
"ParentId": "25648",
"Score": "2"
}
},
{
"body": "<p>You need <a href=\"http://www.ruby-doc.org/core-1.9.2/Enumerable.html#method-i-partition\" rel=\"nofollow\"><code>#partition</code></a>:</p>\n\n<pre><code>irb> a = (1..9).to_a\n=> [1, 2, 3, 4, 5, 6, 7, 8, 9]\nirb> a.partition(&:odd?).tap{ |y, n| a = n }.first\n=> [1, 3, 5, 7, 9]\nirb> a\n=> [2, 4, 6, 8]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T04:49:04.967",
"Id": "39747",
"Score": "2",
"body": "Can you please explain your answer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-02T01:55:16.817",
"Id": "39836",
"Score": "0",
"body": "http://www.ruby-doc.org/core-1.9.2/Enumerable.html#method-i-partition"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T02:59:38.603",
"Id": "25674",
"ParentId": "25648",
"Score": "1"
}
},
{
"body": "<p><code>Array.partition</code> returns an array of two arrays - one where the elements returned <code>true</code> to the condition, and one that returned <code>false</code>.</p>\n\n<p>So, a single liner for your need would be:</p>\n\n<pre><code>odds, ary = (0..9).to_a.partition(&:odd?)\n=> [[1, 3, 5, 7, 9], [0, 2, 4, 6, 8]] \n</code></pre>\n\n<p><code>(&:odd?)</code> acts exactly like writing <code>{ |x| x.odd? }</code> which will return true if the number is, well, odd...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-02-20T13:51:29.067",
"Id": "42303",
"ParentId": "25648",
"Score": "4"
}
},
{
"body": "<p>Since there is no such method yet in ruby, you can always add your own if that makes sense to your use case (if you find yourself needing that method a lot).</p>\n\n<p>Here is and example implementation:</p>\n\n<pre><code>class Array\n def extract! &block\n extracted = select(&block)\n reject!(&block)\n extracted\n end\nend\n</code></pre>\n\n<p>The code above first selects what you want to return and then destructively removes those items which is what you want to avoid doing manually to improve readability.</p>\n\n<p>Note: the method is called <code>extract!</code> with a bang since it modifies the array itself. If the method wuould not modify the underlying object, it would be equivalent to <code>select</code>, so you might name it <code>select!</code>, or <code>select_and_remove!</code> if you prefer.</p>\n\n<p>Usage:</p>\n\n<pre><code>a = (0..10).to_a\n\n# extract even numbers from our array\np a.extract!(&:even?) # => [0, 2, 4, 6, 8, 10]\n\n# odd numbers are left\np a # => [1, 3, 5, 7, 9]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-26T07:33:57.737",
"Id": "111873",
"ParentId": "25648",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T10:58:23.017",
"Id": "25648",
"Score": "6",
"Tags": [
"ruby",
"array"
],
"Title": "A pattern to destructively extract items from an array"
}
|
25648
|
<p>Since I didn't find a way to properly transform JavaScript object to JSON with PHP, I wrote a snippet.</p>
<hr>
<p>Lets assume the following excerpt from Google Fonts JavaScript API:</p>
<pre><code>WebFontConfig = {
google: { families: [ 'Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic,700italic:latin,latin-ext' ] }
};
</code></pre>
<p>This, given straight to PHP's <code>json_decode</code> will <code>null</code> out and <a href="http://jsonlint.com/" rel="nofollow">JSONLint</a> will say it's invalid.</p>
<p>Since I need this data in JSON after the template has been parsed (working on an exporter), I wrote this snippet (which double-quotes the hell out of this one):</p>
<pre><code>// gather WebFontConfig arrays
$webfonts = preg_match_all('/(WebFontConfig\s*?=\s*?)\{(.+?)(\};)/s', $scriptData, $fontdata, PREG_SET_ORDER);
// kids, dont do this at home
foreach ($fontdata as $founddata)
{
$original = $founddata[0];
$WFCVariable = $founddata[1];
// leave outer braces only
$usable = str_replace($WFCVariable, '', $original);
$usable = trim($usable, ';');
// transform keys into double-quoted keys
$usable = preg_replace('/(\w+)(:\s*?)(\{|\[)/im', '"$1"$2$3', $usable);
// prepare to transform array wrapping single quotes to double quotes
$lookups = array(
'/(\[)(\s*?)(\')/',
'/(\')(\s*?)(\])/'
);
$replace = array(
'$1$2"',
'"$2$3'
);
$usable = preg_replace($lookups, $replace, $usable);
// decode
$jsoned = json_decode($usable);
// and check
var_dump($jsoned);
}
</code></pre>
<p><code>$scriptData</code> essentially is the above JavaScript object trim-extracted out of my template through <code>DOMDocument</code> .. <code>DOMNode->nodeValue</code>.</p>
<hr>
<p>There is no problem with the snippet, it converts my data into PHP array without problems. </p>
<p>My concern, though, is, whether <strong>this is the most optimal way of doing it</strong>?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T14:56:34.050",
"Id": "39727",
"Score": "0",
"body": "possible duplicate of [Parsing Javascript (not JSON) in PHP](http://stackoverflow.com/questions/1554100/parsing-javascript-not-json-in-php)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T15:15:29.150",
"Id": "39728",
"Score": "3",
"body": "I'm wondering why you don't just call their (Google Web Fonts) JSON api from the server?. It will return the results properly formatted for you. You do need an API key, however those are easily obtained."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T15:22:38.053",
"Id": "39729",
"Score": "0",
"body": "@rlemon, oh, didn't see that GWF has it. Will look into it."
}
] |
[
{
"body": "<p>As this works for you and as there is no javascript interpreter in PHP unless you install it (there is a V8 PHP extension IIRC), I would say you did this right so far.</p>\n\n<p>Which else criteria could there be than your own ones? You should probably write unit and acceptance tests for it. And remove the <code>var_dump</code> debug cruft out of it. But by the way you do this on it's own, it does not look too far off.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T14:58:31.280",
"Id": "25654",
"ParentId": "25653",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "25654",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T14:50:09.323",
"Id": "25653",
"Score": "3",
"Tags": [
"javascript",
"php",
"json",
"lookup"
],
"Title": "JavaScript object to JSON"
}
|
25653
|
<p>I have written my first jQuery plugin using one of the design patterns suggested on jQuery's site: <a href="http://docs.jquery.com/Plugins/Authoring" rel="nofollow">http://docs.jquery.com/Plugins/Authoring</a>. </p>
<p>As listed below in the description comment, it's purpose is to provide keyboard and mouse navigation and highlighting for the children of elements like tables, ul's, ol's, and nav's. Believe it or not, I could not find a good, current one that fits my needs... </p>
<p>I want to publish it, but I also want to ensure that's it's good enough to throw out there before doing so, so I am asking for a review. </p>
<p>There are some specific things I have questions about, so I will list them all out. </p>
<ul>
<li>My main concern is that in my functions, I wasn't quite clear concerning context, possibly. In order to reference vars declared in the init, one way I found that I could do it was to throw away the var statement, but I know it's best practice to always have them. Otherwise, I can reference the init var's by referring to <code>$.fn.highlightNavigation</code>, which is what is shown below. Seems much better, but I'm just not sure that's good practice. I feel silly about this one..</li>
<li>The .js file is loaded with comments. I did this in order to make everything to clear to anyone who is working with it. Is there a best practice concerning how much you comment?</li>
<li>I didn't want to style everything for the author thinking it may make it difficult when they are working with already styled elements and they wish to keep those styles. So, I just kept it to a bare minimum. Thought on this?</li>
<li>Are there any other things you can see that needs some clarification, fixing, or improvement?</li>
</ul>
<p></p>
<pre><code>/**
* Name: highlight-navigation jQuery plugin
* Author: Stephanie Fischer
* Description: Provides keyboard and mouse navigation and highlighting for elements with items, such as rows belonging to tables, li's belonging to ul's and ol's, and a's belonging to nav's. Currently only the elements listed are supported, but please extend if you see a need for another element. Also, at this time, it will only work for one instance.
*/
;(function($){
methods = {
init: function(options){
var self = this,
$self = $(this);
$.fn.highlightNavigation.self = $self;
self.wrapper = $("<div class=\"highlight-navigation-container\"/>");
$.fn.highlightNavigation.self
.after(self.wrapper)
.detach()
.appendTo(self.wrapper);
$.fn.highlightNavigation.elemObjTag = $.fn.highlightNavigation.self.prop("tagName");
settings = $.extend({}, $.fn.highlightNavigation.defaults, options);
this.selectedItem = {};
$(document).on("keydown", $.proxy(methods.keyPress, self)); //bind keydown to keyPress function.
$(document).on("click", $.proxy(methods.itemClick, self)); //bind click to itemClick function.
$(document).on("touchstart", $.proxy(methods.itemClick, self)); //bind touchstart (mobile) to itemClick function.
methods.selectFirst();
},
selectFirst: function(){
var $firstItem = {},
$allItems = methods.getAllItems();
if($allItems){
$firstItem = $allItems.eq(0);
$firstItem.addClass("selected");
$.fn.highlightNavigation.selectedItem = $firstItem; //Set public selectedItem var to first item.
settings.onSelect(); //onSelect callback.
settings.selectFirst(); //selectFirst callback.
}
},
selectNext: function(direction){ //Apply highlighting for item we're navigating to.
var $selectedItem = {},
$currentselectedItem = methods.getSelectedItem();
if(direction == -1 && $currentselectedItem.prev().prop("tagName") != undefined){ //Go to previous item, if it exists.
$selectedItem = $currentselectedItem.prev();
$selectedItem.addClass("selected");
}
else if(direction == 1 && $currentselectedItem.next().prop("tagName") != undefined){ //Go to next item, if it exists.
$selectedItem = $currentselectedItem.next();
$selectedItem.addClass("selected");
}
if(!$.isEmptyObject($selectedItem)){ //New item was selected
$currentselectedItem.removeClass("selected"); //Remove selected class from current item.
$.fn.highlightNavigation.selectedItem = $selectedItem; //Set selectedItem.
}
settings.onSelect(); //onSelect callback.
settings.selectNext(); //selectNext callback.
},
keyPress: function(e){ //Handle key press.
var keyCode = "",
direction = "";
e.preventDefault();
if(window.event){
keyCode = window.event.keyCode;
}
else if(e){
keyCode = e.which;
}
direction = (keyCode == settings.navPrevItemKey)?-1:(keyCode == settings.navNextItemKey)?1:0; //Previous or Next key was pressed, select applicable item.
if(direction != 0){
methods.selectNext(direction); //Call selectNext on item we're navigating to.
}
if(keyCode == settings.navActionKey){ //Action key (ie: Enter) was pressed, take applicable action defined in callback.
settings.actionKeyPress();
}
this.keyCode = keyCode; //Set public keyCode.
settings.keyPress(); //keyPress callback
},
itemClick: function(e, data){ //Perform item click.
var self = this,
evt = (e)?e:event,
itemClicked = (evt.srcElement)?evt.srcElement:evt.target,
$allItems = methods.getAllItems(),
$itemClicked = {},
$selectedItem = methods.getSelectedItem();
e.preventDefault();
if($.fn.highlightNavigation.elemObjTag == "TABLE"){
$itemClicked = $(itemClicked).parent()
}
else{
$itemClicked = $(itemClicked);
}
if($itemClicked.parent().prop("tagName") != "TH"){ //If table, only apply selection for the rows that are not in the table header.
$allItems.removeClass("selected"); //Remove selected class from all other items.
$itemClicked.addClass("selected"); //Apply selected class to item just clicked.
$.fn.highlightNavigation.selectedItem = $itemClicked; //Set public selectedItem.
settings.itemClick(); //itemClick callback
}
},
getAllItems: function(){ //Return all items.
if($.fn.highlightNavigation.elemObjTag == "TABLE"){ //note: make into case statement
return $.fn.highlightNavigation.self.find("tbody tr");
}
else if($.fn.highlightNavigation.elemObjTag == "UL" || $.fn.highlightNavigation.elemObjTag == "OL"){
return $.fn.highlightNavigation.self.find("li");
}
else if($.fn.highlightNavigation.elemObjTag == "NAV"){
return $.fn.highlightNavigation.self.find("a");
}
else{
return false;
}
},
getSelectedItem: function(){ //Public method to return selected item.
return $.fn.highlightNavigation.selectedItem;
},
selectItem: function(index){ //Public method to return selected item.
var allItems = methods.getAllItems(),
$selectedItem = $(allItems.get(index));
allItems.removeClass("selected"); //Remove selected class from all other items.
$selectedItem.addClass("selected"); //Apply selected class to newly selected item.
$.fn.highlightNavigation.selectedItem = $selectedItem; //Set selectedItem.
settings.onSelect(); //onSelect callback.
return $selectedItem; //return newly selected item.
},
getKeyCode: function(){ //Return keycode.
return $.fn.highlightNavigation.keyCode;
},
destroy: function(){ //Undo everything
var self = this;
methods.getSelectedItem().removeClass("selected"); //Remove selected class
$(document).off("keydown", $.proxy(methods.keyPress, self)); //unbind keydown from keyPress function.
$(document).off("click", $.proxy(methods.itemClick, self)); //unbind click from itemClick function.
$(document).off("touchstart", $.proxy(methods.itemClick, self)); //unbind touchstart (mobile) from itemClick function.
$.fn.highlightNavigation.self.unwrap(); //Remove container element
}
};
$.fn.highlightNavigation = function(method){
$.fn.highlightNavigation.defaults = {
navPrevItemKey: 38, //Up arrow
navNextItemKey: 40, //Down arrow
navActionKey: 13, //Enter
selectFirst: function(){},
selectNext: function(){},
onSelect: function(){},
keyPress: function(){},
itemClick: function(){},
getAllItems: function(){},
selectItem: function(){},
getKeyCode: function(){},
};
if(methods[method]){
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
}
else if(typeof method === "object" || !method){
return methods.init.apply(this, arguments);
}
else{
$.error("Method " + method + " does not exist in highlight-navigation");
}
};
})(jQuery);
</code></pre>
<p>Here's the simple css file that will be bundled with it:</p>
<pre><code>.highlight-navigation-container .selected{
background: #dde3ff;
}
</code></pre>
<p>Here is an example of it's usage with just some basic callbacks to open a new page based on an ID belonging to the table row (marked up in the HTML, not the plugin):</p>
<pre><code> $(".table")
.highlightNavigation({
actionKeyPress: function(event, data){ //When action key (enter) is pressed, or row is clicked, go to applicable record.
var $this = $(this),
$selectedRow = $this.highlightNavigation("getSelectedItem"),
keyCode = $this.highlightNavigation("getKeyCode");
location.href = "users.html#" + $selectedRow.data("id");
},
itemClick: function(event, data){ //When action key (enter) is pressed, or row is clicked, go to applicable record.
var $this = $(this),
$selectedRow = $this.highlightNavigation("getSelectedItem"),
$selectedRowID = $selectedRow.data("id");
if($selectedRowID != undefined){
location.href = "users.html#" + $selectedRowID;
}
}
});
selectThree= $(".table").highlightNavigation("selectItem", 3); //select and highlight item 4.
</code></pre>
|
[] |
[
{
"body": "<p>A late review:</p>\n\n<ul>\n<li>Yes, declaring variables without <code>var</code> is criminal, your approach will do. Do read up on the <a href=\"http://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript\" rel=\"nofollow\">revealing module pattern</a> to avoid the <code>$.fn.highlightNavigation</code> approach.</li>\n<li><p>Comments are hard actually, you have a great set here : </p>\n\n<pre><code>$(document).on(\"keydown\", $.proxy(methods.keyPress, self)); //bind keydown to keyPress function.\n$(document).on(\"click\", $.proxy(methods.itemClick, self)); //bind click to itemClick function.\n$(document).on(\"touchstart\", $.proxy(methods.itemClick, self)); //bind touchstart (mobile) to itemClick function.\n</code></pre>\n\n<ul>\n<li>I can see you are connecting <code>keydown</code> to <code>keypress</code>, and the comment calls out that you are doing something unusual. Unfortunately you decided not to comment <em>why</em> you did this</li>\n<li><code>click</code> to <code>itemClick</code> is so obvious that the comment is a waste of reading time</li>\n<li>The third comment is good, because you indicate what you are doing and why (mobile)</li>\n</ul></li>\n<li>Your sparse usage of styles is a good idea</li>\n</ul>\n\n<p>Other than that, from a once over:</p>\n\n<ul>\n<li><p>This is too verbose:</p>\n\n<pre><code>$selectedItem = $currentselectedItem.prev();\n$selectedItem.addClass(\"selected\");\n</code></pre>\n\n<p>I would rather see</p>\n\n<pre><code>$currentselectedItem.prev().addClass(\"selected\");\n</code></pre>\n\n<p>With or without a line of comment</p></li>\n<li><p>The one line indentation for the function body is consistent, but a tad too hard to read and unorthodox</p></li>\n<li><p>I see use ternaries, but perhaps not enough, this</p>\n\n<pre><code>if(window.event){\n keyCode = window.event.keyCode;\n}\nelse if(e){\n keyCode = e.which;\n}\n</code></pre>\n\n<p>could be</p>\n\n<pre><code>keyCode = window.event ? window.event.keyCode : e.which;\n</code></pre></li>\n<li><p>Even if you are not going to use the revealing module pattern, you could use 'sugar' variables to make things less repetitive, so that this</p>\n\n<pre><code>getAllItems: function(){ //Return all items.\n if($.fn.highlightNavigation.elemObjTag == \"TABLE\"){ //note: make into case statement\n return $.fn.highlightNavigation.self.find(\"tbody tr\");\n }\n else if($.fn.highlightNavigation.elemObjTag == \"UL\" || $.fn.highlightNavigation.elemObjTag == \"OL\"){\n return $.fn.highlightNavigation.self.find(\"li\");\n }\n else if($.fn.highlightNavigation.elemObjTag == \"NAV\"){\n return $.fn.highlightNavigation.self.find(\"a\");\n }\n else{\n return false;\n }\n},\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>getAllItems: function(){ \n var tag = $.fn.highlightNavigation.elemObjTag,\n findFunction = $.fn.highlightNavigation.self.find;\n if( tag == \"TABLE\"){ //note: make into case statement\n return findFunction(\"tbody tr\");\n }\n if(tag == \"UL\" || tag == \"OL\"){\n returnfindFunction(\"li\");\n }\n if(tag == \"NAV\"){\n return findFunction(\"a\");\n }\n return false;\n}, \n</code></pre>\n\n<p>note that <code>else if</code> is not required if the previous <code>if</code> block has a <code>return</code> statement. It makes things more readable.</p></li>\n<li><p>In this code block</p>\n\n<pre><code>itemClick: function(e, data){ //Perform item click.\n var self = this,\n evt = (e)?e:event,\n itemClicked = (evt.srcElement)?evt.srcElement:evt.target,\n $allItems = methods.getAllItems(),\n $itemClicked = {},\n $selectedItem = methods.getSelectedItem();\n</code></pre>\n\n<p>You are not using <code>data</code>, <code>self</code> or <code>$selectedItem</code>.\nYou can use a tool like JsHint to find such inconsistencies.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-03T20:39:48.737",
"Id": "64680",
"ParentId": "25656",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T16:14:37.740",
"Id": "25656",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"plugin"
],
"Title": "jQuery highlightNavigation plugin"
}
|
25656
|
<p>I'm coming close to finishing a site where there are a number of jQuery functions going on. They all work, but the page is just running a bit too clunky. The fading in and out is just not as smooth as it should be, especially on the contact link, and the auto page scrolling is a little jumpy.</p>
<p>I've cached as many selectors as I could, I've minified the script, I'm using the latest jquery, but not much has changed. I'm wondering if someone could tell perhaps why?</p>
<pre><code>$(document).ready(function ()
{
/*--------Variables -----------------------------------*/
var trigger1 = $('#trigger1');
var trigger2 = $('#trigger2');
var trigger3 = $('#trigger3');
var trigger4 = $('#trigger4');
var closed = $('.close');
var scrollContainer = $('#scrollContainer');
var scrollOpen = $('#scrollOpen');
var movie = $('#movie');
var openBook = $('#openBook');
var openChest = $('#openChest');
var theLetter = $('#theLetter');
var synopsis = $('#synopsis');
var shine2 = $('#shine2');
var bookGlow = $('#bookGlow');
var chestGlow = $('#chestGlow');
var iframe = $('iframe');
var contact = $('#contact');
var contactWrapper = $('#contactWrapper');
/*--------End Variables --------------------------------*/
/*-------------------Auto Page Scroll-------------------*/
$('#navigation_container').localScroll({
duration: 1000
});
$('#top').localScroll({
duration: 1000
});
/*-----------------End Auto Page Scroll-------------------*/
/*-------------------Contact Form-------------------------*/
$('ul#Navlist li:last').click(function () {
contact.delay(1000).fadeIn(3000);
var viewportWidth = $(window).width();
var viewportHeight = $(window).height();
var popupWidth = contactWrapper.width();
var popupHeight = contactWrapper.height();
var leftPos = (viewportWidth/2)-(popupWidth/2);
var topPos = (viewportHeight/2)-(popupHeight/2);
contactWrapper.css('top', topPos).css('left', leftPos);
closed.delay(1500).fadeIn(3000);
});
closed.click(function () {
contact.delay(700).fadeOut('slow');
});
/*-------------------End Contact Form-------------------*/
trigger1.click(function () {
scrollContainer.fadeIn('slow');
scrollOpen.delay(1000).animate({
right: 60
}, {
duration: 1000
});
closed.delay(1500).fadeIn('slow')
});
closed.click(function () {
scrollOpen.animate({
right: -579
}, {
duration: 1000
});
scrollContainer.delay(700).fadeOut('slow');
});
trigger2.click(function () {
movie.delay(1000).animate({
bottom: 0
}, {
duration: 1000
});
closed.delay(1500).fadeIn('slow')
});
closed.click(function () {
iframe.attr('src', iframe.attr('src'));
movie.delay(1000).animate({
bottom: -500
}, {
duration: 1000
});
});
trigger3.click(function () {
openBook.fadeIn(1000);
closed.delay(1000).fadeIn('slow')
});
closed.click(function () {
openBook.delay(700).fadeOut('slow');
});
trigger4.click(function () {
openChest.fadeIn('slow');
});
openChest.click(function () {
$(this).fadeOut('slow');
theLetter.delay(1000).fadeIn('slow');
closed.delay(1500).fadeIn(3000);
});
closed.click(function () {
theLetter.delay(700).fadeOut('slow');
});
/*--------------- Audio Begin ------------------------------*/
var audio = $('#magic')[0];
$('#trigger1, #trigger2, #trigger3, #trigger4').mouseenter(function () {
audio.play();
$('#synopsis,#shine2,#chestGlow,#bookGlow').fadeIn('slow');
});
$('#trigger1, #trigger2, #trigger3, #trigger4').mouseleave(function () {
$('#synopsis,#shine2,#chestGlow,#bookGlow').fadeOut('slow');
});
/*---------------End Audio -----------------------------*/
})
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T14:55:56.527",
"Id": "39769",
"Score": "0",
"body": "I took a quick look at the page. Where do you turn off the sound?"
}
] |
[
{
"body": "<p>Clunky is what happens when the browser is using much of the CPU. This could be some animation, timers that keep firing, or something else. In your case:</p>\n\n<ul>\n<li><p>You're streaming an mp3 in the background. It's a 5MB file, too big. I suggest you shrink that mp3, maybe lower its bitrate like 96kbps. It's still a good rate for background audio. The viewers are not after your audio after all.</p></li>\n<li><p>The audio seems to be repetetive. Keep the audio short, around 20-30 seconds rather than almost 3 mins, and just loop it.</p></li>\n<li><p>I sense you are looping the audio, but the file is downloaded every loop. The network tab of the debugger says so. Find a way that your audio file is being reused by the player from cache rather than doing a re-download. If the file isn't dynamic, you could set its cache time to a very long one.</p></li>\n<li><p>Now, over to the code. True, you are caching values, and that's good. But you just don't cache any value. Cache the ones where:</p>\n\n<ul>\n<li>The values get used always, especially ones that fetch DOM elements</li>\n<li>Known non-dynamic values. <code>window</code> and <code>document</code> objects as well as <code>html</code>, <code>head</code> and <code>body</code> elements are known to be non-dynamic. Also, depending on the use case, the context object <code>this</code> could be used more than once especially in handlers.</li>\n</ul></li>\n<li><p>The handlers have <em>delayed</em> responses in your code. I notice that triggers you have are delayed by 700ms - that's considered lag already.</p>\n\n<p>In fact, humans perceive 200ms or less as instant. If you are a gamer, you even aim for < 100ms latency at best. For interfaces, the tolerance range is around 200-400ms, . Anything greater than say 600ms is noticeable lag.</p>\n\n<p>So I suggest that when a user takes action on the UI, provide a snappy feedback. For your code, I suggest removing the <code>delay()</code> and fade them right away. Your fade speeds should be set to <code>fast</code> or within the 200-700ms range.</p></li>\n<li><p>You are repetitively calling <code>audio.play()</code> every <code>mouseenter</code>. Check if the audio is already playing, and if not, that's when you call play.</p></li>\n<li><p>Before running an effect, check for pending animations. If the elements are still animating, don't run another. The effects are queued and won't stop until the queue finishes. </p>\n\n<p>For example, mousing over and out of the triggers. If I mouse in and out for say 5 times, the fade in and out effects get queued. Even if I already left the section and not mousing in and out, it will continue to run until all the 5 events are finished executing.</p>\n\n<p>A handy way to prevent queuing is to add a class to the target, usually called \"isAnimating\". This class name is attached upon animation, and removed after animation. Before you trigger animation, you check if this exists, and if so, don't run the animation code.</p></li>\n<li><p>Structure the DOM properly. Too much excess elements could use up too much memory.</p></li>\n<li><p>Use the off-screen hiding technique. Instead of appending elements when they need to show up, append them early. To hide them, give them a negative <code>left</code> to hide them off to the left. Once needed, set them to <code>visibility:hidden</code>, position them where you want them to appear, and have them fade in. You are avoiding half of the DOM operations, which would be append and remove.</p>\n\n<p>However, don't forget about media elements. If you hide them off left, they will still play. Don't forget to turn them off before hiding.</p></li>\n<li><p>Your site uses a lot of HD graphics and media. I suggest you do the following:</p>\n\n<ul>\n<li>Preload resources that are needed immediately</li>\n<li>Lazy-load the others that are needed much later. Usually, some developers create idle-loaders, which load resources when no other scripts are using the network.</li>\n<li>Scripts can be loaded in parallel using script-loaders or dependency injectors. If you use RequireJS and their optimizer, all scripts are modules than can be shrunk into one script. </li>\n<li>Images can be loaded using image-loading scripts to load them in parallel as well.</li>\n<li>JPGs are usually smaller than PNGs but lack the alpha channel. Use JPGs for background images, and PNGs only for the elements that need to blend with the background.</li>\n<li>Images can be compressed or can lose quality without visual difference. I used Adobe Fireworks before and reduced quality to 70% without noticing differences. This makes images smaller, and almost half their size.</li>\n<li>Using image spriting to have images load faster by lessening HTTP requests.</li>\n</ul></li>\n<li><p>I suggest you keep an eye on events using the debugging tools on the browser. In Chrome, ones to check are:</p>\n\n<ul>\n<li>Network tab - to check the load times of the resources, which take too long or are loading more than once</li>\n<li>Timeline - you can check for events, what fires when and memory usage.</li>\n<li>CPU profiling - check what tasks take up too much CPU time</li>\n</ul></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T12:07:11.077",
"Id": "39761",
"Score": "1",
"body": "+1 for a very good answer - on my connection, Chrome reported over 100 seconds to download the MP3 (and confirms your suspicion that it was downloaded more than once)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-04T11:11:29.060",
"Id": "39939",
"Score": "0",
"body": "Wow great informative answer. I will try all these things and get back to you. Thank you!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T00:16:27.887",
"Id": "25670",
"ParentId": "25657",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "25670",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T16:46:14.410",
"Id": "25657",
"Score": "2",
"Tags": [
"javascript",
"performance",
"jquery",
"animation"
],
"Title": "Scrolling, fade-in, and fade-out effects feeling clunky"
}
|
25657
|
<p>I've posted here before and got pretty helpful reviews. How does my code look now? To keep it really helpful, I just copied this from the middle of one of my projects.</p>
<pre><code> <?php
function findSimilarityBetweenImages($imagePathA, $imagePathB, $accuracy){
//if images are png
$imageA = imagecreatefrompng($imagePathA);
$imageB = imagecreatefrompng($imagePathB);
//if images are jpeg
//$imageA = imagecreatefromjpeg($imagePathA);
//$imageB = imagecreatefromjpeg($imagePathB);
//get image resolution
$imageX = imagesx($imageA);
$imageY = imagesy($imageA);
$pointsX = $accuracy*5;
$pointsY = $accuracy*5;
$sizeX = round($imageX/$pointsX);
$sizeY = round($imageY/$pointsY);
//Compare the color of each point while looping through.
$y = 0;
$match = 0;
$num = 0;
for ($i=0; $i < $pointsY; $i++) {
$x = 0;
for($n=0; $n < $pointsX; $n++){
$rgba = imagecolorat($imageA, $x, $y);
$colorsa = imagecolorsforindex($imageA, $rgba);
$rgbb = imagecolorat($imageB, $x, $y);
$colorsb = imagecolorsforindex($imageB, $rgbb);
if(colorComp($colorsa['red'], $colorsb['red']) && colorComp($colorsa['green'], $colorsb['green']) && colorComp($colorsa['blue'], $colorsb['blue'])){
$match ++; //Match between points.
}
$x += $sizeX;
$num++;
}
$y += $sizeY;
}
//A similarity or percentage of match between the two images.
$similarity = $match*(100/$num);
return $similarity;
}
function colorComp($color, $c){
//To see if the points match
if($color >= $c-2 && $color <= $c+2)
{
return true;
}
else
{
return false;
}
}
?>
</code></pre>
|
[] |
[
{
"body": "<p>Since your question is about coding style, consider to adhere to <a href=\"https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md\">PSR-2</a>.</p>\n\n<p>Your color comparision function is bloated. 'If the expression is true, then return true, else, if the expression is false, then return false.' Just return the expression.</p>\n\n<pre><code>return ($color >= $c-2 && $color <= $c+2);\n</code></pre>\n\n<p>Next, I'd make the literal '2' variable, and add some DocBlock documentation:</p>\n\n<pre><code>/**\n * Check if two color components are similar\n *\n * @param int $color The first color component's value\n * @param int $c The second color component's value\n * @param int $dist The maximum difference for two values to be considered equal\n *\n * @return boolean True, if the color components are similar.\n */\nfunction colorComp($color, $c, $dist)\n{\n return ($color >= $c-$dist && $color <= $c+$dist);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-02T18:46:33.517",
"Id": "39889",
"Score": "0",
"body": "Wow. The DocBlock improves the readability of my code even for me! Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T15:06:50.070",
"Id": "25692",
"ParentId": "25660",
"Score": "5"
}
},
{
"body": "<p><strong>Note:</strong> \nI seriously recommend scjr's response over my own. His code implements all of my (minor) adjustments, but also includes the improved coding practices, organization, and straightforward logic that good code should have.</p>\n\n<hr>\n\n<p>Making it more functional and adjusting the variable names helps make it more readable and helps you more quickly identify what each part of code does what.</p>\n\n<p>TotalPoints can be calculated, and doesn't belong in the loop. I combined x, i, n, and y, to clean up the loops as well. They could be adjusted even more, changing x++ to x+=xIncrement, removing the need to multiply x and y at every point (a performance hit that I introduced that you could remove).</p>\n\n<pre><code><?php\n\n function findSimilarityBetweenImages($imagePathA, $imagePathB, $accuracy){\n\n //if images are png\n $imageA = imagecreatefrompng($imagePathA);\n $imageB = imagecreatefrompng($imagePathB);\n\n //if images are jpeg\n //$imageA = imagecreatefromjpeg($imagePathA);\n //$imageB = imagecreatefromjpeg($imagePathB);\n\n //get image resolution\n $imageWidth = imagesx($imageA);\n $imageHeight = imagesy($imageA);\n\n $density = $accuracy * 5;\n $xIncrement = round($imageWidth/$density);\n $yIncrement = round($imageHeight/$density);\n\n //Compare the color of each point while looping through.\n $matchingPoints = 0;\n\n for ($y=0; $y < $density; $y++) {\n for ($x=0; $x < $density; $x++){\n\n $colorsa = colorData($imageA, $x*$xIncrement, $y*$yIncrement);\n $colorsb = colorData($imageB, $x*$xIncrement, $y*$yIncrement);\n\n if(colorsMatch($colorsa, $colorsb)){\n $matchingPoints++; //Match between points.\n }\n }\n }\n\n $totalPoints = $pointsHeight * $imageHeight;\n\n //A similarity or percentage of match between the two images.\n $similarity = $matchingPoints*(100/$totalPoints);\n return $similarity;\n }\n\n function colorData($imageA, $x, $y){\n $rgb = imagecolorat($imageA, $x, $y);\n return imagecolorsforindex($imageA, $rgb);\n }\n\n function colorsMatch($colorsa, $colorsb){\n //Compare the R, G, and B values\n return colorComp($colorsa['red'], $colorsb['red']) && colorComp($colorsa['green'], $colorsb['green']) && colorComp($colorsa['blue'], $colorsb['blue']);\n }\n\n function colorComp($color, $c){\n //To see if the points match\n return ($color >= $c-2 && $color <= $c+2);\n }\n\n?>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T15:26:56.357",
"Id": "25693",
"ParentId": "25660",
"Score": "3"
}
},
{
"body": "<p>I suggest object oriented programming over the procedural style for many reasons I won't get into here. I also suggest being consistent about using camelCase throughout all of your code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T15:42:49.377",
"Id": "25695",
"ParentId": "25660",
"Score": "2"
}
},
{
"body": "<p>Ok, so I have made lots of changes to the code.</p>\n\n<p>I have left comments starting with <code>>>></code>'s all over the code to note what I have changed and why. </p>\n\n<p>I didn't really look into what the code is for and there could probably be more things I would like to have changed if I did. For some of the parts I didn't understand I checked The Pattern in Pi's code, thanks.</p>\n\n<p>I have made some style changes along the way, I generally follow the <a href=\"http://www.php-fig.org/\" rel=\"nofollow\">PHP Framework Interop Group's standards</a>.</p>\n\n<p>And now the code:</p>\n\n<pre><code><?php\n\ndefine('I_DONT_KNOW_WHAT_THIS_NUMBER_IS', 5);\n\n// >>> I have made it so that the images are passed in as resources\n// this makes the function more flexible and might stop you from\n// needing to read the images from disk at a later point\n// >>> Hmm, I have also changed the name of this function as it doesn't 'find' so much as 'measure'\n// >>> Ok, so I have added some phpdoc style commenting to this function\n// It is important here and not in the helper functions as the idea behind this function would\n// otherwise seem vague.\n/**\n * This measures the similarity between two images.\n * It does so by sampling the image at certain points (determined by the accuracy\n * setting) and comparing the rgb color values for an almost exact match (See COLOR_COMPARISON_FUZZYNESS). The number of \n * matches per number of samples determines the similarity.\n *\n * @arg $imageA Resource An image to compare, should be an image resource\n * @arg $imageB Resource An image to compare, should be an image resource\n * @arg $accuracy Integer This number gets timesed by 5 for some reason and then becomes the number of samples per a dimension\n *\n * @returns float The ratio between the number of matcher per the number of samples for the two images\n */\nfunction measureSimilarityBetweenImages($imageA, $imageB, $accuracy)\n{\n\n // >>> I don't understand this part at all... If you explain it I will check it out\n // >>> Ok after looking at @The Pattern in Pi's answer I sort of understand,\n // I also couldn't help but use some of his variable names, thanks\n\n // >>> Note that I have changed this comment\n // Get the image size of the first image and assume it is the same as the second\n $imageWidth = imagesx($imageA);\n $imageHeight = imagesy($imageA);\n\n // >>> What was this 5, magic numbers should be constants!\n // >>> I still don't know what density means in this context\n // >>> Ok, I know know what density means, I would call it numberOfSamples\n // density normally means means units per (some other unit)^3\n // and have it be the total number of samples over the image\n // but I still don't know where accuracy and the 5 comes in\n $samplesPerDimension = $accuracy * I_DONT_KNOW_WHAT_THIS_NUMBER_IS;\n\n // >>> I like to use units as variable names \n $xPixelsPerSample = round($imageWidth/$samplesPerDimension);\n $yPixelsPerSample = round($imageHeight/$samplesPerDimension);\n\n // >>> This is not the best way to do this but it should work, a \n // better solution might involve changing the above 'round' function \n // to a 'floor'. Be careful with rounding.\n $totalSamples = floor($xPixelsPerSample * $imageWidth) * floor($yPixels * $imageHeight);\n\n // >>> Again I don't understand this part, these loops look very convoluted\n // >>> After looking at The Pattern in Pi's code, again I sort of understand\n // again I sort of can't help use his code... \n // >>> Actually on second thought, it doesn't look like pointsWidth or\n // pointsHeight is defined anywhere in his revision...\n // >>> EDIT: ok I have fixed this up\n // >>> I have changed this name so it is clearer what it represents\n $matchedSamples = 0;\n // >>> Note how I have inlined these loops\n for ($y = 0; $y < $imageHeight; $y =+ $yPixelsPerSample) {\n for ($x = 0; $x < $imageWidth; $x =+ $xPixelsPerSample) {\n // >>> So I cleaned up this part through the use of functions below\n if (comparePixels(getPixel($imageA, $x, $y), getPixel($imageB, $x, $y))) {\n $matchedSamples++; //Match between points.\n }\n }\n }\n\n // >>> I like to leave ratios alone, it can be converted to a percentage when it needs to be output\n return $matchedSamples/$totalSamples;\n}\n\n// Composing these two functions together\nfunction getPixel($image, $x, $y)\n{\n return imagecolorsforindex($image, imagecolorat($image, $x, $y));\n}\n\n// >>> With compare functions I like to just use $a and $b, this is just a preference of mine\nfunction comparePixels($a, $b)\n{\n // >>> Note the usage of the array and the foreach loop\n foreach (array('red', 'blue', 'green') as $color) {\n if (! compareColors($a[$color], $b[$color])) {\n return false;\n }\n }\n return true;\n}\n\n// >>> Constants are normally together at the top (or in a separate parameters file) but I have put it here for effect\ndefine('COLOR_COMPARISON_FUZZYNESS', 2)\n\n// >>> I changed this functions name, this is largely a matter of preference and consistancy.\n// The pattern I use here seems to be verb then noun, see how it matches all the other functions\n// including your `findSimilarityBetweenImages' function.\nfunction compareColors($a, $b)\n{\n // >>> I have clarified what you are doing here, it shows that the difference between the two values\n // must be less a certain amount, which I have made a constant\n if(abs($a - $b) <= COLOR_COMPARISON_FUZZYNESS)) {\n return true;\n }\n return false;\n}\n\n// >>> So you would call it like this to get the same effect\nmeasureSimilarityBetweenImages(imagecreatefrompng($imagePathA), imagecreatefrompng($imagePathB));\n\n?>\n</code></pre>\n\n<p><strong>Some tips:</strong></p>\n\n<p>Keep in mind magic numbers and subtle naming patterns.</p>\n\n<p>Checkout functional programming (it is not just programing using functions), at least the philosophy/paradigm if not a functional language (such as haskel and clojure). Functional programming is definitely not mutually exclusive to object orientated programming, they both can work together.</p>\n\n<p>Your comments didn't prove very useful to me, important things to comment about is the domain specific things. It would be useful for you to explain how you are finding the similarities and what you define a similarity is, I suspect that is where density comes in.</p>\n\n<p>I don't normally comment on what code is doing, I try to make the code readable enough so that I don't have to, in the very rare cases I can't make it readable I put comments in. There is also a style of coding called literate programming which is the opposite of this. </p>\n\n<p>Function signature comments can be useful as well (what nibra's answer was about). </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-07T15:04:53.930",
"Id": "40088",
"Score": "0",
"body": "@ThePatternInPi has made some suggestions as to what the code does and I'll make some fixes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-07T15:49:10.857",
"Id": "40095",
"Score": "1",
"body": "This code could have been more functional by having the sampling part of the code seperate from the pixel comparison in some kind of `booleanSampleImages($imageA, $imageB, $comparePixels, $pixelsPerSample)` function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-07T16:00:06.473",
"Id": "40099",
"Score": "0",
"body": "Great Explanation!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-03T14:53:31.963",
"Id": "25770",
"ParentId": "25660",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "25770",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T19:56:32.153",
"Id": "25660",
"Score": "4",
"Tags": [
"php",
"image"
],
"Title": "Finding similarities between images"
}
|
25660
|
<p>It took me a lot of poking around and unit testing to get the code to look like it is right now. So I have a XML file which in part looks like this</p>
<pre><code><FunctionKeys>
<Name>F13</Name>
<Name>F14</Name>
<Name>F15</Name>
<Name>F16</Name>
</FunctionKeys>
</code></pre>
<p>and So I want to take that data and put it back into my class.</p>
<p>This is in part what I have</p>
<pre><code> public override void Load(string elementText)
{
var ele = XElement.Parse(elementText);
if (ele.Element("FunctionKeys").HasElements)
{
var funcs = ele.Element("FunctionKeys")
.Descendants("Name")
.Select(x=>x.Value)
.ToList();
foreach (string s in funcs)
{
dliUnit.FunctionKeyList.Add(
(System.Windows.Forms.Keys)System.Enum.Parse(typeof(System.Windows.Forms.Keys),
s));
}
}
}
</code></pre>
<p><strong>Class to save to</strong></p>
<pre><code>public class DLIUnit
{
public List<Keys> FunctionKeyList
{
get;set;
}
//Other Members
}
</code></pre>
<p>Somethign about the way that I parse the string back to the Enum (well the entire process really) doesn't sit well with me. I'm very bad at LINQ but have been trying hard to learn it and use it more and more when I play with XML. Is there a better/cleaner way to parse the FunctionKeys?</p>
<p><strong>EDIT</strong></p>
<p>I forgot to mention that I can change any portion of the code or XML file. Right now this is a new idea and can be changed to make it better.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T20:34:14.063",
"Id": "39739",
"Score": "0",
"body": "Could you use XmlSerializer to do what you are after or would you prefer to stick with this approach?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T20:37:31.067",
"Id": "39740",
"Score": "0",
"body": "@dreza If it is easier. The other data types I have for DLIUnit are all basic: FileInfo, String, List<string>, List<Keys> are it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T20:38:32.307",
"Id": "39741",
"Score": "0",
"body": "@dreza woudl it help if i posted my unit test?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T20:46:16.233",
"Id": "39742",
"Score": "0",
"body": "I don't think you need to post your Tests although nice that you have them. As a side note. Something that really helped my Linq abilities was Resharper. I would recommend that if this is something you are looking to improve in."
}
] |
[
{
"body": "<p>Sticking with the approach you used how about this as an alternative.</p>\n\n<pre><code>public override void Load(string elementText)\n {\n var ele = XElement.Parse(elementText);\n\n var xElement = ele.Element(\"FunctionKeys\");\n if (xElement != null && xElement.HasElements)\n {\n _dliUnit.FunctionKeyList.AddRange(xElement\n .Descendants(\"Name\")\n .Select(x => EnumHelper.GetEnum<Keys>(x.Value))\n );\n }\n }\n</code></pre>\n\n<p>I created a little Enum Extensions class just because I like typing GetEnum:</p>\n\n<pre><code>public static class EnumHelper\n{\n public static T GetEnum<T>(string name)\n {\n if (IsValidEnumFor<T>(name))\n return (T)Enum.Parse(typeof(T), name);\n else\n throw new ArgumentException(typeof(T) + \"does not contain a value member = \" + name);\n }\n\n public static T GetEnum<T>(int number)\n {\n if (Enum.IsDefined(typeof(T), number))\n {\n return (T)Enum.ToObject(typeof(T), number);\n }\n else\n {\n throw new ArgumentException(typeof(T) + \"does not contain a value member = \" + number.ToString());\n }\n }\n\n public static bool IsValidEnumFor<T>(string name)\n {\n return Enum.IsDefined(typeof(T), name);\n }\n}\n</code></pre>\n\n<p><strong>Alternative - XmlSerializer</strong></p>\n\n<p>One alternative I have used in the past to parse Xml into objects is the .NET <a href=\"http://msdn.microsoft.com/en-nz/library/system.xml.serialization.xmlserializer.aspx\" rel=\"nofollow\">XmlSerializer</a>. In your case you might do something like:</p>\n\n<pre><code>StringReader sr = new StringReader(xml);\n\n// Create an XmlSerializer object to perform the deserialization\nXmlSerializer xs = new XmlSerializer(typeof(DLIUnit));\nreturn (DLIUnit)xs.Deserialize(sr);\n</code></pre>\n\n<p>This may not work for you but I would recommend having a look into this class as it is fairly easy to use once you get going. Once I got my head around the basics it helped immensely.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T21:00:31.037",
"Id": "39743",
"Score": "0",
"body": "Brilliant i'll give a go tomorrow"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T20:44:47.057",
"Id": "25662",
"ParentId": "25661",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "25662",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-30T20:24:35.650",
"Id": "25661",
"Score": "2",
"Tags": [
"c#",
"array",
"linq",
"parsing",
"xml"
],
"Title": "XML to Windows.Forms.Keys List"
}
|
25661
|
<p>Can someone help me with the following micro optimization for the F# code for lexicographic permutation?</p>
<p>I have code in C# which runs for 0.8s. As a learning practice, I translated it into F#. However, it becomes 2.9s. Just out of curiosity, I am wondering why my code in F# runs that slow? Are there any improvement can be made to my F# code without changing the algorithm?</p>
<p><strong>C#</strong></p>
<pre><code> static bool ToNextLexicographic(int[] myArray)
{
int pivot = -1;
for (int i = myArray.Length - 1; i > 0; i--)
{
if (myArray[i] > myArray[i - 1])
{
pivot = i - 1;
break;
}
}
if (pivot == -1)
return false;
for (int j = myArray.Length - 1; j > pivot; j--)
{
if (myArray[j] > myArray[pivot])
{
// swap
var tmp = myArray[j];
myArray[j] = myArray[pivot];
myArray[pivot] = tmp;
// reverse
for (int i = pivot + 1, k = myArray.Length - 1; i < k;i++,k-- )
{
var tmp = myArray[i];
myArray[i] = myArray[k];
myArray[k] = tmp;
}
break;
}
}
return true;
}
static IEnumerable<int[]> GetPermutationsLexicographic(int[] myArray)
{
Array.Sort(myArray);
yield return myArray;
while (ToNextLexicographic(myArray))
{
//yield return myArray.ToArray();
yield return myArray;
}
}
</code></pre>
<p><strong>F#</strong> (much readable than C#)</p>
<pre><code>let inline toNextLexicographic (myArray: _[]) =
let rec findPivot i =
if i = 0 then -1
else
if myArray.[i] > myArray.[i-1] then i - 1
else findPivot (i - 1)
let rec findTarget value i =
if (myArray.[i] > value) then i
else findTarget value (i - 1)
let inline swap i j =
let tmp = myArray.[i]
myArray.[i] <- myArray.[j]
myArray.[j] <- tmp
let inline reverse i =
let mutable a = i
let mutable b = myArray.Length - 1
while a < b do
swap a b
a <- a + 1
b <- b - 1
let pivot = findPivot (myArray.Length - 1)
if pivot = -1 then false
else
let target = findTarget myArray.[pivot] (myArray.Length - 1)
swap pivot target
reverse (pivot + 1)
true;
let inline getPermutationsLexicographic myArray = seq {
Array.sortInPlace myArray
yield myArray
while toNextLexicographic myArray do
yield myArray
}
// benchmark
let mutable d = 0
for x in getPermutationsLexicographic([|1..11|]) do
d <- d + 1
d
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T00:35:40.603",
"Id": "39744",
"Score": "0",
"body": "Well, have you tried profiling the code to find out what slows it down?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-08T15:58:54.253",
"Id": "40157",
"Score": "0",
"body": "@svick the profiling info shows difference between x64 and x86, even though I struggled to find anything useful"
}
] |
[
{
"body": "<p>You're not comparing apples to apples. The F# code is generic whereas the C# only works with <code>int</code> arrays. Remove every occurrence of <code>inline</code> and add a type annotation to <code>toNextLexicographic</code>: </p>\n\n<pre><code>let toNextLexicographic (myArray: int[])\n</code></pre>\n\n<p>In my tests, that takes the time from 2.152 to 0.146 seconds.</p>\n\n<p>The reason for the poor performance is <code>inline</code> isn't working. You can see this by decompiling. Most of the time is spent in <code>LanguagePrimitives.HashCompare.GenericGreaterThanIntrinsic</code> as a result. This is much more expensive than <code>op_GreaterThan</code>.</p>\n\n<p>I'm not sure under what conditions <code>inline</code> is ignored, but I can only guess, in this case, it's due to the complexity of your code and the closures.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T15:10:01.427",
"Id": "39772",
"Score": "0",
"body": "I did what you suggested, it still takes 2.2s, not improved at all. Also I updated the C# code in question so it becomes generic. (time spent stays the same)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T15:25:45.710",
"Id": "39776",
"Score": "0",
"body": "Something's amiss. You added the type annotation and it stayed the same? I see a huge difference. After the change to the C#, you're still not comparing the same code. Change the F# to use `CompareTo`. `GenericGreaterThanIntrinsic` is slow. You want to eliminate those calls. Also, are you compiling in Release mode?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T15:42:21.283",
"Id": "39777",
"Score": "0",
"body": "I updated the post so that you can see my changed F#, (it is nothing new but to add `int[]` and remove some `inline`) Since the C# version is 0.8s, I don't think you can get less than that in F#. Your result of 0.146s is suspicious. The reason why I use `inline` at the first place is that I know `GenericGreaterThanIntrinsic` (doesn't implement `IComparable<T>`) is slower than `CompareTo<T>`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T15:54:13.033",
"Id": "39779",
"Score": "0",
"body": "Can you update to include your test code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T16:02:38.750",
"Id": "39781",
"Score": "0",
"body": "Ok, done. Btw it doesn't seem that `inline` was broken. Without `inline` and without type annotation, the program takes 20s."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T16:12:10.920",
"Id": "39782",
"Score": "0",
"body": "Have you decompiled this? It is not being `inline`d."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T17:37:14.893",
"Id": "39794",
"Score": "0",
"body": "Sorry, I should have been more specific. Not every function marked `inline` is actually inlined. Some remain generic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-08T15:56:58.387",
"Id": "40156",
"Score": "0",
"body": "Apologies, I am still not fully convinced. The update code with explicit type annotation takes 1.5s in x64 and 2.3s in x86."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T14:53:46.547",
"Id": "25690",
"ParentId": "25666",
"Score": "3"
}
},
{
"body": "<p>I can now confirm the performance difference is due to <code>Seq / IEnumerable</code></p>\n\n<p>Say, if I remove <code>Seq / IEnumerable</code>, and meausre speed simply use <code>while</code> loop, e.g.</p>\n\n<pre><code>while toNextLexicographic myArray do\n d <- d + 2\n</code></pre>\n\n<p>The speed of C# and F# are now the same, being 0.6s. So I conclude it is the <code>IEnumerable</code> that make a difference. Still I don't get why <code>Seq</code> is slower than <code>IEnumerable</code> here, as they should be identical.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-19T15:05:35.873",
"Id": "27551",
"ParentId": "25666",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27551",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T00:05:52.463",
"Id": "25666",
"Score": "3",
"Tags": [
"c#",
"f#",
"combinatorics",
"comparative-review"
],
"Title": "My implementation of lexicographic permutation in F# is 3x slower than C#"
}
|
25666
|
<p>Recently I have been developing a SASSified version of Dave Gamache's <a href="http://getskeleton.com/" rel="nofollow">Skeleton CSS</a> front-end framework. I have publicly posted the code on <a href="https://github.com/atomicpages/skeleton-sass" rel="nofollow">github</a> as well as a <a href="http://atomicpages.github.io/skeleton-sass" rel="nofollow">live demo</a>. </p>
<p>What I am looking for is constructive feedback on my project as a whole and ways to improve/simplify features. I believe my solution is far more elegant and requires less time trying to figure out what file is where and what to edit. In addition to this, I have recreated a grid generator similar to 960.gs so users can customize their own grids.</p>
<p>Here are some relevant snippets of code and structure:</p>
<p>The main purpose of my SASS, SCSS, and Compass translation of the CSS framework is to better utilize the SASS CSS pre-processor. The project contains:</p>
<ul>
<li><p><strong>Compass</strong> Translation which includes:</p>
<ul>
<li>SASS (indented) syntax</li>
<li>SCSS (CSS) syntax</li>
<li>Utilization of Compass SASS framework to accomplish many tasks</li>
</ul></li>
<li><p><strong>SASS</strong> Translation which includes:</p>
<ul>
<li>SASS (indented) syntax</li>
<li>SCSS (CSS) syntax</li>
<li>Custom mixins in <code>_mixins</code> file to accomplish and automate many tasks</li>
</ul></li>
</ul>
<p>One major feature of my translation is that it comes with a grid creator similar to that of 960.gs where you have a fixed and fluid style grid. Here are some snippets from that grid creator:</p>
<pre><code>// function to turn number to string for selectors
$ones: "one", "two", "three", "four", "five", "six", "seven", "eight", "nine";
$teens: "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen";
$tens: "", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "nintey";
@function numToString($int) {
$int: abs($int); // no nonnegative numbers
$number: "";
@if($int > 100) { // I'm sorry Dave; I can't let you do that.
$number: "No numbers past 100";
}
$temp: $int / 10;
$temp: floor($temp);
@if($int >= 1 and $int <= 100) {
@if($temp < 1) { // it's a one!
$number: nth($ones, $int % 10);
}
@if($temp == 1) { // in the teen range
// in the teen range
@if($int % 10 == 0) {
$number: "ten";
} @else {
$number: nth($teens, $int % 10);
}
}
@if($temp >= 2 and $temp <= 9) { // more than our teens
@if($int % 10 == 0) {
// means it's a number evenly divisible by 10
$number: nth($tens, $int / 10);
} @else {
$number: "#{nth($tens, floor($int / 10))}-#{nth($ones, $int % 10)}";
}
}
@if($temp == 10) { // this is the end...
$number: "one-hundred";
}
} @else {
$number: "Invalid parameter passed. Number must be between 1 and 100."
}
@return $number;
}
</code></pre>
<p>and the mixin:</p>
<pre><code>@mixin grid($width: $baseWidth, $fluid: $isFluid, $colWidth: $baseColWidth, $gutterWidth: $baseGutterWidth, $colCount: $baseColCount) {
@if ( $fluid == true ) {
// and for you math heads... a_n = (100n / $colCount) - 2
// where n is the iteration
@include _fluidGrid($colCount);
} @else {
// and for you math heads... a_n = 40 + ( 60 ( n - 1 ) )
// where 40 = column width
// where 60 is the consistent difference between each column
// where n is the iteration
@include _fixedGrid($width, $colWidth, $gutterWidth, $colCount);
}
}
// "PRIVATE" MIXINS - these are mixins the help separate logic and should never be used outside of the grid mixin
// generate the fluid grid
@mixin _fluidGrid($colCount, $unit: "%") {
// override only for fluid
/* Overrides */
.container {
.column,
.columns {
margin: {
left: 1%;
right: 1%;
}
}
}
/* The Grid */
.container {
@for $i from 1 through $colCount {
@if ( $i == 1 ) {
.#{numToString($i)}.column,
.#{numToString($i)}.columns { width: ( ( 100 * $i ) / $colCount ) - 2#{$unit}; }
} @else {
.#{numToString($i)}.columns { width: ( ( 100 * $i ) / $colCount ) - 2#{$unit}; }
}
}
/* The Offsets */
@include _offset($unit, $colCount, false);
}
}
// generate the fixed grid
@mixin _fixedGrid($width, $colWidth, $gutterWidth, $colCount) {
@if($gutterWidth != $baseGutterWidth) {
/* Gutter Overrides */
.container {
.column,
.columns {
margin: {
left: $gutterWidth / 2;
right: $gutterWidth / 2;
};
}
}
}
/* The Grid */
.container {
@for $i from 1 through $colCount {
@if ( $i == 1 ) {
.#{numToString($i)}.column,
.#{numToString($i)}.columns { width: $colWidth; }
} @else {
.#{numToString($i)}.columns { width: $colWidth + ( ( $colWidth + $gutterWidth ) * ( $i - 1 ) ); }
}
}
.one-third.column { width: ( $width / 3 ) - 20}
.two-thirds.column { width: ( ( $width * 2 ) / 3 ) - 20 }
/* The Offsets */
@include _offset("px", $colCount, $colWidth);
}
}
// generate the offset
// Note: although $colWidth is optional, it is REQUIRED by the fixed grid
@mixin _offset($unit, $colCount, $colWidth) {
@if ( $unit == "%" ) {
@for $i from 1 through ( $colCount - 1 ) {
.offset-by-#{numToString($i)} { padding-left: ( ( 100 * $i ) / $colCount ) * $i#{$unit}; }
}
} @else {
@for $i from 1 through ( $colCount - 1 ) {
.offset-by-#{numToString($i)} { padding-left: ( $colWidth + 20 ) * $i; }
}
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T00:12:44.760",
"Id": "25669",
"Score": "4",
"Tags": [
"css",
"sass"
],
"Title": "SaSSified version of Skeleton CSS"
}
|
25669
|
<p>Here is my shopping cart class! I want it to be perfect and never to have to implement it.</p>
<p>What improvements would you do?</p>
<h2>New : IComparable</h2>
<pre><code>interface IComparable
{
public function equals($object);
}
</code></pre>
<h2>New : ICartItem</h2>
<pre><code>interface ICartItem extends IComparable
{
public function setQuantity($quantity);
public function getQuantity();
}
</code></pre>
<h2>New : ICart</h2>
<pre><code>interface ICart
{
public function add(ICartItem $item);
public function remove(ICartItem $item);
public function getQuantity(ICartItem $item);
public function setQuantity(ICartItem $item, $quantity);
public function isEmpty();
public function getItems();
public function clear();
}
</code></pre>
<h2>New : Cart</h2>
<pre><code>class SessionCart implements ICart
{
const IDENTIFIER = '_CART_';
protected $items;
public function __construct(&$container = null)
{
if (is_null($container)) {
if (session_id() == '') {
session_start();
}
if (!isset($_SESSION[self::IDENTIFIER])) {
$_SESSION[self::IDENTIFIER] = array();
}
$container = & $_SESSION[self::IDENTIFIER];
}
$this->items = & $container;
}
public function add(ICartItem $item)
{
$index = $this->getIndexOfItem($item);
if ($index == -1) {
$this->items[] = $item;
} else {
$item = $this->items[$index];
$item->setQuantity($item->getQuantity() + 1);
}
return $item->getQuantity();
}
public function remove(ICartItem $item)
{
$index = $this->getIndexOfItem($item);
if ($index == -1) {
throw new Exception('The item isn\'t inside the cart.');
}
$item = $this->items[$index];
$quantity = $item->getQuantity() - 1;
if ($quantity > 0) {
$item->setQuantity($quantity);
} else {
unset($this->items[$index]);
}
return $quantity;
}
public function getQuantity(ICartItem $item)
{
$index = $this->getIndexOfItem($item);
if ($index == -1) {
return 0;
} else {
return $this->items[$index]->getQuantity();
}
}
public function setQuantity(ICartItem $item, $quantity)
{
if (($quantity = (int)$quantity) < 1) {
throw new Exception('A positive quantity is required.');
}
$index = $this->getIndexOfItem($item);
if ($index == -1) {
$item->setQuantity($quantity);
$this->items[] = $item;
} else {
$item = $this->items[$index];
$item->setQuantity($quantity);
}
return $item->getQuantity();
}
public function isEmpty()
{
return empty($this->items);
}
public function getItems()
{
return $this->items;
}
public function clear()
{
$this->items = array();
}
private function getIndexOfItem(ICartItem $item)
{
foreach ($this->items as $key => $value) {
if ($item->equals($value)) {
return $key;
}
}
return -1;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I would reccomend to use <code>if(session_id() == ''){ //do }</code> instead of <code>if(!isset($_SESSION)) { // do}</code> because $_SESSION can be set while the session is closed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T13:52:07.753",
"Id": "25684",
"ParentId": "25671",
"Score": "3"
}
},
{
"body": "<h2>General</h2>\n\n<p>You should reconsider the naming of some methods. For example,</p>\n\n<pre><code>interface IComparable\n{\n public function equals($obj);\n}\n</code></pre>\n\n<p>is more clear about what it really does (comments are omitted to save space; of course, proper DocBlock comments should always be included with your code). This way, you can easily add other methods like <code>isLessThan</code>, <code>isGreaterOrEqual</code>, and so on. A method named <code>compareTo</code> as in</p>\n\n<pre><code>$a->compareTo($b)\n</code></pre>\n\n<p>I'd expect to be a valid callback for <code>usort</code>, thus returning -1 on <code>$a < $b</code>, 0 on <code>$a == $b</code>, or 1 on <code>$a > $b</code>.</p>\n\n<h2>Cart</h2>\n\n<p>One day, you might want to store your cart items in a database, so using <code>$_SESSION</code> directly is not optimal. I'd define a cart interface:</p>\n\n<pre><code>interface ICart\n{\n public function add(IComparable $obj);\n public function remove(IComparable $obj);\n public function getQuantity(IComparable $obj);\n public function setQuantity(IComparable $obj, $qty);\n public function isEmpty();\n public function getAll();\n public function clear();\n}\n\nclass Cart implements ICart\n{\n const IDENTIFIER = '_CART_';\n protected $container;\n\n public function __construct(&$container = null)\n {\n if (is_null($container)) {\n if (session_id() == '') {\n session_start();\n }\n if (!isset($_SESSION[self::IDENTIFIER])) {\n $_SESSION[self::IDENTIFIER] = array();\n }\n $container = &$_SESSION[self::IDENTIFIER];\n }\n $this->container = &$container;\n }\n}\n</code></pre>\n\n<p>With this approach, you can always build other cart implementations, like a database-aware one. The <code>Cart</code> class can be provided with an array, which will be used to store the data. If you want, you can pass in the <code>$_SESSION</code> superglobal directly, or use any other array. If omitted, a kind of namespace within the session variables (<code>self::IDENTIFIER</code>, <code>'_CART_'</code>) is used to store the data.</p>\n\n<p>Since the session - if needed - is started within the constructor, you can rely on its existence in the subsequent methods. BTW: the existence of the <code>$_SESSION</code> array does not guarantee that a session has been started! Use <code>session_id()</code> to check that instead.)</p>\n\n<h3>Internal Data Structure</h3>\n\n<p>Since your data array can be accessed from outside the cart, the current data structure is prone to get out of sync. It is more robust to swap the indices. Then you can replace <code>getIndex()</code> with <code>getEntry()</code>, which makes the handling much easier.</p>\n\n<pre><code>class Cart implements ICart\n{\n ... // see above\n\n public function add(IComparable $obj)\n {\n $entry = &$this->getEntry($obj);\n $entry['quantity']++;\n\n return $entry['quantity'];\n }\n\n public function remove(IComparable $obj)\n {\n $entry = &$this->getEntry($obj);\n $entry['quantity'] = max(0, --$entry['quantity']);\n\n return $entry['quantity'];\n }\n\n public function getQuantity(IComparable $obj)\n {\n $entry = &$this->getEntry($obj);\n return $entry['quantity'];\n }\n\n public function setQuantity(IComparable $obj, $qty)\n {\n $entry = &$this->getEntry($obj);\n if ($entry['quantity'] > 0) {\n $entry['quantity'] = (int) $qty;\n }\n return $entry['quantity'];\n }\n\n public function isEmpty()\n {\n $total = 0;\n foreach ($this->container as $entry) {\n $total += $entry['quantity'];\n }\n return $total <= 0;\n }\n\n public function getAll()\n {\n $cart = array();\n foreach ($this->container as $entry) {\n if ($entry['quantity'] > 0) {\n $cart[] = $entry;\n }\n }\n return $cart;\n }\n\n public function clear()\n {\n $this->container = array();\n }\n\n private function &getEntry(IComparable $obj)\n {\n foreach ($this->container as &$entry) {\n if ($obj->equals($entry['item'])) {\n return $entry;\n }\n }\n $entry = array(\n 'item' => $obj,\n 'quantity' => 0\n );\n $this->container[] = &$entry;\n return $entry;\n }\n}\n</code></pre>\n\n<p>As you can see, all methods (excl. <code>isEmpty()</code>) become much simpler.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T16:13:31.677",
"Id": "39783",
"Score": "0",
"body": "Only one question : The shopping cart is it a singleton? If so, the variable `container` should it not be static?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T16:20:58.243",
"Id": "39784",
"Score": "2",
"body": "There is no reason for the cart to be a singleton (singleton is an Antipattern). On the other hand, the `container` property holds a *reference* to the cart data, so any cart provided with the same storage container will have identical data."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T16:34:52.077",
"Id": "39786",
"Score": "0",
"body": "For example, should I call the cart this way: `(new Cart())->clear()`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T17:15:39.343",
"Id": "39791",
"Score": "0",
"body": "Why you don't use `array_sum()` for the isEmpty() function? And I don't understand `$this->container[] = &$entry;`. Why you ecrase the table?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T23:56:28.543",
"Id": "39825",
"Score": "1",
"body": "To use the cart, you instantiate it: `$myCart = new Cart;`. Then you can use it's methods: `$myCart->clear();`. Static methods are avoided, because they hamper testing. -- array_sum is not used, because the values are not in the same array (each item is again an array within the main array)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T23:57:43.033",
"Id": "39827",
"Score": "0",
"body": "`$this->container[] = &$entry;` does not erase the array, but adds a reference to the new entry."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-02T00:08:38.087",
"Id": "39830",
"Score": "0",
"body": "Sorry to insist, but I don't understand. Can you explain to me ... Why don't you have to specify the index of the array."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-02T00:28:50.450",
"Id": "39831",
"Score": "1",
"body": "Read this from the PHP manual: php.net/manual/en/language.types.array.php#language.types.array.syntax.modifying. It'll tell you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-02T13:42:34.653",
"Id": "39873",
"Score": "0",
"body": "I do not know why, but I can not increment the quantity of an item. If I follow step by step the execution, I realize that this is the code that does not work: `$entry['quantity']++;` and `$entry['quantity']--;`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-02T13:52:13.973",
"Id": "39874",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/8579/discussion-between-nibra-and-hugo-lapointe-di-giacomo)"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T14:52:30.047",
"Id": "25689",
"ParentId": "25671",
"Score": "6"
}
},
{
"body": "<h2>Based on @nibra's solution</h2>\n\n<ul>\n<li>Same <code>ICompareable</code> interface.</li>\n<li><p>Same <code>ICart</code> interface but derived from <code>IteratorAggregate</code>.</p>\n\n<pre><code>interface ICart extends IteratorAggregate {}\n</code></pre></li>\n</ul>\n\n<h2><code>CartItem</code> class</h2>\n\n<ul>\n<li>Storing an item.</li>\n<li>Storing the quantity if the item.</li>\n</ul>\n\n<p></p>\n\n<pre><code>final class CartItem {\n\n private $_item;\n private $_quantity;\n\n public function __construct(IComparable $item, $quantity = 1) {\n $quantity = (int)$quantity;\n if ($quantity < 1) {\n throw new Exception(\"Invalid quantity\");\n }\n\n $this->_item = $item;\n $this->_quantity = $quantity;\n }\n\n public function GetQuantity() {\n return $this->_quantity;\n }\n\n public function GetItem() {\n return $this->_item;\n }\n}\n</code></pre>\n\n<h2>Changed internal behavior</h2>\n\n<ul>\n<li><code>Cart</code> isn't the best name for this kind of implementation because it's not reflecting anything about the implementation, so call it <code>SessionCart</code>.</li>\n<li><code>session_start();</code> doesn't belong here because starting the session isn't the responsibility of this class; if we wan't to ensure that the session has been started we need another abstraction above the <code>$_SESSION</code> array.</li>\n<li><code>$_SESSION</code> as storage backend implies some kind of singleton behavior so we need to handle multiple instance problem with the <code>SessionCart</code> class but this also not the responsibility of <code>SessionCart</code> class because it depends on the framework.</li>\n<li><code>&</code> operator is bad because it can mess up our code and it really hurts performance; in PHP 5 and above we never really need to use it, see <code>CartItem</code> class.</li>\n<li>quantity: 0; why would we store items with the quantity of 0? If the quantity is 0 then we don't have any item of that type so remove it.</li>\n</ul>\n\n<p></p>\n\n<pre><code>class SessionCart implements ICart {\n protected $container;\n\n public function __construct($storageIndex = \"_CART_\") {\n if (isset($_SESSION[$storageIndex])) {\n throw new Exception($storageIndex . \" exists in SESSION array\");\n }\n\n $_SESSION[$storageIndex] = $this;\n }\n\n public function add(IComparable $obj, $quantity) {\n $quantity = (int)$quantity;\n\n if ($quantity < 1) {\n //throw exception?\n return 0;\n }\n\n $index = $this->getIndexOfEntry($obj, $quantity);\n\n if ($index == -1) {\n $this->container[] = new CartItem($obj);\n return 1;\n } \n\n $this->container[$index] = new CartItem($obj, $this->container[$index]->GetQuantity() + $quantity);\n return $this->container[$index]->GetQuantity();\n }\n\n public function remove(IComparable $obj) {\n $index = $this->getIndexOfEntry($obj);\n unset($this->container[$index]);\n }\n\n public function getQuantity(IComparable $obj) {\n $index = $this->getIndexOfEntry($obj);\n return $index == -1 ? 0 : $this->container[$index]->GetQuantity();\n }\n\n public function setQuantity(IComparable $obj, $qty) {\n $qty = (int)$qty;\n\n if ($qty < 1) {\n $this->remove($obj);\n return;\n }\n\n $index = $this->getIndexOfEntry($obj);\n\n if ($index == -1) {\n $this->container[] = new CartItem($obj, $qty);\n } else {\n $this->container[$index] = new CartItem($obj, $qty);\n }\n }\n\n public function isEmpty() {\n return empty($this->container);\n }\n\n public function getAll() {\n return new SplFixedArray($this->container);\n }\n\n public function clear() {\n $this->container = array();\n }\n\n private function getIndexOfEntry(IComparable $obj) {\n foreach ($this->container as $key => $entry) {\n if ($obj->equals($entry->GetItem())) {\n return $key;\n }\n }\n\n return -1;\n }\n\n public function getIterator() {\n return new ArrayIterator($this->container);\n }\n\n}\n</code></pre>\n\n<h2>Problem</h2>\n\n<p>The code above still depends on <code>$_SESSION</code> array which is bad (hard dependency on a global variable is bad and global variables are always bad) because anyone can modify it's content. I have mentioned another abstraction above the <code>$_SESSION</code> array in the previous section and I think it's a must have to do scenario if we want a perfect implementation of a session based cart.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-02T13:54:59.650",
"Id": "39875",
"Score": "0",
"body": "I like your way of thinking. Would it be a good idea to define the class CartItem inside SessionCart? According, it is the only class that will use it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-02T15:25:33.940",
"Id": "39880",
"Score": "0",
"body": "Why you return the index rather than the entry!?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-02T16:17:32.930",
"Id": "39884",
"Score": "1",
"body": "Becouse the entry (CartItem) is immutable therefore you cannot change the item or the quantity inside it. Yes we can create a class which isn't immutable and we can return the entry it self but then for example the delete would be a little more complicated but yes we can create one method to return an entry and one method to return the index of an entry (IComparable) it's up to you."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-02T07:00:43.173",
"Id": "25724",
"ParentId": "25671",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "25689",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T01:10:45.107",
"Id": "25671",
"Score": "4",
"Tags": [
"php",
"e-commerce"
],
"Title": "My perfect shopping cart class"
}
|
25671
|
<p>There is a lib code, trying to parse an Element Tree object. If exception happens, it either returns an empty dict of dict or a partially constructed object of such type. In this case, caller needs to parse the results to see if parsing is correctly handled or not. Or in other words, the returned dict is not deterministic. How to solve this issue? Or if this is an issue?</p>
<pre><code>def parse_ET(self, ETObj):
if ETObj == None: return None
dict_of_dict = collections.defaultdict(dict)
try:
for doc in ETObj.iter("result"):
id = doc.attrib.get("id")
for elem in doc.iter("attrib"):
dict_of_dict[id].setdefault(elem.attrib.get("name"), elem.text)
except Exception, ex:
logging.exception("%s:%s" % (self.__class__, str(ex)))
finally:
return dict_of_docs
</code></pre>
|
[] |
[
{
"body": "<pre><code>def parse_ET(self, ETObj):\n</code></pre>\n\n<p>Python style guide recommends lowercase_with_underscores for both function and parameter names</p>\n\n<pre><code> if ETObj == None: return None\n</code></pre>\n\n<p>Use <code>is None</code> to check for None. However, consider whether you really want to support None as a parameter. Why would someone pass None to this function? Do they really want a None in return?</p>\n\n<pre><code> dict_of_dict = collections.defaultdict(dict)\n</code></pre>\n\n<p>Avoid names that describe the datastructure. Choose names that describe what you are putting in it.</p>\n\n<pre><code> try:\n for doc in ETObj.iter(\"result\"):\n id = doc.attrib.get(\"id\")\n for elem in doc.iter(\"attrib\"):\n dict_of_dict[id].setdefault(elem.attrib.get(\"name\"), elem.text)\n</code></pre>\n\n<p>Can there be duplicate \"id\" and \"name\"? If not you don't need to use defaultdict or setdefault</p>\n\n<pre><code> except Exception, ex:\n</code></pre>\n\n<p>You should almost never catch generic exceptions. Only catch the actual exceptions you want. </p>\n\n<pre><code> logging.exception(\"%s:%s\" % (self.__class__, str(ex)))\n</code></pre>\n\n<p>Don't log errors and try to continue on as if nothing has happened. If your function fails, it should raise an exception. In this case, you probably shouldn't even catch the exception. </p>\n\n<pre><code> finally:\n return dict_of_docs\n</code></pre>\n\n<p><code>finally</code> is for cleanup tasks. Under no circumstances should you putting a return in it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T18:04:25.137",
"Id": "39796",
"Score": "0",
"body": "Thanks Winston. If I don't want to catch the exception, the best way is to remove try...except? or just raise?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T18:04:25.443",
"Id": "39797",
"Score": "0",
"body": "What's the best way to force argument not None? <br>>>> def func(a):\n... print a"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T18:14:14.200",
"Id": "39798",
"Score": "0",
"body": "@user24622, if the caller caused the error, then you should raise a new error which tells the caller what they did wrong. If its a bug in your code, just don't catch it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T18:15:08.720",
"Id": "39799",
"Score": "0",
"body": "@user24622, as for forcing not None, don't bother. You'll get an fairly obvious error in any case, so you don't gain anything by checking. You can't assume that its safe to pass None into things, and so you don't need to let your callers assume that."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T14:09:42.063",
"Id": "25686",
"ParentId": "25672",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T01:14:45.523",
"Id": "25672",
"Score": "1",
"Tags": [
"python",
"exception"
],
"Title": "How to handle returned value if an exception happens in a library code"
}
|
25672
|
<pre><code>private static List<ConstrDirectedEdge> kruskalConstruct(ConstructionDigraph CG) {
int current = CG.srcVertexIndex();
boolean visited[] = new boolean[CG.V()];
visited[current] = true;
UF uf = new UF(CG.V());
List<ConstrDirectedEdge> feasibleNeighbours = new ArrayList<ConstrDirectedEdge>();
List<ConstrDirectedEdge> solution = new ArrayList<ConstrDirectedEdge>();
do {
/* clear neighbours from prev iteration */
feasibleNeighbours.clear();
/* build feasible neighbour list */
for (ConstrDirectedEdge directedEdge : CG.adj(current)) {
int v = CG.getVertex(directedEdge.to()).getSource();
int w = CG.getVertex(directedEdge.to()).getDestination();
if (!visited[directedEdge.to()] && !uf.connected(v, w)) {
feasibleNeighbours.add(directedEdge);
}
}
//TODO: code smell
if (feasibleNeighbours.isEmpty()) {
break;
}
/* calculate the probability for each neighbour */
double R = calculateR(feasibleNeighbours);
System.out.println("R for source is : " + R);
for (ConstrDirectedEdge feasibleneighbour : feasibleNeighbours) {
feasibleneighbour.calcProbability(R, alpha, beta);
}
/* pick a neighbour */
ConstrDirectedEdge pickedUp = choiceEdgeAtRandom(feasibleNeighbours);
visited[pickedUp.to()] = true;
current = pickedUp.to();
solution.add(pickedUp);
uf.union(CG.getVertex(current).getSource(), CG.getVertex(current).getDestination());
} while (!feasibleNeighbours.isEmpty());
return solution;
}
</code></pre>
<p>I want to eliminate the code smell that is the break in the middle of the loop. As can be seen I have chosen to use a <code>do {} while()</code> in order to do the initialization with the initial node being <code>CG.srcVertexIndex()</code>. What I was thinking about is make the following code:</p>
<pre><code> for (ConstrDirectedEdge directedEdge : CG.adj(current)) {
int v = CG.getVertex(directedEdge.to()).getSource();
int w = CG.getVertex(directedEdge.to()).getDestination();
if (!visited[directedEdge.to()] && !uf.connected(v, w)) {
feasibleNeighbours.add(directedEdge);
}
}
</code></pre>
<p>into a separate function that will be returning a <code>List<ConstrDirectedEdge></code> and then the loop can turn into:</p>
<pre><code>while(!(feasibleNeighbours = getFeasibleNeighbours(CG, visited, uf)).isEmpty()) {
/* calculate the probability for each neighbour */
/* pick a neighbour */
}
</code></pre>
<p>But then I will have to pass <code>visited</code> and <code>uf</code> as parameter which in fact are going to be manipulated by <code>getFeasibleNeighbours</code> functions - in essence I will be using input parameters to store output state which is not a good idea.</p>
<p>Finally I could just make <code>visited</code> and <code>uf</code> static private vars and just reinitialize them when needed and use them directly, but again this seems kind of wrong.</p>
<p>The code is working fine, however I'd like to hear opinions on how this can be made more readable.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T13:17:37.520",
"Id": "39767",
"Score": "0",
"body": "Why would getFeasibleNeighbours modify visited and uf?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T17:25:45.523",
"Id": "39792",
"Score": "0",
"body": "Because in picking the feasible neighbor it will have to accordingly update the state variables - visited and UF, and at the same time those variable need to persist across executions of the loop"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T17:30:01.117",
"Id": "39793",
"Score": "0",
"body": "But getFeasibleNeighbors doesn't pick the neighbour. It just returns a list of them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T18:18:43.103",
"Id": "39800",
"Score": "0",
"body": "Yes, but in order to get the list it needs to follow certain rules such as not creating loop in a graph (the union-find portion) and also it shouldn't consider already visited nodes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T18:22:47.627",
"Id": "39801",
"Score": "0",
"body": "Yes it checks the visited status, but it doesn't change the visited status does it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-02T11:20:11.673",
"Id": "39865",
"Score": "0",
"body": "Oops, you are completely correct. My brain is fried :)"
}
] |
[
{
"body": "<p>If <code>visited</code> and <code>uf</code> are so tightly coupled with the feasibleNeighbor-calculation, maybe you should have something like a <code>FeasibleNeighborCalculator</code> class which is holding all of this stuff, and which you can ask for the next neighbor list?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T14:42:26.843",
"Id": "25688",
"ParentId": "25673",
"Score": "1"
}
},
{
"body": "<p>Your proposed getFeasibleNeighbours doesn't modify the two parameters. The visited array isn't modified at all. The <code>cf</code> is modified by the union-find process, but that's really more of a caching then a modification. So there isn't any concerns about the parameters of getFeasibleNeighbors. </p>\n\n<pre><code>} while (!feasibleNeighbours.isEmpty());\n</code></pre>\n\n<p>There doesn't seem to be any point in checking this here. It can't possibly have changed since you checked it in the middle of the loop.</p>\n\n<pre><code>while(!(feasibleNeighbours = getFeasibleNeighbours(CG, visited, uf)).isEmpty()) {\n</code></pre>\n\n<p>You can do something like this, but I find it rather ugly. </p>\n\n<p>In the general case of break-in-the-middle loops you have something like:</p>\n\n<pre><code>get_stuff_ready();\nwhile(1)\n{\n do_stuff_before();\n if( !some_test() )\n break;\n do_stuff_after();\n}\n</code></pre>\n\n<p>This equivalent to:</p>\n\n<pre><code>get_stuff_ready();\ndo_stuff_before();\nwhile( some_test() )\n{\n do_stuff_after();\n do_stuff_before(); \n}\n</code></pre>\n\n<p>This does repeat <code>do_stuff_before()</code> twice. However, you can often combine <code>get_stuff_ready()</code> and <code>do_stuff_before()</code>. </p>\n\n<p>So you could something like:</p>\n\n<pre><code>private static List<ConstrDirectedEdge> kruskalConstruct(ConstructionDigraph CG) {\n\n int current = CG.srcVertexIndex();\n boolean visited[] = new boolean[CG.V()];\n visited[current] = true;\n UF uf = new UF(CG.V());\n List<ConstrDirectedEdge> solution = new ArrayList<ConstrDirectedEdge>();\n List<ConstrDirectedEdge> feasibleNeighbours = getFeasibleNeighbors(CG, current, uf);\n\n while( !feasibleNeighbours.isEmpty() )\n {\n\n ConstrDirectedEdge pickedUp = pickNeighbour(feasibleNeighbours);\n current = pickedUp.to();\n\n visited[current] = true;\n uf.union(CG.getVertex(current).getSource(), CG.getVertex(current).getDestination());\n solution.add(pickedUp);\n\n feasibleNeighbours = getFeasibleNeighbors(CG, current, uf);\n }\n\n return solution;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-02T14:38:48.817",
"Id": "39878",
"Score": "0",
"body": "+1 for everything after \"So you could something like\", and encapsulating via `getFeasableNeighbors()`. The big clue to putting `while` up front is that the mid-loop `break` and `while` condition look for the same thing."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-02T13:57:46.293",
"Id": "25737",
"ParentId": "25673",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T01:36:48.380",
"Id": "25673",
"Score": "7",
"Tags": [
"java",
"graph"
],
"Title": "Simplifying finding neighbors in graph"
}
|
25673
|
<p>I am working on my own PHP MVCframework. Now I want to know where to get and specify my entities.</p>
<p>For example, should I do this:</p>
<pre><code>class User_Model extends Model {
private $name;
public getName() {}
public setName($var) {}
public getAllUsers() {}
public getUser() {}
public saveUser(User_Model $user) {}
}
</code></pre>
<p>or this:</p>
<pre><code>class User_Model extends Model {
public getAllUsers() {}
public getUser() {}
public saveUser(Entity $user) {}
}
class User extends Entity {
private $name;
public getName() {}
public setName($var) {}
}
</code></pre>
<p>My favorit is the second example. The model is like a repository. But what's your opinion?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-05T17:36:03.190",
"Id": "40000",
"Score": "0",
"body": "The type hinting in saveUser should be User not Entity. I like the second example more."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-08T10:19:57.127",
"Id": "40136",
"Score": "0",
"body": "To me this seems like a relatively superficial question amongst a sea of questions related to building a MVC framework, one that could even be open to your coding preference while building a site within your MVC."
}
] |
[
{
"body": "<p>Model and Entity mean very similar things to me, an Entity being something like an instance of a Model.</p>\n\n<p>What might be of use to you is to rename the Model class in the second example into a Collection class (Repository even). You would retrieve Entities from a Collection and save them back when they are done. This may have some advantages depending on the rest of your architecture and to me this looks better in terms of a separation of roles. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-07T16:33:32.360",
"Id": "25911",
"ParentId": "25676",
"Score": "0"
}
},
{
"body": "<p>The first code snippet is an example of <a href=\"http://www.martinfowler.com/eaaCatalog/activeRecord.html\" rel=\"nofollow\">Active Record</a>, which, I believe, violates the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">Single Responsibility Principle</a> by mixing the <code>Domain</code> logic with the <code>Persistence</code> logic. The second code snippet is thus better in that it separates the responsibilities.</p>\n\n<p>The naming of classes is somewhat ambiguous and inconsistent with the commonly used terminology. The aforementioned responsibilities would often go into two separate layers (namespaces) called <code>Domain</code> layer (sometimes <code>Model</code>, <code>Entity</code>, etc) and <code>DataAccess</code> layer (sometimes <code>Repository</code>, <code>Mapper</code>, <code>Database</code>, <code>Dal</code>, etc). The <code>Domain</code> layer contains <code>Domain</code> objects, like <code>User</code> for instance. The <code>Domain</code> objects may extend a base class often called <code>[Abstract]Model</code> or <code>[Abstract]Entity</code>. The <code>DataAccess</code> layer may contain <a href=\"http://martinfowler.com/eaaCatalog/dataMapper.html\" rel=\"nofollow\"><code>DataMapper</code></a>, <a href=\"http://martinfowler.com/eaaCatalog/repository.html\" rel=\"nofollow\"><code>Repository</code></a>, <a href=\"http://en.wikipedia.org/wiki/Data_access_object\" rel=\"nofollow\"><code>Dao</code></a>, <a href=\"http://martinfowler.com/eaaCatalog/tableDataGateway.html\" rel=\"nofollow\"><code>TableDataGateway</code></a> or <a href=\"http://martinfowler.com/eaaCatalog/rowDataGateway.html\" rel=\"nofollow\"><code>RowDataGateway</code></a> classes depending on which strategy (Design Pattern) you choose for persisting the <code>Domain</code> objects.</p>\n\n<p>So, eventually you might end up with something like the following.</p>\n\n<p><strong>Package structure</strong></p>\n\n<pre><code>SomeModule/\n Domain/\n Model/\n User\n Service/\n SignUpService\n DataAccess/\n UserDao\n</code></pre>\n\n<p><strong>Classes</strong></p>\n\n<p>Domain object</p>\n\n<pre><code>namespace SomeModule\\Domain\\Model;\n\nclass User\n{\n private $name;\n public function setName($name) {}\n public function getName() {}\n}\n</code></pre>\n\n<p>Data Access object</p>\n\n<pre><code>namespace SomeModule\\DataAccess;\n\nclass UserDao\n{\n public function findOneById($id) {}\n}\n</code></pre>\n\n<p><br />\nI would also suggest that you look into some popular MVC frameworks (<a href=\"http://framework.zend.com/\" rel=\"nofollow\">Zend Framework 2</a>, <a href=\"http://symfony.com/\" rel=\"nofollow\">Symfony 2</a>) to get comfortable and confident with the concepts.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-07T16:43:17.143",
"Id": "25912",
"ParentId": "25676",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "25912",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T09:24:09.280",
"Id": "25676",
"Score": "5",
"Tags": [
"php",
"mvc",
"comparative-review"
],
"Title": "Defining entries"
}
|
25676
|
<p>Calling code and attempt at building session variables:</p>
<pre><code>DataTable dtServerVars = clCommonFunctions.TryAutoLogin("europe\\MrTest");
Session["CablingUserID"]= dtServerVars.Rows[0]["CablingUserID"].ToString();
Session["CablingUseremail"] = dtServerVars.Rows[0]["CablingUseremail"].ToString();
Session["CablingLogin"] = dtServerVars.Rows[0]["CablingLogin"].ToString();
Session["CablingPassword"] = dtServerVars.Rows[0]["CablingPassword"].ToString();
Session["CablingPersonnel"] = dtServerVars.Rows[0]["CablingPersonnel"].ToString();
Session["CablingSurname"] = dtServerVars.Rows[0]["CablingSurname"].ToString();
Session["CablingFirstName"] = dtServerVars.Rows[0]["CablingFirstName"].ToString();
Session["CablingSuperUser"] = dtServerVars.Rows[0]["CablingSuperUser"].ToString();
Session["CablingDateAdded"] = dtServerVars.Rows[0]["CablingDateAdded"].ToString();
Session["CablingContact"] = dtServerVars.Rows[0]["CablingContact"].ToString();
Session["CablingApprovalAuthority"] = dtServerVars.Rows[0]["CablingApprovalAuthority"].ToString();
Session["CablingAdminUser"] = dtServerVars.Rows[0]["CablingAdminUser"].ToString();
Session["SharedInfoID"] = dtServerVars.Rows[0]["SharedInfoID"].ToString();
Session["SharedInfousername"] = dtServerVars.Rows[0]["SharedInfousername"].ToString();
Session["SharedInfopassword"] = dtServerVars.Rows[0]["SharedInfopassword"].ToString();
Session["SharedInfoname"] = dtServerVars.Rows[0]["SharedInfoname"].ToString();
Session["SharedInfoemail"] = dtServerVars.Rows[0]["SharedInfoemail"].ToString();
Session["SharedInfoICLlocation"] = dtServerVars.Rows[0]["SharedInfoID"].ToString();
Session["SharedInfoPhone"] = dtServerVars.Rows[0]["SharedInfoPhone"].ToString();
Session["SharedInfoSecLevel"] = dtServerVars.Rows[0]["SharedInfoSecLevel"].ToString();
Session["IMSUserID"] = dtServerVars.Rows[0]["IMSUserID"].ToString();
Session["IMSUserName"] = dtServerVars.Rows[0]["IMSUserName"].ToString();
Session["IMSIsAnonymous"] = dtServerVars.Rows[0]["IMSIsAnonymous"].ToString();
Session["IMSLastActivityDate"] = dtServerVars.Rows[0]["IMSLastActivityDate"].ToString();
Session["loggedin"] = "unknown";
</code></pre>
<p>Code being called:</p>
<pre><code>public static DataTable TryAutoLogin(string strREMOTE_USER)
{
SqlConnection siConnection = new SqlConnection();
siConnection.ConnectionString = Databases.getDbConnectionString("csSharedInfo");
siConnection.Open();
SqlCommand seCmd = new SqlCommand("GetSignOnDetails", siConnection);
seCmd.CommandType = CommandType.StoredProcedure;
seCmd.Parameters.Add(new SqlParameter("@DomainAccount", SqlDbType.NVarChar, 300));
seCmd.Parameters["@DomainAccount"].Value = strREMOTE_USER;
seCmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter sda = new SqlDataAdapter();
seCmd.Connection = siConnection;
sda.SelectCommand = seCmd;
DataTable dtServerVars = new DataTable();
sda.Fill(dtServerVars);
siConnection.Close();
if (dtServerVars != null)
{
if (dtServerVars.Rows.Count > 0)
{
return dtServerVars;
}
}
return null;
}
</code></pre>
|
[] |
[
{
"body": "<p>First your TryAutoLogin:</p>\n\n<ul>\n<li>A <code>SqlConnection</code> is <code>IDisposable</code>. Use it in combination with <code>using</code>.</li>\n<li>You have some duplicate lines of code, like <code>seCmd.CommandType = CommandType.StoredProcedure;</code>.</li>\n<li><code>dtServerVars</code> can never be null.</li>\n<li>You do not have to open the connection, <code>SqlDataAdapter</code> will do that for you.</li>\n<li>Since you are using only ONE datarow, just return one datarow.</li>\n</ul>\n\n<p>Resulting in:</p>\n\n<pre><code> public static DataRow TryAutoLogin(string strREMOTE_USER)\n {\n using(SqlConnection siConnection = new SqlConnection(Databases.getDbConnectionString(\"csSharedInfo\")))\n {\n SqlCommand seCmd = new SqlCommand(\"GetSignOnDetails\", siConnection);\n seCmd.CommandType = CommandType.StoredProcedure;\n seCmd.Parameters.AddWithValue(\"@DomainAccount\", strREMOTE_USER);\n SqlDataAdapter sda = new SqlDataAdapter(seCmd);\n DataTable dtServerVars = new DataTable();\n sda.Fill(dtServerVars);\n if (dtServerVars.Rows.Count > 0)\n return dtServerVars.Rows[0];\n return null;\n }\n }\n</code></pre>\n\n<p>Having done this, the next piece of code will also be a lot easier:</p>\n\n<pre><code>DataRow drServerVars = clCommonFunctions.TryAutoLogin(\"europe\\\\MrTest\");\nSession[\"CablingUserID\"]= drServerVars[\"CablingUserID\"].ToString();\nSession[\"CablingUseremail\"] = drServerVars[\"CablingUseremail\"].ToString();\nSession[\"CablingLogin\"] = drServerVars[\"CablingLogin\"].ToString();\n...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T10:31:00.277",
"Id": "39751",
"Score": "0",
"body": "You could simplify `if (dtServerVars.Rows.Count > 0) { return dtServerVars.Rows[0]; } return null;` to just: `return dtServerVars.AsEnumerable().FirstOrDefault()`. You would need to add a using for `System.Data.DataSetExtensions`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T10:34:50.350",
"Id": "39752",
"Score": "0",
"body": "RobH: True! But MoiD101 is still learning a lot of stuff, I was not willing in introducing him into new techniques like LINQ, but just showing him how he can improve his use on the components he is already using."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T10:49:43.370",
"Id": "39753",
"Score": "0",
"body": "Thank You Martin and thank you RobH for your contribution, as Martin commented though i have gota learn to walk first ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T11:00:56.043",
"Id": "39754",
"Score": "0",
"body": "Martin, just one question, the if statement below, is that some sort of short hand can i go read about it somewhere it seems very forein to me thats all..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T11:06:42.610",
"Id": "39755",
"Score": "0",
"body": "Which if-statement? The only if statement in my answer is from your own code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T11:12:47.453",
"Id": "39756",
"Score": "0",
"body": "yes but it is modified, there are less curly braces and the return null is written right below the first return without any curoly braces eg\nif (blaahhh)\n{\nif true code\n}"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T11:22:28.147",
"Id": "39757",
"Score": "0",
"body": "Ah, good one. Flow control keyswords like `if`, `for` and `while` will only execute the next statement (if the conditions are right). So if two statements are to be executed you will HAVE to surround them with braces, make those statements one \"compound statements\" or \"block of statements\". But if there is only one statement after the flow control keyword, braces can be ommited."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T11:24:45.347",
"Id": "39758",
"Score": "0",
"body": "cool cheers Martin"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T12:09:18.257",
"Id": "39762",
"Score": "0",
"body": "@MoiD101 just to note, although Martin is correct, a lot of people don't like omitting the braces as it can lead to mistakes when other people read/update the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T12:13:26.160",
"Id": "39763",
"Score": "1",
"body": "@RobH+MoiD101: RobH is correct. It is a personal chois with pro's and con's. It can lead to mistakes if your coding style (and how you implement it) is not consistent."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T12:50:05.670",
"Id": "39765",
"Score": "0",
"body": "@RobH+Martin Mulder: i have to confess i did put them back in hehe"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T10:26:44.097",
"Id": "25678",
"ParentId": "25677",
"Score": "1"
}
},
{
"body": "<p>The part where you set session properties could be simplified a lot. If you want to get all columns from the <code>DataTable</code> into <code>Session</code>, then you can use the <code>Columns</code> collection.\nSomething like:</p>\n\n<pre><code>DataTable dtServerVars = clCommonFunctions.TryAutoLogin(\"europe\\\\MrTest\");\n\nforeach (DataColumn column in dtServerVars.Columns)\n{\n Session[column.ColumnName] = dtServerVars.Rows[0][column].ToString();\n}\n</code></pre>\n\n<p>Though it seems some of your column names are different in <code>Session</code>. To do that, you could use a helper method:</p>\n\n<pre><code>private static string TranslateColumnName(string dataTableColumnName)\n{\n switch (dataTableColumnName)\n {\n case \"SharedInfoID\":\n return \"SharedInfoICLlocation\";\n default:\n return dataTableColumnName;\n }\n}\n</code></pre>\n\n\n\n<pre><code>Session[TranslateColumnName(column.ColumnName)] = dtServerVars.Rows[0][column].ToString();\n</code></pre>\n\n<p>Also, if you know that all the columns are <code>string</code>s, I would use <a href=\"http://msdn.microsoft.com/en-us/library/bb383067.aspx\" rel=\"nofollow\">the <code>Field()</code> extension method</a> instead of <code>ToString()</code>. That's because it handles <code>DBNull</code> properly and will throw an exception if the data in the column is actually a different type.</p>\n\n<pre><code>Session[TranslateColumnName(column.ColumnName)] = dtServerVars.Rows[0].Field<string>(column);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T13:23:05.963",
"Id": "25681",
"ParentId": "25677",
"Score": "1"
}
},
{
"body": "<p>My only suggestion, in addition to existing answers, would be to <strong>use a domain object instead of a datatable and multiple session variables</strong>. That way you have a simple, strongly-typed way of accessing all those details at once without dealing with the database fields all over the place.</p>\n\n<p>The idea would be to create a class for containing all the data:</p>\n\n<pre><code>public class SignOnDetails\n{\n public int CablingUserID { get; set; }\n public string CablingUseremail { get; set; }\n public string CablingLogin { get; set; }\n public string CablingPassword { get; set; }\n //All other properties ommited for brevity, but it goes like the previous ones\n}\n</code></pre>\n\n<p>Then, the TryAutoLogin method would return an instance of this class instead of a raw table:</p>\n\n<pre><code>public static SignOnDetails TryAutoLogin(string strREMOTE_USER)\n{\n SqlConnection siConnection = new SqlConnection();\n siConnection.ConnectionString = Databases.getDbConnectionString(\"csSharedInfo\");\n siConnection.Open();\n SqlCommand seCmd = new SqlCommand(\"GetSignOnDetails\", siConnection);\n seCmd.CommandType = CommandType.StoredProcedure;\n seCmd.Parameters.Add(new SqlParameter(\"@DomainAccount\", SqlDbType.NVarChar, 300));\n seCmd.Parameters[\"@DomainAccount\"].Value = strREMOTE_USER;\n seCmd.CommandType = CommandType.StoredProcedure;\n SqlDataAdapter sda = new SqlDataAdapter();\n seCmd.Connection = siConnection;\n sda.SelectCommand = seCmd;\n DataTable dtServerVars = new DataTable();\n sda.Fill(dtServerVars);\n siConnection.Close();\n if (dtServerVars != null)\n {\n if (dtServerVars.Rows.Count > 0)\n {\n //Here we build the SignOnDetails instance from the datatable\n SignOnDetails details = new SignOnDetails();\n details.CablingUserID = dtServerVars.Rows[0][\"CablingUserID\"];\n details.CablingUseremail = dtServerVars.Rows[0][\"CablingUseremail\"];\n details.CablingLogin = dtServerVars.Rows[0][\"CablingLogin\"];\n details.CablingPassword = dtServerVars.Rows[0][\"CablingPassword\"];\n //All other properties ommited for brevity, but it goes like the previous ones\n return details ;\n }\n }\n return null;\n}\n</code></pre>\n\n<p>Then, you save all the data at once in one go:</p>\n\n<pre><code>SignOnDetails details= clCommonFunctions.TryAutoLogin(\"europe\\\\MrTest\");\nSession[\"SignOnDetails\"] = details;\n</code></pre>\n\n<p>And using it becomes strongly typed, requiring accesing a single session variable:</p>\n\n<pre><code>string login = ((SignOnDetails)Session[\"SignOnDetails\"]).CablingLogin;\n</code></pre>\n\n<p>This has the advantages of being stringly typed, don't rely much on magic strings, and the database is nicely encapsulated in one method, while the rest of the program only knows about this class.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-03-19T20:58:32.823",
"Id": "158228",
"ParentId": "25677",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "25678",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T10:13:12.780",
"Id": "25677",
"Score": "2",
"Tags": [
"c#",
"sql",
"asp.net"
],
"Title": "Building session-variables from a SQL stored procedure"
}
|
25677
|
<p>Inspired by a recent question that caught my interest (now <a href="https://codereview.stackexchange.com/questions/25642/re-arrange-letters-to-produce-a-palindrome">deleted</a>), I wrote a function in Python 3 to rearrange the letters of a given string to create a (any!) palindrome:</p>
<ol>
<li>Count the occurrences of each letter in the input</li>
<li>Iterate over the resulting <code>(letter, occurrences)</code> tuples only once:
<ul>
<li>If the occurences are even, we remember them to add them around the center later</li>
<li>A valid palindrome can contain only <strong>0 or 1 letter(s) with an odd number of occurrences</strong>, so if we've already found the center, we raise an exception. Otherwise, we save the new-found center for later</li>
</ul></li>
<li>Finally, we add the sides around the center and join it to create the resulting palindrome string.</li>
</ol>
<p>I'm looking for feedback on every aspect you can think of, including </p>
<ul>
<li>readability (including docstrings),</li>
<li>how appropriate the data structures are,</li>
<li>if the algorithm can be expressed in simpler terms (or replaced altogether) and </li>
<li>the quality of my tests.</li>
</ul>
<hr>
<h2>Implementation: <code>palindromes.py</code></h2>
<pre><code>from collections import deque, Counter
def palindrome_from(letters):
"""
Forms a palindrome by rearranging :letters: if possible,
throwing a :ValueError: otherwise.
:param letters: a suitable iterable, usually a string
:return: a string containing a palindrome
"""
counter = Counter(letters)
sides = []
center = deque()
for letter, occurrences in counter.items():
repetitions, odd_count = divmod(occurrences, 2)
if not odd_count:
sides.append(letter * repetitions)
continue
if center:
raise ValueError("no palindrome exists for '{}'".format(letters))
center.append(letter * occurrences)
center.extendleft(sides)
center.extend(sides)
return ''.join(center)
</code></pre>
<hr>
<h2>Unit tests: <code>test_palindromes.py</code> (using <em>py.test</em>)</h2>
<pre><code>def test_empty_string_is_palindrome():
assert palindrome_from('') == ''
def test_whitespace_string_is_palindrome():
whitespace = ' ' * 5
assert palindrome_from(whitespace) == whitespace
def test_rearranges_letters_to_palindrome():
assert palindrome_from('aabbb') == 'abbba'
def test_raises_exception_for_incompatible_input():
with pytest.raises(ValueError) as error:
palindrome_from('asdf')
assert "no palindrome exists for 'asdf'" in error.value.args
</code></pre>
<hr>
<h2>Manual testing in the console</h2>
<pre><code>while True:
try:
word = input('Enter a word: ')
print(palindrome_from(word))
except ValueError as e:
print(*e.args)
except EOFError:
break
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-14T17:26:20.193",
"Id": "184519",
"Score": "0",
"body": "Rather than checking if you already have a letter with odd frequency, you can just count how many you have total, and if it is not equal to mod2 of the length of the string, it can't be a palindrome. In other words, if(number_of_odd_frequencies == len(word) % 2): it is a palindrome"
}
] |
[
{
"body": "<pre><code>from collections import deque, Counter\n\n\ndef palindrome_from(letters):\n \"\"\"\n Forms a palindrome by rearranging :letters: if possible,\n throwing a :ValueError: otherwise.\n :param letters: a suitable iterable, usually a string\n :return: a string containing a palindrome\n \"\"\"\n counter = Counter(letters)\n sides = []\n center = deque()\n for letter, occurrences in counter.items():\n repetitions, odd_count = divmod(occurrences, 2)\n</code></pre>\n\n<p>odd_count is a bit of a strange name, because its just whether its odd or even, not really an odd_count</p>\n\n<pre><code> if not odd_count:\n sides.append(letter * repetitions)\n continue\n</code></pre>\n\n<p>avoid using continue, favor putting the rest of the loop in an else block. Its easier to follow that way</p>\n\n<pre><code> if center:\n raise ValueError(\"no palindrome exists for '{}'\".format(letters))\n center.append(letter * occurrences)\n center.extendleft(sides)\n center.extend(sides)\n</code></pre>\n\n<p>Avoid reusing variables for something different. Changing center to be the whole phrase isn't all that good an idea. I suggest using <code>itertools.chain(sides, center, reversed(sides))</code> and then joining that.</p>\n\n<pre><code> return ''.join(center)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T13:13:15.043",
"Id": "39766",
"Score": "0",
"body": "Interesting! Using `itertools.chain` eliminates the need to use a `deque` I guess. You need to do `reversed(sides)` for the last argument though (the deque used to do that by itself for some reason)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T13:19:50.703",
"Id": "39768",
"Score": "0",
"body": "@codesparkle, ah I suppose extendleft probably extends in the backwards order."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T13:10:01.467",
"Id": "25680",
"ParentId": "25679",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "25680",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-01T12:39:17.153",
"Id": "25679",
"Score": "4",
"Tags": [
"python",
"algorithm",
"palindrome"
],
"Title": "Create palindrome by rearranging letters of a word"
}
|
25679
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.