body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
Machine learning provides computer algorithms that automatically discover patterns in data and make intelligent decisions from them.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T07:00:03.227",
"Id": "35161",
"Score": "0",
"Tags": null,
"Title": null
}
|
35161
|
Google Chrome is a web browser available on mobile, TV, and desktop platforms. Developed by Google, it uses the Blink layout engine and application framework.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T07:01:53.500",
"Id": "35163",
"Score": "0",
"Tags": null,
"Title": null
}
|
35163
|
<p>Feel free to tell about every possible issue (style, errors, inffective solution etc.) you found. Here is the main part of what I want to be reviewed, through there is some related code on <a href="https://github.com/datalinkE/graph/tree/edd0764f76eb548f39d90249f0cf41912f989e8e" rel="nofollow">GitHub</a>.</p>
<h3>Header</h3>
<pre><code>#ifndef PRIM_GRAPH_MST_H
#define PRIM_GRAPH_MST_H
#include <list>
#include "graph.h"
class PrimGraphMstImplementation;
class PrimGraphMst
// class that should find minimum spanning tree (MST) for the given graph
// and then store obtained result as a list of edges and summary weight
{
public:
PrimGraphMst(const Graph&);
// all work is actualy done in constructor
// then we hold obtained result in some immutable fields
const std::list<Graph::EdgeKey>& edges();
// returns a list of edges from the given graph that forms MST
double weight() const;
// returns MST summary weight
bool valid() const;
// checks if obtained mst contains same number of vertices as the given graph
// it could be wrong if the given graph was not connected
Graph* makeTreeGraph();
// construct new graph that have only edges from our MST
private:
std::shared_ptr<PrimGraphMstImplementation> impl;
};
#endif // PRIM_GRAPH_MST_H
</code></pre>
<h3>C++ Source</h3>
<pre><code>#include <queue>
#include <cassert>
#include "prim_graph_mst.h"
class EdgeWithPriority
// helper class to use graph eges in priority queue
{
public:
double weight;
Graph::EdgeKey key;
EdgeWithPriority(int x, int y, const Graph& graph)
{
weight = graph.distance(x, y);
assert(weight >= 0);
key = Graph::makeEdgeKey(x, y);
}
bool operator<(const EdgeWithPriority& other) const
// such behavior is needed to use this type in std::priority queue
// where top element is always max element and wee need to retrieve
// edge with the lowest weight
{
return weight >= other.weight;
}
};
class PrimGraphMstImplementation
{
//actual implementation of Prim's algorithm
public:
PrimGraphMstImplementation(const Graph& graph) :
graph(graph),
summaryWeight(0)
// we do all the work here in constructor
// we assume that graph is connected
{
assert(graph.verticesCount() > 0);
visitVertex(0);
while(!pq.empty() && visited.size() < graph.verticesCount())
{
EdgeWithPriority element = pq.top();
pq.pop();
if(visited.find(element.key.first) == visited.end())
{
edges.push_back(element.key);
summaryWeight += element.weight;
visitVertex(element.key.first);
}
else if (visited.find(element.key.second) == visited.end())
{
edges.push_back(element.key);
summaryWeight += element.weight;
visitVertex(element.key.second);
}
else
{
continue;
}
}
}
void visitVertex(size_t index)
// helper method marks vertex as visited and adds all it's
// edges to priority queue
{
visited.insert(index);
for(size_t other : graph.getVertexNeighbors(index))
{
pq.push(EdgeWithPriority(index, other, graph));
}
}
bool valid() const
// it could be wrong if given graph was not connected
{
return visited.size() == graph.verticesCount();
}
const Graph& graph;
double summaryWeight;
std::list<Graph::EdgeKey> edges;
private:
std::priority_queue<EdgeWithPriority> pq;
std::set<size_t> visited;
};
PrimGraphMst::PrimGraphMst(const Graph& graph)
{
impl = std::make_shared<PrimGraphMstImplementation>(graph);
}
const std::list<Graph::EdgeKey>& PrimGraphMst::edges()
{
return impl->edges;
}
bool PrimGraphMst::valid() const
{
return impl->valid();
}
double PrimGraphMst::weight() const
{
return impl->summaryWeight;
}
Graph* PrimGraphMst::makeTreeGraph()
{
if(!valid())
return nullptr;
Graph* result = new Graph(impl->graph.verticesCount());
for(Graph::EdgeKey element : impl->edges)
{
double weight = impl->graph.distance(element.first, element.second);
result->connect(element.first, element.second, weight);
}
return result;
}
</code></pre>
|
[] |
[
{
"body": "<p>Generally speaking, it seems to be coded pretty well. I can just find one or two things that could be improved:</p>\n\n<hr>\n\n<pre><code>else\n{\n continue;\n}\n</code></pre>\n\n<p>This piece of code at the end of a <code>while</code> seems fairly useless. I guess it would be the same without it.</p>\n\n<hr>\n\n<pre><code>void visitVertex(size_t index)\n// helper method marks vertex as visited and adds all it's\n// edges to priority queue\n{\n visited.insert(index);\n for(size_t other : graph.getVertexNeighbors(index))\n {\n pq.push(EdgeWithPriority(index, other, graph));\n }\n}\n</code></pre>\n\n<p>Here, you can replace <code>pq.push(EdgeWithPriority(index, other, graph));</code> by <code>pq.emplace(index, other, graph);</code>. The function <a href=\"http://en.cppreference.com/w/cpp/container/priority_queue/emplace\" rel=\"nofollow noreferrer\"><code>emplace</code></a> will construct the object directly in the <code>priority_queue</code> with the given parameters.</p>\n\n<p>You could also probably replace <code>visited.insert(index);</code> by <code>visited.emplace(index);</code> but I don't think it will change anything.</p>\n\n<hr>\n\n<pre><code>Graph* result = new Graph(impl->graph.verticesCount());\nfor(Graph::EdgeKey element : impl->edges)\n{\n double weight = impl->graph.distance(element.first, element.second);\n result->connect(element.first, element.second, weight);\n}\n</code></pre>\n\n<p>I don't know what the methods <code>distance</code> and <code>connect</code> do, but depending on what they really do, it could be better to for your <code>for</code> loop to take <code>const</code> references instead of values. But, well... it depends on <code>distance</code> and <code>connect</code>.</p>\n\n<hr>\n\n<p>You should <a href=\"https://stackoverflow.com/a/5577290/1364752\">use <code>std::unique_ptr</code> instead of <code>std::shared_ptr</code></a> to hold the pointer to the implementation. Since <code>std::unique_ptr</code> cannot be copied, that means that <code>PrimGraphMst</code> cannot be copied either, but that's probably fine since <code>std::shared_ptr</code> was not copying your data either but merely doing an alias to the implementation.</p>\n\n<p>You can also improve the constructor of <code>PrimGraphMst</code> by using a constructor initiaization list instead of a late memory allocation:</p>\n\n<pre><code>PrimGraphMst::PrimGraphMst(const Graph& graph):\n impl{ new PrimGraphMstImplementation{graph} }\n{}\n</code></pre>\n\n<hr>\n\n<p>You may have noted it: I used curly braces in the initialization list of the constructor in the previous section of this review. Contrary to plain parenthesis, curly braces prevent any implicit narrowing type conversion. Using them can help to catch the small errors that are sometimes linked to narrowing conversions.</p>\n\n<hr>\n\n<p><strong>Style:</strong> your indentation often seems off and makes the code quite difficult to review. You should indent your code evrytime you introduce a new scope.</p>\n\n<p>You are placing the comments of your function right after their point of declaration. Generally speaking, comments about a function are placed right before the function declaration.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T16:51:28.337",
"Id": "35181",
"ParentId": "35165",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T07:45:58.317",
"Id": "35165",
"Score": "3",
"Tags": [
"c++",
"c++11",
"tree",
"graph"
],
"Title": "Implementation of Prim's minimum spanning tree"
}
|
35165
|
Initialization is the first assignment for a data object or variable.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T08:57:18.040",
"Id": "35167",
"Score": "0",
"Tags": null,
"Title": null
}
|
35167
|
<p>Two possible solutions but which one? Or is there a Better?</p>
<p>I have a class MP3Track with members: Track number (int), track name (String), artist (String), in faourites (boolean) etc. My catalogue class contains two <code>ArrayList</code>s, one containing all tracks (vectorMain) and the other containing favourites (vectorFav) which are copies of the tracks in the main catalogue.</p>
<p>I want the user to have the option of swapping two track numbers (which are unique in both arrays).</p>
<p>Sample printout of the main catalogue below:
<img src="https://i.stack.imgur.com/oaHui.png" alt="enter image description here"></p>
<p>Both samples get the desired result but:</p>
<ul>
<li>(Solution 1) deleted as didn't work in reverse.</li>
<li>(Solution 2) Below Seems rather cumbersome! </li>
<li>(Solution 3) Below Seems more elegant but very long winded!</li>
</ul>
<p><code>getMainIndex()</code> - returns the index position in the <code>ArrayList</code> for a given track number or <code>-1</code>.</p>
<p>Here is <strong>Solution 2</strong> (overcame problem of solution 1 - but ugly)</p>
<p>Here is start of method:</p>
<pre><code>public void swapTrack(){
int t1 = -1, t2 = -1;
System.out.println(face.getSwapTrackMenu());
System.out.print("1) Please enter first track number to swap: ");
t1 = scan.readInt();
System.out.print("2) Please enter second track number to swap: ");
t2 = scan.readInt();
MP3Track mp31 = null;
MP3Track mp32 = null;
</code></pre>
<p>Now solution 2</p>
<pre><code>if((getMainIndex(t1)!=-1)&&(getMainIndex(t2)!=-1)){
String s1 = null;
String s2 = null;
for(MP3Track track : vectorMain){
if(track.getTrackNo() == t1){
s1 = track.getTitle();
}
if(track.getTrackNo() == t2){
s2 = track.getTitle();
}
}
for(MP3Track track : vectorMain){
if(track.getTitle().equals(s1)){
track.setTrackNo(t2);
}
if(track.getTitle().equals(s2)){
track.setTrackNo(t1);
}
}
for(MP3Track track : vectorFav){
if(track.getTitle().equals(s1)){
track.setTrackNo(t2);
}
if(track.getTitle().equals(s2)){
track.setTrackNo(t1);
}
}
}
</code></pre>
<p>Here is <strong>Solution 3</strong></p>
<pre><code> //Loop thorugh main (ArrayList) looking for both track numbers
for(MP3Track track : vectorMain){
if(track.getTrackNo() == t1){
//If track 1 found assign it to temp var
mp31 = vectorMain.get(getMainIndex(t1));
}
if(track.getTrackNo() == t2){
//If track 2 found assign it to temp var
mp32 = vectorMain.get(getMainIndex(t2));
}
}
//Check if we found track 1
if(vectorMain.contains(mp31)){
//Set temp var new track number
mp31.setTrackNo(t2);
}
//Check if we found track 2
if(vectorMain.contains(mp32)){
//Set temp var new track number
mp32.setTrackNo(t1);
}
mp31 = null; //Remove pointer reference
mp32 = null; //Remove pointer reference
//loop thorugh Fav (ArrayList) looking for track numbers
for(MP3Track track : vectorFav){
if(track.getTrackNo() == t1){
//Assign it to temp var
mp31 = vectorFav.get(getFavIndex(t1));
}
if(track.getTrackNo() == t2){
//Assign it to temp var
mp32 = vectorFav.get(getFavIndex(t2));
}
}
//Check if we found it first
if(vectorFav.contains(mp31)){
mp31.setTrackNo(t2);
}
//Check if we found it first
if(vectorFav.contains(mp32)){
mp32.setTrackNo(t1);
}
</code></pre>
<p>Is there something I'm missing here? I've hit a wall as to a better solution!!</p>
<p>I'm new to Java so any suggestions, improvements & comments appreciated.</p>
<p>Many thanks</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T12:25:04.310",
"Id": "56934",
"Score": "0",
"body": "What is the purposeof the 'track number'? Is it the track number of an album? It appears that it is not the album track number but something used for internal processes... what is it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T12:34:26.527",
"Id": "56935",
"Score": "0",
"body": "Assignment was for it to have a track number, artist name etc...in the program track numbers are unique."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T12:42:41.183",
"Id": "56936",
"Score": "0",
"body": "Assignment was for it to have a track number, artist name etc...in the program track numbers are unique. Also user can search Main by: track number, track title, artist name & album name. User is also able to sort Main & Favs by: track number, track title, artist name, album name (natural ordering). Other functions include: adding & deleting tracks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T07:45:03.343",
"Id": "58534",
"Score": "0",
"body": "It appears `trackNo` is an identity field. It should not be changed. Why would your user want to swap some arbitrary number used to identify tracks?"
}
] |
[
{
"body": "<p>In Solution 3, assuming you initialize <code>mp31</code> and <code>mp32</code> to null, you can replace this</p>\n\n<pre><code>//Check if we found track 1\nif(vectorMain.contains(mp31)){\n //Set temp var new track number\n mp31.setTrackNo(t2);\n}\n</code></pre>\n\n<p>With:</p>\n\n<pre><code>//Check if we found track 1\nif(mp31 != null) {\n //Set temp var new track number\n mp31.setTrackNo(t2);\n}\n</code></pre>\n\n<p>There is really no need to check if the arraylist <em>contains</em> the object since you used the <code>get(...)</code> method on the arraylist to get it in the first place. Therefore, <strong>you know</strong> that if the object has been initialized (is not null), the arraylist contains the object.</p>\n\n<p>Also, I would change the method signature for <code>getMainIndex</code> to also take the list to search in as an argument to the method. In that case, you don't need to have two methods (with probably a lot of duplicated code) <code>getMainIndex</code> and <code>getFavIndex</code> can be the same method, <code>getIndexInList(int trackNumber, List<MP3Track> list)</code>.</p>\n\n<hr>\n\n<p>I am not sure how your <code>getMainIndex</code> method works at the moment, but I assume the code <code>mp31 = vectorMain.get(getMainIndex(t1));</code> within the loop is the same thing as <code>mp31 = track;</code>. Therefore, you can replace this entire loop:</p>\n\n<pre><code>for(MP3Track track : vectorMain){\n if(track.getTrackNo() == t1){\n //If track 1 found assign it to temp var\n mp31 = vectorMain.get(getMainIndex(t1));\n }\n if(track.getTrackNo() == t2){\n //If track 2 found assign it to temp var\n mp32 = vectorMain.get(getMainIndex(t2));\n }\n}\n</code></pre>\n\n<p>With either:</p>\n\n<pre><code>for(MP3Track track : vectorMain){\n if(track.getTrackNo() == t1){\n //If track 1 found assign it to temp var\n mp31 = track;\n }\n if(track.getTrackNo() == t2){\n //If track 2 found assign it to temp var\n mp32 = track;\n }\n}\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>int index = getMainIndex(t1);\nif (index != -1)\n mp31 = vectorMain.get(index);\nindex = getMainIndex(t2);\nif (index != -1)\n mp32 = vectorMain.get(index);\n</code></pre>\n\n<hr>\n\n<p>As for Solution 2, this code here does not guarantee uniqueness of <code>trackNo</code> if two songs have the same title:</p>\n\n<pre><code>for(MP3Track track : vectorMain){\n if(track.getTrackNo() == t1){\n s1 = track.getTitle();\n }\n if(track.getTrackNo() == t2){\n s2 = track.getTitle();\n }\n}\n\nfor(MP3Track track : vectorMain){\n if(track.getTitle().equals(s1)){\n track.setTrackNo(t2);\n }\n if(track.getTitle().equals(s2)){\n track.setTrackNo(t1);\n }\n}\n</code></pre>\n\n<p>What you are essentially doing here is that you first scan through the list to get the <strong>title</strong> of the matching songs, and <strong>then</strong> you <strong>search for their title to change their track number</strong>. Why not change their track number within the first loop? You don't need all the three loops you have in Solution 2. Instead, search through <code>vectorMain</code> once and change the track numbers there, then search through <code>vectorFav</code> and change it there.</p>\n\n<hr>\n\n<p><strong>Some other comments:</strong></p>\n\n<p>I am not sure about how exactly you are using these two vectors and your <code>MP3Track</code> objects, or your <code>trackNumber</code> values. It seems to me as if whenever you swap track numbers, you do it in both of the lists. Therefore, perhaps you should <strong>use the same object references</strong> in both of the list. <strong>Don't create new MP3Track objects to place in <code>vectorFav</code>, you can re-use the same objects.</strong> That way, it will be enough to search only the <code>vectorMain</code> for the tracks, because it's the same object it will also update in <code>vectorFav</code>. As I said, I don't know exactly how you are using the <code>trackNumber</code> values so this might fit for you at the moment, but if it doesn't fit then you might want to change your design of the project.</p>\n\n<p>As far as I have seen of the usage of <code>getMainIndex</code> and <code>getFavIndex</code>, you only use those methods to first get the index in the list, and then get the <code>MP3Track</code> object itself. Consider returning an <code>MP3Track</code> (the object itself) instead of an <code>int</code> (the index of the object in the list). Then you should also rename the method to reflect this change in behavior.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T13:32:37.393",
"Id": "56939",
"Score": "0",
"body": "Hi Simon thanks for your comments. i know that the boolean value in MP3Track is enough information I need to produce the same result with only one list. My objective here with the my Uni assignment solution was to explore the API's to gain experience etc so I made it a little more difficult for myself!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T13:37:45.547",
"Id": "56940",
"Score": "0",
"body": "@user103388 What many programmers actually are looking for when they write code is simplicity. It's good that you give yourself a challenge, but simple and elegant code is often better than complex and difficult code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T13:47:56.560",
"Id": "56941",
"Score": "0",
"body": "You got me thinking now if I should whip it out and re-write it! I have to present my solution giving my reason behind the decisions I've made etc so will I include the challenge to myself then as an added exercise."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T13:50:40.587",
"Id": "56942",
"Score": "0",
"body": "getMainIndex & getfavIndex is used throught the program: You have a good point."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T13:15:37.340",
"Id": "35176",
"ParentId": "35173",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T11:20:51.710",
"Id": "35173",
"Score": "2",
"Tags": [
"java"
],
"Title": "Solution for swapping ArrayList data members with another"
}
|
35173
|
<p>I am working on the following script for python2.7 which "works" on small files. </p>
<p>I ran a sample on an input file of 188kB and it took approx. 1.15 min to complete. However, I need to process a 5GB file using this script and I did the math, it will take 11.48 years to finish it the way it is now. </p>
<p>sample input1</p>
<pre><code>aba_transit_number com
abaca plt|sub|sub|sub
abacus art|art
abalone anm
abamp qud
</code></pre>
<p>sample input2</p>
<pre><code>zoonosis-n of+n-j+n-the-development-n
zoonosis-n of+n-j+n-the-j-collection-n 1
zoonosis-n of+n-j+n-the-j-success-n 1
</code></pre>
<p>Can someone provide me insight on how to optimize my script for computation speed?? </p>
<pre><code> #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import division
from collections import defaultdict, Counter
import codecs
import random
mapping = dict()
#### takes as input a file with the following input1:
with codecs.open ("input1", "rb", "utf-8") as oSenseFile:
for line in oSenseFile:
concept, conceptClass = line.split()
mapping[concept + '-n'] = conceptClass
lemmas = set()
#### takes as input2 a file with the following format
with codecs.open('input2', "rb", "utf-8") as oIndexFile:
for line in oIndexFile:
lemma = line.split()[0]
if lemma in mapping.keys():
lemmas.add(lemma)
### randomly splits input2 into 2 files -- 80% and 20%
# -- and prints the 20% directly into out 2 for the other 80%
# --- it matches each 1st column in input2 with the first column in input 1
# -- if it is a match - it replaces it with the corresponding value in Col2 of Input1
# --- if there is more than one volume in Col2 of Input 1
# -- it prints all of the possible combinations and divides the freq (Col4 in Input2)
# by the number of values present
training_lemmas = random.sample(lemmas, int(len(lemmas) * 0.8))
classFreqs = defaultdict(lambda: Counter())
with codecs.open('out1', 'wb', 'utf-8') as testOutfile:
with codecs.open('input2', "rb", "utf-8") as oIndexFile:
for line in oIndexFile:
lemmaTAR, slot, filler, freq = line.split()
if lemmaTAR in training_lemmas:
senses = mapping[lemmaTAR].split(u'|')
for sense in senses:
classFreqs[sense][tuple([slot, filler])] += int(freq) / len(senses)
elif lemmaTAR in lemmas:
testOutfile.write(line)
with codecs.open('out2', 'wb', 'utf-8') as oOutFile:
for sense in sorted(classFreqs.keys()):
for slotfill in classFreqs[sense].keys():
string_slotfill = '\t'.join(list(slotfill))
outstring = '\t'.join([sense, string_slotfill, str(classFreqs[sense][slotfill])])
oOutFile.write(outstring + '\n')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T11:50:10.313",
"Id": "56926",
"Score": "2",
"body": "Don't write `.keys()`!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T11:58:13.837",
"Id": "56927",
"Score": "0",
"body": "see updated question --- okay, simply removing .keys() will improve speed?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T12:18:14.867",
"Id": "56933",
"Score": "0",
"body": "Yes, pretty much. [See §3 of this answer for an explanation.](http://codereview.stackexchange.com/a/33549/11728)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T12:52:59.063",
"Id": "56937",
"Score": "1",
"body": "Make `training_lemmas` a `set`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T13:04:13.233",
"Id": "56938",
"Score": "0",
"body": "You mention a 5 GB file but you have two inputs. Which is large, or both?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T14:02:35.787",
"Id": "56943",
"Score": "0",
"body": "ONly input 2 is large -- it is the file in which the replacing will occur - the other file (input1) is 1.8 mb"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T14:19:13.260",
"Id": "56944",
"Score": "0",
"body": "I removed .keys() - no improvement in time - in fact, it seems to go slower :s"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T14:47:06.223",
"Id": "56945",
"Score": "0",
"body": "Let's start at the beginning: Include in the question what that does."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T19:16:44.700",
"Id": "56966",
"Score": "0",
"body": "Did you remove *all* the `.keys()`? The one in `if lemma in mapping.keys():` is likely to be the main issue. Which part of the code is slow? You should split it into functions and profile. Can you make your data (the small version) available?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T11:00:55.013",
"Id": "57005",
"Score": "0",
"body": "Update, I removed all `.()keys` and also changed `training_lemmas` to sets. I also removed `codecs.open()`, which seemed to significantly slow down the reading of the large input file. With these changes, it brought down the total processing time (on all the data) to 25 minutes (albeit using almost a full 16GB of memory), but the computation time is much more reasonable than 11 years. Thank you all very much for all of the suggestions."
}
] |
[
{
"body": "<p>Remove all usages of the keys method. Note, this was already mentioned in the comments to your question, but it seems to have mostly done the trick for your problem.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T16:00:14.660",
"Id": "35692",
"ParentId": "35175",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T11:45:31.540",
"Id": "35175",
"Score": "2",
"Tags": [
"python",
"optimization"
],
"Title": "Optimize python script for speed"
}
|
35175
|
<p>I find myself using subject blocks in my tests to setup example because it is succinct. However is this considered bad form and can it have undesired consequences?</p>
<pre><code>require 'spec_helper'
describe "stations/index" do
before(:each) do
stub_user_for_view_test
assign(:stations, [
stub_model(Station),
stub_model(Station)
])
end
context "when not an admin" do
subject {
render
rendered
}
it { should match /[s|S]tations/ }
it { should have_selector('.station', :minimum => 2) }
it { should_not have_link 'Edit' }
it { should_not have_link 'Delete' }
end
context "when an admin" do
subject {
@ability.can :manage, Station
render
rendered
}
it { should have_link 'Edit' }
it { should have_link 'Delete' }
end
end
</code></pre>
|
[] |
[
{
"body": "<p>There are no unintended consequences, but it is a little unusual and may surprise the reader. However, it is a small surprise.</p>\n\n<p>It usually communicates intent well to use <code>subject</code> to declare the subject, and <code>before</code> to setup preconditions unrelated to the subject. For preconditions that involve the subject, those are often better in a <code>before</code> block as well, but it's not too surprising to find them in the <code>subject</code> block.</p>\n\n<p>So, instead of this:</p>\n\n<pre><code>subject {\n @ability.can :manage, Station\n render\n rendered\n}\n</code></pre>\n\n<p>this:</p>\n\n<pre><code>before(:each) do\n @ability.can :manage, Station\n render\nend\n\nsubject {rendered}\n</code></pre>\n\n<p>I used <code>do...end</code> for the multi line block and <code>{}</code> for the single line block; this is a common (although not ubiquitous) practice.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-08T16:30:21.393",
"Id": "38838",
"ParentId": "35178",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "38838",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T15:05:21.037",
"Id": "35178",
"Score": "2",
"Tags": [
"ruby",
"ruby-on-rails",
"rspec",
"tdd"
],
"Title": "Using RSpec subject to setup a test"
}
|
35178
|
<p>Just wondering what I did bad/could have done better. It's a simple script for pulling information from Leafly about cannabis strains. I've also added in a function to search. I am fairly new to Python. Anything is greatly appreciated. I also realize nothing is commented. I will quickly answer any questions, but it's simple enough, so hopefully you can read it.</p>
<pre><code># PYTHON 2.7.3
# Leafly API test
# STumbles
import urllib2
import json
import sys
import pprint
class Leafly:
def __init__(self):
self.author = 'STumbles'
self.title = 'Leafly API python'
self.python_version = '2.7.3'
def get_info(self):
self.search_term = raw_input('[*] Leafly [*]' + '\n\r'*23+': ').lower().replace(' ', '-')
self.url = 'http://www.leafly.com/api/details/%s' % self.search_term
dict_a = json.loads(urllib2.urlopen(self.url).read())
if (dict_a) != {}:
return dict_a
else:
print 'Please type a valid strain name.'
def specific_info(self, dict_a):
try:
self.container = []
if dict_a['Overview']:
self.overview = dict_a['Overview']
try:
self.overview = str(self.overview)
except UnicodeEncodeError:
pass
else:
print "could not open Overview"
if dict_a['Rating']:
self.rating = str(dict_a['Rating']) + '/10'
else:
print "could not open Rating"
if dict_a['Name']:
self.name = dict_a['Name']
else:
print "could not open Name"
if dict_a['Abstract']:
self.details = dict_a['Abstract']
else:
print "could not open Abstract"
if dict_a['Category']:
self.category = 'it is a %s' % dict_a['Category']
else:
print "could not open Category"
if dict_a['Medical'][0]['Name']:
self.medical = 'Helps with %s' % dict_a['Medical'][0]['Name']
else:
print "could not open Medical"
if dict_a['Effects'][0]['Name']:
self.effect = 'Makes you %s' % dict_a['Effects'][0]['Name']
else:
print "could not open Effects"
if dict_a['Negative'][0]['Name']:
self.negative = 'Causes %s' % dict_a['Negative'][0]['Name']
else:
print "could not open Negative"
try:
self.container.append(self.name)
self.container.append(self.rating)
self.container.append(self.overview)
self.container.append(self.details)
self.container.append(self.category)
self.container.append(self.medical)
self.container.append(self.effect)
self.container.append(self.negative)
return self.container
except AttributeError:
pass
except TypeError:
pass
def search(self):
print '\n'*23
self.search_url = json.loads(urllib2.urlopen("http://www.leafly.com/api/strains").read())
self.keyword = raw_input("Search: ").lower().replace(' ', '-')
for i in self.search_url:
for keys in xrange(1):
if self.keyword in i['Key']:
print i['Key']
else:
pass
print '\n'*23
flags = raw_input("Press 1 to search, or press 2 to get strain information\n[*] : ")
try:
if flags == 1 or 2:
flags = int(flags)
except ValueError:
print "please enter a valid number"
leafly = Leafly()
if flags == 2:
weed_info = leafly.get_info()
strain_info = leafly.specific_info(weed_info)
try:
for i in strain_info:
print i
except TypeError:
pass
if flags == 1:
leafly.search()
else:
pass
</code></pre>
|
[] |
[
{
"body": "<p>You have two unused imports:</p>\n\n<pre><code>import pprint\nimport sys\n</code></pre>\n\n<ul>\n<li><p>In your methods, I notice that you are not using local variables and instead you're setting instance variables. There is no need for that, unless those variables need to be used outside of your methods.</p></li>\n<li><p>There is also a bug in your code, see below. It checks if <code>flags</code> is equal to 1, or if 2 is <code>True</code>. All non-zero integer values evaluate to <code>True</code>, else <code>False</code>.</p>\n\n<pre><code>if flags == 1 or 2:\n flags = int(flags)\n</code></pre>\n\n<p>Probably what you wanted:</p>\n\n<pre><code>if flags in (1, 2):\n flags = int(flags)\n</code></pre></li>\n<li><p>Another bug in your flags check is that <code>raw_input</code> returns a string, not an integer.</p>\n\n<p>Final check:</p>\n\n<pre><code>if flags in ('1', '2'):\n flags = int(flags)\n</code></pre></li>\n<li><p>(EDIT 1) Since we are explicitly checking for the two correct int strings, there is no need to catch the <code>ValueError</code> exception that could get raised by an invalid string being passed to the int function.</p></li>\n<li><p>I moved code out of the root of the file, and into a static method of the Leafly class. Also, added a <code>__name__ == '__main__'</code> check so you can use this class in other files without running the root code.</p></li>\n<li><p>You have a constructor that sets unused variables. No need to specify author and Python version as instance variables. If you really must, add them as Docstrings. Look at the final result to see how.</p></li>\n<li><p>You have a giant try/catch method that catches <code>AttributeError</code>. This is because some of your local variables aren't set. Look at the final result to see how I've refactored it so no try/catch is required.</p></li>\n<li><p>I see you only select the first entry in the lists of \"medical\", \"effects\" and \"negative\". Perhaps you should loop through them and add them to a list in the next version of this project. I can't infer too much from your example, so I'll leave it to you to implement.</p></li>\n<li><p>You put try/catch exceptions into your code way too much. Don't do that. Rather figure out why you are getting exceptions so regularly and try deal with it. You are either doing something wrong, or the logic regarding your data and the assumptions around it are not sound. I never, ever add exception handling unless I really know I need it and that's only if I know how to handle it. Crash early, and crash often so that you can expose bugs quickly and fix them, rather than masking them.</p></li>\n<li><p>I've added a sort of enumeration class to hold all your magical strings such as \"Name\" and \"Effects\", etc. It's neater, and saves you from having to find/replace all references of a string if it changes. In this example it's trivial, but for larger projects that require changes, you'll thank me.</p></li>\n<li><p>I've refactored out your separate print instances of <code>print '\\n'*23</code> into a <code>ClearScreen</code> function.</p></li>\n</ul>\n\n<p>Finally, please bear in mind that with any refactoring endeavour, bugs do creep in. Bear in mind, that I have not tested the changes. Please re-test.</p>\n\n<p>Final version of the code, with my changes included:</p>\n\n<pre><code># PYTHON 2.7.3\n# Leafly API test\n# STumbles\n\nimport urllib2\nimport json\n\n\n\nclass Param(object):\n \"\"\"\n Enumeration object for data structure names inside the retrieved JSON.\n \"\"\"\n Overview = \"Overview\"\n Rating = \"Rating\"\n Name = \"Name\"\n Abstract = \"Abstract\"\n Category = \"Category\"\n Medical = \"Medical\"\n Effects = \"Effects\"\n Negative = \"Negative\"\n\n\ndef ClearScreen(lines=23):\n print '\\n' * lines\n\n\nclass Leafly:\n \"\"\"\n @author: STumbles\n @title: Leafly API python\n @python_version: 2.7.3\n \"\"\"\n\n def get_info(self):\n print \"[*] Leafly [*]\"\n ClearScreen()\n self.search_term = raw_input(': ').lower().replace(' ', '-')\n self.url = 'http://www.leafly.com/api/details/%s' % self.search_term\n dict_a = json.loads(urllib2.urlopen(self.url).read())\n if (dict_a) != {}:\n return dict_a\n else:\n print 'Please type a valid strain name.'\n\n def specific_info(self, dict_a):\n try:\n container = []\n if dict_a['Overview']:\n overview = dict_a['Overview']\n try:\n overview = str(overview)\n except UnicodeEncodeError:\n pass\n else:\n print \"could not open Overview\"\n\n if dict_a[Param.Rating]:\n rating = str(dict_a[Param.Rating]) + '/10'\n container.append(rating)\n else:\n print \"could not open Rating\"\n\n if dict_a[Param.Name]:\n name = dict_a[Param.Name]\n container.append(name)\n else:\n print \"could not open Name\"\n\n if dict_a[Param.Abstract]:\n details = dict_a[Param.Abstract]\n container.append(details)\n else:\n print \"could not open Abstract\"\n\n if dict_a[Param.Category]:\n category = 'it is a %s' % dict_a[Param.Category]\n container.append(category)\n else:\n print \"could not open Category\"\n\n if dict_a[Param.Medical][0][Param.Name]:\n medical = 'Helps with %s' % dict_a[Param.Medical][0][Param.Name]\n container.append(medical)\n else:\n print \"could not open Medical\"\n\n if dict_a[Param.Effects][0][Param.Name]:\n effect = 'Makes you %s' % dict_a[Param.Effects][0][Param.Name]\n container.append(effect)\n else:\n print \"could not open Effects\"\n\n if dict_a[Param.Negative][0][Param.Name]:\n negative = 'Causes %s' % dict_a[Param.Negative][0][Param.Name]\n container.append(negative)\n else:\n print \"could not open Negative\"\n\n except TypeError:\n pass\n\n def search(self):\n ClearScreen()\n self.search_url = json.loads(urllib2.urlopen(\"http://www.leafly.com/api/strains\").read())\n self.keyword = raw_input(\"Search: \").lower().replace(' ', '-')\n for i in self.search_url:\n for keys in xrange(1):\n if self.keyword in i['Key']:\n print i['Key']\n else:\n pass\n\n @staticmethod\n def process_user_request():\n ClearScreen()\n flags = raw_input(\"Press 1 to search, or press 2 to get strain information\\n[*] : \")\n try:\n if flags in ('1', '2'):\n flags = int(flags)\n else:\n print \"please enter a valid number\"\n return\n\n leafly = Leafly()\n\n if flags == 2:\n weed_info = leafly.get_info()\n strain_info = leafly.specific_info(weed_info)\n try:\n for i in strain_info:\n print i\n except TypeError:\n pass\n else:\n leafly.search()\n else:\n pass\n\nif __name__ == '__main__':\n Leafly.process_user_request()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-11-19T16:49:51.897",
"Id": "35695",
"ParentId": "35179",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T15:55:45.117",
"Id": "35179",
"Score": "5",
"Tags": [
"python",
"performance",
"beginner"
],
"Title": "Python Leafly API"
}
|
35179
|
<p>I like to create tools for memoization since it can sometimes be useful. I recently created a generic tool for memoizing the results of <a href="https://en.wikipedia.org/wiki/Pure_function" rel="nofollow">pure functions</a>.</p>
<p>Here is an example of how it works:</p>
<pre><code>// Dummy function
auto func(int a, bool b)
-> std::string
{
// Some heavy computations
}
int main()
{
auto memof_f = memoized(func);
auto a = memo_f(5, true);
auto b = memo_f(8, false);
// ...
}
</code></pre>
<p>In this example, <code>memo_f</code> is a wrapper that calls <code>func</code> and memoizes its results. When called, it checks whether the result for the given arguments is in cache and computes it only if it is not.</p>
<p>Here is the implementation of <code>memoized</code>:</p>
<pre><code>template<typename Ret, typename... Args>
class MemoizedFunction
{
public:
MemoizedFunction(const std::function<Ret(Args...)>& func):
_func(func)
{}
auto operator()(Args... args)
-> Ret
{
auto tuple_args = std::make_tuple(args...);
if (not _memory.count(tuple_args))
{
auto res = _func(args...);
_memory[tuple_args] = res;
return res;
}
return _memory[tuple_args];
}
private:
// Stored function
std::function<Ret(Args...)> _func;
// Map containing the pairs args/return
std::unordered_map<std::tuple<Args...>, Ret> _memory;
};
template<typename Ret, typename... Args>
auto memoized(Ret (*func)(Args...))
-> MemoizedFunction<Ret, Args...>
{
return { std::function<Ret(Args...)>(func) };
}
</code></pre>
<p>Also, it's not of utmost importance, but I need these little functions in order to hash a tuple:</p>
<pre><code>template<typename First, typename... Rest>
auto hash_all(First first, Rest... rest)
-> std::size_t
{
auto seed = std::hash<First>()(first);
seed ^= hash_all(rest...);
return seed;
}
template<typename First, typename Second>
auto hash_all(First first, Second second)
-> std::size_t
{
return std::hash<First>()(first) ^ std::hash<Second>()(second);
}
namespace std
{
// Hash function for tuples
template<typename... Args>
struct hash<std::tuple<Args...>>
{
auto operator()(const std::tuple<Args...>& args) const
-> std::size_t
{
return apply(hash_all<Args...>, args);
}
};
}
</code></pre>
<p>Note: the function <code>apply</code> is a function that uses the elements of a tuple as parameters for a given function, as proposed in <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3802.pdf" rel="nofollow">N3802</a>.</p>
<p>My question is simple: since this a low-level tool, which could be used in several contexts, is there any way to improve its performance at least a little bit? And while we are at it, do not hesitate to give tips for that construct to be more versatile too :)</p>
<p><strong>Note:</strong> this class is only intended to work for pure (or "well-behaved" as of <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3744.pdf" rel="nofollow">N3744</a>) functions.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T20:51:18.907",
"Id": "56967",
"Score": "3",
"body": "See http://stackoverflow.com/q/9729212/1157100"
}
] |
[
{
"body": "<p>Thanks to <a href=\"https://stackoverflow.com/a/9729954/1364752\">an answer</a> to a similar question on StackOverflow (thanks @200_success), I improved the implementation of <code>operator()</code>. Using <code>_memory.count</code> is pretty inefficient compared to <code>_memory.find</code> since the latter will stop once the first corresponding key is found:</p>\n\n<pre><code>auto operator()(Args... args)\n -> Ret\n{\n const auto t_args = std::make_tuple(args...);\n auto it = _memory.find(t_args);\n if (it == _memory.cend())\n {\n using val_t = typename std::unordered_map<std::tuple<Args...>, Ret>::value_type;\n it = _memory.insert(val_t(t_args, _func(args...))).first;\n }\n return it->second;\n}\n</code></pre>\n\n<p>While the solution above is indeed better than what I had, I managed to improve it even more: the results of <code>_func</code> should be directly constructed into <code>_memory</code> thanks to the piecewise construction of <code>std::pair</code>:</p>\n\n<pre><code>template<typename Ret, typename... Args>\nauto MemoizedFunction<Ret, Args...>::operator()(Args... args)\n -> Ret\n{\n const auto t_args = std::make_tuple(args...);\n auto it = _memory.find(t_args);\n if (it == _memory.cend())\n {\n it = _memory.emplace(std::piecewise_construct,\n std::forward_as_tuple(t_args),\n std::forward_as_tuple(_func(args...))\n ).first;\n }\n return it->second;\n}\n</code></pre>\n\n<p>Now, <code>operator()</code> is far better than it originally was. I don't know whether it is still possible to improve it or not though.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T17:04:04.733",
"Id": "35765",
"ParentId": "35180",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "35765",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T16:15:16.840",
"Id": "35180",
"Score": "8",
"Tags": [
"c++",
"c++11",
"functional-programming",
"cache",
"memoization"
],
"Title": "Generic pure functions memoization"
}
|
35180
|
C++/CLI is based on C++, modified to allow compilation of a mixture of native code and code for Microsoft's Common Language Infrastructure (CLI). It replaces Microsoft's Managed Extensions for C++, which aimed for stronger C++ conformance.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-11-11T17:51:06.723",
"Id": "35184",
"Score": "0",
"Tags": null,
"Title": null
}
|
35184
|
<p>Use this tag for code that is to be compiled as <a href="http://en.wikipedia.org/wiki/C%2B%2B03" rel="nofollow noreferrer">C++03</a>, published as ISO/IEC 14882:2003 in 2003.</p>
<ul>
<li>Predecessor: C++98</li>
<li>Successor: C++11</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-11-11T17:53:02.420",
"Id": "35185",
"Score": "0",
"Tags": null,
"Title": null
}
|
35185
|
Code that is written to the 2003 version of the C++ standard. Use in conjunction with the 'c++' tag.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-11-11T17:53:02.420",
"Id": "35186",
"Score": "0",
"Tags": null,
"Title": null
}
|
35186
|
A class, data structure, or abstract data type (ADT) whose instances are collections of other objects.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T17:56:52.573",
"Id": "35188",
"Score": "0",
"Tags": null,
"Title": null
}
|
35188
|
<p>I have these lines of code in my view:</p>
<pre><code><?php
$count = count($product->getTags());
$tagsStr = '';
foreach($product->getTags() as $key => $tag){
$tagsStr.= " " . $tag->getTag();
if(($key == 0 && $count < 1) || ($key == 0 && $count >1 && $key != $count)){
$tagsStr .= ',';
}
} ?>
</code></pre>
<p>It prints strings like:</p>
<blockquote>
<p>Fish, Onions</p>
</blockquote>
<p>Or </p>
<blockquote>
<p>Fish, Onions, Eggs</p>
</blockquote>
<p>All these items are stored in an <code>ArrayCollection $product->getTags();</code>.</p>
<p>I find that these are a lot of lines for completing something this simple. I was wondering if you have ideas on simplifying this code.</p>
|
[] |
[
{
"body": "<pre><code>$tagsStr = implode(', ', array_map(function ($tag) { return $tag->getTag(); }, $product->getTags()->toArray()));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T18:33:21.967",
"Id": "56961",
"Score": "0",
"body": "Sorry but that doesn't work since getTags(); returns an array coellection of tag objects."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T18:38:00.917",
"Id": "56962",
"Score": "0",
"body": "You are right we need to use an array_map call or something similar to get the real tags."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T22:21:59.780",
"Id": "57341",
"Score": "0",
"body": "It should be noted that this answer relies on lambda functions, which may not always be available."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T18:28:34.860",
"Id": "35194",
"ParentId": "35189",
"Score": "2"
}
},
{
"body": "<p>Peter Kiss's code works, but it's not fast.</p>\n\n<pre><code><?php\n\n$tags = $product->getTags();\n$c = count($tags);\n$str = null;\nfor ($i = 0; $i < $c; ++$i) {\n if ($str) {\n $str .= \", \";\n }\n $str .= $tags[$i]->getTag();\n}\n\n?>\n</code></pre>\n\n<p>Yes, it’s not short (and not much different to your solution) but it’s highly efficient and therefor the solution I’d go for.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T22:21:16.323",
"Id": "57340",
"Score": "0",
"body": "Also much more legible and backwards compatible as it does not rely on lambda functions +1"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T21:38:24.060",
"Id": "35253",
"ParentId": "35189",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "35194",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T17:58:22.290",
"Id": "35189",
"Score": "1",
"Tags": [
"php",
"strings"
],
"Title": "Building a string made easier?"
}
|
35189
|
Pong is an early tennis arcade game that features simple two-dimensional graphics.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T18:08:37.743",
"Id": "35191",
"Score": "0",
"Tags": null,
"Title": null
}
|
35191
|
A control structure used to loop over a set of instructions, which operates as long as a particular condition is met.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T18:52:48.960",
"Id": "35197",
"Score": "0",
"Tags": null,
"Title": null
}
|
35197
|
<p>I would like to refactor this code a bit further and make it better and more generic.</p>
<p>As of right now, it is doing what I want it to do (reading a list of URL's, splitting the query and the ampersand and writing the split into appropriately named files). However, I would like to take the hash list out and make it as generic as possible. I guess what I mean is, if the loop finds a character, read what the character is (i.e: a=12(character would be 'a')), have Python create a text file for it ('a_file.txt') and append into the newly created text file. So, there was not file there before, but there is now. And Python would do this for every character past the query (<a href="http://www.asdasd.com/asds/asd?a=6&b=12&c=123" rel="nofollow">http://www.asdasd.com/asds/asd?a=6&b=12&c=123</a> would create 'a_file.txt', 'b_file.txt', 'c_file.txt').</p>
<p>I feel as if I am asking the right question, but correct me if I am wrong.</p>
<pre><code>import urlparse
def parse_file(input_file):
tags = {tag: tag + '_file.txt' for tag in {'blog',
'p','attachment_id','lang',
'portfolio','page_id','comments_popup',
'iframe','width','height'}}
with open(input_file) as input:
for line in input:
parsed_url = urlparse.parse_qsl(urlparse.urlparse(line).query)
if parsed_url > 0:
for key, value in parsed_url:
if key in tags:
with open(tags[key], 'a') as output_file:
output_file.write(value)
else:
print key + " not in tags."
else:
print(line + " does not yield query.")
parse_file()
</code></pre>
<p>Once again, correct me if I am wrong or if my question is confusing. </p>
|
[] |
[
{
"body": "<p>This is only partly an answer, intended more as a thought exercise about what you might do. I provide a couple examples that you might want to pick and choose parts of, but you probably will not want to just grab the whole. So let's dive in.</p>\n\n<p>What would benefit from this being more general? This seems like a fairly small and specific task. I could imagine parameterizing the input, the list of tags, the mapping from tag name to file name, or the handling once a matched tag is found. Let's examine doing all at once:</p>\n\n<pre><code>import urlparse\ndef parse_queries(input, get_filename, handle, tags={'blog', 'p', ...}):\n for line in input:\n qsl = urlparse.parse_qsl(urlparse.urlparse(line).query)\n if not qsl:\n print repr(line), \"does not yield query\"\n continue\n for key, value in qsl:\n if key in tags:\n handle(get_filename(tag), value)\n else:\n print key, \"not in tags.\"\n\ndef dot_text(tag):\n return tag + '_file.txt'\n\ndef append_to_file(filename, value):\n with open(filename, 'a') as output_file:\n output_file.write(value)\n\nwith open(\"filename\") as input:\n parse_queries(input, get_filename=dot_text, handle=append_to_file)\n</code></pre>\n\n<p>Do any of these help more than they harm readability? Does extracting the small methods like <code>dot_text</code> and <code>append_to_file</code> offer useful chunks of reusable code? I'm not sure myself. It certainly makes the call harder, but providing defaults is easy enough. Thinking it through should raise other questions, such as whether <code>get_filename</code> should be part of <code>parse_queries</code>, or part of <code>handler</code>.</p>\n\n<p>Perhaps it's the line processing which could be parameterized:</p>\n\n<pre><code>def parse_file(input_file, parse):\n ...\n for line in input:\n for key, value in parse(line):\n if key in tags:\n ...\n\ndef extract_query_params(line):\n qsl = urlparse.parse_qsl(urlparse.urlparse(line).query)\n if not qsl:\n print repr(line), \"does not yield query\"\n return parsed_url\n\nparse_file(\"filename\", extract_query_params)\n</code></pre>\n\n<p>But again ask whether this helps generality more than it harms readability. I'd address other small issues first:</p>\n\n<ul>\n<li>comparing a list to 0 (<code>parsed_url > 0</code>) doesn't have much meaning.</li>\n<li><code>output_file.write(value)</code> seems unlikely to insert newlines, so your values will blur together.</li>\n<li>the name <em>tags</em> has a lot of implied meaning in an HTML context, so your use here in an HTTP context could be confusing.</li>\n<li>indentation, at least here, your with statement is at the same level as its contained for loop.</li>\n<li>unit tests; how better to verify whether this does what you want? Of course if you do want to test this, you may find that parameterizing things makes this measurably easier. Or maybe you really need to look at the resulting files.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T04:02:01.803",
"Id": "35215",
"ParentId": "35198",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T19:33:55.960",
"Id": "35198",
"Score": "0",
"Tags": [
"python",
"parsing",
"url",
"file"
],
"Title": "Reading and writing an unknown character into an appropriately named file"
}
|
35198
|
<p>In programming, annotations are used to add information to a code element which cannot be expressed by the type system.</p>
<h2>In Java</h2>
<p>Sources: <a href="http://docs.oracle.com/javase/tutorial/java/annotations/" rel="nofollow">Oracle docs</a>, <a href="http://en.wikipedia.org/wiki/Java_annotation" rel="nofollow">Wikipedia</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T20:42:21.260",
"Id": "35201",
"Score": "0",
"Tags": null,
"Title": null
}
|
35201
|
In programming, annotations are used to add information to a code element which cannot be expressed by the type system.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T20:42:21.260",
"Id": "35202",
"Score": "0",
"Tags": null,
"Title": null
}
|
35202
|
<p>I am fairly new to Python coding, although I have been coding on and off for 30ish years. I am sure I am writing Python with too much influence from the other languages, such as REXX, VB, and some Powershell.</p>
<p>Maybe I should use more functions? Please let me know where the following the code is straying from being <em>Pythonic</em>, and if it can be more efficient.</p>
<p><strong>Example 1:</strong></p>
<p>The following code was written to provide a TV guide of sorts of the latest files added to a subdirectory of my stored TV programs.</p>
<pre><code>import os
import fnmatch
import time
import datetime
tvseries=[]
currentshow="none"
thestartdate = raw_input('What Start date are you looking for YYYY-MM-DD ')
theenddate = raw_input('What End date are you looking for YYYY-MM-DD ')
for root, dir, files in os.walk("i:/Video\\tvseries\\"):
depth=root.count('\\')
if depth==2:
throway1, throwaway2, goodstuff = root.split('\\')
currentshow=goodstuff
other=">>"
elif depth==3:
throwaway1, throwaway2, goodstuff, other = root.split('\\')
for items in fnmatch.filter(files, "*"):
thecheck = os.path.join(root,items)
thecheck2 = os.path.getmtime(thecheck)
tcreatetime = str(datetime.datetime.fromtimestamp(thecheck2))
if tcreatetime[0:10] >= thestartdate and tcreatetime[0:10] <= theenddate:
tvseries.append(tcreatetime[0:10]+"|"+currentshow+"|"+other+"|"+items)
print len(tvseries), " tvseries"
tvseries.sort()
f = open("i:/Video/info/newshows.txt",'w')
f.write('New Shows added between '+thestartdate+' and '+theenddate+'\n\n')
f.write(str(len(tvseries))+' files added during this timespan'+'\n\n')
for item in tvseries:
f.write(item+'\n\n')
print item
f.close()
print "file written to disk at i:/Video/info/newshows.txt"
</code></pre>
<p><strong>Example 2: client server with sockets</strong></p>
<p>I wanted a client server example I would actually use. The "server" runs on a machine with a directory containing either Python code or some executables like IPSCAN.exe that I often need out and about to diagnose/fix problems. It waits for a connection then pushes a list of files in the directory to the client. If the client asks for it, it sends a file. It uses two different sending algorithms for .exe and everything else. I probably need to use the .exe method for PDFs as well, but I have not tried that yet.</p>
<p>The "client" runs on another machine and receives a directory list. It adds numbers to the list so the user can enter the number to receive the file. The destination directory must already exist, it is not validated by the client program. The client enters the number or the code <code>alldone</code>. If <code>alldone</code> is entered, it is passed to the server, which then shuts down (I should change the server so it just resets the socket and waits for another connection).</p>
<p><strong>Server code:</strong></p>
<pre><code># TCP Server Code this code was written in Python 2.75
# this is version 1.00 2013-11-11 please match with client versions/date for compatibility.
#If you don't bind to YOUR IP this won't work. I am doing this with fixed IP
#I should include code here incase you are on dhcp.. That adds
#complication to the client side though... what host does the client connect to?
#change to 127.0.0.1 if you want to test all on one machine
host="192.168.5.9"
port=4440
from socket import *
import os
import fnmatch
import time
import datetime
s=socket(AF_INET, SOCK_STREAM)
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind((host,port))
s.listen(1)
print "Listening for connections.. "
q,addr=s.accept()
print "Established connection to client at ", addr
data = "nope"
thecmd = "nutin"
while thecmd != "alldone":
filelist=[]
for root, dir, files in os.walk("d:/Sendfiles\\"):
for items in fnmatch.filter(files, "*"):
thecheck = os.path.join(root,items)
thecheck2 = os.path.getmtime(thecheck)
tcreatetime = str(datetime.datetime.fromtimestamp(thecheck2))
filelist.append(tcreatetime[0:10]+"|"+items)
print "File List requested by client"
for items in filelist:
theitem = items.ljust(100)
q.send(theitem)
q.send("Close")
print "File List sent to client"
thecmd = q.recv(7)
thecmd = thecmd.strip(' ')
if thecmd != "alldone":
thenum = int(thecmd)
theentry = filelist[thenum-1]
thedate, thefile = theentry.split("|")
theopenfile = "d:/Sendfiles/"+thefile
if thefile[len(thefile)-3:]=='exe':
sendfile = "@@XF"+thefile
sendfile = sendfile.ljust(500)
q.send(sendfile)
print "Sending EXE File ... ",thefile
f = open(theopenfile,'rb')
while True:
theline = f.read(500)
if theline:
q.send(theline)
else:
break
else:
sendfile = "@@TF"+thefile
sendfile = sendfile.ljust(500)
q.send(sendfile)
print "Sending Text File ... ",thefile
f=open(theopenfile,'r')
for line in f:
theline = line.strip('\n')
theline = theline.ljust(500)
q.send(theline)
f.close()
print "File Sent"
q.send("Done")
q.recv(8)
print "Service Shutdown requested by client "
print "Service shutting down..."
q.close()
</code></pre>
<p><strong>Client code:</strong></p>
<pre><code># TCP Client Code This script was written with python 2.75
# this is version 1.00 2013-11-11 please match with server versions/date for compatibility :)
from socket import *
#change this to 127.0.0.1 if want to test the client and server on the same machine
#note you need to start two python environmetns to make this work and run the client
#in one and the server in another. After starting the first one (windows environment
#just hold shift and single left click on the running one to start another :)
host="192.168.5.9"
port=4440
s=socket(AF_INET, SOCK_STREAM)
s.connect((host,port))
thecommand="notdone"
while thecommand != "alldone":
tfc=1
msg="Nope"
while msg<>'Close':
msg=s.recv(100)
msg = msg.strip(' ')
if msg != "Close":
print tfc,") ",msg,'\n'
tfc=tfc+1
thecommand = raw_input(' Please enter a file # to recieve or "alldone" to end ')
if thecommand=="":
thecommand="alldone"
if thecommand != "alldone":
sendit = str(thecommand).ljust(7)
s.send(sendit)
tgetit="notdone"
print "Getting file from server "
xfertype="?"
while tgetit != "Done":
tgetit=s.recv(500)
thechunk = len(tgetit)
if tgetit[0:4]=="@@XF":
thefile = tgetit[4:].strip(' ')
xfertype="E"
print "Start recieving EXE file ",thefile
f=open(thefile,'wb')
elif tgetit[0:4]=="@@TF":
thefile = tgetit[4:].strip(' ')
xfertype="T"
print "Start recieving TXT file ",thefile
f=open(thefile,'w')
elif tgetit[0:4]=="Done":
tgetit = "Done"
f.close()
print "\nLast bit of file was length of ",thechunk
print "\nFinished receiving file ",thefile
print "\nNote that the file is saved where this python file is executed from"
dummy=raw_input("Press enter to continue ")
s.send("Continue")
else:
if xfertype=="T":
tgetit=tgetit.strip(' ')
tgetit=tgetit+'\n'
if thechunk>0:
f.write(tgetit)
else:
s.send("alldone")
print "Thanks for using the python file transfer program"
print "\nService now shutting down ...."
s.close()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T22:42:04.450",
"Id": "56974",
"Score": "8",
"body": "If you have two separate pieces of code to review, I think you should post them as two separate posts."
}
] |
[
{
"body": "<p>Where are your functions? I see three large chunks of loops and if/elif/else blocks, but absolutely 0 functions.</p>\n\n<p>Just because python is a scripting language, doesn't mean you should treat it as one. This is a piece of work that you created, not a one-off script that you will throw away afterwards. Put some effort and refactor pieces of it into functions.</p>\n\n<p>I say this because your code is completely unsupportable. It may be readable to you, but as soon as you give it to someone else, they are lost. Bear in mind, that might be you in the future, looking at the code you wrote weeks/months/years before.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T13:55:31.997",
"Id": "35834",
"ParentId": "35203",
"Score": "2"
}
},
{
"body": "<h3>Coding style</h3>\n\n<p>Python has an official style guide called <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a>.\nPlease follow it,\nand the code will become more <em>pythonic</em>, as you wished, and easier to read for everyone.</p>\n\n<h3>Naming</h3>\n\n<p>In this code:</p>\n\n<blockquote>\n<pre><code>throway1, throwaway2, goodstuff = root.split('\\\\')\n</code></pre>\n</blockquote>\n\n<p>\"goodstuff\" is poorly named as it doesn't help the reader understand its purpose.</p>\n\n<p>While it's clear that \"throway1\" (with a typo) and \"throwaway2\" are things to be ignored,\nthey indicate a code smell, as throwing things away sounds wasteful.\nCode smell like this indicates that probably there's a better way of doing it.</p>\n\n<h3>Handling multiple depths</h3>\n\n<p>Instead of handling the different depths like this:</p>\n\n<blockquote>\n<pre><code>if depth==2:\n throway1, throwaway2, goodstuff = root.split('\\\\')\n currentshow=goodstuff\n other=\">>\"\nelif depth==3:\n throwaway1, throwaway2, goodstuff, other = root.split('\\\\')\n</code></pre>\n</blockquote>\n\n<p>I suggest something like this:</p>\n\n<pre><code>parts = root.split('\\\\')\nif depth == 2:\n currentshow = parts[2]\n other = \">>\"\nelif depth == 3:\n currentshow = parts[2]\n other = parts[3]\n</code></pre>\n\n<p>Notice that the strange and unused \"throwaway1\", \"throwaway2\" just went away.</p>\n\n<h3>Working with files</h3>\n\n<p>Instead of this:</p>\n\n<blockquote>\n<pre><code>f = open(\"i:/Video/info/newshows.txt\",'w')\nf.write(...)\n# ...\nf.close()\n</code></pre>\n</blockquote>\n\n<p>The recommended, safer way to write is using <code>with</code>:</p>\n\n<pre><code>with open(\"i:/Video/info/newshows.txt\",'w') as f:\n f.write(...)\n # ...\n</code></pre>\n\n<p>Notice that <code>f.close()</code> is no longer necessary,\nPython will automatically call it when leaving the scope of <code>with</code>,\nso it's guaranteed you'll never forget to call it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-23T18:26:33.910",
"Id": "114901",
"ParentId": "35203",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T20:45:00.570",
"Id": "35203",
"Score": "-5",
"Tags": [
"python",
"beginner",
"networking",
"file-system"
],
"Title": "TV guide program and client server with sockets"
}
|
35203
|
<p>I am new to database design but am fairly familiar with SQL and its syntax. I want to create a database for an e-commerce website that will sell a single product type such as a shirt. They could be different sizes, colors, and design. I formulated list of information I thought would be necessary to collect from a visitor and are included in the tables I made.</p>
<p>Right now I have tables being:</p>
<ul>
<li><code>Products</code></li>
<li><code>Customer</code></li>
<li><code>Credit_Card_Details</code></li>
<li><code>Order_Details</code></li>
<li><code>State_tax</code></li>
<li><code>Shopping_Cart</code></li>
<li><code>Purchase_history</code></li>
<li><code>Shipping type</code></li>
</ul>
<p>The tables I created:</p>
<pre><code> CREATE TABLE `shipping_type`
(
`type_of_shipping` VARCHAR(30) NOT NULL DEFAULT '',
`price` DOUBLE(6, 2) NOT NULL,
`aprox_delivery` INT(11) NOT NULL,
PRIMARY KEY (`type_of_shipping`)
)
engine=innodb
DEFAULT charset=latin1;
CREATE TABLE `shopping_cart`
(
`shopping_cart_id` INT(11) UNSIGNED NOT NULL auto_increment,
`inventory_id` VARCHAR(11) NOT NULL DEFAULT '',
`price` DOUBLE(6, 2) NOT NULL,
`date` DATE NOT NULL,
`user_id` VARCHAR(30) NOT NULL DEFAULT '',
`quantity` INT(11) NOT NULL,
PRIMARY KEY (`shopping_cart_id`)
)
engine=innodb
DEFAULT charset=latin1;
CREATE TABLE `state_tax`
(
`state_name` VARCHAR(11) NOT NULL DEFAULT '',
`sales_tax_rate` DOUBLE(6, 2) NOT NULL,
PRIMARY KEY (`state_name`)
)
engine=innodb
DEFAULT charset=latin1;
CREATE TABLE `purchase_history`
(
`user_id` VARCHAR(30) NOT NULL DEFAULT '',
`inventory_id` INT(11) NOT NULL,
`date_ordered` DATE NOT NULL,
`order_id` INT(11) NOT NULL,
`quantity` INT(11) NOT NULL,
`price` DOUBLE(6, 2) NOT NULL,
PRIMARY KEY (`user_id`)
)
engine=innodb
DEFAULT charset=latin1;
CREATE TABLE `products`
(
`inventory_id` INT(11) UNSIGNED NOT NULL auto_increment,
`shirt_name` VARCHAR(50) NOT NULL DEFAULT '',
`shirt_size` VARCHAR(30) NOT NULL DEFAULT '',
`shirt_color` INT(11) NOT NULL,
`price` DOUBLE(6, 2) NOT NULL,
PRIMARY KEY (`inventory_id`)
)
engine=innodb
DEFAULT charset=latin1;
CREATE TABLE `order_details`
(
`order_id` INT(11) UNSIGNED NOT NULL auto_increment,
`user_id` VARCHAR(30) NOT NULL DEFAULT '',
`reciever_name` VARCHAR(100) NOT NULL DEFAULT '',
`address` VARCHAR(30) NOT NULL DEFAULT '',
`city` VARCHAR(30) NOT NULL DEFAULT '',
`zip` VARCHAR(11) NOT NULL DEFAULT '',
`state` VARCHAR(30) NOT NULL DEFAULT '',
`type_of_shipping` VARCHAR(30) NOT NULL DEFAULT '',
`date_ordered` DATE NOT NULL,
PRIMARY KEY (`order_id`)
)
engine=innodb
DEFAULT charset=latin1;
CREATE TABLE `customer`
(
`user_id` VARCHAR(30) NOT NULL DEFAULT '',
`password` VARCHAR(30) NOT NULL DEFAULT '',
`fname` VARCHAR(30) NOT NULL DEFAULT '',
`lname` VARCHAR(30) NOT NULL DEFAULT '',
`email` VARCHAR(30) NOT NULL DEFAULT '',
`address` VARCHAR(30) NOT NULL DEFAULT '',
`city` VARCHAR(30) NOT NULL DEFAULT '',
`zip` INT(11) NOT NULL,
`state` VARCHAR(30) NOT NULL DEFAULT '',
`phone number` VARCHAR(11) DEFAULT NULL,
PRIMARY KEY (`user_id`)
)
engine=innodb
DEFAULT charset=latin1;
CREATE TABLE `credit_card_details`
(
`cc_num` VARCHAR(30) NOT NULL DEFAULT '',
`card_type` VARCHAR(30) NOT NULL DEFAULT '',
`sec_code` INT(3) NOT NULL,
`exp_date` DATE NOT NULL,
`user_id` VARCHAR(30) NOT NULL DEFAULT '',
PRIMARY KEY (`cc_num`)
)
engine=innodb
DEFAULT charset=latin1;
</code></pre>
<p>Is this the most efficient way to do this? I am pretty sure all tables would be in third normal form, and all can be linked. If this is not the correct way to do this, could somebody please point out to me what I could be doing differently to improve my design or how to implement this design in a better way?</p>
|
[] |
[
{
"body": "<p>You need to add foreign keys that reference the primary keys of the tables they are linked to. </p>\n\n<p>I don't usually do a whole lot with building the actual tables but I know that you are missing the foreign keys.</p>\n\n<p>In this Table:</p>\n\n<blockquote>\n<pre><code>CREATE TABLE `shipping_type` \n( \n `type_of_shipping` VARCHAR(30) NOT NULL DEFAULT '', \n `price` DOUBLE(6, 2) NOT NULL, \n `aprox_delivery` INT(11) NOT NULL, \n PRIMARY KEY (`type_of_shipping`) \n) \nengine=innodb \nDEFAULT charset=latin1;\n</code></pre>\n</blockquote>\n\n<p><code>type_of_shipping</code> is not a good primary key here. You should have a generic Table ID that is auto incremented and unique, so that each record has a unique ID on that table.</p>\n\n<p>This table also needs a Table ID column:</p>\n\n<blockquote>\n<pre><code>CREATE TABLE `state_tax` \n( \n `state_name` VARCHAR(11) NOT NULL DEFAULT '', \n `sales_tax_rate` DOUBLE(6, 2) NOT NULL, \n PRIMARY KEY (`state_name`) \n) \nengine=innodb \nDEFAULT charset=latin1;\n</code></pre>\n</blockquote>\n\n<p>Even though <code>state_name</code> will be unique and isn't doubled up when you create the table, you still need a table ID for a table like this. If the table ever grows there is the possibility for duplicates in that column. It's not good practice to write those two tables the way that you have them.</p>\n\n<p>The <code>Password</code> column in your <code>Customers</code> table needs to be encrypted. <a href=\"http://mysqldatabaseadministration.blogspot.com/2006/08/storing-passwords-in-mysql.html\" rel=\"nofollow\">This blog post</a> looks like it talks about hashing and storing the password.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-17T18:48:18.553",
"Id": "35545",
"ParentId": "35204",
"Score": "6"
}
},
{
"body": "<ol>\n<li><p>Never assume that you're only going to have one product. That will end up being a limiting factor of your design and can cause you a lot of pain later down the line and rules out any kind of code re-usability. Make your products table generic enough to handle any kind of product. Create color/size attribute tables that you can tie to the product if you need to. </p></li>\n<li><p>What about handling the case where people want to order as a guest or will you rule that out entirely?</p></li>\n<li><p>How will you handle returned items/payment credits, cancelled orders, or an order where the credit card is declined? Are you going to keep history for those?</p></li>\n<li><p>You will probably need more than 1 line for address. Are you going to handle international orders? If so you'll need to allow for non-numerical zip codes and ones that don't tie to a state.</p></li>\n<li><p>If you tie shopping carts to cookies then you can reload someone's shopping cart when they come back based on their cookie's ID.</p></li>\n<li><p>If you're going to keep credit card numbers in the database then you need to be PCI Compliant (<a href=\"https://www.pcisecuritystandards.org/\">https://www.pcisecuritystandards.org/</a>).</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T21:01:57.690",
"Id": "57751",
"Score": "1",
"body": "Since this is for a school assignment we were given guidelines. 1 product is to be assumed (Im guessing he will show us why this is bad and how to fix it later) 2.) We are to rule guest out 3.) Will look into this. 4.) Ill add addressline2, No international customers ( ill remove country) 5.) we are told we will do this with sessions later on. and 6.) creditcards at this point we just want them to enter directly. (Again we will go over encrypt methods at a later date)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T20:58:47.973",
"Id": "35589",
"ParentId": "35204",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "35545",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T20:55:00.887",
"Id": "35204",
"Score": "4",
"Tags": [
"beginner",
"sql",
"mysql",
"e-commerce"
],
"Title": "E-commerce database design"
}
|
35204
|
<p>The task is to add data or values to members of a given <code>enum</code> class. The compiler should check if a value for each <code>enum</code> member is available, and not just the default constructor empty values. It is a tool to verify that no values are forgotten during a change.</p>
<p>The interface is modeled after the array of enumeration type in Delphi/Pascal which I find very useful.</p>
<p>Since I'm interested to learn about library design, I guess the interface is the important part:</p>
<pre><code>template<typename Enum, typename T>
class enum_array {
public:
typedef typename std::array<T, enum_length<Enum>::result>::const_iterator
const_iterator;
typedef typename std::array<T, enum_length<Enum>::result>::iterator iterator;
typedef T value_type;
//--------------------------------------
template<typename ... Args>
enum_array(Args ... list);
//--------------------------------------
template<typename otherEnum>
enum_array(const enum_array<otherEnum, value_type> &other );
//--------------------------------------
template<typename otherEnum>
enum_array(enum_array<otherEnum, value_type> &&other );
//--------------------------------------
template<typename otherEnum>
enum_array<Enum, value_type>& operator= (const enum_array<otherEnum, value_type> &other);
//--------------------------------------
template<typename otherEnum>
enum_array<Enum, value_type>& operator= (enum_array<otherEnum, value_type> &&other);
//--------------------------------------
constexpr size_t size() const;
//--------------------------------------
// read values
const value_type& at(int index) const;
const value_type& operator[](int index) const;
const value_type& at(Enum type) const;
const value_type& operator[](Enum type) const;
value_type& at(int index);
value_type& operator[](int index);
value_type& at(Enum type);
value_type& operator[](Enum type);
//--------------------------------------
// write values
void set_value(int index, const value_type &value);
void set_value(Enum type, const value_type &value);
//--------------------------------------
// iterator access
iterator begin();
iterator end();
const_iterator begin() const;
const_iterator end() const;
//--------------------------------------
// algorithms
Enum find(const value_type &value) const;
Enum find(const value_type &value, Enum default_value) const;
};
</code></pre>
<p>I provided copy and move constructors, and assignment operators, with the compile time checks mentioned above, as well as value and iterator access. </p>
<p>To have it working, one needs to publish the size of an <code>enum</code> class which is done by these two macros:</p>
<pre><code>#define DEF_ENUM(name, ...) \
enum class name : uint8_t { __VA_ARGS__ }; \
SETUP_ENUM_LENGTH(name, BOOST_PP_VARIADIC_SIZE(__VA_ARGS__))
#define SETUP_ENUM_LENGTH(enum_type, length) \
template<> struct enum_length<enum_type> { enum { result = length }; };
</code></pre>
<p>A use case looks like this:</p>
<pre><code>DEF_ENUM(Columns, name, address, city, country)
// Does not compile, and tells you that the count is not right.
enum_array<Columns, std::string> Columntitle_bad {"Name", "Address", "City"};
// Compiles.
enum_array<Columns, std::string> Columntitle {"Name", "Address", "City", "Country"};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T23:10:58.037",
"Id": "56978",
"Score": "4",
"body": "One common solution for this kind of problems is to use [X-macros](http://en.wikipedia.org/wiki/X_Macro). Well used, you know that the number of elements will be the same."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T23:40:30.760",
"Id": "56980",
"Score": "2",
"body": "@Morwenn: Thank you, I didn't know this idiom. However, to me it doesn't seem very save or natural compared to a enum value. At least not like we want modern C++11 to be."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T03:15:52.093",
"Id": "56995",
"Score": "4",
"body": "Sounds like you're looking for [n3815](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3815.html) or maybe the more general [n3814](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3814.html) to become real. (See also [isocpp](http://isocpp.org/blog/2013/10/n3814)'s [mention](http://isocpp.org/blog/2013/10/n3815))"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-01T15:53:24.907",
"Id": "226414",
"Score": "0",
"body": "To my eyes this looks like what Java has for its enums which can have data members and methods, is this correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-03-28T18:52:21.810",
"Id": "301498",
"Score": "6",
"body": "There is actually nothing here to review. The actual code is missing as are some other parts like the definition of `enum_length`.Voting to close."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-10-23T14:02:35.167",
"Id": "339048",
"Score": "0",
"body": "Two thoughts. First, since you're in C++11, you could do `template<> struct enum_length<enum_type> { static constexpr size_t result = length; }`. It generally doesn't matter, but it's a little more explicit. Maybe also name `result` to `value` (like what `std::true_type` etc do). Second: you can't assume `uint8_t` is big enough for all enums. Since you're already using `BOOST_PP`, go for gold!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-30T15:40:45.267",
"Id": "366310",
"Score": "3",
"body": "This question was discussed on [meta](https://codereview.meta.stackexchange.com/questions/8726/why-is-building-a-good-c11-template-library-compile-time-checked-enum-array/8727#8727)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T22:34:32.510",
"Id": "35208",
"Score": "20",
"Tags": [
"c++",
"c++11",
"library",
"enum",
"template-meta-programming"
],
"Title": "Building a good C++11 template library - compile-time checked enum array"
}
|
35208
|
<p>This program takes blank spaces before some chars like > < />, and if there is more than one blank space in the line, it will reduce to one.</p>
<pre><code>return source.replaceAll("\\s{2,}", " ").replaceAll("[[\\>][\\s]][[\\s][\\>]]", ">").replaceAll("[[\\<][\\s]][[\\s][\\<]]", "<").replaceAll("[\\s][/>]", "/>");
</code></pre>
<p>How can I improve my regex code?</p>
<p>My test code is:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<nfeProc xmlns="http://www.portalfiscal.inf.br/nfe" versao="2.00" >
<NFe xmlns="http://www.portalfiscal.inf.br/nfe"><infNFe Id="NFe31130821483359001109550010002217051649842350" versao="2.00"><ide><cUF>31</cUF><cNF>64984235</cNF><natOp>VENDA PROD.ESTAB.SUBST.TRIBUTA</natOp><indPag>1</indPag><mod>55</mod><serie>1</serie><nNF>221705</nNF><dEmi>2013-08-07</dEmi><dSaiEnt>2013-08-07</dSaiEnt><tpNF>1</tpNF><cMunFG>3147105</cMunFG><tpImp>2</tpImp><tpEmis>1</tpEmis><cDV>0</cDV><tpAmb>1</tpAmb><finNFe>1</finNFe><procEmi>0</procEmi><verProc>4.0.0.36</verProc></ide><emit><CNPJ>21483359001109</CNPJ><xNome>COOPERATIVA DOS GRANJEIROS DO OESTE DE MINAS LTDA</xNome><xFant>ABATEDOURO</xFant><enderEmit><xLgr>Rod RODOVIA BR 262</xLgr><nro>S/N</nro><xCpl>KM - 402</xCpl><xBairro>POVOADO GOMES</xBairro><cMun>3147105</cMun><xMun>PARA DE MINAS</xMun><UF>MG</UF><CEP>35661470</CEP><cPais>1058</cPais><xPais>Brasil</xPais><fone>03732365566</fone></enderEmit><IE>4713164920659</IE><CRT>3</CRT></emit><dest><CNPJ>07121048000105</CNPJ><xNome>SUPERMERCADO SAFRA LTDA</xNome><enderDest><xLgr>RUA TEOFILO ANDRADE</xLgr><nro>7</nro><xBairro>CENTRO</xBairro><cMun>3121407</cMun><xMun>DESTERRO DE ENTRE RIOS</xMun><UF>MG</UF><CEP>35494000</CEP><cPais>1058</cPais><xPais>Brasil</xPais><fone>3137361535</fone></enderDest><IE>2142099300090</IE></dest><det nItem="1"><prod><cProd>11007</cProd><cEAN>7898296060227</cEAN><xProd>COXA S/ COXA FRANGO CONGELADO CX. 20KG</xProd><NCM>02071400</NCM><EXTIPI>00</EXTIPI><CFOP>5401</CFOP><uCom>KG</uCom><qCom>100</qCom><vUnCom>3.7</vUnCom><vProd>370.00</vProd><cEANTrib>7898296060227</cEANTrib><uTrib>KG</uTrib><qTrib>100</qTrib><vUnTrib>3.7</vUnTrib><indTot>1</indTot><xPed>103197</xPed><nItemPed>3</nItemPed></prod><imposto><ICMS><ICMS70><orig>0</orig><CST>70</CST><modBC>3</modBC><pRedBC>61.11</pRedBC><vBC>143.89</vBC><pICMS>18.00</pICMS><vICMS>25.90</vICMS><modBCST>4</modBCST><pMVAST>15.00</pMVAST><pRedBCST>0.39</pRedBCST><vBCST>165.48</vBCST><pICMSST>18.00</pICMSST><vICMSST>3.89</vICMSST></ICMS70></ICMS><IPI><cEnq>999</cEnq><IPINT><CST>53</CST></IPINT></IPI><PIS><PISNT><CST>06</CST></PISNT></PIS><COFINS><COFINSNT><CST>06</CST></COFINSNT></COFINS></imposto><infAdProd>7898296060227 -</infAdProd></det><det nItem="2"><prod><cProd>11046</cProd><cEAN>7898296060173</cEAN><xProd>FRANGO CONGELADO CX. 20KG</xProd><NCM>02071200</NCM><EXTIPI>00</EXTIPI><CFOP>5401</CFOP><uCom>KG</uCom><qCom>200</qCom><vUnCom>3</vUnCom><vProd>600.00</vProd><cEANTrib>7898296060173</cEANTrib><uTrib>KG</uTrib><qTrib>200</qTrib><vUnTrib>3</vUnTrib><indTot>1</indTot><xPed>103197</xPed><nItemPed>1</nItemPed></prod><imposto><ICMS><ICMS70><orig>0</orig><CST>70</CST><modBC>3</modBC><pRedBC>61.11</pRedBC><vBC>233.34</vBC><pICMS>18.00</pICMS><vICMS>42.00</vICMS><modBCST>4</modBCST><pMVAST>15.00</pMVAST><pRedBCST>0.39</pRedBCST><vBCST>268.34</vBCST><pICMSST>18.00</pICMSST><vICMSST>6.30</vICMSST></ICMS70></ICMS><IPI><cEnq>999</cEnq><IPINT><CST>53</CST></IPINT></IPI><PIS><PISNT><CST>06</CST></PISNT></PIS><COFINS><COFINSNT><CST>06</CST></COFINSNT></COFINS></imposto><infAdProd>7898296060173 -</infAdProd></det><det nItem="3"><prod><cProd>11004</cProd><cEAN>7898296060203</cEAN><xProd>PEITO FRANGO CONGELADO CX. 20 KG</xProd><NCM>02071400</NCM><EXTIPI>00</EXTIPI><CFOP>5401</CFOP><uCom>KG</uCom><qCom>100</qCom><vUnCom>3.9</vUnCom><vProd>390.00</vProd><cEANTrib>7898296060203</cEANTrib><uTrib>KG</uTrib><qTrib>100</qTrib><vUnTrib>3.9</vUnTrib><indTot>1</indTot><xPed>103197</xPed><nItemPed>4</nItemPed></prod><imposto><ICMS><ICMS70><orig>0</orig><CST>70</CST><modBC>3</modBC><pRedBC>61.11</pRedBC><vBC>151.67</vBC><pICMS>18.00</pICMS><vICMS>27.30</vICMS><modBCST>4</modBCST><pMVAST>15.00</pMVAST><pRedBCST>0.39</pRedBCST><vBCST>174.42</vBCST><pICMSST>18.00</pICMSST><vICMSST>4.10</vICMSST></ICMS70></ICMS><IPI><cEnq>999</cEnq><IPINT><CST>53</CST></IPINT></IPI><PIS><PISNT><CST>06</CST></PISNT></PIS><COFINS><COFINSNT><CST>06</CST></COFINSNT></COFINS></imposto><infAdProd>7898296060203 -</infAdProd></det><total><ICMSTot><vBC>528.90</vBC><vICMS>95.20</vICMS><vBCST>608.24</vBCST><vST>14.29</vST><vProd>1360.00</vProd><vFrete>0.00</vFrete><vSeg>0.00</vSeg><vDesc>0.00</vDesc><vII>0.00</vII><vIPI>0.00</vIPI><vPIS>0.00</vPIS><vCOFINS>0.00</vCOFINS><vOutro>0.00</vOutro><vNF>1374.29</vNF></ICMSTot></total><transp><modFrete>0</modFrete><transporta><CNPJ>21483359001109</CNPJ><xNome>COOPERATIVA DOS GRANJEIROS DO OESTE DE MINAS LTDA ABATEDOURO</xNome><IE>4713164920659</IE><xEnder>Rod RODOVIA BR 262 N. S/N KM - 402</xEnder><xMun>PARA DE MINAS</xMun><UF>MG</UF></transporta><veicTransp><placa>HIH2860</placa><UF>MG</UF></veicTransp><vol><qVol>500</qVol><esp>VOLUMES</esp><pesoL>400.000</pesoL><pesoB>400.000</pesoB></vol></transp><cobr><fat><nFat>221705</nFat><vOrig>1374.29</vOrig><vLiq>1374.29</vLiq></fat><dup><nDup>000221705-01</nDup><dVenc>2013-08-28</dVenc><vDup>1374.29</vDup></dup></cobr><infAdic><infAdFisco>REDUCAO DE 61,11% CONF LETRA A1 ITEM 19 DA - PARTE 1 DO ANEXO IV RICMS 43.080/02 - E C/ COBRANCA POR ST - -</infAdFisco><infCpl>ORDEM DE CARGA: 18313</infCpl></infAdic></infNFe><Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo><CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /><SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /><Reference URI="#NFe31130821483359001109550010002217051649842350"><Transforms><Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" /><Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /></Transforms><DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /><DigestValue>JOjHIJzegFkL7ZfGkfAgSwP0+s4=</DigestValue></Reference></SignedInfo><SignatureValue>Qvsom1D+sQZdrq9Y5rfMCEDBUPeRD5iToj3prhoUh0Mfy1zR0dLzTIyp56qIGsPXYogheRuR9PQVzqEc3AK5alK3tkEf+T+zYz3F/xAb7Fyo+/txye625R0D4zm23xvINlLcg0Jhs4S+OIwvDjkX6ICD/bQbP0U55mhqSW71hAYzHkRWiitmy5MJQ00YphvPBw2ikaHrFEy8cy/gYxzs3HWOHHk51AavnhQ/eqK2VcJP7NTAXeECJniz21tVE3CwzLLCRqJhm8nNAsVt8zwV0BTX0nk4osW4GtGUgQWuF5u3roHdYNfNn3MVVdV1OBr3JHHVV8RwyFpWuX6ZuQTI0g==</SignatureValue><KeyInfo><X509Data><X509Certificate>MIIHtjCCBZ6gAwIBAgIQMjAxMjEyMDQxMDI2NTI3MzANBgkqhkiG9w0BAQsFADCBijELMAkGA1UEBhMCQlIxEzARBgNVBAoTCklDUC1CcmFzaWwxNjA0BgNVBAsTLVNlY3JldGFyaWEgZGEgUmVjZWl0YSBGZWRlcmFsIGRvIEJyYXNpbCAtIFJGQjEuMCwGA1UEAxMlQXV0b3JpZGFkZSBDZXJ0aWZpY2Fkb3JhIFNFUlBST1JGQiB2MzAeFw0xMjEyMDQxMzE5NTdaFw0xMzEyMDQxMjExNDRaMIIBCjELMAkGA1UEBhMCQlIxEzARBgNVBAoTCklDUC1CcmFzaWwxNjA0BgNVBAsTLVNlY3JldGFyaWEgZGEgUmVjZWl0YSBGZWRlcmFsIGRvIEJyYXNpbCAtIFJGQjERMA8GA1UECxMIQ09SUkVJT1MxEzARBgNVBAsTCkFSQ09SUkVJT1MxFjAUBgNVBAsTDVJGQiBlLUNOUEogQTExFjAUBgNVBAcTDVBBUkEgREUgTUlOQVMxCzAJBgNVBAgTAk1HMUkwRwYDVQQDE0BDT09QRVJBVElWQSBET1MgR1JBTkpFSVJPUyBETyBPRVNURSBERSBNSU5BUyBMVERBOjIxNDgzMzU5MDAwMTM3MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1Az+l21IUDupjr82IL5wM4ciBz2hI5tRil65M86plIyewjws8Cdx7XcxG/lO43SzlgTIb6q9xrDWFSIvpSG10GzDmrFzgstaAs3gPlMIy/xanulswB3Tp3Yyf9S+E5CUUCoaOwpMn2ww4jhEs0oae7CEFqDRHA3CTDST+f+qs7E6J/V/5oonPIBJxo0B8SHGBQ1iMNWw9UH+OVyCoBp1ma3lcfBhDdqTsJEkEPtFJEn47oxNDWqgoJnjHgViUhACS8LRKNWbN2lmmjwaEuHSYHg7JOgCaU9LohvCd6L46OziH+e3BP/HijblVx5WnN4yQHsXKP6P0mTojWBVq7uFawIDAQABo4ICkzCCAo8wDAYDVR0TAQH/BAIwADAfBgNVHSMEGDAWgBSxZ7Ed5xyud0IUrX+eCQ7mhbC3rjAOBgNVHQ8BAf8EBAMCBeAwYAYDVR0gBFkwVzBVBgZgTAECAQowSzBJBggrBgEFBQcCARY9aHR0cHM6Ly9jY2Quc2VycHJvLmdvdi5ici9hY3NlcnByb3JmYi9kb2NzL2RwY2Fjc2VycHJvcmZiLnBkZjCBtgYDVR0RBIGuMIGroDgGBWBMAQMEoC8ELTIyMDcxOTQ5MTYyNTY3MzU2NjgwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMKAgBgVgTAEDAqAXBBVBTlRPTklPIERFIE1FTE8gU0lMVkGgGQYFYEwBAwOgEAQOMjE0ODMzNTkwMDAxMzegFwYFYEwBAwegDgQMMDAwMDAwMDAwMDAwgRlpbmZvcm1hdGljYUBjb2dyYW4uY29tLmJyMCAGA1UdJQEB/wQWMBQGCCsGAQUFBwMCBggrBgEFBQcDBDCBwAYDVR0fBIG4MIG1MDSgMqAwhi5odHRwOi8vY2NkLnNlcnByby5nb3YuYnIvbGNyL2Fjc2VycHJvcmZidjMuY3JsMDWgM6Axhi9odHRwOi8vY2NkMi5zZXJwcm8uZ292LmJyL2xjci9hY3NlcnByb3JmYnYzLmNybDBGoESgQoZAaHR0cDovL3JlcG9zaXRvcmlvLmljcGJyYXNpbC5nb3YuYnIvbGNyL3NlcnByby9hY3NlcnByb3JmYnYzLmNybDBOBggrBgEFBQcBAQRCMEAwPgYIKwYBBQUHMAKGMmh0dHA6Ly9jY2Quc2VycHJvLmdvdi5ici9jYWRlaWFzL2Fjc2VycHJvcmZidjMucDdiMA0GCSqGSIb3DQEBCwUAA4ICAQCv4rUWP0AkysbiVpsrnJFI3Z7TPeKsNeuAIQgTtV9HY7Mq3wmorcZmvidxb1spBp7/7HJuXUO2FmWO4/pCHijYtKQ68o5LxAZ1jswQlrHMEyTbfLi7Y2iN/C7cR2KDg/TG7CxzNrVgJvw+vMHngaNUfqHzBUz++kLtynjXGxiSOg/4RfTP82zkfqdT1sisVNw3n1ZyZpOGAkWAyv8kjsBPKUZlL+lfDYrf9clr9JUSA4UI91cxYMQubFAPvXBKe18OPGZ1P2SINJpwiH/K2MHb7OIydln4Y+vfmoVq/lVwFbmqZNCGRbncv5ZU/qhybmeHyL1P0af1edDmV2kWB6CNDVaUE4KI+Zm3TJwYvC3aasYULvgb+cG1qvh5i+D/VzN+x/ue2x/8KMMGgEhK/OqojES3RGy9ALjz+1QOQbkIo8Yv3/Ram0HcMBRGMdjn68EubyZCPw13ipCjeSTxhLokrFsSiaMjN805wHLoa7IS7KZhR7IjM8RmRP8/SV3lqE4xi8LWe718Ef6olLwPAYWMLD/dPqtCNXdQvZ6M0a0mWfjLx1bbMIbetp9J4pdcr4aAON2lL194ilX6q4g93RktJJAsygJHo7GwiNf89IpuOMz5AT5tDGAV7V4+J2ObSCzIVz8QJClKTuc9+xcbtCHI37T7XREcG+JAOQaBJYvMng==</X509Certificate></X509Data></KeyInfo></Signature></NFe>
<protNFe xmlns="http://www.portalfiscal.inf.br/nfe" versao="2.00"><infProt><tpAmb>1</tpAmb><verAplic>13_0_94</verAplic><chNFe>31130821483359001109550010002217051649842350</chNFe><dhRecbto>2013-08-07T01:52:47</dhRecbto><nProt>131131174998806</nProt><digVal>JOjHIJzegFkL7ZfGkfAgSwP0+s4=</digVal><cStat>100</cStat><xMotivo>Autorizado o uso da NF-e</xMotivo></infProt></protNFe>
</nfeProc>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T00:16:49.367",
"Id": "56982",
"Score": "7",
"body": "Why do you need this? If you have a decent XML-parser then does it really matter how many spaces there are before `>`-characters? Because you **DO** use a XML-parser to parse your XML data, don't you?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T11:50:51.063",
"Id": "57006",
"Score": "0",
"body": "because some documents have `\\n` and I want to take it off."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T12:33:00.780",
"Id": "57009",
"Score": "2",
"body": "Why? What harm has `\\n` ever done to you?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T13:44:08.790",
"Id": "57017",
"Score": "0",
"body": "can brake the string sequence"
}
] |
[
{
"body": "<p>This will suffice:</p>\n\n<pre><code>source.replaceAll(\"\\\\s+([<> ]|/>)\", \"$1\");\n</code></pre>\n\n<p><img src=\"https://www.debuggex.com/i/di6o0MQJ9GZe1NlZ.png\" alt=\"Regular expression visualization\"></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T13:48:16.813",
"Id": "57018",
"Score": "1",
"body": "I know this is pretty simple but would you please try to explain it a little bit?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T13:50:08.527",
"Id": "57019",
"Score": "0",
"body": "\\O/ so fine, could you suggest to me some reading to know about regex?\n\nBecause I want to know about `$1` and how do you generate this image?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T14:07:09.860",
"Id": "57021",
"Score": "0",
"body": "@DiegoMacario For more reading about regex, see http://www.regular-expressions.info"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T13:13:45.480",
"Id": "35228",
"ParentId": "35210",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "35228",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-11T23:47:28.887",
"Id": "35210",
"Score": "1",
"Tags": [
"java",
"regex",
"xml"
],
"Title": "Reducing number of blank spaces"
}
|
35210
|
<p>There are some blocks in my code.</p>
<p>To make it easier to read, I often append comment after the end</p>
<p>such as </p>
<pre><code> end # end upto
end # fileopen
</code></pre>
<p>Because sometimes the indentation still not easy for read.</p>
<p>Is there any better practice?</p>
<p>And my indentation is 2 spaces, is it OK for most Rubier ?</p>
<pre><code>require "faker"
real_sn = 2124100000
File.open("lib/tasks/tw_books.txt", "r").each do |line|
# author = Faker::Lorem.words(2..5).join(' ').gsub('-','').gsub('\s+','\s')
1.upto(1000).each do |x|
location = Faker::Lorem.words(5)
book_name, author, publisher, isbn, comment = line.strip.split("|||")
ap(line)
isbn = isbn[/\d+/]
real_sn+=1
bk = Book.new(:sn => real_sn,:name => book_name, :isbn=>isbn,
:price =>Random.rand(200..5000), :location=>location, :category=>["商業","歷史","體育","政治"].sample,
:author => author, :sale_type => [:fix_priced, :normal, :promotion].sample, :publisher => publisher,
:release_date => rand(10.years).ago, :comment => comment
)
if bk.save()
if (real_sn%100)==0
puts book_name
end
Sunspot.commit
else
puts real_sn
puts bk.errors.full_messages
end
end # end upto
end # fileopen
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-31T00:04:17.093",
"Id": "56988",
"Score": "3",
"body": "Refactor for readability. The trailing comments are irritating and do nothing for readability, they only detract."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-31T07:20:50.073",
"Id": "56989",
"Score": "1",
"body": "@DaveNewton: Trailing `end` comments are irritating for blocks shorter than ~10 lines, and valuable for long blocks, such as module and class definitions. Fortran authors were not completely insane for making the `END` \"comments\" mandatory."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-31T11:06:49.607",
"Id": "56990",
"Score": "0",
"body": "@BorisStitnicky If a block is that long it's almost always missing one or more refactorings. Use normal docs at the *beginning* of classes and modules for visual separation. When we wrote Fortran we wrote in a very different style-and it's not a language feature that survived as we moved forward."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-31T21:22:03.853",
"Id": "56991",
"Score": "0",
"body": "@DaveNewton: ... module and class definitions ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-31T21:33:15.420",
"Id": "56992",
"Score": "0",
"body": "@BorisStitnicky ... They're not valuable."
}
] |
[
{
"body": "<p>Compare your code to how I'd write it:</p>\n\n<pre><code>require \"faker\"\n\nreal_sn = 2124100000\n\nFile.open(\"lib/tasks/tw_books.txt\", \"r\").each do |line|\n# author = Faker::Lorem.words(2..5).join(' ').gsub('-','').gsub('\\s+','\\s')\n\n 1.upto(1000).each do |x|\n\n location = Faker::Lorem.words(5)\n book_name, author, publisher, isbn, comment = line.strip.split(\"|||\")\n\n ap(line)\n\n isbn = isbn[/\\d+/]\n real_sn += 1\n\n bk = Book.new(\n :author => author,\n :category =>[\"商業\",\"歷史\",\"體育\",\"政治\"].sample,\n :comment => comment,\n :isbn => isbn,\n :location =>location,\n :name => book_name,\n :price => Random.rand(200..5000),\n :publisher => publisher,\n :release_date => rand(10.years).ago,\n :sale_type => [\n :fix_priced,\n :normal,\n :promotion\n ].sample,\n :sn => real_sn,\n )\n\n if bk.save()\n\n puts book_name if ((real_sn % 100) == 0)\n Sunspot.commit\n\n else\n\n puts real_sn\n puts bk.errors.full_messages\n\n end\n end\nend\n</code></pre>\n\n<p>Part of writing code is making it readable and maintainable. That means use indentation, vertical alignment, whitespace between operators, vertical whitespace to make changes in logic more obvious, etc. </p>\n\n<p>I sort hash keys alphabetically, such as the parameters for <code>Book.new</code>, especially when there's a lot of them. This makes it a lot easier to see if something is duplicated or missing. Since it's a hash it doesn't matter what order they're in as far as Ruby is concerned; Again this is for maintenance later on.</p>\n\n<p>The editor you use can help you immensely with this. I use <a href=\"http://vim.org\">gvim</a> and <a href=\"http://www.sublimetext.com/\">Sublime Text</a>, both of which allow me to easily reformat/reindent code I'm working on, and I take advantage of that often. It's a good first step when you have code from a \"foreign source\" that makes your eyes bug out. Reindent it, fix long, awkward sections, like your list of hash entries for <code>Book.new</code>, and the code will become more understandable.</p>\n\n<p>Also, your editor needs to have the ability to jump between matching delimiters like <code>()</code>, <code>[]</code>, <code>{}</code> and <code>do</code>/<code>end</code>. gvim can do that plus jump through <code>if</code>/<code>else</code>/<code>end</code> plus <code>rescue</code> blocks. That ability to navigate REALLY helps keep your code flow clear.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-31T04:33:00.133",
"Id": "56993",
"Score": "0",
"body": "I noticed that you left the comments at the end of the `end` statements. Is that really how you would write this, or did you just leave it in?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-31T06:11:46.010",
"Id": "56994",
"Score": "0",
"body": "No, I wouldn't use comments on `end`. If I have to do that to figure out logic or control structures I haven't written it clearly enough up above. Those were there as left-overs; I was mostly showing everything above the final close of the blocks. I'll take them out for thoroughness."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-31T00:24:30.387",
"Id": "35213",
"ParentId": "35212",
"Score": "6"
}
},
{
"body": "<p>To provide an alternative to the respected Tin Man's answer, commenting <code>end</code>s is a practice that I use when the block body is long (yours is longish). When the body is short, commenting <code>end</code>s is unnecessary. I would write your code as:</p>\n\n<pre><code>require \"faker\"\nreal_sn = 2124100000\n\nFile.open( 'lib/tasks/tw_books.txt', ?r ).each do |line|\n # author = Faker::Lorem.words( 2..5 ).join( ' ' ).gsub( '-', '' ).gsub( '\\s+', '\\s' )\n 1.upto( 1000 ).each do |x|\n location = Faker::Lorem.words( 5 )\n book_name, author, publisher, isbn, comment = line.strip.split( \"|||\" )\n ap( line )\n isbn = isbn[ /\\d+/ ]\n real_sn += 1\n bk = Book.new( sn: real_sn, name: book_name, isbn: isbn,\n author: author, publisher: publisher,\n location: location,\n category: %w[ 商業 歷史 體育 政治 ].sample,\n sale_type: %i[fix_priced normal promotion].sample,\n release_date: rand( 10.years ).ago,\n price: Random.rand( 200 .. 5000 ),\n comment: comment )\n if bk.save then\n puts book_name if real_sn % 100 == 0\n Sunspot.commit\n else\n puts real_sn\n puts bk.errors.full_messages\n end\n end # end upto\nend # File.open\n</code></pre>\n\n<p>You can notice a few mainly cosmetic changes, such as colon notation in <code>keyword: arguments</code>, spaces inside parenthesis (I find it more readable), word array and symbol array literals...</p>\n\n<p><em>Reusable</em> code is write once, read many times. When writing reusable code, one should make it brief, but not by using abbreviations of common words, or by cramming characters together. Conversely, when writing one-time code, it is OK to use abbreviations and save keystrokes. I hope that you do not reuse your code example much. If you do, you should refactor it into <a href=\"http://c2.com/cgi/wiki?ComposedMethod\" rel=\"nofollow\">2 or 3 smaller methods</a>, or even <a href=\"http://c2.com/cgi/wiki?MethodObject\" rel=\"nofollow\">method object(s)</a>.</p>\n\n<p>The editor you use can help you immensly. Matz uses <a href=\"http://www.emacswiki.org/\" rel=\"nofollow\">Emacs</a>. In fact, <a href=\"http://www.slideshare.net/yukihiro_matz/how-emacs-changed-my-life\" rel=\"nofollow\">he was inspired by Emacs</a> when creating Ruby. Emacs gives one everything expected of a programming editor. In fact, Emacs gives you power, for the price of having to actually read the manual. With Emacs, I use <code>yasnippet</code> for code snippets, and <code>auto-complete-el</code> as the most intelligent auto completion agent. One other modification that makes life in <code>Emacs</code> easy is <a href=\"http://www.emacswiki.org/emacs-ru/CapsKey#toc4\" rel=\"nofollow\">redefining Caps Lock to be a Ctrl key</a>.</p>\n\n<p>Apart from that, the Ruby style manual that I found valuable is <a href=\"http://www.caliban.org/ruby/rubyguide.shtml\" rel=\"nofollow\">the one by Ian McDonald from Google</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-31T07:05:19.217",
"Id": "35214",
"ParentId": "35212",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "35213",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-31T00:02:34.620",
"Id": "35212",
"Score": "2",
"Tags": [
"ruby"
],
"Title": "How to make the end of loop more readable in Ruby"
}
|
35212
|
<p>I need to concatenate a bunch of delimited text files. In the process, I need to add a new column to the data based on part of the name of one of the directories containing each file. The script works, but I have a feeling that it is inelegant in the extreme.</p>
<p>In particular, I'm wondering whether I should be reading the source files into a data structure that can later be written to file as a delimited text file. It seems like such an approach would be more general and easily extended.</p>
<p>In its current structure, I have doubts about the efficiency of how I'm skipping the header lines in source files with the is_header variable. It seems like this approach requires more condition-checking than should be strictly necessary. Can't I just iterate over some object? I tried <code>for row in reader[1:]:</code> but apparently objects of type csv.reader don't allow subscripting.</p>
<pre><code>#! /usr/bin/env Python3
import glob
import csv
file_names = glob.glob('*/unknown/*.dat')
with open(file_names[0], 'r') as csv_input:
reader = csv.reader(csv_input, delimiter = '\t')
header = ['seed'] + next(reader)
with open('output.dat', 'a') as csv_output:
writer = csv.writer(csv_output, delimiter = '\t')
writer.writerow(header)
for file_name in file_names:
param_dir = file_name.split('/')[0]
seed = param_dir.split('-')[0]
with open(file_name, 'r') as csv_input:
reader = csv.reader(csv_input, delimiter = '\t')
is_header = True
for row in reader:
if not is_header:
out_row = [seed] + row
writer.writerow(out_row)
is_header = False
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T08:43:00.760",
"Id": "57004",
"Score": "3",
"body": "Just do `next(reader)` to skip the header."
}
] |
[
{
"body": "<p>There is some repetition between your header-reading routine and the rest of the code. You could incorporate it into the main loop to remove that duplication and avoid opening the first file twice. You already use <code>next(reader)</code> nicely to read the header; use the same technique to skip the header row.</p>\n\n<p>To determine the seed from a file path, you look for a <code>-</code> in the file path. Your glob should have a <code>-</code> to ensure that that succeeds.</p>\n\n<pre><code>import csv\nfrom glob import glob\n\npaths = glob('*-*/unknown/*.dat')\n\nwith open('output.dat', 'a') as csv_output:\n writer = csv.writer(csv_output, delimiter='\\t')\n header_written = False\n\n for path in paths:\n param_dir = path.split('/')[0]\n seed = param_dir.split('-')[0]\n\n with open(path, 'r') as csv_input:\n reader = csv.reader(csv_input, delimiter='\\t')\n\n header = next(reader)\n if not header_written:\n writer.writerow(['seed'] + header)\n header_written = True\n\n for row in reader:\n writer.writerow([seed] + row)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T19:15:58.360",
"Id": "45646",
"ParentId": "35218",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T08:10:01.577",
"Id": "35218",
"Score": "5",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Script for concatenating delimited text files"
}
|
35218
|
<p>I was referred here from StackOverflow, so here is what I posted over there:</p>
<p>So, for an assignment, I have to construct a binary search tree, plus an assortment of related functions. I have them all working, but I'm looking for a way to optimize my way of finding in-order predecessors and successors. Here's my code for finding the predecessor (successor is, of course, nearly identical):</p>
<pre><code>public double findPredecessor(double num) {
if(this.has(num) == true) {
node temp = this.root;
node iterator = this.root;
node returner = null;
while(temp.key != num) { //match the passed "num" to a key
if(num < temp.key) {
temp = temp.left;
} else {
temp = temp.right;
}
}
if(temp.left != null) {
return findMaxInternal(temp.left);
}
while(iterator != null) {
if(temp.key < iterator.key) {
iterator = iterator.left;
}
else if(temp.key > iterator.key) {
returner = iterator;
iterator = iterator.right;
}
else break;
}
return returner.key;
}
else return Double.NaN;
}
</code></pre>
<p>Yes, it is part of the assignment that my function take a double as argument, and not a node. I'm looking to see if there is a way that I can do this in one loop, to cut a bit on running time. I know that two successive, non-nested loops still is O(n), but still.</p>
|
[] |
[
{
"body": "<p>CodeReview is a good place for this question....</p>\n\n<p>There are a few things that you should consider...</p>\n\n<h2>Style</h2>\n\n<p><code>node</code> is a bad name for a Java class. Standards for Java are that Class names are CamelCase, and your <code>node</code> class should be called <code>Node</code>.</p>\n\n<p>Using <code>==</code> to compare double values is often a cause of bugs. In this case I believe it is 'safe', but you should be aware that it is, in general, a 'bad idea'. </p>\n\n<p>It is typical, though not required, that when you have an <code>if {.....; return ...}</code> block that you do not have an else block. For example, you have:</p>\n\n<pre><code>if (this.hasNum(...)) {\n .....\n return returner.key;\n} else {\n return Double.NaN;\n}\n</code></pre>\n\n<p>In this case the <code>else</code> block is not necessary, and it could simply be:</p>\n\n<pre><code>if (this.hasNum(...)) {\n .....\n return returner.key;\n}\nreturn Double.NaN;\n</code></pre>\n\n<p>Otherwise, the style is good.</p>\n\n<h2>Logic</h2>\n\n<p>You actually loop through the tree three times. I presume <code>hasNum(...)</code> also walks the tree.</p>\n\n<p>With problems like this you can reduce the problem to a single walk of the Tree.</p>\n\n<pre><code>node match = null;\nnode current = root;\nnode predecessor = null;\n// walk the tree until we find our exact match....\n// Our predecessor node will follow us whenever we take a right branch....\nwhile (current != null) {\n if (current.key == num) {\n match = current;\n break;\n }\n if (num < current.key) {\n current = current.left;\n } else {\n predecessor = current;\n current = current.right;\n }\n}\nif (match == null) {\n return Double.NaN;\n}\nif (match.left != null) {\n predecessor = match.left;\n while (predecessor.right != null) {\n predecessor = predecessor.right;\n }\n}\nif (predecessor == null) {\n return Double.NaN;\n}\nreturn predecessor.key;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T18:46:04.100",
"Id": "57037",
"Score": "0",
"body": "In the future, please refrain from posting complete solutions to [tag:homework] problems."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T19:27:24.913",
"Id": "57048",
"Score": "0",
"body": "perhaps.... but his solution was accurate.. just sub-optimal"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T19:33:39.437",
"Id": "57049",
"Score": "0",
"body": "Yes, but it's also possible to guide the student towards a better solution without spelling out the entire code. Ending the review with a hint that a single-walk solution is possible would have sufficed. (It is, after all, an assignment, so the student should be able to figure it out.)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T11:54:48.803",
"Id": "35225",
"ParentId": "35219",
"Score": "2"
}
},
{
"body": "<p>@rolfl wrote a great review. I just have a few minor comments to add.</p>\n\n<p>The original code had a bug: if the <code>num</code> parameter refers to the smallest item in the tree, then a <strong><code>NullPointerException</code></strong> would be thrown. @rolfl fixed that for you without saying so.</p>\n\n<p>Your <code>temp</code> and <code>iterator</code> (or <code>match</code> and <code>current</code>, as @rolfl calls them) are <strong>redundant variables</strong>. Only one is needed.</p>\n\n<p>If you are doing the <code>hasNum()</code> check, then the way to do it would be to <strong>return early</strong>.</p>\n\n<pre><code>if (!this.hasNum(num)) {\n return Double.NaN;\n}\n// The rest of the code here\n...\n</code></pre>\n\n<p>That way, you save one level of indentation, and eliminate the suspense of having to wade through a short story before reaching the <code>else</code> finale. Anyway, it's a moot point, since you're better off not calling <code>hasNum()</code> at all.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T18:45:26.270",
"Id": "35239",
"ParentId": "35219",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "35225",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T08:20:09.227",
"Id": "35219",
"Score": "2",
"Tags": [
"java",
"optimization",
"homework",
"tree"
],
"Title": "In-order Predecessor BST review"
}
|
35219
|
<p>I'm building a hash table for this problem:</p>
<blockquote>
<p><strong>Implement a class for storing a set of integers:</strong></p>
<pre><code>class FixedSet {
public:
FixedSet();
void Initialize(const vector<int>& numbers);
bool Contains(int number) const;
};
</code></pre>
<p>After the call of the <code>Initialize()</code> function, <code>FixedSet</code> contains integers from the input vector. The set of numbers stored by <code>FixedSet</code> does not change (until the <code>Initialize()</code> function is called again).</p>
<p>The <code>Contains()</code> function returns true if number is in the set, or false otherwise. The <code>Initialize()</code> function should run in expected O(n), where <em>n</em> is the number of elements in numbers. The memory consumption should not exceed O(n). The <code>Contains()</code> function should run in guaranteed O(1).</p>
<p>Using this class, solve the following problem. The input has a set of different numbers followed by a set of requests, each of which is represented by an integer number. For each request, you need to determine whether or not the number is in the set.</p>
<p>The sizw of set is not bigger than 100000 elements; the absolute values of elements |val| <= 10<sup>9</sup>.</p>
</blockquote>
<p>I've implemented perfect hashing from Cornmen:</p>
<pre><code>#include <time.h>
#include <algorithm>
#include <iostream>
#include <vector>
#include <list>
#include <stdio.h>
using std::cout;
using std::cin;
using std::endl;
using std::vector;
using std::list;
typedef long long int long_int;
const int max_int = 1000000001; // value, that could't be in the table. Analog of NULL.
// function for calculation of hash
inline int hash(long_int a_prime, long_int b_prime, int p_prime, int table_size, int key)
{
return (((a_prime * key + b_prime) % p_prime) % table_size);
}
// class for mini-hash table in cells of main hash-table
class Bucket
{
vector<int> _cells;
int size; // the size of mini-table should be greater then 4
long_int hash_a;
long_int hash_b;
int prime;
public:
Bucket() {}
void Initialize()
{
prime = 17;
hash_a = std::rand() % prime;
hash_b = 1 + std::rand() % (prime - 1);
}
// construct hash table from list of elements
void Construct(list<int>& input)
{
if (input.empty())
{
size = 0;
return;
}
size = input.size() * input.size();
bool flag = true;
// while there is no collisions in table
while (flag)
{
_cells.assign(size, max_int);
Initialize();
list<int>::iterator elem = input.begin();
while (elem != input.end() && flag)
{
int hashKey = hash(hash_a, hash_b, prime, size, *elem);
if (hashKey < 0)
hashKey = - hashKey;
// if collision then construct hash table from the begining!
if (_cells[hashKey] != max_int)
{
flag = false;
break;
}
_cells[hashKey] = *elem;
++elem;
}
if (!flag)
flag = true;
else
flag = false;
}
}
bool Contains(int elem)
{
if (size == 0)
return false;
int hashKey = hash(hash_a, hash_b, prime, size, elem);
if (hashKey < 0)
hashKey = - hashKey;
if (_cells[hashKey] == elem)
return true;
return false;
}
};
// class for main hash table
class FixedSet
{
int _tableSize;
long_int _hashFuncA;
long_int _hashFuncB;
int _primeNumber;
vector<list<int> > _elementsInCells;
vector<Bucket> _buckets;
public:
FixedSet()
{
_primeNumber = 100013; // the maximum prime number
_hashFuncA = std::rand() % _primeNumber;
_hashFuncB = 1 + std::rand() % (_primeNumber - 1);
}
void setTableSize(int size)
{
_tableSize = size;
_buckets.resize(size);
}
void Initialize(const vector<int>& numbers)
{
_tableSize = numbers.size();
_buckets.resize(numbers.size());
_elementsInCells.resize(numbers.size());
for (int i = 0; i < numbers.size(); ++i)
{
int hashKey = hash(_hashFuncA, _hashFuncB, _primeNumber, _tableSize, numbers[i]);
if (hashKey < 0)
hashKey = - hashKey;
_elementsInCells[hashKey].push_back(numbers[i]);
}
for (int i = 0; i < numbers.size(); ++i)
{
_buckets[i].Construct(_elementsInCells[i]);
}
}
bool Contains(int number)
{
int hashKey = hash(_hashFuncA, _hashFuncB, _primeNumber, _tableSize, number);
if (hashKey < 0)
hashKey = - hashKey;
return _buckets[hashKey].Contains(number);
}
};
int main(int argc, char* argv[])
{
clock_t begin, end;
double time_spent;
std::srand (time(NULL));
int numberOfElements;
scanf("%i", &numberOfElements);
FixedSet fs;
begin = clock();
vector<int> inputVector;
fs.setTableSize(numberOfElements);
for (int i = 0; i < numberOfElements; ++i)
{
int elemValue;
scanf("%d", &elemValue);
inputVector.push_back(elemValue);
}
fs.Initialize(inputVector);
end = clock();
int numberOfElementsForSearch;
scanf("%i", &numberOfElementsForSearch);
for (int i = 0; i < numberOfElementsForSearch; ++i)
{
int elem;
scanf("%d", &elem);
if (fs.Contains(elem))
{
cout << "Yes" << endl;
}
else
{
cout << "No" << endl;
}
}
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
cout << time_spent << endl;
return 0;
}
</code></pre>
<p>It works rather fast, but on a vector of 100000 elements, the function <code>Initialize()</code> works for <strong>0,7 ms</strong> in Release. But on a vector of 50000, this function works for <strong>1.8 ms</strong>. </p>
<p>Could you explain why this is so? How can I improve my code to make it work faster?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T20:39:12.797",
"Id": "57181",
"Score": "0",
"body": "Ann, I don't understand why the code of Bucket is more or less repeated in FixedSet. I guess I am being stupid, but can you please explain."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T08:28:36.130",
"Id": "57226",
"Score": "0",
"body": "These 2 classes have the same interface, but implementations are different. So I've decided to create 2 classes, for hash-table of first level and hash-table of second level. May be it would be better to make abstact class HashTable with virtual methods Initialize() and Contains() and inherit my classes from it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T16:45:23.017",
"Id": "57308",
"Score": "0",
"body": "But why do you need a second level at all?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T05:16:31.000",
"Id": "57362",
"Score": "0",
"body": "This is the idea of perfect hashing - to use hash table of second level for elements that have the same hash value (in average, if I use good hash function it won't be greater than 2 elements with the same hash). In this way I can check if an element in the table in O(1) time. But if I use linked list for collisions in the cells it won't be O(1)."
}
] |
[
{
"body": "<p>I tried running your implementation on my machine but with the following input (input is 25 random integers within the interval <code>[0; 10^9]</code>) <code>Initialize</code> never completes (it's stuck in the bucket <code>while (flag)</code> loop):</p>\n<pre><code>25\n882868245\n264589055\n955665379\n570725902\n186426836\n425509062\n780811177\n528755197\n921593609\n210302061\n162860187\n237314629\n771563954\n716724339\n500613765\n749586096\n118952462\n708453275\n530816792\n697958285\n841037949\n796725013\n123270367\n470484394\n578476359\n1\n252678354\n</code></pre>\n<p>Note: Never in this context means I killed it after 10 or 15 seconds.</p>\n<p>So it's not surprising that a list with 50,000 random elements can easily result in a higher setup time than 100,000 depending on the distribution of the values (the algorithm attempts to re-create the table every time there is a collision). As per given example it's easy to generate inputs which will make it run for a long time for very few values.</p>\n<p>Given the problem restrictions I'd say you can get away with the fastest perfect hash function there is: Identity.</p>\n<p>You could simply use a bitset with the values as indices and flip the bits on if the value is present. This requires a bitset with 10^9 bits - approx. 125MB of memory which is not all that much these days (at least on desktops).</p>\n<p>Resulting implementation:</p>\n<pre><code>class FixedSet\n{\n vector<bool> _set;\n\npublic:\n FixedSet() : _set(1000000000) { }\n\n void Initialize(const vector<int>& numbers)\n { \n for (int i = 0; i < numbers.size(); ++i)\n {\n _set[numbers[i]] = true;\n }\n }\n\n bool Contains(int number)\n {\n return _set[number];\n }\n};\n</code></pre>\n<p><code>Initialize</code> takes approx 45ms on my machine - it doesn't matter if it's 1 or 100,000 input elements. Apparently allocating the memory for the bitset takes the bulk of the time. Flipping the bits on seems to hardly take any time at all.</p>\n<p>Searching for 10,000 random elements takes about 3ms</p>\n<p>Some notes:</p>\n<ul>\n<li>In case you are wondering: <a href=\"http://en.cppreference.com/w/cpp/container/vector_bool\" rel=\"nofollow noreferrer\"><code>std::vector<bool></code></a> is a specialization of a vector packing bools as bits. This container is considered somewhat as a failure in the C++ standard but happens to do exactly what we need here.</li>\n<li>This implementation of <code>FixedSet</code> has space complexity <code>O(1)</code> (albeit a fairly big constant)</li>\n<li>Initializing it has time complexity <code>O(n)</code> although the difference between 1 and 100,000 input elements is not measurable with the provided timing method</li>\n<li>Looking up an element has time complexity of <code>O(1)</code> (indexed container access)</li>\n<li>Disadvantages:\n<ul>\n<li>Fairly big initial upfront cost for setup (memory allocation)</li>\n<li>Might not have been in the spirit of the assignment</li>\n</ul>\n</li>\n</ul>\n<p><strong>Update</strong></p>\n<p>I think the main problem with your implementation is that the bucket size is fairly small (from testing it looks like you rarely get more than 6 or 7 collisions). Especially in buckets with more than 4 collisions your hash function actually throws away all hashes larger than 17 (which is <code>p_prime</code> you pass in from bucket) so you reduce your available bucket space. Also my suspicion is that in your hash function <code>a_prime</code> and <code>b_prime</code> should actually be, well, prime but <code>rand() % prime</code> does not yield a prime number.</p>\n<p>While reading up on hashing, a popular version seems to be <a href=\"http://en.wikipedia.org/wiki/Cuckoo_hashing\" rel=\"nofollow noreferrer\">Cuckoo Hashing</a> which has a constant look up time (if you use two hash functions it will perform at most two lookups) and also a constant worst case insert time for an element (even if you have to rehash).</p>\n<p>I threw together a quick hack implementation which does not do re-hashing and just relies on the sets being big enough:</p>\n<pre><code>class FixedSet\n{\n // min 36500, sweetspot 73000\n static const int _size = 73000;\n int _noentry;\n std::vector<int> _set1;\n std::vector<int> _set2;\n std::vector<int> _set3;\n\npublic:\n FixedSet() : _noentry(std::numeric_limits<int>::min()), _set1(_size, _noentry), _set2(_size, _noentry), _set3(_size, _noentry) { }\n\n void Initialize(const vector<int>& numbers)\n { \n for (int i = 0; i < numbers.size(); ++i)\n {\n if (!add(numbers[i]))\n {\n std::ostringstream o;\n o << "Failed to insert after " << i << " elements, rehashing not implemented";\n throw new std::exception(o.str().c_str());\n }\n }\n }\n\n bool Contains(int number)\n {\n for (int round = 0; round < 3; ++round)\n {\n std::vector<int>& _set = (round % 3 == 0) ? _set1 : ((round % 3 == 1) ? _set2 : _set3);\n int h = hash(round + 1, number);\n if (number == _set[h])\n return true;\n }\n return false;\n }\n\nprivate:\n int hash(int rounds, int number)\n {\n int withOffset = number;\n srand(withOffset);\n int h = bigRand() % _size;\n while (--rounds)\n {\n h = bigRand() % _size;\n }\n return h;\n }\n\n inline int bigRand()\n {\n return (rand() << 15) | rand(); // RAND_MAX is 0x7FFF in VS2010\n }\n\n bool add(int number)\n {\n int toInsert = number;\n for (int i = 0; i < _size; ++i)\n {\n int h = hash(i % 3 + 1, toInsert);\n std::vector<int>& _set = (i % 3 == 0) ? _set1 : ((i % 3 == 1) ? _set2 : _set3);\n int current = _set[h];\n if (current == _noentry)\n {\n _set[h] = toInsert;\n return true;\n }\n _set[h] = toInsert;\n toInsert = current;\n }\n return false;\n }\n};\n</code></pre>\n<p>Notes:</p>\n<ul>\n<li>I'm using 3 hash functions instead of the classic 2. Can't get the load factor high enough with just 2 functions for some reason.</li>\n<li>The above is tweaked for no more than 100,000 input elements</li>\n<li><code>36500</code> seems to be the minimum set size which yields a 91% load factor of the sets which is pretty much the limit for Cuckoo with 3 hash functions according to wikipedia.</li>\n<li>With <code>36500</code> set size it takes approx. 74ms on my machine to insert 100,000 elements.</li>\n<li>Doubling to <code>73000</code> yields a 75% reduction in run time to 17ms.</li>\n<li>Further increases in the set size do not seem to have much effect.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T18:05:25.360",
"Id": "57167",
"Score": "1",
"body": "Unfortunatly, this algorithm fails with \"Memory Limit\" error in our check system on the first test. And my variant failed on 84 test with \"Time Limit\" error. So I need to find the way to speed up my algorithm, or reduce space complexity in your algorithm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T11:31:10.407",
"Id": "57238",
"Score": "0",
"body": "The bitset idea would not be O(_n_) memory. Rather, the memory needed depends on the range of values."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T19:05:25.857",
"Id": "57321",
"Score": "2",
"body": "@200_success: Yes but the range is defined fixed as part of the problem description and therefor it is considered constant. As general solution you are right."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T19:30:44.420",
"Id": "57322",
"Score": "0",
"body": "Haha! Loophole!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T01:48:54.627",
"Id": "57472",
"Score": "0",
"body": "@AnnOrlova: Updated my answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-18T09:48:57.690",
"Id": "57757",
"Score": "0",
"body": "Thank you very much for this solution! It is really faster, than mine. I haven't heard about this type of hashing before."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-18T17:38:24.110",
"Id": "57812",
"Score": "0",
"body": "\"When in doubt, use brute force.\" - Kenneth Thompson"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-11-13T09:51:28.490",
"Id": "35284",
"ParentId": "35220",
"Score": "6"
}
},
{
"body": "<p>Chris has given a great answer on the hashing so here are some comments on the implementation.</p>\n\n<p>My main observation is that you should avoid duplicating so much code, however you implement it.</p>\n\n<p>Your <code>hash</code> function should return the absolute (unsigned) value of the hash,\nas each use of <code>hash</code> is followed by an <code>if</code>:</p>\n\n<pre><code>int hashKey = hash(hash_a, hash_b, prime, size, *elem);\nif (hashKey < 0)\n hashKey = - hashKey;\n</code></pre>\n\n<p>And perhaps modify the return type to that expected of vector indices (and\nnoting that the parameters don't seem to need to be <code>long long</code>):</p>\n\n<pre><code>typedef std::vector<int>::size_type Hashkey;\n\nstatic Hashkey hash(int a, int b, int p, int size, int key)\n{\n return (Hashkey) abs((((a * key + b) % p) % size));\n}\n</code></pre>\n\n<p>Also on types, where you have a defined range for a variable, the types in\n<code>stdint.h</code> can be useful - eg <code>int64_t</code> is guaranteed to be 64 bits which\nsuits your input range while your <code>long long int</code> might be longer (also the\n<code>int</code> is usually omitted, ie. just <code>long long</code>).</p>\n\n<p>Your use of <code>flag</code> to continue the outer loop in <code>Bucket::Construct</code> is very\nstrange. I'd prefer to see the inner loop extracted to a function which\nshould use a <code>for</code> loop:</p>\n\n<pre><code>for (auto e = input.begin(); e != input.end(); ++e) {\n ...\n if (cells[hashKey] != max_int) {\n return false;\n }\n ...\n}\nreturn true;\n</code></pre>\n\n<p>and called, as in:</p>\n\n<pre><code>while (createHashTable(...) == false) {\n // nothing\n}\n</code></pre>\n\n<p>I don't understand why you (and many other people posting here) use leading\nunderscores on variable names. For me these are just noise and detract from\notherwise nice looking code (for example, your <code>_cells</code>). Also on variable\nnames, some of your names are too long. Where the scope of a variable is\nsmall, its name can (and I think should) also be small.</p>\n\n<p>Finally, your prime numbers (17 and 100013) would be better not embedded in\nthe code (perhaps use a <code>#define</code> or <code>const</code> at the top). Also a comment on\nhow these numbers were determined would be useful (and the origin of the hash\nfunction?).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-18T16:48:25.303",
"Id": "35607",
"ParentId": "35220",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "35284",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T08:27:02.283",
"Id": "35220",
"Score": "13",
"Tags": [
"c++",
"performance",
"homework",
"hash-map"
],
"Title": "Perfect Hashing Implementation"
}
|
35220
|
<p>I have written a common class for finding display sizes in pre-honeycomb and for the latest versions of Android. Could anyone review my code and suggest possible modifications for this code?</p>
<pre><code>import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Point;
import android.os.Build;
import android.view.Display;
import android.view.WindowManager;
public class DisplayManager {
private Display mDisplay;
private WindowManager mWindowManager;
public DisplayManager(Context mContext) {
mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
mDisplay = mWindowManager.getDefaultDisplay();
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public int getDisplayHeight() {
if (Integer.valueOf(android.os.Build.VERSION.SDK_INT) < 13) {
return mDisplay.getHeight();
} else {
Point size = new Point();
mDisplay.getSize(size);
return size.y;
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public int getDisplayWidth() {
if (Integer.valueOf(android.os.Build.VERSION.SDK_INT) < 13) {
return mDisplay.getWidth();
} else {
Point size = new Point();
mDisplay.getSize(size);
return size.x;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>First of all, this line:</p>\n\n<pre><code>if (Integer.valueOf(android.os.Build.VERSION.SDK_INT) < 13) {\n</code></pre>\n\n<p>Should be replaced with this:</p>\n\n<pre><code>if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2) {\n</code></pre>\n\n<p>Because a) There's no need to use <code>Integer.valueOf</code> for something that is already an int. b) <code>Build.VERSION_CODES.HONEYCOMB_MR2</code> is a constant (or as we call it in Java, <code>public static final</code>) with the value 13. Avoid using \"magic numbers\" in your code like that, instead refer to existing constants or create new constants when necessary.</p>\n\n<p>Secondly, I really doubt that the size of your screen will change while your object exists. Which means that this code need only to be run once and can therefore be placed in the constructor:</p>\n\n<pre><code>Point size = new Point();\nmDisplay.getSize(size);\n</code></pre>\n\n<p>Now to the last point I want to make. Your <code>mWindowManager</code> variable is only used within the constructor. I see no need at all for that to be a field in your class. Change that to a local variable instead.</p>\n\n<p>It is also a good practice to make your class fields <code>final</code> when possible (which is both possible for the <code>mDisplay</code> and also your newly created <code>Point size</code> field). The final keyword makes sure that you get a compiler error if you try to change the value of the variable after it has been initialized. Note that <code>mDisplay.getSize(size)</code> <em>doesn't change the variable itself, it changes the values within the variable</em>, i.e. the object <code>size</code> remains the same.</p>\n\n<p>Besides this, I have to say that your code looks excellent. You have good variable names. I don't even see any indentation problems (except those that StackExchange create, but they're not your fault).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T12:40:34.670",
"Id": "35227",
"ParentId": "35222",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T10:04:11.683",
"Id": "35222",
"Score": "4",
"Tags": [
"java",
"android"
],
"Title": "Getting display size compact class in Android"
}
|
35222
|
<p>This is one of the first RSpec tests I've written, and I'm not really sure what the best practices are etc. </p>
<p>My question basically is: what would you do differently? What is good? What is bad?</p>
<p>The complete code can be found <a href="https://gist.github.com/asmand/d1ccbcd01789353c01c3" rel="nofollow">here</a>.</p>
<p>Here is the class to be tested:</p>
<pre><code>class WeeklyFlexCalculator
attr_reader :params
def initialize(params)
@params = params
end
def calculate
group_efforts(
(params.start_date..params.end_date).map do |date|
daily_effort(date)
end.compact
)
end
def group_efforts(result)
weekly = result.group_by { |e| get_week_key(e[:date]) }
weekly.map do |key,w|
{
year: get_year_from_week_key(key),
week: get_week_from_week_key(key),
weekTarget: get_target_sum(w),
weekEffort: get_effort_sum(w),
efforts: w
}
end.sort { |a, b| b.efforts[0].date <=> a.efforts[0].date }
end
def daily_effort(date)
target = get_target(date)
effort = get_effort(date)
return if target == 0 && effort == 0
{
date: date,
effort: effort,
target: target,
diff: effort - target
}
end
def get_target_sum(efforts)
efforts.inject(0){|sum,e| sum + e[:target]}
end
def get_effort_sum(efforts)
efforts.inject(0){|sum,e| sum + e[:effort]}
end
def get_week_key(date)
date.cwyear.to_s + "|" + date.cweek.to_s
end
def get_year_from_week_key(key)
key.split('|')[0]
end
def get_week_from_week_key(key)
key.split('|')[1]
end
def get_target(date)
day_off?(date) ? 0 : params.user.hours_per_day
end
def get_effort(date)
ts = get_timesheet(date)
ts.nil? ? 0.0 : ts.TimeInHours
end
def day_off?(date)
date.wday == 0 or date.wday == 6 or params.holidays.include? date.to_s
end
def get_timesheet(date)
params.timesheets.select {|ts| ts.Date == date.to_s}.first
end
end
</code></pre>
<p>And here is the test: </p>
<pre><code>require './WeeklyFlexCalculator'
describe WeeklyFlexCalculator, "during Christmas week" do
subject(:calculation) { WeeklyFlexCalculator.new(params).calculate }
let(:params) do
messages = {
:start_date => Date.new(2013,12,23),
:end_date => Date.new(2013,12,29),
:holidays => ["2013-12-24", "2013-12-25", "2013-12-26"],
:timesheets => [],
:user => user
}
double(:params,messages)
end
let(:user) do
messages = {
:hours_per_day => 7.5
}
double(:user, messages)
end
let(:timesheet) do
messages = {
:Date => Date.new(2013,12,23).to_s,
:TimeInHours => 5.0
}
double(:timesheet, messages)
end
context "with no work performed" do
it { should have(1).item }
context "the week calculated" do
subject(:workweek) {calculation[0]}
its([:year]) { should eq "2013" }
its([:week]) { should eq "52" }
its([:weekTarget]) { should eq 15.0 }
its([:weekEffort]) { should eq 0.0 }
context "the work efforts" do
subject(:efforts) {workweek[:efforts]}
it { should have(2).items }
context "the first work effort" do
subject(:effort) {efforts[0]}
its([:target]) {should eq 7.5}
its([:diff]) {should eq -7.5}
its([:effort]) {should eq 0.0}
end
end
end
end
context "with work effort on normal day" do
before do
params.stub(:timesheets => [timesheet])
end
it { should have(1).item }
context "the week calculated" do
subject(:workweek) {calculation[0]}
its([:year]) { should eq "2013" }
its([:week]) { should eq "52" }
its([:weekTarget]) { should eq 15.0 }
its([:weekEffort]) { should eq 5.0 }
context "the work efforts" do
subject(:efforts) {workweek[:efforts]}
it { should have(2).items }
context "the first work effort" do
subject(:effort) {efforts[0]}
its ([:effort]) { should eq 5.0 }
its ([:diff]) { should eq -2.5 }
end
end
end
end
context "with work effort on a holiday" do
before do
timesheet.stub(:Date => Date.new(2013,12,24).to_s)
params.stub(:timesheets => [timesheet])
end
it { should have(1).item }
context "the week calculated" do
subject(:workweek) {calculation[0]}
its([:year]) { should eq "2013" }
its([:week]) { should eq "52" }
its([:weekTarget]) { should eq 15.0 }
its([:weekEffort]) { should eq 5.0 }
context "the work efforts" do
subject(:efforts) {workweek[:efforts]}
it { should have(3).items }
context "the first work effort" do
subject(:effort) {efforts[0]}
its ([:effort]) { should eq 0.0 }
its ([:diff]) { should eq -7.5 }
end
context "the second work effort" do
subject(:effort) {efforts[1]}
its ([:effort]) {should eq 5.0}
its ([:diff]) { should eq 5.0}
end
end
end
end
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T22:17:14.783",
"Id": "57084",
"Score": "2",
"body": "@CMW [There are reasons why we close questions that just link to code instead of editing the question for the OP.](http://meta.codereview.stackexchange.com/q/467/2041)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T09:33:41.247",
"Id": "57116",
"Score": "0",
"body": "Don't suggested edits need to be approved by the OP anyway? In that case it's completely under their control, or is it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T13:47:13.320",
"Id": "57137",
"Score": "2",
"body": "@CMW that isn't how it works. other people approve the suggested edits by vote."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T13:51:09.497",
"Id": "57138",
"Score": "0",
"body": "@Malachi, svick My apologies then, I didn't have that case yet of the community approving any edits on my questions. Only did so myself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T14:17:14.113",
"Id": "57141",
"Score": "1",
"body": "@CMW : the edits are always sent to the review queue but that is bypassed if you accept the edit, so it is whatever happens first, vote or OP approval"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T20:12:31.167",
"Id": "57177",
"Score": "0",
"body": "Is there still something wrong with the post that I could change? I mean, since it's still on hold?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T03:16:35.600",
"Id": "57904",
"Score": "0",
"body": "@AndreasFinne StackExchange sites are moderated by the community - there are review queues for suggested edits, close votes, ...and reopen votes - see [here](http://codereview.stackexchange.com/help/privileges)"
}
] |
[
{
"body": "<h1>Spec</h1>\n\n<h2>The Good</h2>\n\n<p>There's not much here that needs changing. </p>\n\n<ul>\n<li>You only check one condition per <code>it</code> or <code>specify</code></li>\n<li>Good use of <code>let</code>, <code>subject</code>, <code>before</code>, etc. to keep the test DRY and simple.</li>\n<li>Appropriate use of <code>#stub</code> for methods which are referentially transparent (when you say <em>#stub</em>, you are telling the reader of the test, \"We don't care how many times this gets called, because it has no side-effects.\"</li>\n</ul>\n\n<h2>Can be improved</h2>\n\n<p>There are some minor inconsistencies in indentation (see #daily_effort).</p>\n\n<p>Some instances of <code>context</code> might be better as <code>describe</code> instead. Use context to indicate a precondition; describe to indicate a class, method, or behavior being tested.</p>\n\n<pre><code>describe SomeClass\n\n context 'when things are setup a certain way' do\n\n describe 'the aspect of its behavior being checked' do\n its(:metasyntacticvariable) {should eq :foo}\n its(:meaning) {should eq 42}\n end\n\n describe 'a different aspect of its behavior being checked' do\n its(:shoe_size) {should eq 7}\n its(:hair_color) {should eq 'brown'}\n end\n\n end\n\n context 'when things are setup a different way' do\n # etc\n end\n\nend\n</code></pre>\n\n<p>Here are a few of the <code>context</code> calls I would consider changing to <code>describe</code>:</p>\n\n<pre><code>context \"the work efforts\"\ncontext \"the first work effort\"\ncontext \"the second work effort\"\n</code></pre>\n\n<p>There's a little bit of missing test coverage:</p>\n\n<ul>\n<li>In #get_timesheet, the <code>.first</code> can be changed to <code>.last</code> and the test still passes.</li>\n<li>In #group_efforts, the entire <code>.sort {...}</code> can be removed without the test noticing.</li>\n</ul>\n\n<h1>The code under test</h1>\n\n<h2>The good</h2>\n\n<p>There's a little more here that could be better, but overall the class has a lot going for it:</p>\n\n<ul>\n<li>Small, concrete methods</li>\n<li>Immutable</li>\n<li>Good names</li>\n</ul>\n\n<h2>Could be improved</h2>\n\n<p>In #group_efforts, the sort can <em>probably</em> be changed from:</p>\n\n<pre><code>sort { |a, b| b.efforts[0].date <=> a.efforts[0].date \n</code></pre>\n\n<p>to:</p>\n\n<pre><code>sort_by { |e| e.efforts.first.date }\n</code></pre>\n\n<p>I say <em>probably</em> because the sort has no test coverage.</p>\n\n<p>There's much that could be improved if attribute access were via accessor methods rather than by <code>[]</code>, but that goes outside the scope of this class and imposes changes on its collaborators. For example, if an effort's target could be accessed by <code>effort.target</code> instead of <code>effort[:target]</code>, then this:</p>\n\n<pre><code>efforts.inject(0){|sum,e| sum + e[:target]}\n</code></pre>\n\n<p>could be changed to:</p>\n\n<pre><code>efforts.map(&:target).inject(0, :+)\n</code></pre>\n\n<p>The pipe separator \"|\" appears repeatedly. It deserves a constant.</p>\n\n<p>These methods:</p>\n\n<pre><code> def get_year_from_week_key(key)\n key.split('|')[0]\n end\n\n def get_week_from_week_key(key)\n key.split('|')[1]\n end\n</code></pre>\n\n<p>are a little damp. Consider:</p>\n\n<pre><code> def get_year_from_week_key(key)\n split_key(key)[0]\n end\n\n def get_week_from_week_key(key)\n split_key(key)[1]\n end\n\n def split_key(key)\n key.split('|')\n end\n</code></pre>\n\n<p>In <code>#day_off?</code>\"</p>\n\n<pre><code>date.wday == 0 or date.wday == 6 or params.holidays.include? date.to_s\n</code></pre>\n\n<p>Replace the <code>or</code> with <code>||</code>:</p>\n\n<pre><code>date.wday == 0 || date.wday == 6 || params.holidays.include?(date.to_s) |\n</code></pre>\n\n<p><code>or</code> (and <code>and</code>) have odd (and often surprising) precedence rules. They are not interchangeable with && and ||, a common source of bugs, and are seldom used in practice.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T23:11:43.597",
"Id": "64799",
"Score": "0",
"body": "What about using rspec 2.0 expect vs should? https://github.com/rspec/rspec-expectations/blob/master/Should.md"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T23:33:14.817",
"Id": "64803",
"Score": "0",
"body": "@Fred, good point. Note that it's not the method `should` that's deprecated, it's the use of the globally defined `should`. The use of `should` in the form 'its(:foo) {should eq 1}` is not deprecated."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T22:28:30.260",
"Id": "38799",
"ParentId": "35223",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T11:15:08.110",
"Id": "35223",
"Score": "4",
"Tags": [
"ruby",
"rspec"
],
"Title": "Weekly flex calculator"
}
|
35223
|
<p>My question is for validation of my code (any loop holes / bugs) and guidance the best methodology to implement for my requirement.</p>
<p>I am developing a Python application that will have many classes. We need to communicate in between each class - pass data. It would be very clumsy if across all classes I create a setter/getter method and refer them across different classes, hence I prefer to pass a container object in between all of them:</p>
<pre><code>class One
def __init__(self, container):
class Two
def __init__(self, container):
</code></pre>
<p>Now obviously I want that this container object should be a Singleton object - only one instance to pass multiple data structures. Below is my code for same [class declaration for Container class]:</p>
<pre><code>import abc
class Container(object):
__metaclass__ = abc.ABCMeta
__data1 = 0
__data2 = 0
@abc.abstractmethod
def dummy():
raise NotImplementedError()
def __init__(self):
self.__data1 = 0
self.__data2 = 1
def SetData(self,value):
self.__data1 = value
def GetData(self):
return self.__data1
class Singleton(Container):
_instances = {}
def __new__(class_, *args, **kwargs):
if class_ not in class_._instances:
class_._instances[class_] = super(Singleton, class_).__new__(class_, *args, **kwargs)
return class_._instances[class_]
def dummy():
pass
</code></pre>
<p>Now in my application, I would not be able to create an another separate instance of Container [abstract class] / Singleton class. So I can pass the object of Singleton like as mentioned below:</p>
<pre><code>class One:
def __init__(self, container)
self.value = container.GetData()
................................
container.SetData(9)
Two(container)
class Two:
def __init__(self, container)
self.value = container.GetData()
................................
container.SetData(19)
................................
class Three:
def __init__(self, container)
self.container = Singleton()
................................
container.GetData() # will return value 19 only
container.SetData(19)
................................
if __name__ == "__main__":
container = Singleton()
container.SetData(9)
One(container)
</code></pre>
<p>Please comment on my approach and modifications required if any. This code will be pushed in production box - so I want to double check my implementation.</p>
|
[] |
[
{
"body": "<p>I don't see why you need a singleton. You are already passing around container references as parameters. So, if you only create one container in <code>__main__</code> and pass that to the class instances, they will all be accessing the same container.</p>\n\n<p>Instead of calling <code>Singleton()</code> in <code>Three.__init__</code> you would simply do the usual thing:</p>\n\n<pre><code>class Three:\n def __init__(self, container)\n self.container = container\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T18:49:45.477",
"Id": "35872",
"ParentId": "35226",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T11:56:48.217",
"Id": "35226",
"Score": "0",
"Tags": [
"python",
"classes",
"singleton",
"container"
],
"Title": "Creating a singleton container class for intrer-class messaging"
}
|
35226
|
<p>I'm adding a function to my test library to assist in testing if two <code>IDictionary</code> objects contain the same keys/values.</p>
<p>I need the method to be generic and support a dictionary that has collections as values. So I thought I'd try to do it without using class types.</p>
<p>It <em>appears</em> to be working, but I would like to clarify that I didn't make any mistakes that would impact my tests later.</p>
<pre><code> /// <summary>
/// Checks if two dictionaries contain the same values. Supports recursive
/// dictionaries and collections as values.
/// </summary>
/// <param name="pExpect">Expected value</param>
/// <param name="pActual">Actual value</param>
// ReSharper disable CanBeReplacedWithTryCastAndCheckForNull
public static void dictionary(IDictionary pExpect, IDictionary pActual)
{
Assert.IsNotNull(pExpect);
Assert.IsNotNull(pActual);
if (pExpect.Keys.Count != pActual.Keys.Count)
{
Assert.Fail("Expected {0} keys, but contains {1} keys.", pExpect.Keys.Count, pActual.Keys.Count);
}
object[] expectKeys = new object[pExpect.Keys.Count];
object[] actualKeys = new object[pExpect.Keys.Count];
pExpect.Keys.CopyTo(expectKeys, 0);
pActual.Keys.CopyTo(actualKeys, 0);
// check if the two key sets are the same
CollectionAssert.AreEquivalent(expectKeys, actualKeys);
for (int i = 0, c = expectKeys.Length; i < c; i++)
{
object expect = pExpect[expectKeys[i]];
object actual = pActual[actualKeys[i]];
// both can be null
if (expect == null && actual == null)
{
continue;
}
// both must be assigned a value
Assert.IsNotNull(expect);
Assert.IsNotNull(actual);
// must be same types
Assert.AreEqual(expect.GetType(), actual.GetType());
if (expect is IDictionary)
{
// support recursive dictionary checks
dictionary((IDictionary)expect, (IDictionary)actual);
}
else if (expect is ICollection)
{
CollectionAssert.AreEquivalent((ICollection)expect, (ICollection)actual);
}
else
{
Assert.AreEqual(expect, actual);
}
}
}
</code></pre>
<p>I am wondering if my last check <code>Assert.AreEqual(expect, actual)</code> will cover most remaining test cases.</p>
<p><strong>EDIT:</strong> Fixed testing dictionaries that have keys in different orders.</p>
|
[] |
[
{
"body": "<p>Your code doesn't work, because items in a dictionary aren't ordered in any way.</p>\n\n<p>Example code that fails your test:</p>\n\n<pre><code>dictionary(\n new Dictionary<int, int> { { 0, 0 }, { 1, 1 } },\n new Dictionary<int, int> { { 1, 1 }, { 0, 0 } });\n</code></pre>\n\n<p>Some more notes about your code:</p>\n\n<pre><code>public static void dictionary(IDictionary pExpect, IDictionary pActual)\n</code></pre>\n\n<p><code>dictionary</code> is a bad name for this method, because it doesn't really explain what it's supposed to do. Something like <code>DictionaryEqualityTest</code> would be better.</p>\n\n<p>Also, I would avoid using the non-generic <code>IDictionary</code> if possible, <code>IDictionary<TKey, TValue></code> would be better (though it would complicate the recursion).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T22:17:04.283",
"Id": "57083",
"Score": "0",
"body": "thanks for the fail. I'll see if I can fix it. I know the name is weak, but it's in a class called \"Same\" which does nothing but same checks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T23:25:32.150",
"Id": "57086",
"Score": "0",
"body": "I fixed the problem and updated the question. thanks for the help."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T22:09:34.683",
"Id": "35255",
"ParentId": "35233",
"Score": "4"
}
},
{
"body": "<p>You could get an endless recursion with the following code:</p>\n\n<pre><code>var dict1 = new Hashtable(); \nvar dict2 = new Hashtable();\ndict1.Add(1,dict1);\ndict2.Add(1,dict2);\ndictionary(dict1,dict2);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-03T15:36:25.110",
"Id": "36579",
"ParentId": "35233",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "35255",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T17:15:11.390",
"Id": "35233",
"Score": "4",
"Tags": [
"c#",
"unit-testing",
"hash-map"
],
"Title": "Test if two IDictionary objects contain the same values"
}
|
35233
|
<p>I'm currently working on a BMI calculator and just wondered if there was a shorter or more condensed version of doing the <code>if</code> validating statement.</p>
<p>I have currently done it this way for both Height and Weight, but I find it to be a mess and it seems to cluttered. There must be a way of shortening this down or condensing it.</p>
<pre><code>boolean Hresult = false;
int resulth = 0;
while(Hresult == false) {
System.out.print("\nPlease enter your feet: ");
int heightft = scanner.nextInt();
if (heightft >=2 && heightft <=7 ){
System.out.println("You entered: " + heightft);
Hresult = true;
}
else {
System.out.println("Please try again");
Hresult = false;
}
System.out.print("Please enter your inches: ");
int heightin = scanner.nextInt();
if (heightin >=0 && heightin <=11 ){
System.out.println("You entered: " + heightin);
Hresult = true;
}
else {
System.out.println("Please try again");
Hresult = false;
}
int resultin = (heightft * 12);
resulth = (resultin + heightin);
}
return resulth;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T18:36:10.267",
"Id": "57034",
"Score": "0",
"body": "That's not a natural way of asking for height. Users should be able to enter height as 5'9\", for example, and the computer should parse it. It would also simplify the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T18:39:20.047",
"Id": "57035",
"Score": "0",
"body": "I know, unfortunately I'm unsure of how to tell the console to read in the two different integers and then validate them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T18:41:12.143",
"Id": "57036",
"Score": "7",
"body": "Don't read two different integers. Read a single string and the extract the value(s) using a regular expression (keeping in mind that `6'` is shorthand for `6'0\"` and you probably don't want to allow negative values)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T19:19:00.270",
"Id": "57045",
"Score": "6",
"body": "Feature request: Add support for the metric system! :)"
}
] |
[
{
"body": "<p>What about some while blocks?</p>\n\n<pre><code>int heightft = 0;\nboolean validHeight = false;\ndo {\n height = scanner.nextInt();\n validHeight = heightft >=2 && heightft <=7;\n} while( !validHeight );\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T19:12:43.390",
"Id": "57042",
"Score": "0",
"body": "@Malachi I don't really agree that `while` is better coding practice / more readable than `do while`. They both have their uses I think. You have a (more or less) reliable source for that? As far as I can see, using `height` instead of `heightft` within the do-while loop is probably just a typo. Although I agree that this code could be improved, there's no use for a `validHeight` variable here. Just change the while condition."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T19:15:01.143",
"Id": "57043",
"Score": "0",
"body": "@SimonAndréForsberg, I agree with you. but the way that it is written it will fall into an infinite loop regardless of how the `while` statement is written, if the `heightft` is not valid. it would be better as an `if` statement, which is what the OP already has."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T19:18:03.717",
"Id": "57044",
"Score": "1",
"body": "@Malachi `do { heightft = scanner.nextInt(); } while (heightft < 2 || heightft > 7);` How would that be an infinite loop?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T19:22:42.057",
"Id": "57047",
"Score": "1",
"body": "@SimonAndréForsberg, my bad. I see it now. still, if the code should be a `do while` then it should be written `do{height =scanner.nextInt();boolean validHeight = heightft >=2 && heightft<=7;}while(!validHeight);` if that is even possible otherwise it should be written as `while (!validHeight)...` it will still enter the while statement on the first run, and it is clear what the condition is"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T18:41:46.350",
"Id": "35238",
"ParentId": "35235",
"Score": "-3"
}
},
{
"body": "<p>The short answer is: Yes, there are ways to improve it!</p>\n\n<p><strong>Coding conventions</strong></p>\n\n<p>First of all, you are not following some Java coding conventions of indentation and where to put <code>}</code>-characters and similar.</p>\n\n<p><strong>Error messages</strong></p>\n\n<p>\"Please try again\" is not a message that really describes what went wrong. If I would see that message my first reaction would be to try to enter <strong>the exact same value</strong> again, which would just give me the same error message.</p>\n\n<p><strong>What your code does</strong></p>\n\n<p>Your code is essentially divided into two parts. The first part is:</p>\n\n<pre><code> System.out.print(\"\\nPlease enter your feet: \");\n int heightft = scanner.nextInt();\n\n if (heightft >= 2 && heightft <= 7) {\n System.out.println(\"You entered: \" + heightft);\n Hresult = true;\n }\n else {\n System.out.println(\"Please try again\"); \n Hresult = false;\n }\n</code></pre>\n\n<p>Second part:</p>\n\n<pre><code> System.out.print(\"Please enter your inches: \");\n int heightin = scanner.nextInt();\n\n if (heightin >= 0 && heightin <= 11) {\n System.out.println(\"You entered: \" + heightin);\n Hresult = true;\n }\n else {\n System.out.println(\"Please try again\"); \n Hresult = false;\n } \n</code></pre>\n\n<p>Hresult in the first part of the code essentially <strong>has no effect because it will be overwritten</strong> by Hresult in the second part.</p>\n\n<p>Now let's see what the common areas of this code are:</p>\n\n<ul>\n<li>Show a message</li>\n<li>Read an int from the Scanner</li>\n<li>Check the range of the entered value</li>\n<li>Show what you entered</li>\n<li>Return whether or not the result was successful.</li>\n</ul>\n\n<p>This could become <strong>it's own method</strong>.</p>\n\n<pre><code>public static int inputWithExpectedRange(String message, int min, int max) {\n do {\n System.out.print(message);\n int value = scanner.nextInt();\n\n if (value >= min && value <= max) {\n System.out.println(\"You entered: \" + value);\n }\n else {\n System.out.println(\"Expected a value between \" + min + \" and \" + max + \". Please try again\"); \n } \n }\n while (value < min || value > max);\n return value;\n}\n</code></pre>\n\n<p>Now what you can do is to call this method twice from your previously existing method. It is also likely that you will find use for that method when the user should enter his/her weight.</p>\n\n<pre><code>System.out.println(); // this will print a line break *before* entering the input-method.\nint feet = inputWithExpectedRange(\"Please enter your feet: \", 2, 7);\nint inches = inputWithExpectedRange(\"Please enter your inches: \", 0, 11));\nreturn feet * 12 + inches;\n</code></pre>\n\n<p>Violà.</p>\n\n<p><strong>An entirely different approach</strong></p>\n\n<p>As mentioned in the comments to your question, you can also use <a href=\"http://www.regular-expressions.info\">Regular Expressions</a> to verify input and parse it. Here is a brief example of how to use Regular Expressions to input this. I will let you work on the details for it (such as making sure <code>feet</code> and <code>inches</code> are in the proper ranges). And you probably also want it inside some kind of loop (either <code>while</code> or <code>do-while</code>) to make sure that the user enters acceptable values.</p>\n\n<pre><code> String input = scanner.nextLine();\n String regex = \"(\\\\d+)'(\\\\d+)\\\"\";\n Pattern pattern = Pattern.compile(regex);\n Matcher matcher = pattern.matcher(input);\n if (!matcher.find()) {\n System.out.println(\"Input was not in normal feet and inch format\");\n }\n int feet = Integer.parseInt(matcher.group(1));\n int inches = Integer.parseInt(matcher.group(2));\n</code></pre>\n\n<p>If you enter <code>5'11\"</code> the variable <code>feet</code> will be 5 and <code>inches</code> will be 11.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T19:20:05.403",
"Id": "57046",
"Score": "3",
"body": "For better usability, I would use a very liberal regex, like `\"(\\\\d+)(?:\\s+|\\s*[Ff']\\\\D*)(\\\\d+)\"` (accepting any two numbers separated by whitespace or an apostrophe or anything starting with an \"f\"). Then `\"5 ft. 5 in.\"` would also be acceptable. Since the regex is so sloppy, though I would echo the result as feedback."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T23:16:34.693",
"Id": "57085",
"Score": "1",
"body": "I'd recommend handling the case of \"6'\" meaning 6'0\", but otherwise I approve."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T18:48:09.417",
"Id": "35240",
"ParentId": "35235",
"Score": "17"
}
},
{
"body": "<p>@Simon has posted a good solution. Also, several users have suggested that asking for feet and inches at the same time and parsing the response would yield a better user experience. Since you asked for a code review, though, I'd just like to point out some concerns that are not directly related to the prompting problem.</p>\n\n<h3>Loop logic</h3>\n\n<p>Your while-loop doesn't make sense. It looks like your intention is to retry the prompt on invalid input. However, it doesn't actually do that. Once it gets to the bottom of the loop, it's going to <code>return</code> a value immediately no matter what.</p>\n\n<h3>Variable usage</h3>\n\n<p>On top of that, I would add that you aren't using variables very effectively.</p>\n\n<ul>\n<li><strong>Naming two variables similarly</strong> (<code>Hresult</code> and <code>resulth</code>) is confusing.</li>\n<li>A variable name starting with uppercase also defies <strong>convention</strong>.</li>\n<li>Attempting to indirectly influence the <strong>execution flow using a variable</strong> like <code>Hresult</code> is poor practice; you should eliminate such variables in favour of more active means such as <code>continue</code> and <code>break</code>.</li>\n<li><code>resulth</code> is <strong>superfluous</strong>. You can just <code>return 12 * heightft + heightin</code>.</li>\n<li>Even if you did need <code>resulth</code>, you should <strong>declare it near the point of use</strong> to reduce mental workload.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T19:51:26.420",
"Id": "35245",
"ParentId": "35235",
"Score": "4"
}
},
{
"body": "<p>Some people may find it more convinient to enter the height as something like <code>70\"</code> to indicate 5 feet 10 inches. Why disallow that by requiring inches be 11 or fewer?</p>\n\n<p>What about <s>exceptionally</s> abnormally short or <s>exceptionally</s> abnormally tall people?</p>\n\n<p>Also, the code</p>\n\n<pre><code>if (heightin >=0 && heightin <=11 ){\n</code></pre>\n\n<p>would be much better off written as </p>\n\n<pre><code>if (heightin >=0 && heightin < 12 ){\n</code></pre>\n\n<p>since fractional inches do actually exist (even if your implementation doesn't support them).</p>\n\n<p>Validation is not needed here, because, even if a user enters their info wrong, the only thing that can happen is that it might tell them the wrong BMI. Not a critical failure-means-people-die, or even failure-means-monetary-loss; It is only failure-means-try-again-for-free.</p>\n\n<p>By restricting your program, you restrict its possible utility. What if someone wants to enter bogus info for fun? If you allow it, they will be happy, and if you filter it, they will not be.</p>\n\n<p>Get rid of the validation entirely. Users should be able to enter whatever they want into your program, even unlikely values, and more code always means more bugs.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T22:35:48.177",
"Id": "35257",
"ParentId": "35235",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "35240",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T18:32:13.950",
"Id": "35235",
"Score": "7",
"Tags": [
"java",
"validation"
],
"Title": "Shorter way of prompting for a height of x feet y inches?"
}
|
35235
|
<p>I'm wondering what people think about Dependency Injection vs Service Locator patterns. Specifically I'm using Prism with MEF. I'm also using the MVVM pattern.</p>
<p>So I have a service which I export. I also have a class which doesn't export its class type as I don't need that to be registered with MEF. This class is actually a View-Model which is assigned to a hierarchical data template inside a TreeView. </p>
<p>However the view-model needs to import an interface registered with MEF. </p>
<p>Now I have three possible ways to do this:</p>
<ol>
<li>Set an <code>[Import]</code> on the interface and use <code>ComposeParts</code> in the constructor to inject the dependency.</li>
<li>Use <code>SerivceLocator.Current</code> pattern to get the instance of the service.</li>
<li>Pass in the service interface on the constructor, which is kind of a manual dependency injection.</li>
</ol>
<p>Here some example code to demonstrate.</p>
<pre><code>public interface IFooService
{
}
[Export(typeof(IFooService))]
[PartCreationPolicy(CreationPolicy.Shared)]
class FooSevice : IFooService
{
}
</code></pre>
<p>Then the three possible implementation of the View-Model are:</p>
<pre><code>public class TreeItemVM_MefInjection
{
[Import]
public IFooService FooService { get; set; }
public TreeItemVM_MefInjection()
{
var catalog = new AssemblyCatalog
(System.Reflection.Assembly.GetExecutingAssembly());
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
}
public class TreeItemVM_ServiceLocator
{
[Import]
public IFooService FooService { get; set; }
public TreeItemVM_ServiceLocator()
{
FooService = ServiceLocator.Current.GetInstance<IFooService>();
}
}
public class TreeItemVM_ManualInjection
{
public IFooService FooService { get; set; }
public TreeItemVM_ManualInjection(IFooService fooService)
{
FooService = fooService;
}
}
</code></pre>
<p>Each of the tree-view items actually has an <code>ObservableCollection</code> as the tree is hierarchical. Each <code>ViewModel</code> can create it's own children, based on the model data it uses (this is not shown in the above examples just to keep them simple).</p>
<p>So my issues with each of these are:</p>
<ol>
<li>It seems a lot of code to write to get automatic injection and I'm worried about the performance of creating a catalog and container temporarily. Is this OK to do it like this?</li>
<li>The service locator seems easier but I've read that the service locator is an anti-pattern. Should I be concerned with this?</li>
<li>The last one will give better performance as each instance just passes the <code>IFooService</code> interface on the constructor, and can pass it down to it's children when they are instantiated. However if I want to add more dependency injection latter on I need to change the constructor so maybe automatic injection or service locator maybe better.</li>
</ol>
<p>So what would people say is the best method? Is there is a defined best practices method to follow? Are all the methods valid is it is up to the company coding standards to define the pattern to use?</p>
<p>Obviously the <code>TreeItems</code> are just normally instanced with new. I don't want these to be exported to MEF as that is overkill and nothing outside of the class library needs to know about them. They are just normal class that need to have MEF dependency injection or find MEF registered interfaces.</p>
<p>Anyone have an opinion on the most desirable solution and any gotchas I should be aware of? I'm sure there are other possible solutions to this as well. Any info would be appreciated.</p>
|
[] |
[
{
"body": "<ol>\n<li><p><a href=\"http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/\" rel=\"noreferrer\">Service locator is an anti-pattern</a> because it tends to create implicit dependencies which are not easy to see and usually cause grieve when trying to write unit tests. Especially your implementation which references what seems like a singleton instance which can cause additional problems (i.e. you need to take care to reset it between tests).</p>\n<p>Avoid it.</p>\n</li>\n<li><p>I can't say much about the MEF injection but it seems roundabout having to write all that code. It also creates an implicit dependency which will probably cause grieve when unit testing your class and makes it directly dependent on MEF while there is no need for it.</p>\n<p>Avoid it.</p>\n</li>\n<li><p>Clean and simple. Explicit dependency, easy to unit test and injection can be easily manged by any IoC container of your choice (Unity, Ninject, Windsor, etc.).</p>\n<p>The way to go.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T13:38:14.823",
"Id": "57135",
"Score": "3",
"body": "+1 nice answer. I'll only add that the MEF ViewModel is `new`ing up stuff, which means *tight coupling* with stuff that's not declared in the constructor; the SL ViewModel is using *ambient context* and that's bad, the VM could instantiate just about anything; the *poor man's DI* ViewModel not only looks much cleaner, it *says what it wants* and that's in line with the *Hollywood Principle*: don't call them, they'll call you - nobody except your *composition root* should know there's an IoC container involved, if there's one involved. SL is the exact opposite of that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-17T15:10:21.973",
"Id": "229447",
"Score": "0",
"body": "I was going to say exactly the same. By the way, I don't know nothing about MEF but with Unity everything is very simple and approach 3 is automatically resolved."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T10:11:05.633",
"Id": "35286",
"ParentId": "35247",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T20:05:50.090",
"Id": "35247",
"Score": "5",
"Tags": [
"c#",
"dependency-injection"
],
"Title": "Looking for advice - Dependency Injection over Service Locator in Mef"
}
|
35247
|
<p>I'm kind of new to C++ and was just wondering if anyone could give me tips on how I could make my code more efficient (I added some comments to the code to help you understand it better).</p>
<p>Is it a good idea to use <code>switch</code> <code>case</code>s? Is there a way I can use more functions/arrays/pointers?</p>
<p><a href="http://codepad.org/ZVPVODsR" rel="noreferrer">Source code</a></p>
<p>Here is some of the code:</p>
<pre><code>case 1:
//Asks for number to place bet on
cout << endl << "Please choose a number to place your bet on: ";
cin >> betNumber;
//Checks if number is valid (between 1 and 36)
while (betNumber < 1 || betNumber > 36) {
cout << endl << "You must choose a valid number between 1 and 36, inclusive!" << endl;
cout << "Please choose a number to place your bet on: ";
cin >> betNumber;
}
//Asks for amount to bet on that number
cout << endl << "How much would you like to bet on the number " << betNumber << "? $";
cin >> betAmount;
//Checks if minimum amount is $1 and if the player has enough money in their account
while (betAmount < 1 || betAmount > bankAccount) {
cout << endl << "You have $" << bankAccount << " in your bank account: $";
cin >> betAmount;
}
//Seeds random number to the generator
srand(time(0));
//Generates a random number
randomNumber = 1 + (rand() % 36);
cout << endl << "The ball landed on the number " << randomNumber << ".";
//Checks if player won or lost their bet
if (betNumber == randomNumber) {
bankAccount = win(betAmount, betOdds, bankAccount);
cout << endl << "Congratulations, you won! You now have $" << bankAccount << " in your account." << endl;
} else {
bankAccount = lose(betAmount, bankAccount);
cout << endl << "Bad luck, you lost! You now have $" << bankAccount << " in your account." << endl;
}
break;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T20:21:31.483",
"Id": "57061",
"Score": "1",
"body": "Right off the bat, `srand()` should go in `main()`. If you call it repeatedly (such as where you have it now), you'll receive the same random values each time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T20:35:02.200",
"Id": "57064",
"Score": "0",
"body": "Thanks for that, Jamal! Doesn't the `time(0)` ensure that it is random, though?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T20:39:25.850",
"Id": "57065",
"Score": "0",
"body": "It just sets the seed to 0, which is how it's usually done. The problem is with multiple calls to `std::srand()`, which will keep setting it to zero. You don't want that. You want to let `std::rand()` give a \"true\" random value each time, which is also why you use `std::time()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T20:40:06.023",
"Id": "57066",
"Score": "0",
"body": "You could also use `NULL` instead of 0, preferably `nullptr` if you're using C++11."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T20:43:42.117",
"Id": "57068",
"Score": "0",
"body": "As this was provided by a comment, you may make those changes in your original code. For future reference, do not make any changes you receive from *answers*, as that will invalidate them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T11:47:12.893",
"Id": "57120",
"Score": "0",
"body": "Food for thought: English roulette also has 0, and American has 00 on top of that. Bets can be on rows, columns, dozens, colors, odd/even, and you can also bet 1-18 and 19-36. *No more bets!*"
}
] |
[
{
"body": "<p>Since there aren't any loops in your code that aren't waiting for the user to provide some input, it's probably way premature to talk about efficiency. Is your code measurably slow? Does it leave you hanging? If not, unless you have an unusual need, save questions on efficiency for later.</p>\n\n<p>So let's talk about some more important things: readability and maintainability. Here are some tips on ways to improve the readability and maintainability of your code. These aren't hard rules that you should never break (especially the one on comments); they are guidelines on ways to make your life easier that you should learn to bend when the guideline makes things awkward instead.</p>\n\n<p>I hope this helps, even though it may be a lot to take in all at once. Feel free to ask follow-up questions and get other opinions.</p>\n\n<h2>Avoid Redundancy</h2>\n\n<p>Redundancy can show up in many forms. One example of it is in your declaration of arrays, using code like <code>int betType[11] = {35, 17, 8, 11, 5, 2, 1, 1, 2, 1, 1};</code>. Unless there's something very special about the number 11, there's no reason to call it out. Instead just say <code>int betType[] = {35, 17, 8, 11, 5, 2, 1, 1, 2, 1, 1};</code> which will automatically determine the size of the array for you.</p>\n\n<p>When you later check your bounds with <code>while (betChoice < 1 || betChoice > 11) {</code>, you can instead use a calculated size (<code>_countof(betType)</code> or <code>sizeof(betType)/sizeof(betType[0])</code>), or even use a <code>std::vector<int></code> instead of an <code>int[]</code>, and check against the vector's <code>size()</code>.</p>\n\n<p>This will help you avoid magic numbers that don't mean much later. After all, if someone asks you what's special about 11, would you think it's the number of available bet types? But if they asked what betTypes.size() meant, it would be easy to answer.</p>\n\n<p>Another way redundancy shows up is in large blocks of repeating code. For instance, <code>case 1</code> and <code>case 2</code> have almost the same code. In fact I had to read it a couple times to find the part that was different. Sometimes this can be best handled by refactoring similar parts of code into functions, and passing parameters to them that control how they differ. Sometimes it's better just to extract the parts that are identical into simpler functions, and use them. I'll touch on this more below, but I certainly don't have <em>the</em> answer.</p>\n\n<h2>Avoid Obfuscation</h2>\n\n<p>In the code commented <code>Displays a large dollar sign</code>, there are a lot of casts from <code>int</code> to <code>char</code> so that <code>cout</code> prints the value as a character. But the characters in question are not that unusual. Just use the actual character you want to show, for example replacing </p>\n\n<pre><code>cout << endl << \" \" << (char)36 << (char)36 << (char)36 << (char)36 << (char)36;\n</code></pre>\n\n<p>with</p>\n\n<pre><code>cout << endl << \" $$$$$\"\n</code></pre>\n\n<p>This will not only be easier to type or update, it will be easier to read.</p>\n\n<h2>Avoid Comments</h2>\n\n<p>This recommendation is somewhat controversial, but it begins to target your question about functions. Instead of commenting what a line of code does, comment how a block of code does something unusual. When you're first starting out, everything seems unusual, but eventually you will see patterns and only need to comment on things that are not common patterns.</p>\n\n<p>But then, instead of commenting what a block of code does, give it a name instead by putting it in a function. For example, you have several cases where you ask how much the user wants to bet on a number, then loop until they enter a valid number. You could extract this loop into a helper function like this:</p>\n\n<pre><code>int getBetAmount(int bankAccount)\n{\n int betAmount;\n cin >> betAmount;\n while (betAmount < 1 || betAmount > bankAccount)\n {\n cout << endl << \"You have $\" << bankAccount << \" in your bank account: $\";\n cin >> betAmount;\n }\n return betAmount;\n}\n\nint _tmain() {\n : : :\n case 1:\n : : :\n cout << endl << \"How much would you like to bet on the number\" << betNumber << \"? $\";\n betAmount = getBetAmount(bankAccount);\n : : :\n : : :\n case 2:\n : : :\n cout << endl << \"How much would you like to bet on the numbers\" << betNumber << \" and \" << betNumber + 3 << \"? $\";\n betAmount = getBetAmount(bankAccount);\n : : :\n}\n</code></pre>\n\n<p>Find some other code that doesn't change much and extract that into functions as well. For example, the code commented <code>Checks if player won or lost their bet</code>, I see creating a function you'd call like this:</p>\n\n<pre><code>case 1:\n : : :\n bankAccout = awardWinnings(betNumber == randomNumber, betAmount, betOdds, bankAccount);\n break;\ncase 2:\n : : :\n bankAccount = awardWinnings(betNumber == randomNumber || betNumber + 3 == randomNumber, betAmount, betOdds, bankAccount);\n break;\n</code></pre>\n\n<p>After you make these changes, ideally the parts that are different will start to stand out, and the parts that are the same will have good names that tell you what they do even if they don't have a comment. And then you can more easily avoid incorrect comments like <code>case 2</code>'s <code>Check if number is valid (between 1 and 36)</code> that actually checks for 33.</p>\n\n<p>You can also avoid comments by naming constants. Instead of starting with <code>int bankAccount = 500</code> and then 500 lines later referencing 500 to figure out your overall winnings, perhaps declare <code>const int StartingBankAccount = 500;</code> and use the name instead of the number in both places. If you decide to change the initial account wealth, this also helps ensure your ending summary remains correct.</p>\n\n<h2>Avoid Bad Dice</h2>\n\n<p>While this is a toy program, and a person is unlikely to play long enough for it to matter, <code>rand() % max</code> is a flawed approach to generating random numbers. It's flawed in ways too subtle for me to explain (I understand it, but not well enough to explain it). However Stephan T. Lavavej knows it much better and explains it in a video called <a href=\"http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful\" rel=\"noreferrer\">rand() Considered Harmful</a>; watch it and use the approach he recommends if you want a more uniformly distributed random number.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T06:01:43.093",
"Id": "57110",
"Score": "0",
"body": "Thank you so much for all of those amazing tips! I extremely appreciate all of your time and effort! Here is my current code: http://codepad.org/UVgOUz7u"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T06:07:41.460",
"Id": "57111",
"Score": "0",
"body": "I also created a function just then to reduce the code even more! Thanks a lot, Michael!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T13:19:42.320",
"Id": "57133",
"Score": "0",
"body": "You're welcome! I see you've already started to apply the advice. Always be on the look out for more code you can factor into existing or new functions; for example after each call to `getBetAmount` you then call pause; should that then also be part of `getBetAmount`?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T04:08:48.233",
"Id": "35273",
"ParentId": "35248",
"Score": "5"
}
},
{
"body": "<p>I have found a couple of things that could help you improve your code.</p>\n\n<h2>Don't abuse <code>using namespace std</code></h2>\n\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">a bad habit</a> that you'd do well to avoid. I don't know that you've actually done that, but it's an alarmingly common thing for new C++ programmers to do. </p>\n\n<p>An alternative could be to do the following, preferably within the calling function.</p>\n\n<pre><code>using std::cout;\n</code></pre>\n\n<h2>Separate I/O from game logic</h2>\n\n<p>The program currently has game logic and I/O all intermixed. It would be better to separate the two. Specifically I'd recommend that the player, each bet and the roulette wheel each be made separate objects. That way, if you decided to have multiple players with multiple types of bets at the same wheel, it could be done very simply by applying the state of the wheel to each bet and then updating the player's status (account balance) accordingly.</p>\n\n<h2>Eliminate \"magic numbers\"</h2>\n\n<p>There are a few numbers in the code, such as <code>1</code> and <code>36</code> that have a specific meaning in their particular context. By using named constants such as <code>MINIMUM_BET_AMOUNT</code> or <code>WHEEL_SLOTS</code>, the program becomes easier to read and maintain. For cases in which the constant only has sense with respect to a particular object, consider making that constant part of the object.</p>\n\n<h2>Reduce the scope of variables</h2>\n\n<p>Within the current code essentially all variables are all in the same scope. Better would be to minimize the scope of variables so that a variable such as <code>betAmount</code> are only in scope for the duration they're actually needed. Object orientation will help a great deal with that.</p>\n\n<h2>Add realism to the game</h2>\n\n<p>Most real roulette tables have at least one zero slot (many have both 0 and 00). Adding those to the game would make things a little more realistic. I've also seen video screens in casinos which display the last dozen or so results. On a fair wheel this, of course, has no useful value to bettors, but people often have fun looking at the previous results and making some bet based on that, thereby illustrating why they call it <a href=\"https://en.wikipedia.org/wiki/Gambler's_fallacy\" rel=\"nofollow noreferrer\">the Gambler's fallacy</a>.</p>\n\n<h2>Use a menu object or at least a common menu function</h2>\n\n<p>In a number of places in your code, you have something like a menu. Your code presents a couple of options and then asks the user to pick one based on an input number. Rather than repeating that code in many places, it would make sense to make it generic. Only the prompt strings actually change, but the underlying logic of presenting the choices and asking for input are all the same. It looks like you're a beginning programmer, and so perhaps you haven't learned about objects yet, but this kind of repeated task with associated data is really well-suited to <em>object-oriented programming</em> and that's something that C++ is very good at expressing. </p>\n\n<h2>Consider using a better random number generator</h2>\n\n<p>You are currently using this code to generate random numbers:</p>\n\n<pre><code>srand(time(0));\nrandomNumber = 1 + (rand() % 36);\n</code></pre>\n\n<p>There are two problems with this approach. One is that the low order bits of the random number generator are not particularly random, so neither with <code>random1</code> be. On my machine, there's a slight but measurable bias toward 0 with that. The second problem is that you should only seed the random number generator once and not every time it's used.</p>\n\n<p>A better solution, if your compiler and library supports it, would be to use the <a href=\"http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution\" rel=\"nofollow noreferrer\">C++11 `std::uniform_int_distribution</a>. It looks complex, but it's actually pretty easy to use:</p>\n\n<pre><code>// random number generator from Stroustrup: \n// http://www.stroustrup.com/C++11FAQ.html#std-random\nint rand_int(int low, int high)\n{\n static std::default_random_engine re {};\n using Dist = std::uniform_int_distribution<int>;\n static Dist uid {};\n return uid(re, Dist::param_type{low,high});\n}\n</code></pre>\n\n<p>For a roulette table with possible values 0 to 36, call it with <code>rand_int(0,36);</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-09T13:45:58.397",
"Id": "122360",
"ParentId": "35248",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "35273",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T20:09:05.063",
"Id": "35248",
"Score": "7",
"Tags": [
"c++",
"beginner",
"random",
"game"
],
"Title": "Roulette game in C++"
}
|
35248
|
<p>I did most of my PHP coding back with PHP 4, and among the projects I did was a popular pagination class. I've been meaning to bring it up to date with PHP 5 and OOP practices. I've also been working on updating my database code, using PDO over the deprecated mysql* functions. What I'd like from you is your input and feedback about my updates.</p>
<p><strong>Pagination Class</strong></p>
<pre><code>class Paginator{
public $items_per_page;
public $total_items;
public $current_page;
public $num_pages;
public $mid_range;
public $limit;
public $limit_start;
public $limit_end;
public $return;
public $querystring;
public $ipp_array;
public $get_ipp;
public $get_page;
public function __construct($total,$mid_range=7,$ipp_array=array(10,25,50,100,'All')) {
$this->total_items = $total;
$this->mid_range = $mid_range;
$this->ipp_array = $ipp_array;
$this->items_per_page = (isset($_GET['ipp'])) ? $_GET['ipp'] : $this->ipp_array[0];
$this->get_ipp = isset($_GET['ipp']) ? $_GET['ipp'] : NULL;
$this->get_page = isset($_GET['page']) ? (int) $_GET['ipp'] : 1;
$this->default_ipp = $this->ipp_array[0];
if($this->get_ipp == 'All') {
$this->num_pages = 1;
} else {
if(!is_numeric($this->items_per_page) OR $this->items_per_page <= 0) $this->items_per_page = $this->ipp_array[0];
$this->num_pages = ceil($this->total_items/$this->items_per_page);
}
$this->current_page = (isset($_GET['page'])) ? (int) $_GET['page'] : 1 ; // must be numeric > 0
if($_GET) {
$args = explode("&",$_SERVER['QUERY_STRING']);
foreach($args as $arg) {
$keyval = explode("=",$arg);
if($keyval[0] != "page" And $keyval[0] != "ipp") $this->querystring .= "&" . $arg;
}
}
if($_POST) {
foreach($_POST as $key=>$val) {
if($key != "page" And $key != "ipp") $this->querystring .= "&$key=$val";
}
}
if($this->num_pages > 10) {
$this->return = ($this->current_page > 1 And $this->total_items >= 10) ? "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=".($this->current_page-1)."&ipp=$this->items_per_page$this->querystring\">Previous</a> ":"<span class=\"inactive\" href=\"#\">Previous</span> ";
$this->start_range = $this->current_page - floor($this->mid_range/2);
$this->end_range = $this->current_page + floor($this->mid_range/2);
if($this->start_range <= 0) {
$this->end_range += abs($this->start_range)+1;
$this->start_range = 1;
}
if($this->end_range > $this->num_pages) {
$this->start_range -= $this->end_range-$this->num_pages;
$this->end_range = $this->num_pages;
}
$this->range = range($this->start_range,$this->end_range);
for($i=1;$i<=$this->num_pages;$i++) {
if($this->range[0] > 2 And $i == $this->range[0]) $this->return .= " ... ";
// loop through all pages. if first, last, or in range, display
if($i==1 Or $i==$this->num_pages Or in_array($i,$this->range)) {
$this->return .= ($i == $this->current_page And $this->get_page != 'All') ? "<a title=\"Go to page $i of $this->num_pages\" class=\"current\" href=\"#\">$i</a> \n":"<a class=\"paginate\" title=\"Go to page $i of $this->num_pages\" href=\"$_SERVER[PHP_SELF]?page=$i&ipp=$this->items_per_page$this->querystring\">$i</a> \n";
}
if($this->range[$this->mid_range-1] < $this->num_pages-1 And $i == $this->range[$this->mid_range-1]) $this->return .= " ... ";
}
$this->return .= (($this->current_page < $this->num_pages And $this->total_items >= 10) And ($this->get_page != 'All') And $this->current_page > 0) ? "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=".($this->current_page+1)."&ipp=$this->items_per_page$this->querystring\">Next</a>\n":"<span class=\"inactive\" href=\"#\">Next</span>\n";
$this->return .= ($this->get_page == 'All') ? "<a class=\"current\" style=\"margin-left:10px\" href=\"#\">All</a> \n":"<a class=\"paginate\" style=\"margin-left:10px\" href=\"$_SERVER[PHP_SELF]?page=1&ipp=All$this->querystring\">All</a> \n";
} else {
for($i=1;$i<=$this->num_pages;$i++) {
$this->return .= ($i == $this->current_page) ? "<a class=\"current\" href=\"#\">$i</a> ":"<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=$i&ipp=$this->items_per_page$this->querystring\">$i</a> ";
}
$this->return .= "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=1&ipp=All$this->querystring\">All</a> \n";
}
$this->return = str_replace('&','&amp;',$this->return);
$this->limit_start = ($this->current_page <= 0) ? 0:($this->current_page-1) * $this->items_per_page;
if($this->current_page <= 0) $this->items_per_page = 0;
$this->limit_end = ($this->get_ipp == 'All') ? (int) $this->total_items: (int) $this->items_per_page;
}
public function display_items_per_page() {
$items = NULL;
natsort($this->ipp_array); // This sorts the drop down menu options array in numeric order (with 'all' last after the default value is picked up from the first slot
if(is_null($this->get_ipp)) $this->items_per_page = $this->ipp_array[0];
foreach($this->ipp_array as $ipp_opt) $items .= ($ipp_opt == $this->items_per_page) ? "<option selected value=\"$ipp_opt\">$ipp_opt</option>\n":"<option value=\"$ipp_opt\">$ipp_opt</option>\n";
return "<span class=\"paginate\">Items per page:</span><select class=\"paginate\" onchange=\"window.location='$_SERVER[PHP_SELF]?page=1&amp;ipp='+this[this.selectedIndex].value+'$this->querystring';return false\">$items</select>\n";
}
public function display_jump_menu() {
$option=NULL;
for($i=1;$i<=$this->num_pages;$i++) {
$option .= ($i==$this->current_page) ? "<option value=\"$i\" selected>$i</option>\n":"<option value=\"$i\">$i</option>\n";
}
return "<span class=\"paginate\">Page:</span><select class=\"paginate\" onchange=\"window.location='$_SERVER[PHP_SELF]?page='+this[this.selectedIndex].value+'&amp;ipp=$this->items_per_page$this->querystring';return false\">$option</select>\n";
}
public function display_pages() {
return $this->return;
}
}
</code></pre>
<p><strong>Sample Instantiation</strong></p>
<pre><code><?php
include('paginator.class.php');
try {
$conn = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$num_rows = $conn->query('SELECT COUNT(*) FROM City')->fetchColumn();
$pages = new Paginator($num_rows,9,array(15,3,6,9,12,25,50,100,250,'All'));
echo $pages->display_pages();
echo "<span class=\"\">".$pages->display_jump_menu().$pages->display_items_per_page()."</span>";
$stmt = $conn->prepare('SELECT City.Name,City.Population,Country.Name,Country.Continent,Country.Region FROM City INNER JOIN Country ON City.CountryCode = Country.Code ORDER BY City.Name ASC LIMIT :start,:end');
$stmt->bindParam(':start', $pages->limit_start, PDO::PARAM_INT);
$stmt->bindParam(':end', $pages->limit_end, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();
echo "<table><tr><th>City</th><th>Population</th><th>Country</th><th>Continent</th><th>Region</th></tr>\n";
foreach($result as $row) {
echo "<tr><td>$row[0]</td><td>$row[1]</td><td>$row[2]</td><td>$row[3]</td><td>$row[4]</td></tr>\n";
}
echo "</table>\n";
echo $pages->display_pages();
echo "<p class=\"paginate\">Page: $pages->current_page of $pages->num_pages</p>\n";
echo "<p class=\"paginate\">SELECT * FROM table LIMIT $pages->limit_start,$pages->limit_end (retrieve records $pages->limit_start-".($pages->limit_start+$pages->limit_end)." from table - $pages->total_items item total / $pages->items_per_page items per page)";
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
</code></pre>
<p><strong>Live Demos</strong></p>
<ul>
<li><a href="http://www.catchmyfame.com/paginator/2/ex1.php" rel="nofollow">Demo 1</a></li>
<li><a href="http://www.catchmyfame.com/paginator/2/ex2.php" rel="nofollow">Demo 2</a></li>
</ul>
<p><strong>Areas of Concern</strong></p>
<p>I noticed in my query that if I try to execute the SQL with:</p>
<pre><code>$stmt->execute( array(':start'=>$pages->limit_start,':end'=>$pages->limit_end) );
</code></pre>
<p>I get an error unless I also use <code>$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);</code>. However I can get around that if I use <code>bindParam</code> instead:</p>
<pre><code>$stmt->bindParam(':start', $pages->limit_start, PDO::PARAM_INT);
$stmt->bindParam(':end', $pages->limit_end, PDO::PARAM_INT);
$stmt->execute();
</code></pre>
<p>Should I be using <code>$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);</code> or the separate bindParam calls?<code>bindParam</code> seems like a decent solution, whereas using <code>ATTR_EMULATE_PREPARES</code>seems a little hacky.</p>
<p>Within the class, am I setting the visibility (public, private, protected) of my parameters and methods properly?</p>
<p>If you see anything that jumps out at you like "what in the world was he thinking?", you can assume that I was dealing with something I hadn't done before. Any tips or suggestions overall would be appreciated.</p>
|
[] |
[
{
"body": "<p>Okay, I’m going to list anything and everything that came in my mind while reading your code.</p>\n\n<ol>\n<li>Start documenting your code for better maintainability</li>\n<li>Validate every and any user input</li>\n<li>Use proper camelCase notation for property and method names</li>\n<li>Separate your code into more methods (especially in <code>__construct</code>)</li>\n<li>Keep everything <code>protected</code> unless you have a good reason to keep it <code>private</code> or expose it with <code>public</code></li>\n<li>Use single <strong>or</strong> double quotes throughout your code, but don’t mix it (consistency)</li>\n<li>Enclose your variables in <code>{}</code> if you embed them in strings</li>\n<li>Use single quotes for your HTML if you use double quotes for creating the string (prevent escaping mistakes)</li>\n<li>Use namespace’s (even if you don’t need them now)</li>\n</ol>\n\n<p>An example class:</p>\n\n<pre><code><?php\n\n/*!\n * My license\n */\nnamespace \\Fleshgrinder;\n\n/**\n * Example class for Code Review at Stack Exchange.\n *\n * @author Fleshgrinder <email@example.com>\n */\nclass ExampleClass {\n\n /**\n * The example class's example property.\n *\n * @var mixed\n */\n protected $camelCasePropertyName;\n\n /**\n * Instantiate new example class.\n *\n * @var string $param1\n * Example parameter 1.\n * @var string $param2 [optional]\n * Optional example parameter 2.\n * @throws \\RuntimeException\n */\n public function __construct($param1, $param2 = \"foo\") {\n if ($param2 == \"foo\") {\n $this->camelCasePropertyName = $this->camelCaseMethodName();\n }\n elseif ($param2 == \"bar\") {\n throw new \\RuntimeException(\"No bar!\");\n }\n else {\n $this->camelCasePropertyName = $param1;\n }\n }\n\n /**\n * Get <var>$str</var> wrapped in <code>span</code> HTML element.\n *\n * @param string $str\n * The string to wrap.\n * @return string\n * The wrapped string.\n */\n protected function camelCaseMethodName($str) {\n return \"<span class='foo'>{$str}</span>\";\n }\n\n}\n</code></pre>\n\n<hr>\n\n<p>Example regarding creation of methods that help to understand the code better (see comments):</p>\n\n<pre><code><?php\n\n// No comments to keep it short, but always write comments!\nclass Database extends FictivePHPDBClass {\n\n public function __construct($user, $password, $host, $port, $database) {\n $this->setUser($user);\n $this->setPassword($password);\n $this->setHostname($host);\n $this->setPort($port);\n $this->connect();\n $this->selectDatabase($database);\n }\n\n protected function setUser($user) {\n if (empty($user) || !is_string($user)) {\n throw new \\IllegalArgumentException(\"Username cannot be empty.\");\n }\n $this->user = $user;\n }\n\n protected function setPassword($password) {}\n\n protected function setHostname($hostname) {}\n\n protected function setPort($port) {}\n\n protected function connect() {\n $phpDB = parent::connect($this->user, $this->password, $this->hostname, $this->port);\n if ($phpDB->errorCount > 0) {\n throw new \\Fleshgrinder\\Exception\\DatabaseException(\"Couldn't connect to {$this->hostname} database.\");\n }\n $this->connection = $phpDB;\n }\n\n protected function selectDatabase($database) {\n if (empty($database) || !is_string($database)) {\n throw new \\IllegalArgumentException(\"Bla bla ...\");\n }\n if (!($this->connection instanceof \\FictivePHPDBClass)) {\n throw new \\LogicException(\"Bla bla ...\");\n }\n $this->connection->selectDatabase($database);\n if ($this->connection->errorCount > 0) {\n throw new \\Fleshgrinder\\Exception\\DatabaseException(\"Bla bla ...\");\n }\n }\n\n}\n</code></pre>\n\n<p>That's stuff you often see in OO PHP code, wrapping some other classes and trying to make some real OO code out of them. But what I really want to show you is the fact that the methods are short, easy to understand because of that and that you already know what each method does only by reading their name.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T21:29:51.560",
"Id": "57077",
"Score": "0",
"body": "Awesome, just the kind of input I'm looking for, thanks. Could you expand on point #4?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T21:40:01.177",
"Id": "57078",
"Score": "0",
"body": "Try to create methods (functions in OO) that have a name that explains what the do and try to keep the method's body (the actual code) short, so that's easy to grasp what's going on. For instance, start by calling a method for each if/else if/else you have. I extend my answer with an example in a minute."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T12:51:33.770",
"Id": "57128",
"Score": "0",
"body": "You've added a sample defining `class Database extends FictivePHPDBClass`. Please, please, please: it would appear you're advocating/approving of extending from classes like `PDO`! Don't... PDO child classes are like broken pencils: pointless. I've been quite verbose [about the subject here!](http://codereview.stackexchange.com/questions/29362/very-simple-php-pdo-class/29394#29394)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T13:14:44.130",
"Id": "57131",
"Score": "0",
"body": "It's only an example for coding style and not a call to extend core classes. I illustrated it with something one often stumbles upon in endless projects. Personally I totally agree with your point in almost 99% of the cases (there are exceptions)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T21:27:47.220",
"Id": "35252",
"ParentId": "35251",
"Score": "4"
}
},
{
"body": "<p>You can use commas to separate similarly scoped class properties. This will make your code a little easier to read and make it easier to modify.</p>\n\n<pre><code>public\n $items_per_page,\n $total_items,\n $current_page,\n //etc...\n $get_page\n;\n</code></pre>\n\n<p>You probably shouldn't rely on GET variables. Passing these values in as parameters allows for more extensibility. That being said, I think your constructor might be doing a tad too much already and you might consider using some individual setters. Look into the Single Responsibility Principle. This goes along with what Fleshgrinder said about using more methods.</p>\n\n<p>Please, always use braces on your statements, especially on long complex ones. PHP, by default, does not support true braceless syntax, otherwise you would be able to neglect them everywhere. Doing so makes your code much more legible. The advantages of neglecting them, if there even are any, are negligible.</p>\n\n<pre><code>if(!is_numeric($this->items_per_page) OR $this->items_per_page <= 0) $this->items_per_page = $this->ipp_array[0];\n\n//compared to\nif(!is_numeric($this->items_per_page) OR $this->items_per_page <= 0) {\n $this->items_per_page = $this->ipp_array[0];\n}\n</code></pre>\n\n<p>The same applies for foreach loops. In addition, ternary statements are nifty, but should only be used when doing so does not detract from legibility. In the following code I have no idea what's going on.</p>\n\n<pre><code>foreach($this->ipp_array as $ipp_opt) $items .= ($ipp_opt == $this->items_per_page) ? \"<option selected value=\\\"$ipp_opt\\\">$ipp_opt</option>\\n\":\"<option value=\\\"$ipp_opt\\\">$ipp_opt</option>\\n\";\n\n//compared to\nforeach($this->ipp_array as $ipp_opt) {\n if($ipp_opt == $this->items_per_page) {\n $items .= \"<option selected value=\\\"$ipp_opt\\\">$ipp_opt</option>\\n\";\n } else {\n $items .= \"<option value=\\\"$ipp_opt\\\">$ipp_opt</option>\\n\";\n }\n}\n</code></pre>\n\n<p>Additionally, the above could be modified to reduce repetition like so:</p>\n\n<pre><code>$selected = $ipp_opt == $this->items_per_page ? 'selected' : '';\n$items .= \"<option $selected value=\\\"$ipp_opt\\\">$ipp_opt</option>\\n\";\n</code></pre>\n\n<p>In response to some of Fleshgrinder's points:</p>\n\n<p><strong>Use proper cameCase notation for property and method names</strong></p>\n\n<p>This is a stylistic choice, though one I agree with. This is entirely up to you.</p>\n\n<p><strong>Keep everything protected unless you have a good reason to keep it private or expose it with public</strong></p>\n\n<p>Good advice, but to expand upon this, an element only has to be public if it should be accessible or modifiable outside of its current scope (the current class).</p>\n\n<p><strong>Use single or double quotes throughout your code, but don’t mix it (consistency)</strong></p>\n\n<p>Again, another stylistic point... sort of... Single quotes are string literals. This means that PHP interprets the contents between single quotes as being nothing more than a string. Double quotes are processed by PHP for evaluation, thus you are able to put PHP variables directly in the string and have them be properly escaped. As such, double quotes are ever-so-slightly slower, but it is negligible. Consistency is important, but don't let it stop you from using single/double quotes as they were meant to be used.</p>\n\n<p><strong>Enclose your variables in {} if you embed them in strings</strong></p>\n\n<p>This is only necessary if the variable you are including is complex. For example:</p>\n\n<pre><code>$string = \"This is $simple, and this is {$complex[ 'elem' ]}\";\n</code></pre>\n\n<p>Sorry this is kind of rushed, I might come back and add to this later. Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T00:07:15.957",
"Id": "57345",
"Score": "0",
"body": "Thanks! I understand what you and Fleshgrinder are saying about the long constructor, but I'm not sure what I might gain by breaking it up. It really only has a single purpose and that's to do the bulk of the work building the actual pagination. Am I missing the obvious here? How should I break the constructor up and what will the user gain?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T02:10:47.000",
"Id": "57350",
"Score": "0",
"body": "Grouping with spaces of properties isn't good if you want to properly document them all because the visibility is too far away. Always using `{}` = consistency. Double quotes are faster than single quotes, this is a common disbelief (see http://micro-optimization.com/single-vs-double-quotes) and embedding rather than concatenating is faster as well. Other than that I agree on all your points. @j08691 it greatly improves maintainability, but it hurts performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T02:49:17.410",
"Id": "57351",
"Score": "0",
"body": "@Fleshgrinder: What do you mean the visibility is too far away? You can use doccomments like normal. Always using `{}` isn't consistency, its a preference. Its only necessary for complex variables. As for your double vs single quotes argument, I'll have to do some of my own research on that, because I've seen a similar site that proposed the exact opposite, either way, the difference is negligible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T02:56:54.227",
"Id": "57352",
"Score": "0",
"body": "@j08691: It improves maintainability, as fleshgrinder said, and the loss in performance is negligible. The users will not gain anything from it, but those extending your code will better be able to read it and extend it, thus you will better be able to read it and extend it. A couple of examples of how you could abstract methods from your constructor, initiation() to initialize properties and getQueryString() to produce the query string based on input type. There are more in your code, these are just a couple."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T03:19:50.487",
"Id": "57354",
"Score": "0",
"body": "@mseancole - Thanks. In my older code the constructor was smaller and the class had more methods, but I thought combining them would make more sense and streamline things, since the constructor really is doing the heavy lifting in this particular class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T08:07:51.600",
"Id": "57367",
"Score": "0",
"body": "Of course it's consistency if your coding standard says to always use `{}` to enclose variables. Otherwise your Devs always have to think \"is this now complex or not?\". I made various benchs for single and double to decide for my latest project and doubles were faster and embedding is very nice. Not using methods for everything is even a performance tip from Google (see: https://developers.google.com/speed/articles/optimizing-php) and it really helps to gain performance. A function call in PHP is very costly. But this is only from interest for HP sites. Maintainability is more important."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T08:25:05.570",
"Id": "57378",
"Score": "0",
"body": "And regarding the commas in the properties. Of course you can document it, but the visibility is extremely far away from the documented property. It also complicates later changes to the visibility. Consider a class with 10+ properties and proper documentation."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T23:09:45.043",
"Id": "35389",
"ParentId": "35251",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T21:09:27.773",
"Id": "35251",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"classes",
"pdo",
"pagination"
],
"Title": "Critique Requested on PHP Pagination Class"
}
|
35251
|
<p>This copies the level graphics but uses a scale parameter. If the scale is 1, it copies a screen size segment. If it's 2, it copies a half-screen size piece and scales it to the screen size, etc.</p>
<p>How can I optimise this game level code or achieve the same outcome but simpler?</p>
<pre><code> public void render(Graphics g){
int test = (screenwidth/2)-((screenwidth/2)/scale);
int test2 = (screenheight/2)-((screenheight/2)/scale);
int scaledstartx=test;
int scaledstarty=test2;
int scaledwidth=screenwidth-test;
int scaledheight=screenheight-test2;
int locationx=(wherex)+halfpwidth-(screenwidth/2);
int locationy=(wherey)+halfpheight-(screenheight/2);
g.drawImage(DrawnLevel,0,0,screenwidth,screenheight,
scaledstartx+locationx,scaledstarty+locationy, scaledwidth+locationx,scaledheight+locationy, null );
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T01:01:07.703",
"Id": "57093",
"Score": "1",
"body": "Can you provide a bit more code? Where the screenwidth, screenheight, wherex, wherey, halfpwidth and halfpheight variables are declared? Where else they are used? What is their intended purpose? How they are initialized? What is the DrawnLevel (its name looks like a class, but it is being used as a variable)?"
}
] |
[
{
"body": "<p>First, lets eliminate the <code>test</code> and <code>test2</code> variables, which are uneeded (we already have <code>scaledstartx</code> and <code>scaledstarty</code>). Second keep <code>screenwidth/2</code> and <code>screenheight/2</code> in variables to avoid recalculating it over and over (the compiler will already do this, but doing manually the code will become clearer). Third, to increase the readability a bit, lets avoid doing calculations in the parameters.</p>\n\n<p>So, this is your code now:</p>\n\n<pre><code>public void render(Graphics g) {\n\n int halfScreenWidth = screenwidth / 2;\n int halfScreenHeight = screenheight / 2;\n int scaledStartX = halfScreenWidth - (halfScreenWidth / scale); \n int scaledStartY = halfScreenHeight - (halfScreenHeight / scale); \n\n int scaledWidth = screenwidth - scaledStartX;\n int scaledHeight = screenheight - scaledStartY;\n int locationX = wherex + halfpwidth - halfScreenWidth;\n int locationY = wherey + halfpheight - halfScreenHeight;\n\n int spriteStartX = scaledStartX + locationX;\n int spriteStartY = scaledStartY + locationY;\n int spriteEndX = scaledWidth + locationX;\n int spriteEndY = scaledHeight + locationY;\n g.drawImage(DrawnLevel, 0, 0, screenwidth, screenheight, spriteStartX,\n spriteStartY, spriteEndX, spriteEndY, null);\n }\n</code></pre>\n\n<p>We can improve it by observing that the terms in the <code>spriteblabla</code> variables are decomposed in terms that have <code>halfScreenWidth</code> and <code>halfScreenHeight</code> both adding and subtracting. So, we can achieve a simpler expression. To do so, lets replace the variables in the assignment to the <code>spriteblabla</code> variables:</p>\n\n<pre><code>public void render(Graphics g) {\n\n int halfScreenWidth = screenwidth / 2;\n int halfScreenHeight = screenheight / 2;\n\n int spriteStartX = halfScreenWidth - (halfScreenWidth / scale) + wherex + halfpwidth - halfScreenWidth;\n int spriteStartY = halfScreenHeight - (halfScreenHeight / scale) + wherey + halfpheight - halfScreenHeight;\n int spriteEndX = screenwidth - (halfScreenWidth - (halfScreenWidth / scale)) + wherex + halfpwidth - halfScreenWidth;\n int spriteEndY = screenheight - (halfScreenHeight - (halfScreenHeight / scale)) + wherey + halfpheight - halfScreenHeight;\n\n g.drawImage(DrawnLevel, 0, 0, screenwidth, screenheight, spriteStartX,\n spriteStartY, spriteEndX, spriteEndY, null);\n }\n</code></pre>\n\n<p>Now, lets simplify that, since (<code>halfScreenWidth - halfScreenWidth</code>) and (<code>screenwidth - halfScreenWidth - halfScreenWidth</code>) are zero:</p>\n\n<pre><code>public void render(Graphics g) {\n\n int halfScreenWidth = screenwidth / 2;\n int halfScreenHeight = screenheight / 2;\n\n int spriteStartX = -(halfScreenWidth / scale) + wherex + halfpwidth;\n int spriteStartY = -(halfScreenHeight / scale) + wherey + halfpheight;\n int spriteEndX = (halfScreenWidth / scale) + wherex + halfpwidth;\n int spriteEndY = (halfScreenHeight / scale) + wherey + halfpheight;\n\n g.drawImage(DrawnLevel, 0, 0, screenwidth, screenheight, spriteStartX,\n spriteStartY, spriteEndX, spriteEndY, null);\n }\n</code></pre>\n\n<p>Now, moving some common subexpressions into variables:</p>\n\n<pre><code>public void render(Graphics g) {\n\n int halfScaledWidth = screenwidth / 2 / scale;\n int halfScaledHeight = screenheight / 2 / scale;\n int spriteCenterX = wherex + halfpwidth;\n int spriteCenterY = wherey + halfpheight;\n\n int spriteStartX = spriteCenterX - halfScaledWidth;\n int spriteStartY = spriteCenterY - halfScaledHeight;\n int spriteEndX = spriteCenterX + halfScaledWidth;\n int spriteEndY = spriteCenterY + halfScaledHeight;\n\n g.drawImage(DrawnLevel, 0, 0, screenwidth, screenheight, spriteStartX,\n spriteStartY, spriteEndX, spriteEndY, null);\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T17:40:24.953",
"Id": "57163",
"Score": "0",
"body": "Should `assert scale != 0;` somewhere in the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T17:47:38.050",
"Id": "57165",
"Score": "1",
"body": "I am assuming that the given code was correct, so didn't thought about asserting. If that is not the case, we should as well `assert screenwidth > 0;`, `assert screenheight > 0;`, `assert DrawnLevel != null;` and `assert g != null;`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T01:39:03.673",
"Id": "35266",
"ParentId": "35258",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "35266",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T22:40:52.487",
"Id": "35258",
"Score": "2",
"Tags": [
"java",
"game",
"graphics"
],
"Title": "Platform game rendering method"
}
|
35258
|
<p>I recently wrote a code for a encoder and decoder that works off of a key and the only way to decode the message is with this program and the case-sensitive key. I have yet to incorporate punctuation but that will come soon. I am currently designing a GUI using the Tkinter module. I would love any feedback.</p>
<pre><code>from random import seed, shuffle
#Encoder Function
def Encoder(user_input,SEED):
user_input = user_input.lower()
letter = ["a","b","c","d","e","f","g","h","i","j","k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
Letter_code = {"a":0,"b":1,"c":2,"d":3,"e":4,"f":5,"g":6,"h":7,"i":8,"j":9,"k":10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,'s':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'z':25}
code = ["a","b","c","d","e","f","g","h","i","j","k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',]
n = []
seed(SEED)
shuffle(code)
for letter in user_input:
for let in letter:
if letter != " ":
if letter == let:
first = Letter_code[let]
n.append(code[first])
else:
n.append("~")
return ''.join(n)
#Decoder Function
def Decoder(user_input,SEED):
user_input = user_input.lower
key_list = ["a","b","c","d","e","f","g","h","i","j","k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
final = ["a","b","c","d","e","f","g","h","i","j","k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
seed(SEED)
shuffle(key_list)
key_code = {}
z = 0
n = []
for key in key_list:
key_code[key] = z
z += 1
for let in user_input:
if let != "~":
for Ke in key_list:
if let == Ke:
a = key_code[Ke]
n.append(final[a])
else:
n.append(" ")
return ''.join(n)
#Prompt
encode_decode = raw_input("Would you like to encode or decode a message?(encode/decode)")
encode_decode = encode_decode.lower()
if encode_decode == "encode":
message = raw_input("Message to encode (no puncuation):")
SEED = raw_input("Key:")
print Encoder(message,SEED)
elif encode_decode == "decode":
message = raw_input("Message to decode:")
SEED = raw_input("Key:")
print Decoder(message,SEED)
else:
print "!!!INVALID RESPONSE!!!"
</code></pre>
|
[] |
[
{
"body": "<h3>Concept</h3>\n\n<p>Interesting idea to use the pseudo-random number generator seed as an encryption key. Note, however, that there's no guarantee that the PRNG implementation will be consistent from release to release of Python, or that it will act identically across platforms. The same goes for the <code>shuffle()</code> function.</p>\n\n<p>As you probably know, you should never try to implement your own cryptography for any meaningful usage, and this substitution cipher is trivially crackable by letter frequency analysis. I'll treat this as nothing more than a fun programming exercise.</p>\n\n<h3>Correctness</h3>\n\n<p>In the decoder, the call to <code>lower()</code> is missing parentheses. The <code>return</code> statement is incorrectly indented.</p>\n\n<p>In the encoder, the <code>letter</code> iteration dummy variable shadows the <code>letter</code> array defined earlier. In effect, the code becomes:</p>\n\n<pre><code>def Encoder(user_input,SEED):\n user_input = user_input.lower()\n letter = [\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\",\"k\",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']\n Letter_code = {\"a\":0,\"b\":1,\"c\":2,\"d\":3,\"e\":4,\"f\":5,\"g\":6,\"h\":7,\"i\":8,\"j\":9,\"k\":10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,'s':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'z':25}\n code = [\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\",\"k\",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',]\n n = []\n seed(SEED)\n shuffle(code)\n for letter in user_input: # Note: This letter variable shadows the previous letter\n let = letter # Originally… for let in letter:\n if letter != \" \":\n if True: # Originally… if letter == let:\n first = Letter_code[let]\n n.append(code[first])\n else:\n n.append(\"~\")\n return ''.join(n)\n</code></pre>\n\n<p>That happens to mostly work! The only thing that breaks was that you had intended to filter out unencodable characters, and now it will raise a <code>KeyError</code> if <code>user_input</code> contains anything other than letters or spaces.</p>\n\n<p>If you dig deeper for a root cause of your bug, you can blame it on a proliferation of variables, causing confusion. See if you can eliminate some variables, and name the remaining ones better.</p>\n\n<h3>Efficiency</h3>\n\n<p>In the encoder, your <code>if letter != \" \"</code> should be put between the outer and inner for-loops. The decoder does it right.</p>\n\n<p>Nested for-loops are a sign of poor efficiency. Lookups should be done using a dictionary. A dictionary would be more efficient (constant-time access rather than a scan through 26 list items), and it would look cleaner in the code. (If you were doing serious cryptography, you would <em>need</em> all operations to be constant-time, to thwart attacks based on analyzing timing.)</p>\n\n<h3>Style</h3>\n\n<ul>\n<li><strong>Naming conventions:</strong>\n<ul>\n<li><code>Encoder(user_input, SEED)</code> → <code>encode(user_input, seed)</code> because it's a function, not a class. You want a verb, not a noun. <code>SEED</code> is not a constant.</li>\n<li><code>Decoder(user_input, SEED)</code> → <code>decode(user_input, seed)</code> for the same reasons.</li>\n<li><code>letter</code> → <code>LETTER</code> because it's a constant.</li>\n<li><code>Letter_code</code> → <code>LETTER_CODE</code> because it's a constant.</li>\n<li><code>n</code> → <code>encoded</code> or <code>n</code> → <code>decoded</code> because <code>n</code> has the connotation of being a number.</li>\n</ul></li>\n<li><strong>Prefer list comprehensions to loops:</strong> If you ever want to transform one list into another list, use a list comprehension instead of a for-loop if it's at all possible. It's one assignment statement, and it forces you to express yourself using higher-level functions rather than step-by-step procedural code.</li>\n<li><strong>Work smarter, not harder:</strong> Save yourself some error-prone typing — let the computer generate your lists of letters and their corresponding codes.</li>\n<li><strong>Symmetry:</strong> The decoder is just the inverse of the encoder, so there's no reason why it should be any more complex.</li>\n<li><p><strong>If-else:</strong> Whenever you have an if-else construct, prefer to put the branch with the shorter body first to reduce mental workload. For example, write the decoder this way:</p>\n\n<pre><code>if let == \"~\":\n n.append(\" \")\nelse:\n for Ke in key_list:\n if let == Ke:\n a = key_code[Ke]\n n.append(final[a])\n</code></pre></li>\n</ul>\n\n<h3>Proposal</h3>\n\n<pre><code>from collections import defaultdict\nfrom random import seed, shuffle\n\ndef encode(plaintext, key):\n \"\"\"\n Performs a toy-grade substitution cipher on plaintext using the key.\n Any characters other than letters and spaces in plaintext will be discarded.\n \"\"\"\n LETTERS = [chr(ord('a') + i) for i in range(26)]\n seed(key) # influences shuffle()\n code = LETTERS[:] ; shuffle(code)\n # letter_code maps LETTERS to a copy of LETTERS that is scrambled using the key;\n # unrecognized characters map to the empty string.\n letter_code = defaultdict(str, zip(LETTERS, code))\n letter_code[' '] = '~'\n return ''.join([letter_code[c] for c in plaintext.lower()])\n\ndef decode(ciphertext, key):\n \"\"\"\n Performs the inverse of encode().\n Any characters other than letters and spaces in ciphertext will be discarded.\n \"\"\"\n LETTERS = [chr(ord('a') + i) for i in range(26)]\n seed(key) # influences shuffle()\n code = LETTERS[:] ; shuffle(code)\n # The inverse of letter_code in encode()\n code_letter = defaultdict(str, zip(code, LETTERS))\n code_letter['~'] = ' '\n return ''.join([code_letter[c] for c in ciphertext.lower()])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T12:12:15.527",
"Id": "57123",
"Score": "1",
"body": "+1, but a couple of points: (i) Python has a built-in [`string.ascii_lowercase`](http://docs.python.org/3/library/string.html#string.ascii_lowercase), so no need to define your own `LETTERS`; (ii) Python strings have a built-in [`translate`](http://docs.python.org/3/library/stdtypes.html#str.translate) method which would simplify this code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T07:53:10.843",
"Id": "35281",
"ParentId": "35259",
"Score": "2"
}
},
{
"body": "<p>Here's a simple way to implement this, using <a href=\"http://docs.python.org/3/library/stdtypes.html#str.maketrans\" rel=\"nofollow\"><code>str.maketrans</code></a> to build the encryption table, and <a href=\"http://docs.python.org/3/library/stdtypes.html#str.translate\" rel=\"nofollow\"><code>str.translate</code></a> to apply it:</p>\n\n<pre><code>from string import ascii_lowercase as letters\nfrom random import seed, shuffle\n\ndef encode(plaintext, key):\n cipher = list(letters)\n seed(key)\n shuffle(cipher)\n return plaintext.translate(str.maketrans(letters, ''.join(cipher)))\n\ndef decode(ciphertext, key):\n cipher = list(letters)\n seed(key)\n shuffle(cipher)\n return ciphertext.translate(str.maketrans(''.join(cipher), letters))\n</code></pre>\n\n<p>You write:</p>\n\n<blockquote>\n <p>the only way to decode the message is with this program and the case-sensitive key</p>\n</blockquote>\n\n<p>Unfortunately, that's not the case. What you've implemented here is a <a href=\"https://en.wikipedia.org/wiki/Substitution_cipher#Simple_substitution\" rel=\"nofollow\">monoalphabetic substitution cipher</a>, and that's easy to break using <a href=\"https://en.wikipedia.org/wiki/Frequency_analysis\" rel=\"nofollow\">frequency analysis</a> and <a href=\"https://en.wikipedia.org/wiki/Known-plaintext_attack\" rel=\"nofollow\">cribbing</a>.</p>\n\n<p>For example, a code-breaker might do this kind of thing:</p>\n\n<pre><code>from collections import Counter\nfrom itertools import combinations\nfrom math import log\n\ndef scorer(n, corpus):\n \"\"\"Return a function that scores a plaintext based on the frequency of\n occurrence of n-grams compared to those found in a corpus.\n\n \"\"\"\n ngrams = len(corpus) - n + 1\n freq = Counter(corpus[i:i + n] for i in range(ngrams))\n log_freq = {k: log(float(v) / ngrams) for k, v in freq.items()}\n min_log_freq = log(0.1 / ngrams)\n def score(plaintext):\n return sum(log_freq.get(plaintext[i:i + n], min_log_freq)\n for i in range(len(plaintext) - n + 1))\n return score\n\ndef decrypt(ciphertext, score_fun):\n \"\"\"Decrypt ciphertext by hill-climbing search, using score_fun\n to score the decryptions. Return the best decryption found.\n\n \"\"\"\n best_score = float('-inf')\n best_cipher = list(letters)\n best_plaintext = ciphertext\n swaps = list(combinations(range(len(letters)), 2))\n while True:\n shuffle(swaps)\n for i, j in swaps:\n cipher = best_cipher[:]\n cipher[i], cipher[j] = cipher[j], cipher[i]\n plaintext = ciphertext.translate(str.maketrans(''.join(cipher), letters))\n score = score_fun(plaintext)\n if score > best_score:\n best_score = score\n best_cipher = cipher\n best_plaintext = plaintext\n break\n else:\n return best_plaintext\n</code></pre>\n\n<p>This easily breaks your encryption if there's enough ciphertext and the cryptanalyst knows (or can guess) a good model:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> ciphertext = encode(plaintext, 442389743299116)\n>>> print(ciphertext)\nvhlgd nvr mdclfflfc ia cdi jdsz ilsdt aq rliilfc mz kds rlrids\naf ikd mvfu, vft aq kvjlfc faiklfc ia ta: afgd as inlgd rkd kvt\noddodt lfia ikd maau kds rlrids nvr sdvtlfc, mxi li kvt fa\nolgixsdr as gafjdsrvilafr lf li, vft nkvi lr ikd xrd aq v maau,\nikaxcki vhlgd, nlikaxi olgixsdr as gafjdsrvilaf?\n>>> corpus = open('War and Peace.txt').read().lower()\n>>> score_fun = scorer(4, corpus)\n>>> print(decrypt(ciphertext, score_fun))\nalice was beginning to get very tired of sitting by her sister\non the bank, and of having nothing to do: once or twice she had\npeeped into the book her sister was reading, but it had no\npictures or conversations in it, and what is the use of a book,\nthought alice, without pictures or conversation?\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T17:35:41.750",
"Id": "57160",
"Score": "0",
"body": "You dropped the space ⟷ tilde substitution that was in the original code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T17:38:25.870",
"Id": "57162",
"Score": "0",
"body": "Yes, that's right. It didn't seem like a critical detail to me: once you've seen how to use `maketrans` then it's easy enough to add more substitutions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T17:43:45.883",
"Id": "57164",
"Score": "0",
"body": "Also, note that this version preserves unrecognized characters, whereas the original would discard them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T17:48:19.153",
"Id": "57166",
"Score": "0",
"body": "In Python 2, it's `string.maketrans()` and `string.translate()`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T17:25:23.247",
"Id": "35304",
"ParentId": "35259",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T22:47:19.630",
"Id": "35259",
"Score": "3",
"Tags": [
"python",
"strings"
],
"Title": "Successful Encoder and Decoder for messages"
}
|
35259
|
<p>I recently wrote a small demo that allows users to send and receive files from an HTML5 Javascript application. It's all client-side. I thought this would be a good place to get feedback about what I've done.</p>
<p>It's hosted here: <a href="http://danielsadventure.info/HTML5FileDemo/" rel="nofollow">http://danielsadventure.info/HTML5FileDemo/</a></p>
<pre><code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>HTML5 File Upload Demo With Saxon-CE and ACE</title>
<style>
/* ACE won't work without explicit CSS. */
.aceEditor
{
position: relative;
width: 500px;
height: 200px;
}
</style>
<script src='Scripts/ace/ace.js'></script>
<script src='Scripts/saxon-ce/Saxonce.nocache.js'></script>
<!--
FileSaver.js is an open-source Javascript project that provides support for the HTML5 FileSaver API
on browsers that do not natively support it.
-->
<script src='Scripts/FileSaver.js'></script>
</head>
<body>
Input XML
<br />
<div class='aceEditor' id='aceInputXml' style='float:left;'>&lt;test&gt;
&lt;testing&gt;
1 2 3
&lt;/testing&gt;
&lt;/test&gt;</div>
<div>
To input XML, drag-and-drop a file into the text editor to the left,
use the file input below, or key XML into the text editor.
<br />
<input id='xmlFileInput' type='file' />
</div>
<br style='clear:both;' />
Input XSLT
<br />
<div class='aceEditor' id='aceInputXslt' style='float:left;'>&lt;!--
Note: This sample XSLT is an "identity" transformation.
The result of applying this transformation to a document should be the original document.
--&gt;
&lt;xsl:stylesheet version=&quot;1.0&quot;
xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot;&gt;
&lt;xsl:template match=&quot;node()|@*&quot;&gt;
&lt;xsl:copy&gt;
&lt;xsl:apply-templates select=&quot;node()|@*&quot;/&gt;
&lt;/xsl:copy&gt;
&lt;/xsl:template&gt;
&lt;/xsl:stylesheet&gt;</div>
<div>
To input XSLT, drag-and-drop a file into the text editor to the left,
use the file input below, or key XSLT into the text editor.
<br />
<input id='xsltFileInput' type='file' />
</div>
<br style='clear:both;' />
Output
<div class='aceEditor' id='aceOutputXml'></div>
<br />
<input type='button' id='btnTransform' value='Transform' />
<input type='button' id='btnSave' value='Save' />
</body>
<script>
(function () {
'use strict';
var aceInputXml, aceInputXslt, aceOutputXml, editors, saxon;
setupAce();
setupFileDragAndDrop();
setupFileInput();
setupFileDownload();
setupSaxonce();
// Initialize the ACE editors and save their object references.
function setupAce() {
var x;
aceInputXml = ace.edit('aceInputXml');
aceInputXslt = ace.edit('aceInputXslt');
aceOutputXml = ace.edit('aceOutputXml');
editors = [aceInputXml, aceInputXslt, aceOutputXml];
for (x in editors) {
editors[x].setTheme('ace/theme/monokai');
editors[x].getSession().setMode('ace/mode/xml');
}
}
// Rig up the Input XML and Input XSLT ACE editors so that the user can populate them
// by dragging and dropping a file that contains XML.
function setupFileDragAndDrop() {
var inputXml, inputXslt;
inputXml = document.getElementById('aceInputXml');
inputXslt = document.getElementById('aceInputXslt');
addFileDragAndDropEventListeners(inputXml, aceInputXml);
addFileDragAndDropEventListeners(inputXslt, aceInputXslt);
function addFileDragAndDropEventListeners(aceInputDiv, aceObject) {
aceInputDiv.addEventListener('dragover', function (e) {
stopEvent(e);
});
aceInputDiv.addEventListener('drop', function (e) {
putFileContentsInAceEditor(e.dataTransfer.files[0], aceObject);
stopEvent(e);
});
function stopEvent(e) {
e.stopPropagation();
e.preventDefault();
}
} // end addFileDragAndDropEventListeners
} // end setupFileDragAndDrop
// Set up the HTML5 file inputs so that the user can populate the ACE editors
// by selecting a file.
function setupFileInput() {
(function () {
var xmlFileInput;
xmlFileInput = document.getElementById('xmlFileInput');
xmlFileInput.addEventListener('change', function (e) {
var file;
file = e.srcElement.files[0];
putFileContentsInAceEditor(file, aceInputXml);
});
})();
(function () {
var xsltFileInput;
xsltFileInput = document.getElementById('xsltFileInput');
xsltFileInput.addEventListener('change', function (e) {
var file;
file = e.srcElement.files[0];
putFileContentsInAceEditor(file, aceInputXslt);
});
})();
}
// Setup the button that the user can click to download the output.
function setupFileDownload() {
var button;
button = document.getElementById('btnSave');
button.addEventListener('click', function (e) {
var outputXmlStr, blob;
outputXmlStr = aceOutputXml.getSession().getValue();
// If the string is null or empty, do nothing.
if (!outputXmlStr)
return;
blob = new Blob([outputXmlStr], { type: 'text/plain' });
// Use the FileSaver.js interface to download the file.
saveAs(blob, 'Output.xml');
});
}
// A small function that takes a file and an ACE editor object.
// The function reads the file and copies its contents into the ACE editor.
function putFileContentsInAceEditor(file, aceEditor) {
var reader, text;
reader = new FileReader();
reader.onload = (function (file) {
text = file.target.result;
aceEditor.getSession().setValue(text);
});
reader.readAsText(file);
}
function setupSaxonce() {
// This object is required by Saxon.
// Saxon will automatically invoke this function when it loads.
window.onSaxonLoad = function () {
saxon = Saxon;
setupTransformButton(Saxon);
};
}
// Note that this gets called when setupSaxonce runs.
// This ensures that the Saxon object is available when the user clicks the [Transform] button.
function setupTransformButton(Saxon) {
var button;
button = document.getElementById('btnTransform');
button.addEventListener('click', function (e) {
var inputXmlStr, inputXsltStr, outputXmlStr,
inputXmlDoc, inputXsltDoc, outputXmlDoc, processor;
// Get the input XML and XSLT strings from the ACE editors.
inputXmlStr = aceInputXml.getSession().getValue();
inputXsltStr = aceInputXslt.getSession().getValue();
// Transform the inputs into Saxon XML documents.
inputXmlDoc = Saxon.parseXML(inputXmlStr);
inputXsltDoc = Saxon.parseXML(inputXsltStr);
// Get an XSLT20Processor object that will apply the transformation.
processor = Saxon.newXSLT20Processor(inputXsltDoc);
// Apply the transformation.
outputXmlDoc = processor.transformToDocument(inputXmlDoc);
outputXmlStr = Saxon.serializeXML(outputXmlDoc);
// Put the results of the transformation in the output ACE editor.
aceOutputXml.getSession().setValue(outputXmlStr);
});
}
})();
</script>
</html>
</code></pre>
|
[] |
[
{
"body": "<p>Your code looks fine to me,</p>\n\n<p>I would probably have <code>aceInputXml</code>, <code>aceInputXslt</code> and <code>aceOutputXml</code> be properties of 'editors'.</p>\n\n<p>Then you could slightly rewrite setupAce as</p>\n\n<pre><code>function setupAce() \n{\n var key;\n editors = \n {\n InputXml : ace.edit('aceInputXml'),\n InputXslt : ace.edit('aceInputXslt'),\n OutputXml : ace.edit('aceOutputXml')\n }\n for (key in editors)\n {\n editors[key].setTheme('ace/theme/monokai');\n editors[key].getSession().setMode('ace/mode/xml');\n }\n}\n</code></pre>\n\n<p>In <code>setupFileDragAndDrop</code> you could probably make it so that you dont have to re-use the id's like <code>'aceInputXml'</code> again ( DRY ). Also you should consider putting stopEvent out of addFileDragAndDropEventListeners, since you will now have 2 stopEvent functions ?</p>\n\n<p><code>setupFileInput</code> contains 50% copy pasted code, not DRY.</p>\n\n<p><code>setupTransformButton</code> contains a lot of declarations and assignments that could be merged.\nAlso since you don't keep the button value around you could simply replace </p>\n\n<pre><code>function setupTransformButton(Saxon) {\n var button;\n button = document.getElementById('btnTransform');\n button.addEventListener('click', function (e) {\n var inputXmlStr, inputXsltStr, outputXmlStr,\n inputXmlDoc, inputXsltDoc, outputXmlDoc, processor;\n // Get the input XML and XSLT strings from the ACE editors.\n inputXmlStr = aceInputXml.getSession().getValue();\n inputXsltStr = aceInputXslt.getSession().getValue();\n // Transform the inputs into Saxon XML documents.\n inputXmlDoc = Saxon.parseXML(inputXmlStr);\n inputXsltDoc = Saxon.parseXML(inputXsltStr);\n // Get an XSLT20Processor object that will apply the transformation.\n processor = Saxon.newXSLT20Processor(inputXsltDoc);\n // Apply the transformation.\n outputXmlDoc = processor.transformToDocument(inputXmlDoc);\n outputXmlStr = Saxon.serializeXML(outputXmlDoc);\n // Put the results of the transformation in the output ACE editor.\n aceOutputXml.getSession().setValue(outputXmlStr);\n });\n }\n</code></pre>\n\n<p>with</p>\n\n<pre><code>function setupTransformButton(Saxon)\n{\n document.getElementById('btnTransform').addEventListener('click', function (e) \n {\n /* Get the input XML and XSLT strings from the ACE editors. */\n var inputXmlStr = aceInputXml.getSession().getValue(), \n inputXsltStr = aceInputXslt.getSession().getValue(); \n /* Transform the inputs into Saxon XML documents. */\n var inputXmlDoc = Saxon.parseXML(inputXmlStr),\n inputXsltDoc = Saxon.parseXML(inputXsltStr);\n /* Get an XSLT20Processor object that will apply the transformation */\n var processor = Saxon.newXSLT20Processor(inputXsltDoc);\n /* Apply the transformation */\n var outputXmlDoc = processor.transformToDocument(inputXmlDoc),\n outputXmlStr = Saxon.serializeXML(outputXmlDoc);\n /* Put the results of the transformation in the output ACE editor. */\n aceOutputXml.getSession().setValue(outputXmlStr);\n });\n}\n</code></pre>\n\n<p>After writing this, I guess it really is a matter of taste, something to consider rather than a hard rule.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T23:44:45.600",
"Id": "35264",
"ParentId": "35263",
"Score": "2"
}
},
{
"body": "<p>I'm just changed a bit, to get local file is running!</p>\n\n<pre><code> function setupFileInput(evt) {\n (function () {\n var xmlFileInput;\n xmlFileInput = document.getElementById('xmlFileInput');\n xmlFileInput.addEventListener('change', function (evt) {\n var file;\n file = evt.target.files[0];\n putFileContentsInAceEditor(file, aceInputXml);\n });\n })();\n (function () {\n var xsltFileInput;\n xsltFileInput = document.getElementById('xsltFileInput');\n xsltFileInput.addEventListener('change', function (evt) {\n var file;\n file = evt.target.files[0];\n putFileContentsInAceEditor(file, aceInputXslt);\n });\n })();\n }\n</code></pre>\n\n<p>Tested in mozilla firefox v.42.0</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-12-29T09:36:18.683",
"Id": "350054",
"Score": "4",
"body": "Please, don't just rewrite the code. CodeReview is about providing feedback and explaining better practices."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-12-29T16:26:33.857",
"Id": "350106",
"Score": "0",
"body": "What do you mean by *\"to get local file is running\"* ? Is that some sort of improvement over the original code? Can you please explain what is the advice you are giving here?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-12-29T09:28:28.897",
"Id": "183856",
"ParentId": "35263",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T23:26:30.563",
"Id": "35263",
"Score": "1",
"Tags": [
"javascript",
"html5",
"file"
],
"Title": "HTML5 File API Demo"
}
|
35263
|
<p>I am an artist and a total beginner in C++.</p>
<p>I would like to find a better method of importing my variables from a <code>values.txt</code> file, which may contain 18 values in one column:</p>
<pre><code>63.64474122
5.214728341
0.405110193
0.261556475
-2.00743E-09
2.76001E-10
34.45902482
15.62249852
0.220861685
2.88127E-09
0.445804979
2.76001E-10
82.11020306
14.02709406
0.507487944
2.88127E-09
-2.00743E-09
0.159178722
</code></pre>
<p>… or it could contain three rows of six tab-separated columns:</p>
<pre><code>63.64474122 5.214728341 0.405110193 0.261556475 -2.00743E-09 2.76001E-10
34.45902482 15.62249852 0.220861685 2.88127E-09 0.445804979 2.76001E-10
82.11020306 14.02709406 0.507487944 2.88127E-09 -2.00743E-09 0.159178722
</code></pre>
<p>I know my code is ugly. Could somebody help?</p>
<pre><code>#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
#define PI 3.14159265
//___________________________________________________
/// variables from the *.txt file
double x_A = 0;
double y_A = 0;
double d_A = 0;
double m_A = 0;
double c_A = 0;
double t_A = 0;
double x_B = 0;
double y_B = 0;
double d_B = 0;
double m_B = 0;
double c_B = 0;
double t_B = 0;
double x_C = 0;
double y_C = 0;
double d_C = 0;
double m_C = 0;
double c_C = 0;
double t_C = 0;
//__________________________________________________
int trash = 0;
//___________________________________
int main() {
ifstream ifs ("values.txt"); ///LOADING
if (!ifs)
// process error
ifs >> trash;
ifs >> x_A;
ifs >> y_A;
ifs >> d_A;
ifs >> m_A;
ifs >> c_A;
ifs >> t_A;
ifs >> x_B;
ifs >> y_B;
ifs >> d_B;
ifs >> m_B;
ifs >> c_B;
ifs >> t_B;
ifs >> x_C;
ifs >> y_C;
ifs >> d_C;
ifs >> m_C;
ifs >> c_C;
ifs >> t_C;
cout << x_A << endl;
cout << y_A << endl;
cout << d_A << endl;
cout << m_A << endl;
cout << c_A << endl;
cout << t_A << endl;
cout << x_B << endl;
cout << y_B << endl;
cout << d_B << endl;
cout << m_B << endl;
cout << c_B << endl;
cout << t_B << endl;
cout << x_C << endl;
cout << y_C << endl;
cout << d_C << endl;
cout << m_C << endl;
cout << c_C << endl;
cout << t_C << endl;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T03:43:35.713",
"Id": "57215",
"Score": "0",
"body": "As a fly-by comment, it seems like this should possibly be something like a `struct xydmct { double x, y, d, m, c, t; }` with appropriate constructor, `operator>>` and `operator<<` functions. This would cut down on the repetition or allow it to be placed in a container such as a vector. Would you need help figuring out how to do that?"
}
] |
[
{
"body": "<p>Storing the data in 18 independent variables is awkward. The naming of your variables suggests that each group of six <code>double</code>s represents an object, which I've called a <code>Sexdoublet</code>.</p>\n\n<p>Throwing all the code into <code>main()</code> is poor practice; there should be a function to do the importing. It should accept an <code>istream</code> parameter and return a <code>vector</code> of <code>Sexdoublet</code>s.</p>\n\n<p>I don't know what you were hoping to accomplish with <code>if (!ifs) ifs >> trash;</code> — if the <code>ifstream</code> is bad then you shouldn't try reading from it.</p>\n\n<p>Hard-coding the filename is probably a bad idea. I've used the convention of reading from either a file that is specified on the command line, or from standard input otherwise.</p>\n\n<pre><code>#include <fstream>\n#include <iostream>\n#include <string.h>\n#include <vector>\n\n/* A struct of six doubles */\nstruct Sexdoublet {\n double x, y, d, m, c, t;\n\n friend std::istream &operator>>(std::istream &in, Sexdoublet &r) {\n return in >> r.x >> r.y >> r.d >> r.m >> r.c >> r.t;\n }\n\n friend std::ostream &operator<<(std::ostream &out, const Sexdoublet &r) {\n return out << \"[ x = \" << r.x\n << \", y = \" << r.y\n << \", d = \" << r.d\n << \", m = \" << r.m\n << \", c = \" << r.c\n << \", t = \" << r.t << \" ]\";\n }\n};\n\nstd::vector<Sexdoublet> import(std::istream &in) {\n std::vector<Sexdoublet> data;\n Sexdoublet s;\n while (in >> s) {\n data.push_back(s);\n }\n return data;\n}\n\nint main(int argc, char *argv[]) {\n // If the first command-line argument is not \"-\", treat it as the filename\n // from which to read the input. Otherwise, read from STDIN.\n const char *filename = (argc >= 2 && 0 != strcmp(\"-\", argv[1])) ?\n argv[1] : NULL;\n std::ifstream f;\n std::istream &in = filename ? (f.open(filename), f) : std::cin;\n if (!f) {\n std::cerr << \"Error opening \" << filename << \": \"\n << strerror(errno) << std::endl;\n return 1;\n }\n\n std::vector<Sexdoublet> data = import(in);\n std::for_each(data.begin(), data.end(), [](const Sexdoublet &s) {\n std::cout << s << std::endl;\n });\n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T08:11:42.980",
"Id": "35330",
"ParentId": "35265",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T01:29:59.053",
"Id": "35265",
"Score": "2",
"Tags": [
"c++",
"beginner",
"io"
],
"Title": "Better importation of variables from .txt file"
}
|
35265
|
<p>I wrote a python function that writes a integer to a file in binary form. But are there any ways that I can reduce the number of steps, is there a more efficient way to write a integer to a file?</p>
<pre><code>def IntWrite(FileName, Integer):
#convert to hexadecimal
data = str('{0:0x}'.format(Integer))
#pad number if odd length
if(len(data) % 2 != 0):
data="0"+data
#split into chucks of two
info = [data[i:i+2] for i in range(0, len(data), 2)]
#convert each chuck to a byte
data2 = "".join([chr(int(a, 16)) for a in info])
#write to file
file(FileName, "wb").write(data2)
#convert back to integer
def IntRead(FileName):
RawData = file(FileName, "rb").read()
HexData = "".join(['{0:0x}'.format(ord(b)) for b in RawData])
return int(HexData, 16)
IntWrite("int_data.txt", 100000)
print IntRead("int_data.txt")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T03:02:29.693",
"Id": "57102",
"Score": "2",
"body": "This is more of a SO question. See [struct](http://docs.python.org/dev/library/struct.html#module-struct).pack, struct.unpack, in this case with a format character of `i` or `I`, unless you need more than 32 bits."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T05:58:22.020",
"Id": "57109",
"Score": "0",
"body": "… but it's also acceptable as a Code Review question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T13:16:45.590",
"Id": "57132",
"Score": "0",
"body": "Sure, especially if there is a need to handle arbitrarily large integers, which the original code seems to offer. Otherwise the best code is that which you don't have to write. :)"
}
] |
[
{
"body": "<p>Python comes with a built-in <a href=\"http://docs.python.org/3/library/pickle.html\" rel=\"nofollow\"><code>pickle</code></a> module for serialization:</p>\n\n<pre><code>>>> import pickle\n>>> with open('data', 'wb') as f: pickle.dump(9 ** 33, f)\n>>> with open('data', 'rb') as f: print(pickle.load(f))\n30903154382632612361920641803529\n</code></pre>\n\n<p>(P.S. I wouldn't use a filename ending with <code>.txt</code> to store binary data.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T15:51:37.573",
"Id": "57149",
"Score": "1",
"body": "Note that pickle's binary format is incompatible with the original question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T15:54:41.243",
"Id": "57150",
"Score": "0",
"body": "Yes, that's right: I'm assuming here that the OP is starting from scratch."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T13:02:28.630",
"Id": "35291",
"ParentId": "35267",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "35291",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T01:55:56.453",
"Id": "35267",
"Score": "4",
"Tags": [
"python",
"file",
"integer",
"serialization",
"io"
],
"Title": "Writing integer to binary file"
}
|
35267
|
<p>I'm looking for bugs. I tried to test all functionality in a variety of ways.</p>
<pre><code>#by JB0x2D1
from decimal import Decimal
import math
import numbers
import operator
from fractions import Fraction
class Mixed(Fraction):
"""This class implements Fraction, which implements rational numbers."""
# We're immutable, so use __new__ not __init__
def __new__(cls, whole=0, numerator=None, denominator=None):
"""Constructs a Rational.
Takes a string like '-1 2/3' or '1.5', another Rational instance, a
numerator/denominator pair, a float, or a whole number/numerator/
denominator set. If one or more non-zero arguments is negative,
all are treated as negative and the result is negative.
General behavior: whole number + (numerator / denominator)
Examples
--------
>>> Mixed(Mixed(-1,1,2), Mixed(0,1,2), Mixed(0,1,2))
Mixed(-2, 1, 2)
Note: The above call is similar to:
>>> Fraction(-3,2) + Fraction(Fraction(-1,2), Fraction(1,2))
Fraction(-5, 2)
>>> Mixed('-1 2/3')
Mixed(-1, 2, 3)
>>> Mixed(10,-8)
Mixed(-1, 1, 4)
>>> Mixed(Fraction(1,7), 5)
Mixed(0, 1, 35)
>>> Mixed(Mixed(1, 7), Fraction(2, 3))
Mixed(0, 3, 14)
>>> Mixed(Mixed(0, 3, 2), Fraction(2, 3), 2)
Mixed(1, 5, 6)
>>> Mixed('314')
Mixed(314, 0, 1)
>>> Mixed('-35/4')
Mixed(-8, 3, 4)
>>> Mixed('3.1415')
Mixed(3, 283, 2000)
>>> Mixed('-47e-2')
Mixed(0, -47, 100)
>>> Mixed(1.47)
Mixed(1, 2116691824864133, 4503599627370496)
>>> Mixed(2.25)
Mixed(2, 1, 4)
>>> Mixed(Decimal('1.47'))
Mixed(1, 47, 100)
"""
self = super(Fraction, cls).__new__(cls)
if (numerator is None) and (denominator is None): #single argument
if isinstance(whole, numbers.Rational) or \
isinstance(whole, float) or \
isinstance(whole, Decimal):
if type(whole) == Mixed:
return whole
f = Fraction(whole)
whole = 0
elif isinstance(whole, str):
# Handle construction from strings.
arg = whole
fail = False
try:
f = Fraction(whole)
whole = 0
except ValueError:
n = whole.split()
if (len(n) == 2):
try:
whole = Fraction(n[0])
f = Fraction(n[1])
except ValueError:
fail = True
else:
fail = True
if fail:
raise ValueError('Invalid literal for Mixed: %r' %
arg)
else:
raise TypeError("argument should be a string "
"or a Rational instance")
elif (isinstance(numerator, numbers.Rational) and #two arguments
isinstance(whole, numbers.Rational) and (denominator is None)):
#here whole is treated as numerator and numerator as denominator
if numerator == 0:
raise ZeroDivisionError('Mixed(%s, 0)' % whole)
f = Fraction(whole, numerator)
whole = 0
elif (isinstance(whole, numbers.Rational) and #three arguments
isinstance(numerator, numbers.Rational) and
isinstance(denominator, numbers.Rational)):
if denominator == 0:
raise ZeroDivisionError('Mixed(%s, %s, 0)' % whole, numerator)
whole = Fraction(whole)
f = Fraction(numerator, denominator)
else:
raise TypeError("all three arguments should be "
"Rational instances")
#handle negative values and convert improper to mixed number fraction
if (whole < 0) and (f > 0):
f = -f + whole
elif (whole > 0) and (f < 0):
f += -whole
else:
f += whole
numerator = f.numerator
denominator = f.denominator
if numerator < 0:
whole = -(-numerator // denominator)
numerator = -numerator % denominator
else:
whole = numerator // denominator
numerator %= denominator
self._whole = whole
self._numerator = numerator
self._denominator = denominator
return self
def __repr__(self):
"""repr(self)"""
return ('Mixed(%s, %s, %s)' % (self._whole, self._numerator,
self._denominator))
def __str__(self):
"""str(self)"""
if self._numerator == 0:
return str(self._whole)
elif self._whole != 0:
return '%s %s/%s' % (self._whole, self._numerator,
self._denominator)
else:
return '%s/%s' % (self._numerator, self._denominator)
def to_fraction(self):
n = self._numerator
if self._whole != 0:
if self._whole < 0:
n *= -1
n += self._whole * self._denominator
return Fraction(n, self._denominator)
def limit_denominator(self, max_denominator=1000000):
"""Closest Fraction to self with denominator at most max_denominator.
>>> Mixed('3.141592653589793').limit_denominator(10)
Mixed(3, 1, 7)
>>> Mixed('3.141592653589793').limit_denominator(100)
Mixed(3, 14, 99)
>>> Mixed(4321, 8765).limit_denominator(10000)
Mixed(0, 4321, 8765)
"""
return Mixed(self.to_fraction().limit_denominator(max_denominator))
@property
def numerator(a):
return a.to_fraction().numerator
@property
def denominator(a):
return a._denominator
@property
def whole(a):
"""returns the whole number only (a % 1)
>>> Mixed(10,3).whole
3
"""
return a._whole
@property
def fnumerator(a):
""" returns the fractional portion's numerator.
>>> Mixed('1 3/4').fnumerator
3
"""
return a._numerator
def _add(a, b):
"""a + b"""
return Mixed(a.numerator * b.denominator +
b.numerator * a.denominator,
a.denominator * b.denominator)
__add__, __radd__ = Fraction._operator_fallbacks(_add, operator.add)
def _sub(a, b):
"""a - b"""
return Mixed(a.numerator * b.denominator -
b.numerator * a.denominator,
a.denominator * b.denominator)
__sub__, __rsub__ = Fraction._operator_fallbacks(_sub, operator.sub)
def _mul(a, b):
"""a * b"""
return Mixed(a.numerator * b.numerator, a.denominator * b.denominator)
__mul__, __rmul__ = Fraction._operator_fallbacks(_mul, operator.mul)
def _div(a, b):
"""a / b"""
return Mixed(a.numerator * b.denominator,
a.denominator * b.numerator)
__truediv__, __rtruediv__ = Fraction._operator_fallbacks(_div, operator.truediv)
def __pow__(a, b):
"""a ** b
If b is not an integer, the result will be a float or complex
since roots are generally irrational. If b is an integer, the
result will be rational.
"""
if isinstance(b, numbers.Rational):
if b.denominator == 1:
return Mixed(Fraction(a) ** b)
else:
# A fractional power will generally produce an
# irrational number.
return float(a) ** float(b)
else:
return float(a) ** b
def __rpow__(b, a):
"""a ** b"""
if b._denominator == 1 and b._numerator >= 0:
# If a is an int, keep it that way if possible.
return a ** b.numerator
if isinstance(a, numbers.Rational):
return Mixed(a.numerator, a.denominator) ** b
if b._denominator == 1:
return a ** b.numerator
return a ** float(b)
def __pos__(a):
"""+a: Coerces a subclass instance to Fraction"""
return Mixed(a.numerator, a.denominator)
def __neg__(a):
"""-a"""
return Mixed(-a.numerator, a.denominator)
def __abs__(a):
"""abs(a)"""
return Mixed(abs(a.numerator), a.denominator)
def __trunc__(a):
"""trunc(a)"""
if a.numerator < 0:
return -(-a.numerator // a.denominator)
else:
return a.numerator // a.denominator
def __hash__(self):
"""hash(self)"""
return self.to_fraction().__hash__()
def __eq__(a, b):
"""a == b"""
return Fraction(a) == b
def _richcmp(self, other, op):
"""Helper for comparison operators, for internal use only.
Implement comparison between a Rational instance `self`, and
either another Rational instance or a float `other`. If
`other` is not a Rational instance or a float, return
NotImplemented. `op` should be one of the six standard
comparison operators.
"""
return self.to_fraction()._richcmp(other, op)
def __reduce__(self):
return (self.__class__, (str(self),))
def __copy__(self):
if type(self) == Mixed:
return self # I'm immutable; therefore I am my own clone
return self.__class__(self.numerator, self.denominator)
def __deepcopy__(self, memo):
if type(self) == Mixed:
return self # My components are also immutable
return self.__class__(self.numerator, self.denominator)
</code></pre>
<p>Latest version download <a href="https://sourceforge.net/projects/pythonmixedfractionsclass/files/mixed_fractions.py/download" rel="nofollow">here</a>.</p>
|
[] |
[
{
"body": "<h3>1. Bugs</h3>\n\n<p>Your doctests do not pass:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>$ python3.3 -mdoctest cr35274.py\n**********************************************************************\nFile \"./cr35274.py\", line 76, in cr35274.Mixed.__new__\nFailed example:\n Mixed(Mixed(-1,1,2), Mixed(0,1,2), Mixed(0,1,2))\nExpected:\n Mixed(-2, 1, 2)\n Note: The above call is similar to:\nGot:\n Mixed(-2, 1, 2)\n**********************************************************************\nFile \"./cr35274.py\", line 97, in cr35274.Mixed.__new__\nFailed example:\n Mixed('-47e-2')\nExpected:\n Mixed(0, -47, 100)\nGot:\n Mixed(0, 47, 100)\n**********************************************************************\n1 items had failures:\n 2 of 14 in cr35274.Mixed.__new__\n***Test Failed*** 2 failures.\n</code></pre>\n\n<h3>2. Commentary</h3>\n\n<p>As far as I can see, there are really only two things that you are trying to achieve:</p>\n\n<ol>\n<li><p>To create the mixed fraction <em>a</em> <sup><em>b</em></sup>/<sub><em>c</em></sub> from the string <code>\"a b/c\"</code>. But instead of implementing a whole new class, why not just write a function to parse the string and return a <code>Fraction</code>?</p>\n\n<pre><code>import re\nfrom fractions import Fraction\n\n_MIXED_FORMAT = re.compile(r\"\"\"\n \\A\\s* # optional whitespace at the start, then\n (?P<sign>[-+]?) # an optional sign, then\n (?P<whole>\\d+) # integer part\n \\s+ # whitespace\n (?P<num>\\d+) # numerator\n /(?P<denom>\\d+) # denominator\n \\s*\\Z # and optional whitespace to finish\n\"\"\", re.VERBOSE)\n\ndef mixed(s):\n \"\"\"Parse the string s as a (possibly mixed) fraction.\n\n >>> mixed('1 2/3')\n Fraction(5, 3)\n >>> mixed(' -1 2/3 ')\n Fraction(-5, 3)\n >>> mixed('-0 12/15')\n Fraction(-4, 5)\n >>> mixed('+45/15')\n Fraction(3, 1)\n\n \"\"\"\n m = _MIXED_FORMAT.match(s)\n if not m:\n return Fraction(s)\n d = m.groupdict()\n result = int(d['whole']) + Fraction(int(d['num']), int(d['denom']))\n if d['sign'] == '-':\n return -result\n else:\n return result\n</code></pre></li>\n<li><p>To format a fraction in mixed notation. But why not just write this as a function:</p>\n\n<pre><code>def format_mixed(f):\n \"\"\"Format the fraction f as a (possibly) mixed fraction.\n\n >>> all(format_mixed(mixed(f)) == f for f in ['1 2/3', '-3 4/5', '7/8'])\n True\n\n \"\"\"\n if abs(f) <= 1 or f.denominator == 1:\n return str(f)\n return '{0} {1.numerator}/{1.denominator}'.format(int(f), abs(f - int(f)))\n</code></pre></li>\n</ol>\n\n<p>The rest of your code seems unnecessary and complicated.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T16:41:43.570",
"Id": "57155",
"Score": "0",
"body": "Thanks for the bug (fixed). I chose to implement it as a class to make it easy to represent any rational or float (or string representation of either) as a mixed number. In short, if I'm going to bother to handle strings, why stop there?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T18:12:50.047",
"Id": "57168",
"Score": "0",
"body": "To me, it is much more convenient if I want to manipulate the value 29 9/16 to use `Mixed(29,9,16)` instead of `Fraction((29*16)+9,16)`. That is why I wrote the full blown class. Even if I wanted a Fraction type to manipulate, I could use `Fraction(Mixed(29,9,16))` for convenience and let Python figure out the details."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T18:18:12.117",
"Id": "57169",
"Score": "1",
"body": "What's wrong with `29 + Fraction(9, 16)`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T19:17:18.950",
"Id": "57172",
"Score": "1",
"body": "Nothing at all. This class is written to add convenience. `Mixed` does everything that `Fraction` does and a bit more. Not to mention that `>>>print(mix)` `29 9/16` is a little more meaningful to me than `>>>print(frac)` `473/16`. Functionally, they are more or less interchangeable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T19:30:54.483",
"Id": "57174",
"Score": "0",
"body": "I guess it comes down to the fact that if one prefers the mixed number style, they can easily implement it without wiring the function to parse the string and return the fraction. They don't have to write the function to display the value in mixed number format. And they can switch back and forth at will, effortlessly. It's already done for you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T14:35:19.167",
"Id": "57284",
"Score": "0",
"body": "I took your feedback to heart in version 1.0. I decided to get out of the way and let a fraction be a fraction. I feel like I've removed a lot of unnecessary and complicated code and left a solution much closer to your answer. Thank you."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T11:53:08.517",
"Id": "35288",
"ParentId": "35274",
"Score": "2"
}
},
{
"body": "<p>Don't ever reinvent the wheel. Fraction is decently cooperative class, you should never have to write basic operations from scratch. Use the inherited stuff. Here is the solution for basic arithmetic, shouldn't be hard to adapt for many other protocols. Also, it doesn't handle negative numbers because I'm lazy, I trust you can add support for that too.</p>\n\n<pre><code>from fractions import Fraction\nclass Mixed(Fraction):\n def __new__(cls, a, b, c):\n return super().__new__(cls, a*c + b, c)\n def __str__(self):\n return '{} {}'.format(*divmod(Fraction(self), 1))\n def inject(name, *, namespace = locals()):\n name = '__{}__'.format(name)\n def method(*args):\n result = getattr(Fraction, name)(*args)\n return Fraction.__new__(Mixed, result)\n namespace[name] = method\n for name in 'add sub mul truediv'.split():\n inject(name)\n inject('r' + name)\n for name in 'abs pos neg'.split():\n inject(name)\n del name, inject\nprint(Fraction(122,3) / Mixed(4,5,6) + 5) # 13 12/29\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-14T08:06:38.580",
"Id": "96878",
"ParentId": "35274",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T04:19:59.353",
"Id": "35274",
"Score": "4",
"Tags": [
"python",
"rational-numbers"
],
"Title": "Mixed number fractions class"
}
|
35274
|
<p>This code works 100%, but I am trying to see if I can use a <code>for</code>-statement to make my second method less-cumbersome and more efficient instead of making so many variables. </p>
<p>I have to show the differences between each quarter for every department.</p>
<p>My array has 6 Departments and 4 Quarters. </p>
<pre><code>import java.util.*;
public void setQuarter()
{
final int DEPARTMENT = 6;
final int QUARTER = 4;
private static double [][] sales = new double [DEPARTMENT][QUARTER];
Scanner keyboard = new Scanner(System.in);
double total = 0;
for (int row = 0; row < DEPARTMENT ; row++)
{
for (int col = 0; col < QUARTER; col++)
{
// This will input value into my array
System.out.print(" \n What Were The Total Sales For Department : " + (row + 1 ) + " Quarter : " + (col + 1 ) + " = ");
sales[row][col] = keyboard.nextDouble();
}
}
}
</code></pre>
<p>This is the only thing that I could come up with, since I am new to Java and 2-D arrays. I want to know if there is an easier way of getting the quarterly differences for each department. I was told I could use a nested <code>for</code>-statement to subtract the elements in the 2-D array. However, I have tried but I can't seem to get one done. I am pretty sure the use of a nested <code>for</code>-statement would clean my code up quickly. Can anyone help me out with this?</p>
<pre><code>public void departmentdiff()
{
double dept1Qrt1 = sales [0] [0];
double dept2Qrt1 = sales [1] [0];
double dept3Qrt1 = sales [2] [0];
double dept4Qrt1 = sales [3] [0];
double dept5Qrt1 = sales [4] [0];
double dept6Qrt1 = sales [5] [0];
double dept1Qrt2 = sales [0] [1];
double dept2Qrt2 = sales [1] [1];
double dept3Qrt2 = sales [2] [1];
double dept4Qrt2 = sales [3] [1];
double dept5Qrt2 = sales [4] [1];
double dept6Qrt2 = sales [5] [1];
double dept1Qrt3 = sales [0] [2];
double dept2Qrt3 = sales [1] [2];
double dept3Qrt3 = sales [2] [2];
double dept4Qrt3 = sales [3] [2];
double dept5Qrt3 = sales [4] [2];
double dept6Qrt3 = sales [5] [2];
double dept1Qrt4 = sales [0] [3];
double dept2Qrt4 = sales [1] [3];
double dept3Qrt4 = sales [2] [3];
double dept4Qrt4 = sales [3] [3];
double dept5Qrt4 = sales [4] [3];
double dept6Qrt4 = sales [5] [3];
double total1 = 0;
double total2 = 0;
double total3= 0;
// Instructs User To Press Enter To Continue
System.out.println(" \n \n \n Please Press Enter To Display The Department's Difference In Each Quarter ");
// Scanner Type Waits For the "Enter" Input Before Proceeding
new Scanner(System.in).nextLine();
total1 = dept1Qrt1 - dept1Qrt2;
total2 = dept1Qrt2 - dept1Qrt3;
total3 = dept1Qrt3 - dept1Qrt4;
System.out.println( " \n The Quarterly Differences For Department-1 is :");
System.out.println( " ********************************************** ");
System.out.println( " \n From Quarter : 1 to Quarter : 2 The Difference Is ( " + total1 + " ) ");
System.out.println( " \n From Quarter : 2 to Quarter : 3 The Difference Is ( " + total2 + " ) ");
System.out.println( " \n From Quarter : 3 to Quarter : 4 The Difference Is ( " + total3 + " ) ");
total1 = dept2Qrt1 - dept2Qrt2;
total2 = dept2Qrt2 - dept2Qrt3;
total3 = dept2Qrt3 - dept2Qrt4;
System.out.println( " \n \n The Quarterly Differences For Department-2 is :");
System.out.println( " ********************************************** ");
System.out.println( " \n From Quarter : 1 to Quarter : 2 The Difference Is ( " + total1 + " ) ");
System.out.println( " \n From Quarter : 2 to Quarter : 3 The Difference Is ( " + total2 + " ) ");
System.out.println( " \n From Quarter : 3 to Quarter : 4 The Difference Is ( " + total3 + " ) ");
total1 = dept3Qrt1 - dept3Qrt2;
total2 = dept3Qrt2 - dept3Qrt3;
total3 = dept3Qrt3 - dept3Qrt4;
System.out.println( " \n \n The Quarterly Differences For Department-3 is :");
System.out.println( " ********************************************** ");
System.out.println( " \n From Quarter : 1 to Quarter : 2 The Difference Is ( " + total1 + " ) ");
System.out.println( " \n From Quarter : 2 to Quarter : 3 The Difference Is ( " + total2 + " ) ");
System.out.println( " \n From Quarter : 3 to Quarter : 4 The Difference Is ( " + total3 + " ) ");
total1 = dept4Qrt1 - dept4Qrt2;
total2 = dept4Qrt2 - dept4Qrt3;
total3 = dept4Qrt3 - dept4Qrt4;
System.out.println( " \n \n The Quarterly Differences For Department-4 is :");
System.out.println( " ********************************************** ");
System.out.println( " \n From Quarter : 1 to Quarter : 2 The Difference Is ( " + total1 + " ) ");
System.out.println( " \n From Quarter : 2 to Quarter : 3 The Difference Is ( " + total2 + " ) ");
System.out.println( " \n From Quarter : 3 to Quarter : 4 The Difference Is ( " + total3 + " ) ");
total1 = dept5Qrt1 - dept5Qrt2;
total2 = dept5Qrt2 - dept5Qrt3;
total3 = dept5Qrt3 - dept5Qrt4;
System.out.println( " \n \n Quarterly Differences For Department-5 is :");
System.out.println( " ********************************************** ");
System.out.println( " \n From Quarter : 1 to Quarter : 2 The Difference Is ( " + total1 + " ) ");
System.out.println( " \n From Quarter : 2 to Quarter : 3 The Difference Is ( " + total2 + " ) ");
System.out.println( " \n From Quarter : 3 to Quarter : 4 The Difference Is ( " + total3 + " ) ");
total1 = dept6Qrt1 - dept6Qrt2;
total2 = dept6Qrt2 - dept6Qrt3;
total3 = dept6Qrt3 - dept6Qrt4;
System.out.println( " \n \n The Quarterly Differences For Department-6 is :");
System.out.println( " ********************************************** ");
System.out.println( " \n From Quarter : 1 to Quarter : 2 The Difference Is ( " + total1 + " ) ");
System.out.println( " \n From Quarter : 2 to Quarter : 3 The Difference Is ( " + total2 + " ) ");
System.out.println( " \n From Quarter : 3 to Quarter : 4 The Difference Is ( " + total3 + " ) ");
}
</code></pre>
|
[] |
[
{
"body": "<p>Refactoring should get you there</p>\n\n<pre><code> total1 = dept1Qrt1 - dept1Qrt2;\n total2 = dept1Qrt2 - dept1Qrt3;\n total3 = dept1Qrt3 - dept1Qrt4;\n System.out.println( \" \\n The Quarterly Differences For Department-1 is :\");\n System.out.println( \" ********************************************** \");\n System.out.println( \" \\n From Quarter : 1 to Quarter : 2 The Difference Is ( \" + total1 + \" ) \");\n System.out.println( \" \\n From Quarter : 2 to Quarter : 3 The Difference Is ( \" + total2 + \" ) \");\n System.out.println( \" \\n From Quarter : 3 to Quarter : 4 The Difference Is ( \" + total3 + \" ) \");\n</code></pre>\n\n<p>We're going to make it look worse for a moment...</p>\n\n<pre><code> total1 = sales [0] [0]- sales [0] [1];\n total2 = sales [0] [1]- sales [0] [2];\n total3 = sales [0] [2]- sales [0] [3];\n System.out.println( \" \\n The Quarterly Differences For Department-1 is :\");\n System.out.println( \" ********************************************** \");\n System.out.println( \" \\n From Quarter : 1 to Quarter : 2 The Difference Is ( \" + total1 + \" ) \");\n System.out.println( \" \\n From Quarter : 2 to Quarter : 3 The Difference Is ( \" + total2 + \" ) \");\n System.out.println( \" \\n From Quarter : 3 to Quarter : 4 The Difference Is ( \" + total3 + \" ) \");\n</code></pre>\n\n<p>Re arrange, so things line up better</p>\n\n<pre><code> System.out.println( \" \\n The Quarterly Differences For Department-1 is :\");\n System.out.println( \" ********************************************** \");\n total1 = sales [0] [0]- sales [0] [1];\n System.out.println( \" \\n From Quarter : 1 to Quarter : 2 The Difference Is ( \" + total1 + \" ) \");\n total2 = sales [0] [1]- sales [0] [2];\n System.out.println( \" \\n From Quarter : 2 to Quarter : 3 The Difference Is ( \" + total2 + \" ) \");\n total3 = sales [0] [2]- sales [0] [3];\n System.out.println( \" \\n From Quarter : 3 to Quarter : 4 The Difference Is ( \" + total3 + \" ) \");\n</code></pre>\n\n<p>Inject a variable to represent the quarter</p>\n\n<pre><code> System.out.println( \" \\n The Quarterly Differences For Department-1 is :\");\n System.out.println( \" ********************************************** \");\n int quarter = 0;\n total1 = sales [0] [quarter]- sales [0] [quarter+1];\n System.out.println( \" \\n From Quarter : 1 to Quarter : 2 The Difference Is ( \" + total1 + \" ) \");\n quarter = 1;\n total2 = sales [0] [quarter]- sales [0] [quarter+1];\n System.out.println( \" \\n From Quarter : 2 to Quarter : 3 The Difference Is ( \" + total2 + \" ) \");\n quarter = 2;\n total3 = sales [0] [quarter]- sales [0] [quarter+1];\n System.out.println( \" \\n From Quarter : 3 to Quarter : 4 The Difference Is ( \" + total3 + \" ) \");\n</code></pre>\n\n<p>Now it should be obvious where the for loop falls out; note the introduction of \"quarterNames\", which is a lookup table (aka array) to make sure the spellings are correct in the strings; you need to do something to ensure that you don't confuse 1-based humans by printing 0-based identifiers.</p>\n\n<pre><code> System.out.println( \" \\n The Quarterly Differences For Department-1 is :\");\n System.out.println( \" ********************************************** \");\n for (int quarter = 0; quarter < 3; ++quarter {\n double total = sales [0] [quarter]- sales [0] [quarter+1];\n System.out.println( \" \\n From Quarter : \" + quarterNames[quarter] + \" to Quarter : \" + quarterNames[quarter+1] + \" The Difference Is ( \" + total + \" ) \");\n }\n</code></pre>\n\n<p>For more readability, use better variable names</p>\n\n<pre><code> System.out.println( \" \\n The Quarterly Differences For Department-1 is :\");\n System.out.println( \" ********************************************** \");\n for (int thisQuarter = 0; thisQuarter < 3; ++thisQuarter {\n int nextQuarter = 1 + thisQuarter;\n\n double total = sales [0] [thisQuarter]- sales [0] [nextQuarter];\n System.out.println( \" \\n From Quarter : \" + quarterNames[thisQuarter] + \" to Quarter : \" + quarterNames[nextQuarter] + \" The Difference Is ( \" + total + \" ) \");\n }\n</code></pre>\n\n<p>Eliminate some magic numbers</p>\n\n<pre><code> int thisDepartment = 0;\n System.out.println( \" \\n The Quarterly Differences For Department-\" + departmentId[thisDepartment] + \" is :\");\n System.out.println( \" ********************************************** \");\n for (int thisQuarter = 0; thisQuarter < QUARTER; ++thisQuarter {\n int nextQuarter = 1 + thisQuarter;\n\n double total = sales [thisDepartment] [thisQuarter]- sales [thisDepartment] [nextQuarter];\n System.out.println( \" \\n From Quarter : \" + quarterNames[thisQuarter] + \" to Quarter : \" + quarterNames[nextQuarter] + \" The Difference Is ( \" + total + \" ) \");\n }\n</code></pre>\n\n<p>At this point, it should be clear how to create a for loop that generates the report for each department.</p>\n\n<p>BUT: more advanced programmers wouldn't do it this way. Part of the reason that this is such a mess, is that you are storing each piece of data independently, and then trying to reconstruct the data relationships.</p>\n\n<p>In this example, there are three (simple) abstractions. There's the concept of a \"quarter\", there's the concept of a department - which has sales for each quarter, and there is the concept of a report, which tracks changes per quarter.</p>\n\n<pre><code>class Quarter {\n // this would normally be a date range, or a year/fiscal quarter pair, or something\n // for your simple example, it could even be an enum.\n int id;\n\n // These two methods, because it's important to get key semantics correct.\n @Override\n boolean equals(Object other);\n\n @Override\n int hashCode();\n}\n\nclass Department {\n // Not going to define Sales. In your example, it could just be a Double.\n Map<Quarter, Sales> = salesResults;\n}\n\nclass Report {\n Quarter start;\n Quarter end;\n}\n\nList<Department> departments = new ArrayList();\nList<Report> reports = new ArrayList();\n\nfor(Department department : departments) {\n for(Report report : reports) {\n double total = department.salesResults.get(report.start) - department.salesResults.get(report.end);\n // do something with the total\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T06:44:16.257",
"Id": "35278",
"ParentId": "35276",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T06:01:14.177",
"Id": "35276",
"Score": "6",
"Tags": [
"java",
"beginner",
"array"
],
"Title": "Reporting quarterly changes for each department"
}
|
35276
|
<p>Please review this JavaScript text editing webapp. Review the code quality. Give me suggestions to simplify the code.</p>
<pre><code>var textarea = document.getElementById("textarea"),
statusBar = document.getElementById("status-bar"),
inputFile = document.getElementById("input-file"),
appname = "Notepad",
isModified = false,
statusBarOn,
filename;
function changeDocTitle(newFilename) {
filename = newFilename;
document.title = filename + " - " + appname;
}
function dontSave() {
if (!textarea.value || confirm("You have unsaved changes that will be lost.")) {
isModified = false;
return true;
}
}
function newDoc(text, newFilename) {
if (!isModified || dontSave()) {
textarea.value = text || "";
changeDocTitle(newFilename || "untitled.txt");
}
if (statusBarOn) updateStatusBar();
textarea.focus();
}
function openDoc() {
if (!isModified || dontSave()) inputFile.click();
textarea.focus();
}
function renameDoc() {
var newFilename = prompt("Name this document:", filename);
if (newFilename !== null) {
if (newFilename === "")
changeDocTitle("untitled.txt");
else
changeDocTitle(newFilename.lastIndexOf(".txt") == -1 ? newFilename + ".txt" : newFilename);
return true;
}
}
function saveDoc() {
if (renameDoc()) {
var blob = new Blob([textarea.value.replace(/\n/g, "\r\n")], {
type: "text/plain;charset=utf-8"
});
saveAs(blob, filename);
isModified = false;
}
textarea.focus();
}
function updateStatusBar() {
var text = textarea.value,
chars = text.length,
words = text.split(/\b\S+\b/g).length - 1,
lines = text.split("\n").length;
statusBar.value = lines + " lines, " + words + " words, " + chars + " characters";
}
function showHideStatusBar(toState) {
statusBarOn = toState;
if (statusBarOn) {
textarea.style.height = "calc(100% - 21px)";
statusBar.removeAttribute("hidden");
updateStatusBar();
} else {
textarea.style.height = "";
statusBar.setAttribute("hidden", "");
}
}
textarea.addEventListener("input", function() {
isModified = true;
if (statusBarOn) updateStatusBar();
});
inputFile.addEventListener("change", function() { // load file
var file = inputFile.files[0],
reader = new FileReader();
reader.onload = function() {
newDoc(reader.result, file.name);
};
reader.readAsText(file);
});
document.addEventListener("keydown", function(e) { // shortcuts
var key = {
66: function() { // B
showHideStatusBar(statusBarOn ? false : true); // toggle
},
79: openDoc, // O
82: newDoc, // R
83: saveDoc, // S
191: function() { // /
alert("Welcome to " + appname + "!");
},
"noctrl9": function() { // tab
var sStart = textarea.selectionStart,
text = textarea.value;
textarea.value = text.substring(0, sStart) + "\t" + text.substring(textarea.selectionEnd);
textarea.selectionEnd = sStart + 1;
}
}, fn = e.ctrlKey ? key[e.keyCode] : key["noctrl" + e.keyCode];
if (fn) {
e.preventDefault();
fn();
}
});
onunload = function() { // store localStorage
if (isModified) {
localStorage.setItem("text", textarea.value);
localStorage.setItem("filename", filename);
} else
localStorage.removeItem("text");
localStorage.setItem("statusBarOn", statusBarOn);
};
onload = function() { // load localStorage
if (localStorage.getItem("text")) {
newDoc(localStorage.getItem("text"), localStorage.getItem("filename"));
isModified = true;
} else
newDoc();
if (localStorage.getItem("statusBarOn"))
showHideStatusBar(JSON.parse(localStorage.getItem("statusBarOn")) ? true : false);
else
showHideStatusBar(true); // default
};
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>First of all, you should declare all of these in it's own scope, not in the global scope. That way, other code (or your own code) won't collide with naming. A simple IIFE would do:</p>\n\n<pre><code>(function(){\n //All code in here\n}());\n</code></pre></li>\n<li><p>Your code assumes that it will run on modern browsers. But <em>what if</em> your user doesn't use one or can't use one (<em>cough</em>, enterprise, <em>cough</em>)? You code should check if these new APIs like <a href=\"http://caniuse.com/#feat=filereader\" rel=\"nofollow\"><code>FileReader</code></a> and <a href=\"http://caniuse.com/#feat=blobbuilder\" rel=\"nofollow\"><code>Blob</code></a> exists. <a href=\"http://modernizr.com/\" rel=\"nofollow\">Modernizr</a> is a handy library for this.</p></li>\n<li><p>Likewise, you should also prepare for inconsistent APIs on browsers. <code>addEventListener</code> doesn't exist in older IE browsers. I suggest you use a library like <a href=\"http://jquery.com/\" rel=\"nofollow\">jQuery</a> for this as well as for other operations to normalize the results. It's easier, and you won't be repeating code.</p></li>\n<li><p>Use libraries to simplify the job. True, libraries can add a bit of baggage to your code, but it shouldn't be an excuse not to use them. jQuery is just 40KB. In contrast, images and backgrounds in websites reach 1MB. How's that for size?</p></li>\n<li><p>Scale. This code assumes you will only have one editor. What if you wanted more than just one in the near future? What if the app increases to 100k lines of code? Would you dig deep to change element id's and variable names for a second editor?</p>\n\n<p>Or would prefer calling a function, and a set of configs in a few lines of code and create a second one? Something like:</p>\n\n<pre><code>$('#some-element,#another-element').myVeryCoolTextEditor({\n emoji : true,\n someCoolConfig : true,\n});\n</code></pre>\n\n<p>I suggest you take a look at <a href=\"https://github.com/jquery-boilerplate/jquery-boilerplate\" rel=\"nofollow\">jQuery Boilerplate</a> to easily structure plugins and plugin states. </p></li>\n<li><p>Reusablility. A jQuery plugin is not the answer to everything, but I'm just suggesting it for a clean and structured code (Check the comments in the source). You can even go without it, as long as you keep your code reusable and \"plugin-like\". Think \"Drop this script and a one-liner <em>and it just works</em>!\"</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T13:46:59.307",
"Id": "35293",
"ParentId": "35280",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T07:02:06.247",
"Id": "35280",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "JavaScript text editing webapp"
}
|
35280
|
<p>I have the following set. <code>a = [1,2,3,4,5]</code> and i want to find all of the following sequences of consecutive elements:</p>
<pre><code>1,
1,2
1,2,3
1,2,3,4
1,2,3,4,5
2,
2,3,
2,3,4,
2,3,4,5
3,
3,4
3,4,5
4
4,5
5
</code></pre>
<p>This is the following code that I use and works correctly. My only problem is with the complexity of the algorithm <strong>O(n<sup>2</sup>)</strong>. Is there a better approach that I can use to reduce the complexity?</p>
<pre><code> int main()
{
int a[5] = {1,2,3,4,5};
vector<vector<int>> all;
for(int i = 0; i < 5; i ++)
{
vector<int> g;
g.push_back(a[i]);
all.push_back(g);
for(int j = i+1; j < 5; j++)
{
g.push_back(a[j]);
all.push_back(g);
}
g.clear();
}
for(int i = 0; i < all.size();i++)
{
for(int j = 0; j < all[i].size();j++)
{
cout << all[i][j] << " ";
}
cout << endl;
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T12:17:50.493",
"Id": "57124",
"Score": "0",
"body": "Do you just want to print them out, or do you want them stored in `all`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T12:19:23.560",
"Id": "57125",
"Score": "0",
"body": "@Dukeling I just want to store them in **all**. The printing part is just to test if my work was ok that's all. I can remove the printing part from the question, if it doesn't help.\n\nKEEP IN MIND: **all** is a vector of vectors. So every line in the output is a vector!"
}
] |
[
{
"body": "<p>You cannot get better than <code>O(n²)</code> because the result has the size of <code>O(n²)</code></p>\n\n<p>The Output has <code>(n+1)*n/2</code> elements therefore you will always need <code>O(n²)</code> time to do the output.</p>\n\n<p>You can only try to reduce the constant factor.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T14:47:32.970",
"Id": "35295",
"ParentId": "35289",
"Score": "2"
}
},
{
"body": "<p>If only for comparison, counters first</p>\n\n<pre><code>static const int N( Max * (Max + 1) / 2); // number of all permutations\nstatic int Max(5); // series upper bound\nint vc(1); // vector counter\nstatic int seed = 1; // counts upwards after each full series\nstatic int vmax = seed; // starts at floor during every series\n</code></pre>\n\n<p>for each is passing every vector here</p>\n\n<pre><code>void v_perm(std::vector<int>& vref) {\n for (int i(0 + seed); i <= vmax; i++) { vref.push_back(i); }\n vmax++; // grows to ceiling\n if (Max < vmax) { seed++; vmax = seed; } // floor gets raised after each series\n}\n</code></pre>\n\n<p>and main employs the for_each</p>\n\n<pre><code>int main() {\nstd::vector< std::vector<int> > all(N);\nstd::for_each(all.begin(), all.end(), v_perm);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T01:08:32.423",
"Id": "57205",
"Score": "0",
"body": "The `static` counters are kinda nasty, though."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T17:06:45.743",
"Id": "35300",
"ParentId": "35289",
"Score": "1"
}
},
{
"body": "<p>As @MrSmith42 points out, the complexity can't be improved.</p>\n\n<p>However, at the least, it would be a good habit to separate the routines for</p>\n\n<ul>\n<li>initialization of your input</li>\n<li>calculation</li>\n<li>output</li>\n</ul>\n\n<p>Here's how it could be better expressed in C++:</p>\n\n<pre><code>#include <iostream>\n#include <vector>\n\nusing std::vector;\n\ntemplate<typename T>\nstd::ostream &operator<<(std::ostream &out, const vector<T> &v) {\n out << '[';\n for (typename vector<T>::const_iterator i = v.begin(); i != v.end(); ++i) {\n if (i != v.begin()) {\n out << \", \";\n }\n out << *i;\n }\n out << ']';\n return out;\n}\n\ntemplate<typename T>\nvector<vector<T> > consecutive_sequences(const vector<T> &v) {\n vector<vector<T> > all;\n for (typename vector<T>::const_iterator i = v.begin(); i != v.end(); ++i) {\n for (typename vector<T>::const_iterator j = i; j != v.end(); ++j) {\n all.push_back(vector<T>(i, j + 1));\n }\n }\n return all;\n}\n\nint main() {\n const int a[] = { 1, 2, 3, 4, 5 };\n const vector<int> a_vec(a, a + sizeof(a) / sizeof(a[0]));\n /* An alternative to the above in C++11…\n #include <numeric>\n vector<int> a_vec(5);\n std::iota(a_vec.begin(), a_vec.end(), 1);\n */\n\n std::cout << consecutive_sequences(a_vec) << std::endl;\n return 0;\n}\n</code></pre>\n\n<p>Output:</p>\n\n<blockquote>\n <p>[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5], [2], [2, 3], [2, 3, 4], [2, 3, 4, 5], [3], [3, 4], [3, 4, 5], [4], [4, 5], [5]]</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T01:05:04.457",
"Id": "35323",
"ParentId": "35289",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "35300",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T12:10:58.420",
"Id": "35289",
"Score": "1",
"Tags": [
"c++",
"complexity"
],
"Title": "Find all consecutive sequences in an ordered set"
}
|
35289
|
<p>Last week I posted a piece of code to apply Dijkastra algorithm to calculate the shortest path between to nodes in a graph. Now, I've made some improvements, but I am still having difficulties.</p>
<p>I have a class <code>Graph</code> that is going to be constructed by two other classes. A vector of elements are instances of a class <code>Edge</code>, and another vector of elements of class <code>Vertex</code>. Every vertex has an id and a carried to keep the accumulated distance from the source node, and every edge has two vertices and weight.</p>
<p>Class <code>Graph</code> has a method named <code>shortest</code> and takes two vertices as arguments. The first one is for the source of the graph and the second is for the destination.</p>
<p>My approach is to eliminate the edges that are connected to the source vertex. This is done by adding their weights to the adjacent vertices, and saving them in "carried" which is in class <code>Vertex</code>. There is a field to keep tracking the situation of every vertex, which then goes to the next round, selecting the lowest vertex base on its carried to be a new source, while doing the same operation over and over until we end up with just one edge. </p>
<p>To demonstrate the result, I've initialized a graph with five vertices: <code>vers[0</code>], <code>vers[1]</code>, <code>vers[2]</code>, <code>vers[3]</code>, <code>vers[4]</code>. There are 10 edges connecting those vertices starting from <code>eds[0]</code>, <code>eds[1]</code>, ....<code>eds[9]</code>.</p>
<p>The destination vertex is <code>vers[4]</code> while the source vertex is <code>vers[2]</code>. It is connected by 4 edges, so when applying the method shortest as it is shown in the code below, I should get rid of all those 4 edges and end with 6 edges at the end of the first round.</p>
<p>The results as follows:</p>
<pre><code>Hello, This is a graph
0____1 5
0____3 4
0____4 6
1____3 5
1____4 7
3____4 3
size of edges 6
size of vertices 4
curried vertex_0 9
curried vertex_1 2
curried vertex_2 1
curried vertex_3 8
</code></pre>
<p>The result looks good so far because we don't see the the source vertex, which is 2, and we remained with just 6 edges after eliminating the four edges connected to the source vertex. We have to the right-hand side the weight of every edge, and down we have the carried of each remained vertex.</p>
<p>Now if we apply the second round, we get the following results:</p>
<pre><code>Hello, This is a graph
0____1 5
0____4 6
1____4 7
size of edges 3
size of vertices 3
curried vertex_0 9
curried vertex_1 2
curried vertex_2 8
</code></pre>
<p>We have 3 edges remained (which is correct) and three vertices (also correct), and the weights of edges are correct. But the problem is that I have the wrong "carried" for each vertex, and that will cause the code to select a wrong new source to continue in the following rounds (we should have 5, 2, 4 instead of 9, 2, 8).</p>
<p>I can see where is the problem, but I cannot understand why I am not getting the right solution when modifying the code. I think that the problem is located between the asterisks lines shown in the code.</p>
<pre><code>#include<iostream>
#include<vector>
#include <stdlib.h> // for rand()
using namespace std;
class Vertex
{
private:
unsigned int id; // the name of the vertex
unsigned int carried; // the weight a vertex may carry when calculating shortest path
vector<unsigned int> previous_nodes;
public:
unsigned int get_id(){return id;};
unsigned int get_carried(){return carried;};
void set_id(unsigned int value) {id = value;};
void set_carried(unsigned int value) {carried = value;};
void previous_nodes_update(unsigned int val){previous_nodes.push_back(val);};
void previous_nodes_erase(unsigned int val){previous_nodes.erase(previous_nodes.begin() + val);};
Vertex(unsigned int init_val = 0, unsigned int init_carried = 0) :id (init_val), carried(init_carried) // constructor
{}
~Vertex() {}; // destructor
};
class Edge
{
private:
Vertex first_vertex; // a vertex on one side of the edge
Vertex second_vertex; // a vertex on the other side of the edge
unsigned int weight; // the value of the edge ( or its weight )
public:
unsigned int get_weight() {return weight;};
void set_weight(unsigned int value) {weight = value;};
Vertex get_ver_1(){return first_vertex;};
Vertex get_ver_2(){return second_vertex;};
void set_first_vertex(Vertex v1) {first_vertex = v1;};
void set_second_vertex(Vertex v2) {second_vertex = v2;};
Edge(const Vertex& vertex_1 = 0, const Vertex& vertex_2 = 0, unsigned int init_weight = 0)
: first_vertex(vertex_1), second_vertex(vertex_2), weight(init_weight) {}
~Edge() {} ; // destructor
};
class Graph
{
private:
std::vector<Vertex> vertices;
std::vector<Edge> edges;
public:
Graph(vector<Vertex> ver_vector, vector<Edge> edg_vector)
: vertices(ver_vector), edges(edg_vector){}
~Graph() {}
vector<Vertex> get_vertices(){return vertices;}
vector<Edge> get_edges(){return edges;}
void set_vertices(vector<Vertex> vector_value) {vertices = vector_value;}
void set_edges(vector<Edge> vector_ed_value) {edges = vector_ed_value;}
unsigned int shortest(Vertex src, Vertex dis);
};
unsigned int Graph::shortest(Vertex src, Vertex dis) {
vector<Vertex> ver_out;
vector<Edge> track;
for (unsigned int i = 0; i < edges.size();) { // no ++i here
if ((edges[i].get_ver_1().get_id() == src.get_id()) || (edges[i].get_ver_2().get_id() == src.get_id())) {
track.push_back(edges[i]);
if (edges[i].get_ver_1().get_id() == src.get_id()) {
ver_out.push_back(edges[i].get_ver_2());
ver_out.back().set_carried(edges[i].get_weight());
} else {
ver_out.push_back(edges[i].get_ver_1());
ver_out.back().set_carried(edges[i].get_weight());
}
edges.erase(edges.begin() + i);
} else {
++i; // increment only if not erasing
}
}
for(unsigned int i = 0; i < vertices.size(); ++i)
for(unsigned int iii = 0; iii < ver_out.size(); ++iii) {
if(vertices[i].get_id() == ver_out[iii].get_id()){vertices[i].set_carried(ver_out[iii].get_carried());};};
for(unsigned int i = 0; i < vertices.size(); ++i)
if(vertices[i].get_id() == src.get_id()) vertices.erase(vertices.begin() + i);
track.clear();
if(ver_out[0].get_id() != dis.get_id()) {src = ver_out[0];}
else {src = ver_out[1];}
for(unsigned int i = 0; i < ver_out.size(); ++i)
if((ver_out[i].get_carried() < src.get_carried()) && (ver_out[i].get_id() != dis.get_id()))
src = ver_out[i];
ver_out.clear();
for(unsigned int round = 0; round < 1 ; ++round) //vertices.size()
{
for(unsigned int k = 0; k < edges.size(); ) //++k)
{
if((edges[k].get_ver_1().get_id() == src.get_id()) || (edges[k].get_ver_2().get_id() == src.get_id()))
{
track.push_back (edges[k]);
for(unsigned int i = 0; i < vertices.size(); ++i)
{
if(track.back().get_ver_1().get_id() == vertices[i].get_id()) edges[k].get_ver_1().set_carried(vertices[i].get_carried());
if(track.back().get_ver_2().get_id() == vertices[i].get_id()) edges[k].get_ver_2().set_carried(vertices[i].get_carried());
}
if(track.back().get_ver_1().get_id() == src.get_id())
{
ver_out.push_back (track.back().get_ver_2()); //************************************
if(track.back().get_ver_2().get_carried() > (track.back().get_ver_1().get_carried() + track.back().get_weight())) //<===
ver_out.back().set_carried(track.back().get_ver_1().get_carried() + track.back().get_weight());
else ver_out.back().set_carried(track.back().get_ver_2().get_carried());
}
else{
ver_out.push_back (track.back().get_ver_1());
if(track.back().get_ver_1().get_carried() > (track.back().get_ver_2().get_carried() + track.back().get_weight())) // <===
ver_out.back().set_carried(track.back().get_ver_2().get_carried() + track.back().get_weight());
else {ver_out.back().set_carried(track.back().get_ver_1().get_carried());}
}
//*****************************
edges.erase(edges.begin() + k);
}
else{
++k; // increment only if not erasing
}
};
for(unsigned int t = 0; t < vertices.size(); ++t)
if(vertices[t].get_id() == src.get_id()) vertices.erase(vertices.begin() + t);
track.clear();
if(ver_out[0].get_id() != dis.get_id()) {src = ver_out[0];}
else {src = ver_out[1];}
for(unsigned int tt = 0; tt < edges.size(); ++tt)
{
if(ver_out[tt].get_carried() < src.get_carried())
{
src = ver_out[tt];
}
}
ver_out.clear();
}
if(edges[0].get_ver_1().get_id() == dis.get_id()) return edges[0].get_weight() +edges[0].get_ver_2().get_carried();
else return edges[0].get_weight() +edges[0].get_ver_1().get_carried();
}
int main()
{
cout<< "Hello, This is a graph"<< endl;
vector<Vertex> vers(5);
vers[0].set_id(0);
vers[1].set_id(1);
vers[2].set_id(2);
vers[3].set_id(3);
vers[4].set_id(4);
vector<Edge> eds(10);
eds[0].set_first_vertex(vers[0]);
eds[0].set_second_vertex(vers[1]);
eds[0].set_weight(5);
eds[1].set_first_vertex(vers[0]);
eds[1].set_second_vertex(vers[2]);
eds[1].set_weight(9);
eds[2].set_first_vertex(vers[0]);
eds[2].set_second_vertex(vers[3]);
eds[2].set_weight(4);
eds[3].set_first_vertex(vers[0]);
eds[3].set_second_vertex(vers[4]);
eds[3].set_weight(6);
eds[4].set_first_vertex(vers[1]);
eds[4].set_second_vertex(vers[2]);
eds[4].set_weight(2);
eds[5].set_first_vertex(vers[1]);
eds[5].set_second_vertex(vers[3]);
eds[5].set_weight(5);
eds[6].set_first_vertex(vers[1]);
eds[6].set_second_vertex(vers[4]);
eds[6].set_weight(7);
eds[7].set_first_vertex(vers[2]);
eds[7].set_second_vertex(vers[3]);
eds[7].set_weight(1);
eds[8].set_first_vertex(vers[2]);
eds[8].set_second_vertex(vers[4]);
eds[8].set_weight(8);
eds[9].set_first_vertex(vers[3]);
eds[9].set_second_vertex(vers[4]);
eds[9].set_weight(3);
unsigned int path;
Graph graf(vers, eds);
path = graf.shortest(vers[2], vers[4]);
cout<<graf.get_edges()[0].get_ver_1().get_id() <<"____"<<graf.get_edges()[0].get_ver_2().get_id() <<" "<<graf.get_edges()[0].get_weight()<< endl; //test
cout<<graf.get_edges()[1].get_ver_1().get_id() <<"____"<<graf.get_edges()[1].get_ver_2().get_id() <<" "<<graf.get_edges()[1].get_weight()<< endl; //test
cout<<graf.get_edges()[2].get_ver_1().get_id() <<"____"<<graf.get_edges()[2].get_ver_2().get_id() <<" "<<graf.get_edges()[2].get_weight()<< endl; //test
//cout<<graf.get_edges()[3].get_ver_1().get_id() <<"____"<<graf.get_edges()[3].get_ver_2().get_id() <<" "<<graf.get_edges()[3].get_weight()<< endl; //test
//cout<<graf.get_edges()[4].get_ver_1().get_id() <<"____"<<graf.get_edges()[4].get_ver_2().get_id() <<" "<<graf.get_edges()[4].get_weight()<< endl; //test
//cout<<graf.get_edges()[5].get_ver_1().get_id() <<"____"<<graf.get_edges()[5].get_ver_2().get_id() <<" "<<graf.get_edges()[5].get_weight()<< endl; //test
//cout<<graf.get_edges()[6].get_ver_1().get_id() <<"____"<<graf.get_edges()[6].get_ver_2().get_id() <<" "<<graf.get_edges()[6].get_weight()<< endl; //test
//cout<<graf.get_edges()[7].get_ver_1().get_id() <<"____"<<graf.get_edges()[7].get_ver_2().get_id() <<" "<<graf.get_edges()[7].get_weight()<< endl; //test
//cout<<graf.get_edges()[8].get_ver_1().get_id() <<"____"<<graf.get_edges()[8].get_ver_2().get_id() <<" "<<graf.get_edges()[8].get_weight()<< endl; //test
//cout<<graf.get_edges()[9].get_ver_1().get_id() <<"____"<<graf.get_edges()[9].get_ver_2().get_id() <<" "<<graf.get_edges()[9].get_weight()<< endl; //test
cout<<"size of edges "<<graf.get_edges().size()<< endl;
cout<<"size of vertices "<<graf.get_vertices().size()<< endl;
cout<<"curried vertex_0 "<<graf.get_vertices()[0].get_carried()<< endl;
cout<<"curried vertex_1 "<<graf.get_vertices()[1].get_carried()<< endl;
cout<<"curried vertex_2 "<<graf.get_vertices()[2].get_carried()<< endl;
//cout<<"curried vertex_3 "<<graf.get_vertices()[3].get_carried()<< endl;
//cout<< path << endl;
return 0;
}
</code></pre>
<p><em><strong></em> *<em>edition was added so now it is same code but with some editions</strong> *</em>*** </p>
<p>I have added the == operator to the class Vertex and tried to get rid of every call to get_id() method when it was used in comparison operation , as<code>200_success</code>suggested earlier. </p>
<pre><code>#include<iostream>
#include<vector>
#include <stdlib.h> // for rand()
using namespace std;
class Vertex
{
private:
unsigned int id; // the name of the vertex
unsigned int carried; // the weight a vertex may carry when calculating shortest path
vector<unsigned int> previous_nodes;
public:
unsigned int get_id(){return id;};
unsigned int get_carried(){return carried;};
void set_id(unsigned int value) {id = value;};
void set_carried(unsigned int value) {carried = value;};
inline bool operator==( const Vertex& ver_1){ return id == ver_1.id;};
Vertex(unsigned int init_val = 0, unsigned int init_carried = 0) :id (init_val), carried(init_carried) // constructor
{}
~Vertex() {}; // destructor
};
class Edge
{
private:
Vertex first_vertex; // a vertex on one side of the edge
Vertex second_vertex; // a vertex on the other side of the edge
unsigned int weight; // the value of the edge ( or its weight )
public:
unsigned int get_weight() {return weight;};
void set_weight(unsigned int value) {weight = value;};
Vertex get_ver_1(){return first_vertex;};
Vertex get_ver_2(){return second_vertex;};
void set_first_vertex(Vertex v1) {first_vertex = v1;};
void set_second_vertex(Vertex v2) {second_vertex = v2;};
Edge(const Vertex& vertex_1 = 0, const Vertex& vertex_2 = 0, unsigned int init_weight = 0)
: first_vertex(vertex_1), second_vertex(vertex_2), weight(init_weight) {}
~Edge() {} ; // destructor
};
class Graph
{
private:
std::vector<Vertex> vertices;
std::vector<Edge> edges;
public:
Graph(vector<Vertex> ver_vector, vector<Edge> edg_vector)
: vertices(ver_vector), edges(edg_vector){}
~Graph() {}
vector<Vertex> get_vertices(){return vertices;}
vector<Edge> get_edges(){return edges;}
void set_vertices(vector<Vertex> vector_value) {vertices = vector_value;}
void set_edges(vector<Edge> vector_ed_value) {edges = vector_ed_value;}
unsigned int shortest(Vertex src, Vertex dis);
};
unsigned int Graph::shortest(Vertex src, Vertex dis) {
vector<Vertex> ver_out;
vector<Edge> track;
for (unsigned int i = 0; i < edges.size();) {
if ((edges[i].get_ver_1() == src) || (edges[i].get_ver_2() == src)) {
track.push_back(edges[i]);
if (edges[i].get_ver_1() == src) {
ver_out.push_back(edges[i].get_ver_2());
ver_out.back().set_carried(edges[i].get_weight());
} else {
ver_out.push_back(edges[i].get_ver_1());
ver_out.back().set_carried(edges[i].get_weight());
}
edges.erase(edges.begin() + i);
} else {
++i; // increment only if not erasing
}
}
for(unsigned int i = 0; i < vertices.size(); ++i)
for(unsigned int iii = 0; iii < ver_out.size(); ++iii) {
if(vertices[i] == ver_out[iii]){vertices[i].set_carried(ver_out[iii].get_carried());};};
for(unsigned int i = 0; i < vertices.size(); ++i)
if(vertices[i] == src) vertices.erase(vertices.begin() + i);
track.clear();
if(!(ver_out[0] == dis)) {src = ver_out[0];}
else {src = ver_out[1];}
for(unsigned int i = 0; i < ver_out.size(); ++i)
if((ver_out[i].get_carried() < src.get_carried()) && (!(ver_out[i] == dis)))
src = ver_out[i];
ver_out.clear();
for(unsigned int round = 0; round < 1 ; ++round) //vertices.size()
{
for(unsigned int k = 0; k < edges.size(); )
{
if((edges[k].get_ver_1() == src) || (edges[k].get_ver_2() == src))
{
track.push_back (edges[k]);
for(unsigned int i = 0; i < vertices.size(); ++i)
{
if(track.back().get_ver_1() == vertices[i]) edges[k].get_ver_1().set_carried(vertices[i].get_carried());
if(track.back().get_ver_2() == vertices[i]) edges[k].get_ver_2().set_carried(vertices[i].get_carried());
}
if(track.back().get_ver_1() == src)
{
ver_out.push_back (track.back().get_ver_2()); //************************************
if(track.back().get_ver_2().get_carried() > (track.back().get_ver_1().get_carried() + track.back().get_weight())) //<===
ver_out.back().set_carried(track.back().get_ver_1().get_carried() + track.back().get_weight());
else ver_out.back().set_carried(track.back().get_ver_2().get_carried());
}
else{
ver_out.push_back (track.back().get_ver_1());
if(track.back().get_ver_1().get_carried() > (track.back().get_ver_2().get_carried() + track.back().get_weight())) // <===
ver_out.back().set_carried(track.back().get_ver_2().get_carried() + track.back().get_weight());
else {ver_out.back().set_carried(track.back().get_ver_1().get_carried());}
}
//*****************************
edges.erase(edges.begin() + k);
}
else{
++k; // increment only if not erasing
}
};
for(unsigned int t = 0; t < vertices.size(); ++t)
if(vertices[t] == src) vertices.erase(vertices.begin() + t);
track.clear();
if(!(ver_out[0] == dis)) {src = ver_out[0];}
else {src = ver_out[1];}
for(unsigned int tt = 0; tt < edges.size(); ++tt)
{
if(ver_out[tt].get_carried() < src.get_carried())
{
src = ver_out[tt];
}
}
ver_out.clear();
}
if(edges[0].get_ver_1() == dis) return edges[0].get_weight() +edges[0].get_ver_2().get_carried();
else return edges[0].get_weight() +edges[0].get_ver_1().get_carried();
}
int main()
{
cout<< "Hello, This is a graph"<< endl;
vector<Vertex> vers(5);
vers[0].set_id(0);
vers[1].set_id(1);
vers[2].set_id(2);
vers[3].set_id(3);
vers[4].set_id(4);
vector<Edge> eds(10);
eds[0].set_first_vertex(vers[0]);
eds[0].set_second_vertex(vers[1]);
eds[0].set_weight(5);
eds[1].set_first_vertex(vers[0]);
eds[1].set_second_vertex(vers[2]);
eds[1].set_weight(9);
eds[2].set_first_vertex(vers[0]);
eds[2].set_second_vertex(vers[3]);
eds[2].set_weight(4);
eds[3].set_first_vertex(vers[0]);
eds[3].set_second_vertex(vers[4]);
eds[3].set_weight(6);
eds[4].set_first_vertex(vers[1]);
eds[4].set_second_vertex(vers[2]);
eds[4].set_weight(2);
eds[5].set_first_vertex(vers[1]);
eds[5].set_second_vertex(vers[3]);
eds[5].set_weight(5);
eds[6].set_first_vertex(vers[1]);
eds[6].set_second_vertex(vers[4]);
eds[6].set_weight(7);
eds[7].set_first_vertex(vers[2]);
eds[7].set_second_vertex(vers[3]);
eds[7].set_weight(1);
eds[8].set_first_vertex(vers[2]);
eds[8].set_second_vertex(vers[4]);
eds[8].set_weight(8);
eds[9].set_first_vertex(vers[3]);
eds[9].set_second_vertex(vers[4]);
eds[9].set_weight(3);
unsigned int path;
Graph graf(vers, eds);
path = graf.shortest(vers[2], vers[4]);
cout<<graf.get_edges()[0].get_ver_1().get_id() <<"____"<<graf.get_edges()[0].get_ver_2().get_id() <<" "<<graf.get_edges()[0].get_weight()<< endl; //test
cout<<graf.get_edges()[1].get_ver_1().get_id() <<"____"<<graf.get_edges()[1].get_ver_2().get_id() <<" "<<graf.get_edges()[1].get_weight()<< endl; //test
cout<<graf.get_edges()[2].get_ver_1().get_id() <<"____"<<graf.get_edges()[2].get_ver_2().get_id() <<" "<<graf.get_edges()[2].get_weight()<< endl; //test
//cout<<graf.get_edges()[3].get_ver_1().get_id() <<"____"<<graf.get_edges()[3].get_ver_2().get_id() <<" "<<graf.get_edges()[3].get_weight()<< endl; //test
//cout<<graf.get_edges()[4].get_ver_1().get_id() <<"____"<<graf.get_edges()[4].get_ver_2().get_id() <<" "<<graf.get_edges()[4].get_weight()<< endl; //test
//cout<<graf.get_edges()[5].get_ver_1().get_id() <<"____"<<graf.get_edges()[5].get_ver_2().get_id() <<" "<<graf.get_edges()[5].get_weight()<< endl; //test
//cout<<graf.get_edges()[6].get_ver_1().get_id() <<"____"<<graf.get_edges()[6].get_ver_2().get_id() <<" "<<graf.get_edges()[6].get_weight()<< endl; //test
//cout<<graf.get_edges()[7].get_ver_1().get_id() <<"____"<<graf.get_edges()[7].get_ver_2().get_id() <<" "<<graf.get_edges()[7].get_weight()<< endl; //test
//cout<<graf.get_edges()[8].get_ver_1().get_id() <<"____"<<graf.get_edges()[8].get_ver_2().get_id() <<" "<<graf.get_edges()[8].get_weight()<< endl; //test
//cout<<graf.get_edges()[9].get_ver_1().get_id() <<"____"<<graf.get_edges()[9].get_ver_2().get_id() <<" "<<graf.get_edges()[9].get_weight()<< endl; //test
cout<<"size of edges "<<graf.get_edges().size()<< endl;
cout<<"size of vertices "<<graf.get_vertices().size()<< endl;
cout<<"curried vertex_0 "<<graf.get_vertices()[0].get_carried()<< endl;
cout<<"curried vertex_1 "<<graf.get_vertices()[1].get_carried()<< endl;
cout<<"curried vertex_2 "<<graf.get_vertices()[2].get_carried()<< endl;
//cout<<"curried vertex_3 "<<graf.get_vertices()[3].get_carried()<< endl;
//cout<< path << endl;
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>According to the rules of this site, we don't fix non-working code. However, I think that this question deserves a response anyway, since problems with your programming style are a major impediment to reaching a solution. To be frank, the snippet you emphasized looks overwhelming.</p>\n\n<p>You want to push as much complexity out of the algorithm as possible by making <code>Edge</code> and <code>Vertex</code> work better. One obvious simplification is to override <code>Vertex.operator==(const Vertex &v)</code> so that you don't have to call <code>.get_id()</code> everywhere.</p>\n\n<p>You frequently iterate over all vertices in the graph and all edges in the graph to find objects that you care about. That makes your code cumbersome to read, and it will also hurt performance. Currently, your vertices and edges basically exist in isolation. When you construct your <code>Graph</code>, you should interpret the data into a more useful form by linking up the vertices and edges.</p>\n\n<p>Compare your code against a what <a href=\"http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Pseudocode\" rel=\"nofollow\">Dijkstra's algorithm is supposed to look like</a>. Right now, I don't see much resemblance. Taking line 16 of the pseudocode, for example (<code>for each neighbor v of u</code>), you should take the hint to implement a <code>Vertex.neighbor_iterator()</code> or something similar.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T19:56:21.773",
"Id": "57176",
"Score": "0",
"body": "the first point you have mentioned is very important , actually i am very new to C++ and even i thought about operators overriding but i was wondering on the real reason why the code is not producing the correct result, now i am going to work on defining the operators overriding trying to simplifying the complexity of the code.Thanks a lot (i wanted to vote up but i have not enough reputations), i hope i can find the bug of this code , my wonder is why it is not working more than Dijkastra algorithm itself as a learner of C++."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T21:34:00.953",
"Id": "57183",
"Score": "0",
"body": "i added the operator == to the class Vertex , and edited the code to get rid of many calls to get_id(). Once again thank you 200_success"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T19:34:46.723",
"Id": "35310",
"ParentId": "35290",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T12:44:49.820",
"Id": "35290",
"Score": "2",
"Tags": [
"c++",
"algorithm",
"graph"
],
"Title": "Applying Dijkastra's algorithm on a graph of five nodes"
}
|
35290
|
<p><a href="http://en.wikipedia.org/wiki/ColdFusion_Markup_Language" rel="nofollow">CFML</a> is the main scripting language for the <a href="/questions/tagged/coldfusion" class="post-tag" title="show questions tagged 'coldfusion'" rel="tag">coldfusion</a> web application platform. In addition to Adobe's ColdFusion server, CFML code can also run on the JVM, the <a href="/questions/tagged/.net" class="post-tag" title="show questions tagged '.net'" rel="tag">.net</a> framework, <a href="/questions/tagged/google-app-engine" class="post-tag" title="show questions tagged 'google-app-engine'" rel="tag">google-app-engine</a>, <a href="http://www.getrailo.org" rel="nofollow">Railo</a>, <a href="http://www.newatlanta.com/bluedragon/" rel="nofollow">New Atlanta BlueDragon</a>, and <a href="http://openbd.org/" rel="nofollow">Open BlueDragon</a>.</p>
<p>In its simplest form, like many other web scripting languages, CFML augments standard HTML files with database commands, conditional operators, high-level formatting functions, and other elements to produce web applications. (CFML can generate output other than HTML, such as XML, JavaScript, and CSS.) CFML also includes numerous other constructs including ColdFusion Components (CFCs): CFML's version of objects that allow for separation of business logic from presentation. CFML can be written using either tags or CFScript, which is an ECMAScript-style language.</p>
<p>The pages in a CFML application include the server-side CFML tags and functions in addition to HTML tags, and modern CFML applications also tend to have CFCs that are accessed by the CFML pages for executing business logic.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T17:17:50.180",
"Id": "35301",
"Score": "0",
"Tags": null,
"Title": null
}
|
35301
|
CFML is the main scripting language for the ColdFusion web application platform. In addition to Adobe's ColdFusion server, CFML code can also run on the JVM, the .NET framework, Google App Engine, Railo, New Atlanta BlueDragon, and Open BlueDragon. Use this tag for code written in CFML, and add other tags for the targeted platform if applicable.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T17:17:50.180",
"Id": "35302",
"Score": "0",
"Tags": null,
"Title": null
}
|
35302
|
<p>Which of the following is better coding style and why?</p>
<pre><code>print("We have x = %i" %x)
print("We have x = "+str(x))
</code></pre>
|
[] |
[
{
"body": "<p>Your first example was better. <code>print(\"We have x = %i\" %x)</code> because you are working with a string object. It takes less memory than working with 2 string objects and an int.</p>\n\n<p>Since you are asking with a python3 tag, here is a newer format for python string formatting using str.format</p>\n\n<pre><code>dic = { 'x': '1'}\nprint(\"We have x = {x}\".format(**dic))\n</code></pre>\n\n<p>or you can do this positionally:</p>\n\n<pre><code>print(\"The sum of 1 + 2 is {0}\".format(1+2))\n</code></pre>\n\n<p>This works with 2.6+ and 3.3+</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T18:25:05.267",
"Id": "57170",
"Score": "0",
"body": "For most people I think the reason for using substitution is more about style than performance. According to this SO answer from 2008 http://stackoverflow.com/questions/376461/string-concatenation-vs-string-substitution-in-python, concatenation is actually faster than substitution. However I don't know if this has changed with Python3."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T18:16:15.113",
"Id": "35305",
"ParentId": "35303",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "35305",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T17:23:19.207",
"Id": "35303",
"Score": "-2",
"Tags": [
"python",
"python-3.x"
],
"Title": "Best way to print the value of a variable?"
}
|
35303
|
<p>How can I write a better database query wrapper?</p>
<pre><code>//code for connection
exports.connect = function(callback) {
client.connect(function(err, conInfo){
if (err) callback(err);
conInfo = "Connection at " + client.host + ":" + client.port + "/"
+ client.database + " used by " + client.user;
callback(null, conInfo);
});
};
//for queries that do not return realation
exports.runQuery = function(query_str, columns, params, callback) {
var sqlQuery = query_str + " " + columns;
client.query(sqlQuery, params, function(err) {
console.log("NEW QUERY____________________");
console.log(sqlQuery);
console.log(params);
if (err) throw err;
callback(null);
});
};
//for select queries
exports.executeQuery = function(query_str, callback) {
var query = client.query(query_str, function(err){
console.log("NEW QUERY____________________");
console.log(query_str);
if (err) throw err;
query.on("row", function(row, result) {
result.addRow(row);
});
query.on("end", function (result) {
callback(null, result.rows);
});
});
};
</code></pre>
|
[] |
[
{
"body": "<p>I don't do JS, even less <code>node.js</code>, but from the looks of it you seem to be taking in a <code>string</code> for your query, which means client code can do something like <code>\"select x, y, sum(z) from mytable where x = \" + someValue + \" group by x, y\"</code> - which is prone to SQL-injection: your client code needs to remember that.</p>\n\n<p>If your <code>executeQuery</code> also took parameters, I think it would be clearer that when you need parameters, they should be passed as arguments to that function, not concatenated into the query string.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T18:33:25.663",
"Id": "35709",
"ParentId": "35306",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "35709",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T18:42:23.877",
"Id": "35306",
"Score": "2",
"Tags": [
"javascript",
"sql",
"node.js"
],
"Title": "SQL database query wrapper"
}
|
35306
|
<p>I am writing non-blocking code as it should be in Node.JS. If I want run function A after B I do it using callback.</p>
<p>But I find <a href="http://nodeguide.com/style.html" rel="nofollow">this</a> style guide:</p>
<blockquote>
<p>Use closures, but don't nest them. Otherwise your code will become a
mess.</p>
<p><strong>Right:</strong></p>
<pre><code>setTimeout(function() {
client.connect(afterConnect);
}, 1000);
function afterConnect() {
console.log('winning');
}
</code></pre>
<p><strong>Wrong:</strong></p>
<pre><code>setTimeout(function() {
client.connect(function() {
console.log('losing');
});
}, 1000);
</code></pre>
</blockquote>
<p>How deep should my closures be? Specifically, I'd like to consider this sample:</p>
<pre><code>exports.profileImage = function(req, res) {
var id = req.params.user_id;
userProvider.get(id, function(err, user){
if (err) throw err;
userProvider.getImageById(user['image_id'], function(err, image) {
if (err) throw err;
userProvider.writeImageToDisk(image, function(err, path){
if (err) throw err;
res.sendfile(path);
});
});
});
};
</code></pre>
|
[] |
[
{
"body": "<p>as a personal preference I like the \"Right\" way that you have listed. it looks cleaner to me. </p>\n\n<p>On the other hand I see lots of Java and JavaScript where they have nested functions that are not used anywhere else in the code, personally I don't like this, it looks way to complicated and if you want to use the inside function later on you have to rewrite it if it is nested inside of another function or use the outside function to use the inside function.</p>\n\n<p>I would agree the \"Right\" example is the Right example. </p>\n\n<p>Again, this is my personal preference.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-01T20:14:49.037",
"Id": "232131",
"Score": "1",
"body": "I tend to agree with you, in general the 'arrow' design (you have multiple nests and the code shape resembles an arrowhead), is considered very bad practice; it can lead to missing brackets as well as scoping issues that are missed."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T19:04:46.917",
"Id": "35309",
"ParentId": "35307",
"Score": "2"
}
},
{
"body": "<p>First of all, you are correct. One way to prevent deep nesting is to pull out the callback into it's own named function. This allows you to only be as deep as 2-3 levels in blocks of code.</p>\n\n<pre><code>function task1(){\n async1(task2);\n}\n\nfunction task2(){\n async1(task3);\n}\n\nfunction task3(){\n async1(task4);\n}\n</code></pre>\n\n<p>Another way to do it is by using flow-control libraries which take advantage of the concept of <a href=\"https://github.com/FuturesJS/FuturesJS\" rel=\"nofollow\">Futures</a>/<a href=\"http://api.jquery.com/category/deferred-object/\" rel=\"nofollow\">Deferreds</a>/<a href=\"http://wiki.commonjs.org/wiki/Promises/A\" rel=\"nofollow\">Promises</a>. There are a lot of ways to call them, but they are the same thing most of the time.</p>\n\n<p>The basic concept is that they usually stack up callbacks via utility functions and then run them, depending on the result of the previous or depending on the used utility function. The code will look linear and synchronous, but it actually is running async and the library controls the flow of calls and results. In jQuery, you can do something like</p>\n\n<pre><code>//Run an addition in the server\n$.get('add.php',{\n op1 : 1,\n op2 : 2\n })\n .then(function(result){\n //get the addition result (3) and multiply it on the server (another async)\n return $.get('multiply.php'{\n op1 : result,\n op2 : 3\n });\n })\n .then(function(result){\n //get the multiplication result (9) and divide it on the server (another async)\n return $.get('divide.php'{\n op1 : result,\n op2 : 9\n });\n })\n .done(function(result){\n console.log(result); //1\n });\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T01:43:19.707",
"Id": "35325",
"ParentId": "35307",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "35325",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T18:49:32.563",
"Id": "35307",
"Score": "4",
"Tags": [
"javascript",
"node.js",
"error-handling",
"closure"
],
"Title": "Writing a user's profile image to disk using nested Node.JS closures"
}
|
35307
|
<p>PROMELA is a process modeling language whose intended use is to verify the logic of parallel systems. Given a program in PROMELA, the SPIN model checker can verify the model for correctness by performing random or iterative simulations of the modeled system's execution, or it can generate a C program that performs a fast exhaustive verification of the system state space.</p>
<p><em>Summary taken from <a href="http://en.wikipedia.org/wiki/Promela" rel="nofollow">Wikipedia</a>.</em></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T19:40:20.120",
"Id": "35311",
"Score": "0",
"Tags": null,
"Title": null
}
|
35311
|
PROMELA (Process or Protocol Meta Language) is a process modeling language whose intended use is to verify the logic of parallel systems.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T19:40:20.120",
"Id": "35312",
"Score": "0",
"Tags": null,
"Title": null
}
|
35312
|
<p>I have an application which currently uses AJAX for CRUD operations on a simple <code>Person</code> object. The following script works fine, but I'm looking for some pointers on how to structure my code. Currently, I have four methods for CRUD operations, and I'll extend my <code>person</code> module as needed, but I was hoping to get an idea of whether or not this is a nice way to manage code. </p>
<pre><code> $(document).ready(function () {
//open the modal
//the update, delete and insert functions come from boxes present in a modal not shown
$('#openModal').click(function () {
$('#contact').modal();
});
//insert
$('#btnSavePerson').click(function () {
//is it a good idea to have the data objects inside all of these functions?
var data = {
personId: $('#tbPersonId').val(),
firstName: $('#tbFirstName').val(),
lastName: $('#tbLastName').val()
};
person.insert(data);
});
//delete
$('#btnDeletePerson').click(function () {
var personId = $('#tbDelete').val();
person.remove(personId);
});
//update
$('#btnUpdatePerson').click(function () {
var data = {
personId: $('#tbPersonId').val(),
firstName: $('#tbFirstName').val(),
lastName: $('#tbLastName').val()
};
console.log(JSON.stringify(data));
person.update(data);
});
//get
$('#getPeople').click(function () {
person.get();
});
//*********************person module
var person = (function () {
//the ajax object will be passed and shared between
//the functions here (type and dataType dont change in this example)
var ajax = {
type: "POST",
url: "",
data: {},
dataType: "json",
contentType: "application/json",
success: {},
error: {}
}
//************ insert
function insert(data) {
ajax.url = '../Service.asmx/InsertPerson';
ajax.success = function () {
console.log('success before setTimeout');
var successMessage = $('<div>').text('Successfully added to the database...')
.css('color', 'green')
.attr('id', 'success');
$('.modal-body').append(successMessage);
window.setTimeout(function () {
$('.modal-body').each(function () {
$(this).val('');
});
$('#contact').modal('hide');
}, 1000);
}
ajax.data = JSON.stringify(data);
ajax.error = function (xhr, ajaxOptions) {
console.log(xhr.status);
console.log(ajaxOptions);
};
$.ajax(ajax);
}
//************* delete
function remove(data) {
ajax.url = '../Service.asmx/DeletePerson';
console.log('working string: ');
var obj = { personId: data };
console.log(JSON.stringify(obj));
ajax.data = JSON.stringify(obj);
console.log(ajax.data);
ajax.success = function () {
console.log('person successfully deleted');
var successMessage = $('<div>').text('Person successfully deleted from the database')
.css('color', 'red');
$('.modal-body').append(successMessage);
window.setTimeout(function () {
$('.modal-body input').each(function () {
$(this).val('');
});
$('#contact').modal('hide');
}, 1000);
};
ajax.error = function (xhr, ajaxOptions) {
console.log(xhr.status);
console.log(ajaxOptions);
}
$.ajax(ajax);
}
//*************** update
function update(data) {
ajax.url = '../Service.asmx/UpdatePerson',
ajax.data = JSON.stringify(data),
ajax.success = function () {
console.log('update was successful');
var successMessage = $('<div>').text('Record successfully updated...')
.css('color', 'green');
$('modal-body').append(successMessage);
window.setTimeout(function () {
$('.modal-body input').each(function () {
$(this).val('');
});
$('#contact').modal('hide');
}, 1000);
};
ajax.error = function (xhr, ajaOptions) {
console.log(xhr.status);
};
$.ajax(ajax);
};
//************** get
function get() {
//****** appropriate to have this function here?
function style(json) {
json = $.parseJSON(json);
var $personArray = [];
for (var obj in json) {
var $person = $('<div>').addClass('person');
for (var prop in json[obj]) {
var label = $('<span>').text(prop).addClass('badge pull-left').appendTo($person);
var propertyData = $('<span>').text(json[obj][prop]).addClass('pull-right').appendTo($person);
}
$personArray.push($person);
}
return $personArray;
}
ajax.url = '../Service.asmx/GetPersons';
ajax.success = function (data) {
data = data.d;
console.log('ajax successful');
$('body').append(style(data));
};
ajax.error = function (xhr, ajaxOptions) {
console.log(xhr.status);
console.log(ajaxOptions);
}
$.ajax(ajax);
}
//*********** public methods
return {
insert: insert,
remove: remove,
update: update,
get: get
};
})();
});
</code></pre>
<p>HTML in case someone wants to see it:</p>
<pre><code><body>
<div class="navbar navbar-inverse navbar-static-top">
<div class="container">
<a href="#" class="navbar-brand">ui</a>
<button class="navbar-toggle" data-toggle="collapse" data-target=".navHeaderCollapse">
<span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar">
</span>
</button>
<div class="collapse navbar-collapse navHeaderCollapse">
<ul class="nav navbar-nav navbar-right">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Blog</a></li>
<li><a id="openModal" href="#contact">Contact</a></li>
</ul>
</div>
</div>
</div>
<p id="getPeople" class="btn btn-block">get them peoples</p>
<div class="modal fade" id="contact" role="diaglog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h2>contact: </h2>
</div>
<div class="modal-body">
The improtant information from the database is going to be displayed here.
<span class="label label-success">Person ID: </span><input id="tbPersonId" class="warning" /><br />
<span class="label label-success">First Name:</span><input id="tbFirstName" /><br />
<span class="label label-success">Last Name: </span><input id="tbLastName" /><br />
<span class="label label-danger">Delete box: </span><input id="tbDelete" />
</div>
<div class="modal-footer">
<a class="btn btn-default" id="modalClose" >Close</a>
<a class="btn btn-primary" id="btnSavePerson">Save changes</a>
<a class="btn btn-danger" id="btnDeletePerson">Delete person</a>
<a class="btn btn-block" id="btnUpdatePerson">Update Person</a>
</div>
</div>
</div>
</div>
</body>
</code></pre>
|
[] |
[
{
"body": "<p>Right, I'm on a break, so this is just a few pointers to help you along. I'll probably get back to this answer and add some more details in days to come...</p>\n\n<p>the first thing I noticed is that you declared your <code>person</code> module somewhere half-way your <code>ready</code> callback function. Though the variable <code>person</code> will be hoisted to the top of the scope the IIFE (Immediatly invoked function expression) that assigns it <em>cannot be hoisted</em>. It's an expression, so your code evaluates to:</p>\n\n<pre><code>$(document).ready(function()\n{\n var person;\n //some code, using person as a module\n person = (function()\n {\n }());//assignment happens here!\n});\n</code></pre>\n\n<p>Though it's very unlikely this will cause problems, it's generally a good idea to move the assignment to the top of the scope:</p>\n\n<pre><code>$(document).ready(function()\n{\n var person = (function()\n {\n }());\n //rest of your code here...\n});\n</code></pre>\n\n<p>Another thing that sort of annoys me is your use of <code>window</code>:</p>\n\n<pre><code>window.setTimeout\n</code></pre>\n\n<p>But at the same time, you're using:</p>\n\n<pre><code>console.log();\n</code></pre>\n\n<p>without the <code>window</code> reference. That's inconsistent and, if anything, quite redundant. JS resolves the <code>window</code> name in the same way as it resolves <code>console</code> or <code>setTimeout</code>: it scans the current scope, if it can't find the name there, it moves up to a higher scope until it reaches the global namespace/scope.<br/>\nAs you may know, the global NS is, effectively an object that has no name. (try <code>console.log(this === window)</code> in your console). This object has a property, called <code>window</code>, which is nothing more than a circular reference to this nameless object. Hence <code>console.log(this.window === window); console.log(this.window === this)</code> will both log true. As a result <code>setTimeout</code> will be very, very marginally <em>faster</em> than <code>window.setTimeout</code> anyway, so I'd suggest you loose the <code>window</code> where you can.</p>\n\n<p>Next: the <code>person</code> module isn't exactly <em>stand-alone</em>, in it, you assume <code>$</code> to be the jQuery object, and you expect it to be defined in a higher scope. I wouldn't do that. Here's why:</p>\n\n<pre><code>var dependency = {foo: function()\n{\n return 'bar';\n}};\nvar unsafeModule = (function()\n{\n return { getBar : dependency.foo};\n}());\nunsafeModule.getBar();//returns bar, fine...\ndependency = 213;\nunsafeModule.getBar();//ERROR\n</code></pre>\n\n<p>A better, safer approach would be:</p>\n\n<pre><code>var dependency = {foo: function()\n{\n return 'bar';\n}};\nvar saferModule = (function(d)\n{\n return { getBar : d.foo};\n}(dependency));\n</code></pre>\n\n<p>By passing a reference to the object my module, that object remains in scope, and my module will continue to work just fine 'n dandy, no matter how many times the <code>dependency</code> variable gets reassigned.<Br/>\nBut even better would be:</p>\n\n<pre><code>var dependency = {foo: function()\n{\n return 'bar';\n}};\nvar saferModule = (function(d)\n{\n var mod = {setter: function(dep)\n {\n d = dep;\n this.getBar = d.foo;\n delete (this.setter);\n return this;\n }};\n\n if (d === undefined) return mod;\n return mod.setter(d);\n}());//no dependency passed!\nd.setter(dependency);//sets dependency\nd.getBar();//works\n</code></pre>\n\n<p>When we apply this logic to your module, you can safely move the <code>person</code> module declaration to another file, or outside of the <code>$(document)ready</code> callback's scope:</p>\n\n<pre><code>var person = (function()\n{\n var mod = { remove : function(){},\n get : function(){}};//declare your module\n return {init: function($)\n {\n var p;\n if($ instanceof jQuery)\n {\n delete(this.init);//unset init method\n for (p in mod)\n {//copy module properties into person\n this[p] = mod[p];\n }\n return this;\n }\n throw {message: 'Module needs jQ to work', code: 666};\n }};\n}\n$(document).ready(function()\n{\n person.init($);//pass jQ ref to module, it'll init itself.\n});\n</code></pre>\n\n<p>Lastly, a side-note. You're trying to implement the module pattern. That's good, but a module requires a closure. You can use closures all over the place to avoid, for example, excessive DOM queries.<br/>\nFor example:</p>\n\n<pre><code>$('#openModal').click(function () {\n $('#contact').modal();\n});\n</code></pre>\n\n<p>Now each time I click on <code>$('#openModal')</code>, the callback function gets called. this function will query the DOM, because <code>$('#contact')</code> is a DOM selector. If I click this element 10 times, the DOM will be queried 10 times. A closure can reduce this:</p>\n\n<pre><code>$('#openModal').click((function(contact)\n{\n return function()\n {\n contact.modal();//use ref in scope, no more DOM lookups required\n };\n}($('#contact')));//pass DOM ref here, query dom once\n</code></pre>\n\n<p>These sort of, seemingly trivial, optimizations are easy, but can make a difference the bigger your script gets, and the more interactive your site has to be.</p>\n\n<hr>\n\n<p>Ok, another update. I've noticed you write code like this:</p>\n\n<pre><code>$('#getPeople').click(function()\n{\n person.get();\n});\n</code></pre>\n\n<p>This is typical jQ code: passing an anonymous function to the event handler. When a callback function (ie the anonymous function) merely calls another function, wouldn't it be easier, shorter <em>and</em> more efficient to just pass a reference to the function you need in the first place?</p>\n\n<pre><code>$('#getPeople').click(person.get);\n</code></pre>\n\n<p>It'll do pretty much the same thing, is shorter to write and saves on a pointless function object.<br/>\nThe only downside being: you're losing the call-context (within the <code>person.get</code> function <code>this</code> won't point to <code>person</code> anymore). So I had a look at your <code>person.get</code> function. I'll paste it here, with some comments. I'll address some issues further down</p>\n\n<pre><code>function get()\n{\n //****** appropriate to have this function here?\n // NO, this function will be redeclared each time person.get is called\n //it should be defined somewhere else, in a higher scope\n function style(json)\n {\n json = $.parseJSON(json);\n var $personArray = [];\n for (var obj in json)\n {//still best to filter a for-in loop\n var $person = $('<div>').addClass('person');//again, DOM query?\n for (var prop in json[obj])\n {//I can't see where you're using the label var...\n var label = $('<span>').text(prop).addClass('badge pull-left').appendTo($person);\n var propertyData = $('<span>').text(json[obj][prop]).addClass('pull-right').appendTo($person);\n }\n $personArray.push($person);\n }\n return $personArray;\n }\n ajax.url = '../Service.asmx/GetPersons';\n ajax.success = function (data)\n {//this callback can be reused, too\n data = data.d;\n console.log('ajax successful');\n $('body').append(style(data));//avoid DOM access!\n };\n ajax.error = function (xhr, ajaxOptions)\n {//another callback to be avoided!\n console.log(xhr.status);\n console.log(ajaxOptions);\n }\n $.ajax(ajax);\n}\n</code></pre>\n\n<p>So, let's consider what the <code>get</code> function actually <em>needs</em> to do its job:</p>\n\n<ul>\n<li>a <code>style</code> function</li>\n<li>a couple of callbacks (<code>success</code> and <code>onerror</code>) for the <code>ajax</code> object literal, and its own URL</li>\n<li>A couple of DOM elements, for example the <code>$('body')</code>. That's a pretty static element, I do believe.</li>\n</ul>\n\n<p>So instead of getting all these objects, why not define/declare them when we're creating our <code>get</code> function, and reuse them every time this function is called? Instead of declaring <code>function get</code> inside the IIFE that returns the <code>person</code> module, we could write something like:</p>\n\n<pre><code>var get = (function(body)\n{\n var successCallback, style,\n errorCallback = function(xhr, ajaxOptions)\n {//or declare as local var to function\n console.log(xhr.status);\n console.log(ajaxOptions);\n };\n successCallback = function (data)\n {\n console.log('ajax successful');\n //use DOM reference, parse it here already... SRP!\n body.append(style($.parseJSON(data.d)));\n };\n style = function(json)\n {\n var personArray = [], obj, prop, person;//declare at top of scope\n for (obj in json)\n {//I do hope this isn't an array!\n if (json.hasOwnProperty(obj))\n {//best to check, still\n person = $('<div class=\"person\"'>);//avoid addClass call\n for (prop in json[obj])\n {\n if (json[obj].hasOwnProperty(prop))\n {//no point in assigning return val to vars you do not use\n $('<span class=\"badge pull-left\">')\n .text(prop).appendTo(person);\n $('<span class=\"pull-right\">')\n .text(json[obj][prop]).appendTo(person);\n }\n }\n personArray.push(person);\n }\n }\n return personArray;\n };\n //the actual get function:\n return function()\n {\n ajax.url = '../Service.asmx/GetPersons';\n ajax.success = successCallback;\n ajax.error = errorCallback;\n return $.ajax(ajax);\n };\n}($('body')));//either pass as argument\n</code></pre>\n\n<p>Now what I've done here is sort-of created a get <em>module</em> within the main <em>person</em> module. You can (and probably eventually will) work some more on this, since all of your person module functions perform ajax requests, you might add a more generic <em><code>getAjax</code></em> function that you choose not to expose.<Br/>\nA function that gouverns the <code>ajax</code> object, and keeps track of the callbacks and urls each function in the module requires, and that sets the ajax object accordingly:</p>\n\n<pre><code>var doAjax = function()\n{\n var ajax = {},//your ajax object literal\n callers = {get: {url: '../Service.asmx/GetPersons',\n success: function(){},\n error: function(){}},\n insert: {url: '../Service.asmx/InsertPerson',\n success: function(){}},\n default: {url: 'some/default',\n success: function(){}}\n };\n return function(data,caller)\n {\n var settings,p;\n caller = caller || 'default';\n settings = callers[caller] || callers.default;\n for (p in settings)\n {\n if (settings.hasOwnProperty(p)) ajax[p] = settings[p];\n }\n return $.ajax(ajax);\n };\n}());\n</code></pre>\n\n<p>Now all your module functions can just call this function like so:</p>\n\n<pre><code>doAjax(myData, 'insert');\n//or\ndoAjax(undefined, 'get');\n</code></pre>\n\n<p>Oh, and this code would go here:</p>\n\n<pre><code>var person = (function()\n{\n var doAjax = (function(){}());//in module!\n}());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T13:29:06.397",
"Id": "57278",
"Score": "0",
"body": "This is exactly the type of stuff that I was looking for. I'll be honest, some of the concepts here are a little outside of my league at first blush, but this gives me a good idea of what a BETTER idea would be and that's what I was looking for. I'll leave this unchecked as the answer until you're finished adding whatever you think it necessary. Great stuff, gracias!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-17T15:06:29.877",
"Id": "57647",
"Score": "1",
"body": "@wootscootinboogie: I've added some more details, mainly on the `get` function you wrote. I did mention context (`this`) bindings. This concept is, to many, quite difficult to understand at first, [perhaps refer to MDN for details](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-17T16:25:22.030",
"Id": "57653",
"Score": "0",
"body": "danke this is all great stuff."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T12:10:57.743",
"Id": "35338",
"ParentId": "35316",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "35338",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T22:21:03.733",
"Id": "35316",
"Score": "5",
"Tags": [
"javascript",
"jquery",
"design-patterns"
],
"Title": "JavaScript Module Pattern with AJAX"
}
|
35316
|
<p>I must implement a simple <a href="http://en.wikipedia.org/wiki/Caesar_cipher" rel="noreferrer">Caesar cipher</a> class. Initializer takes two parameters - number of positions to shift the alphabet (integer) and the alphabet used (as string, not necessarily the standard English alphabet). The class must have two instance methods <code>encrypt</code> and <code>decrypt</code>, which take a string and do the respective action based on the parameters of the initializer. These are my rspec tests:</p>
<pre><code>describe "Caesar" do
latin_encrypter = Caesar.new 4
dna_encrypter = Caesar.new 3, 'ACTG'
it 'encrypts correctly' do
expect(latin_encrypter.encrypt 'hello').to eq "lipps"
end
it 'encrypts correctly using DNA alphabet' do
expect(dna_encrypter.encrypt 'ACCTGA').to eq "GAACTG"
end
it 'decrypts correctly' do
expect(latin_encrypter.decrypt 'lipps').to eq 'hello'
end
it 'decrypts correctly using DNA alphabet' do
expect(dna_encrypter.decrypt 'GAACTG').to eq 'ACCTGA'
end
end
</code></pre>
<p>and this is my implementation:</p>
<pre><code>class Caesar
def initialize(shift, alphabet = 'abcdefghijklmnopqrstuvwxyz')
@shift = shift % alphabet.size
@alphabet = alphabet
end
def encrypt(string)
string.chars.map { |char| @alphabet[@alphabet.index(char) + @shift - @alphabet.size] }.join
end
def decrypt(string)
string.chars.map { |char| @alphabet[@alphabet.index(char) - @shift] }.join
end
end
</code></pre>
<p>Is this an optimal algorithm for encryption/decryption or is there a better one (perhaps using <code>gsub</code>)?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T23:18:32.530",
"Id": "57193",
"Score": "0",
"body": "`Caesar.new(1).encrypt('1337')` → `NoMethodError: undefined method \\`+' for nil:NilClass`. The parameter may be invalid, but the error message should be more helpful."
}
] |
[
{
"body": "<p>The only (conceptual) problem I see in your code is that both <code>encrypt</code>/<code>decrypt</code> perform a O(n) operation (<code>detect</code>) for every character (so at then end it's a O(n*m) algorithm), that's unnecessarily inefficient. Build a hash object to use as an indexer:</p>\n\n<pre><code>class Caesar\n def initialize(shift, alphabet = ('a'..'z').to_a.join)\n @shift = shift\n @alphabet = alphabet\n @indexes = alphabet.chars.map.with_index.to_h\n end\n\n def encrypt(string)\n string.chars.map { |c| @alphabet[(@indexes[c] + @shift) % @alphabet.size] }.join\n end\n\n def decrypt(string)\n string.chars.map { |c| @alphabet[(@indexes[c] - @shift) % @alphabet.size] }.join\n end\nend\n</code></pre>\n\n<p>You can also build encrypter/decrypter hash tables at initialization:</p>\n\n<pre><code>class Caesar\n def initialize(shift, alphabet = ('a'..'z').to_a.join)\n chars = alphabet.chars.to_a\n @encrypter = chars.zip(chars.rotate(shift)).to_h\n @decrypter = @encrypter.invert\n end\n\n def encrypt(string)\n @encrypter.values_at(*string.chars).join\n end\n\n def decrypt(string)\n @decrypter.values_at(*string.chars).join\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T23:01:22.963",
"Id": "57190",
"Score": "1",
"body": "Yes, exactly, `Array#rotate` was the thing I was looking for. Thank you very much! The second version is really elegant!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T22:47:46.227",
"Id": "35318",
"ParentId": "35317",
"Score": "4"
}
},
{
"body": "<p>Ruby has <code>tr</code>, a very efficient method for substituting one character to another. It does not error on \"unknown\" characters, like spaces etc. Using that, the Caesar class becomes:</p>\n\n<pre><code>class Caesar\n def initialize(shift, alphabet = ('a'..'z').to_a.join)\n i = shift % alphabet.size #I like this\n @decrypt = alphabet\n @encrypt = alphabet[i..-1] + alphabet[0...i]\n end\n\n def encrypt(string)\n string.tr(@decrypt, @encrypt)\n end\n\n def decrypt(string)\n string.tr(@encrypt, @decrypt)\n end\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T23:19:11.813",
"Id": "35501",
"ParentId": "35317",
"Score": "4"
}
},
{
"body": "<p>Your code does not work with letters like \"A..Z\".\nThe following does:</p>\n\n<pre><code>puts \"Text for encrypt please: \"\ntext_for_encrypt = gets.chomp\n\nputs \"Input encrypt key: \"\nkey = gets.chomp.to_i\n\ntext_arrow = text_for_encrypt.split('').to_a\nalphabet_az = (\"a\"..\"z\").to_a.join\nalphabet_AZ = (\"A\"..\"Z\").to_a.join\ni = key % alphabet_az.size\n\n\nencrypt_az = alphabet_az.chars.rotate(i).join\nencrypt_AZ = alphabet_AZ.chars.rotate(i).join\n\nres = []\ntext_arrow.each do |letter|\n if (\"a\"..\"z\") === letter\n letter = letter.tr( alphabet_az, encrypt_az )\n res << letter\n else\n letter = letter.tr( alphabet_AZ, encrypt_AZ )\n res << letter\n end\nend\n\nputs \"Your code: #{res.join}\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-03-02T15:10:50.503",
"Id": "296670",
"Score": "2",
"body": "Welcome to StackExchange Code Review! Please see: [How do I write a good answer?](http://codereview.stackexchange.com/help/how-to-answer), where you will find: \"Every answer must make at least one insightful observation about the code in the question. Answers that merely provide an alternate solution with no explanation or justification do not constitute valid Code Review answers and may be deleted\"."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-03-02T14:45:04.537",
"Id": "156718",
"ParentId": "35317",
"Score": "-2"
}
}
] |
{
"AcceptedAnswerId": "35501",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T22:34:37.517",
"Id": "35317",
"Score": "8",
"Tags": [
"ruby",
"caesar-cipher"
],
"Title": "Caesar cipher in Ruby"
}
|
35317
|
<p>Release 10 of Adobe's <a href="/questions/tagged/coldfusion" class="post-tag" title="show questions tagged 'coldfusion'" rel="tag">coldfusion</a> platform (Codenamed: Zeus) was released on May 15, 2012. New or improved features available in all editions include:</p>
<ul>
<li>Security enhancements</li>
<li>Hotfix installer and notification</li>
<li>Improved scheduler (based on a version of quartz)</li>
<li>Improved web services support (WSDL 2.0, SOAP 1.2)</li>
<li>Support for <a href="/questions/tagged/html5" class="post-tag" title="show questions tagged 'html5'" rel="tag">html5</a> WebSockets</li>
<li>Tomcat integration</li>
<li>Support for RESTful <a href="/questions/tagged/web-services" class="post-tag" title="show questions tagged 'web-services'" rel="tag">web-services</a></li>
<li>Language enhancements (including <a href="/questions/tagged/closure" class="post-tag" title="show questions tagged 'closure'" rel="tag">closure</a> support)</li>
<li>Search integration with Apache Solr</li>
<li>HTML5 video player and Adobe Flash Player</li>
<li>Flex and Adobe AIR lazy loading</li>
<li>XPath integration</li>
<li>HTML5 enhancements</li>
</ul>
<p>Additional new or improved features in ColdFusion Enterprise or Developer editions include:</p>
<ul>
<li>Dynamic and interactive HTML5 charting</li>
<li>Improved and revamped scheduler (additional features over what is added in CF10 Standard)</li>
<li>Object relational mapping enhancements</li>
</ul>
<p><em>List taken from <a href="http://en.wikipedia.org/wiki/Adobe_ColdFusion#Adobe_ColdFusion_10" rel="nofollow">Wikipedia</a></em></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T23:49:16.777",
"Id": "35319",
"Score": "0",
"Tags": null,
"Title": null
}
|
35319
|
A tag for code targeting release 10 of Adobe's ColdFusion platform.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T23:49:16.777",
"Id": "35320",
"Score": "0",
"Tags": null,
"Title": null
}
|
35320
|
<p>The question is:</p>
<blockquote>
<p>Each new term in the Fibonacci sequence is generated by adding the previous two terms.<br>
By starting with 1 and 2, the first 10 terms will be:</p>
<p>1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... </p>
<p>By considering the terms in the Fibonacci sequence whose values do not exceed four
million, find the sum of the even-valued terms.</p>
</blockquote>
<pre><code>#Problem 2
P2 = 0
fib= 0
f1 = 1
f2 = 0
debugP2 = []
while fib < 4000000:
fib = f1 + f2
f2 = f1
f1 = fib
if fib % 2 == 0:
P2 += fib
debugP2.append(fib)
print(debugP2)
print(P2)
</code></pre>
<p>This script can</p>
<ol>
<li><p>Give me all Fibonacci numbers up to 4000000 </p></li>
<li><p>Give the sum of all even numbers up to 4000000</p></li>
<li><p>It satisfies Project Euler Question #2.</p></li>
</ol>
<p>Is there a way to make this shorter or more efficient?</p>
|
[] |
[
{
"body": "<p>Assuming you want to stick with a minimalist for-loop implementation, it could be simplified by using Python's simultaneous assignment feature to eliminate a variable and perform the \"swap\" gracefully. Of course, the question does not require you to produce the even-valued items of the Fibonacci sequence, so you could eliminate <code>debugP2</code> as well.</p>\n\n<pre><code>sum = 0\nf1, f2 = 0, 1\nwhile f2 < 4000000:\n if f2 % 2 == 0:\n sum += f2\n f1, f2 = f2, f1 + f2\nprint(sum)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T07:53:43.610",
"Id": "35674",
"ParentId": "35322",
"Score": "1"
}
},
{
"body": "<p>More elegantly, using a generator:</p>\n\n<pre><code>def fib(max):\n f1, f2 = 0, 1\n while f1 < max:\n yield f1\n f1, f2 = f2, f1 + f2\n\nprint(sum(filter(lambda n: n % 2 == 0, fib(4000000))))\n</code></pre>\n\n<p>I would consider this to be more elegant because it decomposes the problem into describable, reusable components, instead of mingling all the logic together:</p>\n\n<ul>\n<li>The <code>fib()</code> generator is responsible for generating Fibonacci numbers</li>\n<li><code>filter(lambda n: n % 2 == 0, ...)</code> keeps just the even-valued elements</li>\n<li><code>sum(...)</code> adds them up</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T08:16:10.877",
"Id": "35678",
"ParentId": "35322",
"Score": "7"
}
},
{
"body": "<p>Your current implementation, and the suggested improvements are all brute force implementations, i.e. enumerating all fibonacci numbers, and they will all run in O(n).</p>\n\n<p>By using some mathematical tricks, you can turn this into an O(1) implementation. Since this is a project Euler problem, I won't spell out the answer, but here are some pointers:</p>\n\n<ol>\n<li><p>When starting at F(0) = 1 (instead of starting at F(1) as in the problem description), every third number is an even fibonacci number</p></li>\n<li><p>Because the fibonacci numbers are by definition based on the addition of the previous two numbers, the sum of all even fibonacci numbers up to <em>n</em> is equal to the sum of all fibonacci numbers up to <em>n</em> divided by two. </p></li>\n<li><p>There are cool formula's to calculate the sum of fibonacci numbers and the index of the highest fibonacci number up to <em>n</em>. Refer to wolframalpha or wikipedia to find them.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T11:09:05.633",
"Id": "57926",
"Score": "1",
"body": "Upvoted for interesting mathematical observations, even though it's not exactly a code review. In practice, [applying the O(1) formula is not that easy](http://mathematica.stackexchange.com/a/37275), and the \"brute-force\" approach might be faster once you consider the ease of implementation vs. the trivial amount of computation involved."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T12:44:01.603",
"Id": "57931",
"Score": "1",
"body": "@200_success you raise an interesting point -- in my opinion, discussions about the underlying algorithm and its impact on performance *are* part of a code review. However, the about pages are a bit vague on this. Could anyone clarify?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T15:47:06.993",
"Id": "57953",
"Score": "1",
"body": "I take that back about \"not exactly a code review\". \"You used the wrong algorithm because …\" is perfectly fair as a review. It's just that I disagree that your suggested O(1) solution would result in better code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T11:10:04.500",
"Id": "58092",
"Score": "1",
"body": "Point taken, and I agree that the O(1) solution is not necessarily more readable; probably not. I do feel that this solution is more in the spirit of project Euler :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T09:39:33.357",
"Id": "35684",
"ParentId": "35322",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T00:28:15.127",
"Id": "35322",
"Score": "10",
"Tags": [
"python",
"project-euler",
"fibonacci-sequence"
],
"Title": "Project Euler Question #2: Sum of even Fibonacci numbers under 4 million"
}
|
35322
|
<blockquote>
<p>You will prompt a user for a month, a day and a year. You will then
tell the user how many days since January 1 of that year the input
date is. For example if the user inputs a 3 for the month, a 2 for the
date, and 2000 for the year the program outputs the number of days as
being 62. Note 2000 is a leap year. Therefore you must test to see if
a year is a leap year when doing this problem.</p>
</blockquote>
<p>I'm trying to build onto this one:</p>
<pre><code>#include<iostream>
using namespace std;
int main()
{
int days_in_months[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int day;
int month;
int year;
int days_difference;
int reg_year = 365;
int leap_year = 366;
cout << "Program to calculate how many days are in between the date and the start of the year." << endl;
cout << endl;
cout << "Please enter the date by day, month, year." << endl;
cout << endl;
cout << "First date:: " << endl;
cout << endl;
cout << "Day: ";
cin >> day;
if (day > 31 || day <= 0)
{
cout << "Incorrect day entered" << endl;
cin.ignore();
return 0;
}
cout << "Month: ";
cin >> month;
if (month > 12 || month <= 0)
{
cout << "Incorrect Month entered" << endl;
cin.ignore();
return 0;
}
cout << "Year: ";
cin >> year;
if (year > 9999 || year < 0)
{
cout << "Incorrect year entered" << endl;
cin.ignore();
return 0;
</code></pre>
<p>or just edit this one:</p>
<pre><code>#include<iostream>
using namespace std;
int main()
{
int days_in_months[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int first_day, second_day;
int first_month, second_month;
int first_year, second_year;
int years_difference, days_difference;
int months_total;
int reg_year = 365;
cout << "Program to calculate how many days are in between the day/month/year entered." << endl;
cout << endl;
cout << "Please enter the date by day, month, year." << endl;
cout << endl;
cout << "First date:: " << endl;
cout << endl;
cout << "Day: ";
cin >> first_day;
if (first_day > 31 || first_day <= 0)
{
cout << "Incorrect day entered" << endl;
cin.ignore();
return 0;
}
cout << "Month: ";
cin >> first_month;
if (first_month > 12 || first_month <= 0)
{
cout << "Incorrect Month entered" << endl;
cin.ignore();
return 0;
}
cout << "Year: ";
cin >> first_year;
if (first_year > 9999 || first_year < 0)
{
cout << "Incorrect Year Entered" << endl;
cin.ignore();
return 0;
}
cout << endl;
cout << "\nSecond date:: " << endl;
cout << endl;
cout << "Day: ";
cin >> second_day;
if (second_day > 31 || second_day <= 0)
{
cout << "Incorrect day entered" << endl;
cin.ignore();
return 0;
}
cout << "Month: ";
cin >> second_month;
if (second_month > 12 || second_month <= 0)
{
cout << "Incorrect Month entered" << endl;
cin.ignore();
return 0;
}
cout << "Year: ";
cin >> second_year;
if (second_year > 9999 || second_year < 0)
{
cout << "Incorrect Year Entered" << endl;
cin.ignore();
return 0;
}
/////////////////////////////Years/////////////////////////////////
if (first_year == second_year)
{
years_difference = 0;
}
else
{
if (first_year % 4 == 0 && first_year % 100 != 0 || first_year % 400 == 0)
{
if (second_year % 4 == 0 && second_year % 100 != 0 || second_year % 400 == 0)
{
if (first_year > second_year)
{
years_difference = (first_year - second_year) * (reg_year)+2;
}
else
{
years_difference = (second_year - first_year) * (reg_year)+2;
}
if (second_month > first_month)
{
if (days_in_months[first_month - 1] > days_in_months[1])
{
--years_difference;
}
}
}
else
{
if (first_year > second_year)
{
years_difference = (first_year - second_year) * (reg_year)+1;
}
else
{
years_difference = (second_year - first_year) * (reg_year)+1;
}
if (first_month > second_month)
{
if (days_in_months[second_month - 1] > days_in_months[1])
{
--years_difference;
}
}
}
}
else
{
if (first_year > second_year)
{
years_difference = (first_year - second_year) * (reg_year);
}
else
{
years_difference = (second_year - first_year) * (reg_year);
}
}
}
/////////////////////////////Months////////////////////////////////////
if (first_month == second_month)
{
months_total = 0;
}
else
{
if (first_month > second_month)
{
for (int i = (first_month - 1); i > (second_month - 1); i--)
{
static int months_total_temp = 0;
months_total_temp += days_in_months[i];
months_total = months_total_temp;
}
}
else
{
for (int i = (first_month - 1); i < (second_month - 1); i++)
{
static int months_total_temp = 0;
months_total_temp += days_in_months[i];
months_total = months_total_temp;
}
}
}
////////////////////////////Days//////////////////////////////////
int days_total;
if (first_day == second_day)
{
days_difference = 0;
days_total = (years_difference + months_total) - days_difference;
}
else
{
if (first_day > second_day)
{
days_difference = first_day - second_day;
days_total = (years_difference + months_total) - days_difference;
}
else
{
days_difference = second_day - first_day;
days_total = (years_difference + months_total) + days_difference;
}
}
//////////////////////////In Between Leap Years///////////////////////////////
if (first_year == second_year)
{
}
else
{
if (first_year > second_year)
{
for (int i = (second_year + 1); i < first_year; i++)
{
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0)
{
cout << endl;
cout << i << endl;
++days_total;
}
}
}
else
{
for (int i = (first_year + 1); i < second_year; i++)
{
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0)
{
cout << endl;
cout << i << endl;
++days_total;
}
}
}
}
//////////////////////////Output//////////////////////////////////
cout << endl;
cout << "\nThe total days in between your dates are: " << days_total << endl;
cout << endl;
cin.get();
cin.ignore();
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T04:20:52.803",
"Id": "57218",
"Score": "1",
"body": "Looks better! I'm not sure if you're still encountering issues or asking for more code (both are off-topic), but I could still provide a few pointers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T04:23:36.370",
"Id": "57219",
"Score": "0",
"body": "Are you allowed to factor code into functions, like taking that leap year logic into some `bool isLeapYear(int year)` function?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T04:27:39.343",
"Id": "57220",
"Score": "0",
"body": "There are also missing closing curly braces in the first block, but I'm too tired to fix all the indentation. In general, all that can be fixed by using spaces instead of tabs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T04:27:47.157",
"Id": "57221",
"Score": "0",
"body": "everything is strictly if statements, and its killing me. i have to take the current program and completely redo it with a set date and with only if statements."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T01:16:55.193",
"Id": "57348",
"Score": "0",
"body": "This question appears to be off-topic because it breaks [rule #4 of CR on-topic questions](http://codereview.stackexchange.com/help/on-topic): *Do I want the code to be good code, (i.e. not code-golfing, obfuscation, or similar)*."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T18:57:19.390",
"Id": "57522",
"Score": "1",
"body": "@retailcoder: I don't think that's quite the goal. The OP did mention a certain form (if-statements), but not code-golfing or obfuscation specifically."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T19:05:35.490",
"Id": "57528",
"Score": "0",
"body": "@Jamal I did interpret the rule, resolving a problem with only if statements did look like some programming game to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T19:09:09.030",
"Id": "57530",
"Score": "0",
"body": "@retailcoder: It may just be a requirement, possibly for school. If you look at the votes put in, there's much division on whether or not this should be closed. I haven't put in my vote as I'm sort of undecided, but we should all decide soon lest this post becomes locked."
}
] |
[
{
"body": "<p>Your code could use a lot of work, but it should be easier to clean up the algorithmic things after getting the language cleaned up. I'll go after the \"obvious\" things for now, which is still a good start.</p>\n\n<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Try not to use <code>using namespace std</code></a>.</p></li>\n<li><p><code>days_in_months[]</code>, <code>reg_year</code>, and <code>leap_year</code> should be <code>const</code>s and optionally defined above <code>main()</code>. This will protect them from any accidental changes throughout the program.</p></li>\n<li><p><a href=\"https://stackoverflow.com/questions/213907/c-stdendl-vs-n\">Prefer <code>\"\\n\"</code> over <code>std::endl</code></a> when only a newline is needed. <code>std::endl</code> also flushes the buffer, which takes longer.</p>\n\n<pre><code>std::cout << \"This printing does three newlines\\n\\n\\n\";\n</code></pre>\n\n<p></p>\n\n<pre><code>std::cout << \"This printing does a newline and a flush\" << std::endl;\n</code></pre></li>\n<li><p>Prefer to declare/initialize variables as close in scope as possible:</p>\n\n<pre><code>std::cout << \"Message: \";\nint input;\nstd::cin >> input;\n</code></pre></li>\n<li><p><code>cin.ignore()</code> is redundant if you'll be terminating right away. Just get rid of all of them.</p></li>\n<li><p>I <em>strongly</em> recommend using functions. Cramming everything into <code>main()</code> just makes the code hard to read and maintain, especially for a program like this. Consider giving the years, months, and days their own functions. You may also put recurring executions into their own functions (one task per function), while also avoiding creating functions that just display a message.</p>\n\n<p>For now, you could do that and move all this code into the appropriate functions. The more organized you make your existing code, the easier it will be to refactor all those <code>for</code>s and <code>if</code>s.</p></li>\n<li><p>Considering adding comments to explain what the code is supposed to do. No need to comment obvious operations such as receiving an input. Only comment where explanation is needed. Adding comments for the <code>if</code>s and <code>for</code>s could especially help others understand what it's doing.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T04:49:43.820",
"Id": "35329",
"ParentId": "35326",
"Score": "3"
}
},
{
"body": "<p>(This question smells like a homework assignment, so the follow review comment likely isn't applicable. Anyway...)</p>\n\n<p>This code looks like it is going to implement the date difference calculation. I would't do that. Instead, I'd use your favorite date library/operating system call to parse the user's input. Then, using the same library, I'd compute the difference for output.</p>\n\n<p>Time and date computations are <em>really</em> hard to get right. For example, the year 1900 wasn't a leap year, but both 2000 and 2004 were. Such a library would also--probably--deal with computing the difference both ways. On 1999-12-31, there were -1 days since 2000-1-1.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T14:39:29.067",
"Id": "57414",
"Score": "0",
"body": "Yes date libraries are hard but not for the reason you state. The leap year problem is trivial. 4 Yes 100 No 400 Yes. And the above code has already taken that into account."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T14:40:53.650",
"Id": "57415",
"Score": "2",
"body": "Additionally this site is for review. You are supposed to review the code not fix the issues. So perfectly good site for getting a second look at your home work (since we tend to rip things apart)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T09:53:10.720",
"Id": "35423",
"ParentId": "35326",
"Score": "0"
}
},
{
"body": "<p>There is a much easier technique to use.</p>\n\n<p>Assign numbers for each day (0->N). Given a data calculate the number for that day. The difference is simply subtracting the two numbers.</p>\n\n<pre><code>day1 = GetIdOf(year1, month1, day1);\nday2 = GetIdOf(year2, month2, day2);\n\nstd::cout \"Diff: \" << abs(day1 - day2) << \"\\n\";\n</code></pre>\n\n<h3>GetIdOf</h3>\n\n<pre><code>int GetIdOf(int year, int month, int day)\n{\n // Note: No month 0.\n // We are counting the all the days up to this month.\n // In Jan (month 1) there are no days before.\n // In Feb (month 2) we count all the days in Jan\n // In Mar (month 3) we count all the days in Jan + Feb\n // etc ... (leap years sorted separately).\n static int daysInMonth[] = {0,0,31,59,....};\n\n int result = year * 365;\n result += leapYearsSince0(year-1); // don't include this year.\n result += daysInMonth[month];\n result += isLeapYear(year) & month > 2 ? 1 : 0;\n result += day;\n return result;\n}\n</code></pre>\n\n<h3>Years:</h3>\n\n<pre><code>if (year > 9999 || year < 0)\n</code></pre>\n\n<p>There is no year 0 in the Gregorian calender. It goes from -1 (or 1 BC) to 1 (or 1 AD). Also I would not go back that far. Limit your application to years above 1900. Before that it gets very complicated and actually depends on what country you are in.</p>\n\n<p>Or (assuming this is just a school project) you can make the assumption we used the Gregorian all the way back to pre-history.</p>\n\n<h3>Remove Repeated code.</h3>\n\n<p>Replaece repeated code with a function call.</p>\n\n<pre><code>if (day > 31 || day <= 0)\n{\n cout << \"Incorrect day entered\" << endl;\n cin.ignore();\n return 0;\n}\ncout << \"Month: \";\ncin >> month;\nif (month > 12 || month <= 0)\n{\n cout << \"Incorrect Month entered\" << endl;\n cin.ignore();\n return 0;\n}\ncout << \"Year: \";\ncin >> year;\n\nif (year > 9999 || year < 0)\n{\n cout << \"Incorrect year entered\" << endl;\n cin.ignore();\n return 0;\n}\n</code></pre>\n\n<p>That would be so much simpler to write as:</p>\n\n<pre><code>int getAndCheckRange(int max, int min, std::string const& type)\n{\n int val;\n cout << type << \": \";\n cin >> val;\n\n if (val > max || val < min)\n {\n cout << \"Incorrect \" << type << \" entered\" << endl;\n cin.ignore();\n throw std::runtime_error(\"Failed\");\n }\n}\n\n.....\n\ngetAndCheckRange(day, 31, 0, \"day\");\ngetAndCheckRange(month, 12, 0, \"month\");\ngetAndCheckRange(year, 9999, 0, \"year\"); // Note this corrects for the 0 problem\n // I already mentioned.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T15:05:47.193",
"Id": "35437",
"ParentId": "35326",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T04:08:11.223",
"Id": "35326",
"Score": "1",
"Tags": [
"c++",
"datetime"
],
"Title": "Telling the user the number of days it's been since January 1st"
}
|
35326
|
<p>I've just posted this <a href="/a/35330/9357">solution</a> in my review of @adrienlucca's question, which is to read three rows of six tab-separated doubles.</p>
<pre><code>#include <fstream>
#include <iostream>
#include <string.h>
#include <vector>
struct Sexdoublet {
double x, y, d, m, c, t;
friend std::istream &operator>>(std::istream &in, Sexdoublet &r) {
return in >> r.x >> r.y >> r.d >> r.m >> r.c >> r.t;
}
friend std::ostream &operator<<(std::ostream &out, const Sexdoublet &r) {
return out << "[ x = " << r.x
<< ", y = " << r.y
<< ", d = " << r.d
<< ", m = " << r.m
<< ", c = " << r.c
<< ", t = " << r.t << " ]";
}
};
std::vector<Sexdoublet> import(std::istream &in) {
std::vector<Sexdoublet> data;
Sexdoublet s;
do {
in >> s;
} while (in && (data.push_back(s), true));
return data;
}
int main(int argc, char *argv[]) {
// If the first command-line argument is not "-", treat it as the filename
// from which to read the input. Otherwise, read from STDIN.
const char *filename = (argc >= 2 && 0 != strcmp("-", argv[1])) ?
argv[1] : NULL;
std::ifstream f;
std::istream &in = filename ? (f.open(filename), f) : std::cin;
if (!f) {
std::cerr << "Error opening " << filename << ": "
<< strerror(errno) << std::endl;
return 1;
}
std::vector<Sexdoublet> data = import(in);
std::for_each(data.begin(), data.end(), [](const Sexdoublet &s) {
std::cout << s << std::endl;
});
return 0;
}
</code></pre>
<p>I ended up using the comma operator twice — both times as a "workaround" for the fact that a function I call returns <code>void</code>:</p>
<ul>
<li><code>(data.push_back(s), true)</code> — I have to check whether the <code>istream</code> extractions succeeded before adding an element to the result.</li>
<li><code>(f.open(filename), f)</code> — I like the ternary operator because it expresses the fact that <code>in</code> is going to be assigned to one value or another. Also, the <code>in</code> reference has to be initialized immediately and irrevocably, right?</li>
</ul>
<p>It is my impression that the comma operator is rarely used in C and C++. So, I'd like to ask, are these reasonable uses of the comma operator? Or too clever? Or too dumb, because I've missed an entirely better solution?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T08:52:07.363",
"Id": "57229",
"Score": "0",
"body": "If you primarily need to check for a successful `in` when looping, do you still need to check the `push_back()`? I'll admit I've never seen the latter being used like that before. `push_back()` automatically reallocates, so it'll throw `bad_alloc` if it fails."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T09:01:41.713",
"Id": "57230",
"Score": "0",
"body": "Try feeding it a partial line ending with EOF and you'll see. If `in` stops working prematurely, then `s` will contain some fields whose values came from the previous iteration."
}
] |
[
{
"body": "<p>the first use can be replaced with:</p>\n\n<pre><code>while(in >> s) {\n data.push_back(s)\n}\n</code></pre>\n\n<p>the second case is much more readable with a simple if else:</p>\n\n<pre><code>std::ifstream f;\nif(argc >= 2 && 0 != strcmp(\"-\", argv[1])) {\n f.open(argv[1]);\n if (!f) {\n std::cerr << \"Error opening \" << argv[1] << \": \"\n << strerror(errno) << std::endl;\n return 1;\n }\n\n}\nstd::istream &in = f.is_open() ? f : std::cin;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T09:37:56.370",
"Id": "57234",
"Score": "0",
"body": "I don't object to the while-loop being wordier. However, the `while (true)` is a fiction — the structure of the loop remains a mystery until the reader finds the `break`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T09:58:35.580",
"Id": "57236",
"Score": "0",
"body": "you can add `in` to the condition, and change the ternary to `f.is_open()`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T10:21:45.617",
"Id": "57237",
"Score": "0",
"body": "`while (in)` is arguably worse than `while (true)`, since it's doing a superfluous test that appears to be useful but actually isn't."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T13:01:13.697",
"Id": "57275",
"Score": "2",
"body": "@200_success actually you could do `while(in >> s){data.push_back(s);}` (`operator>>` returns the stream)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T15:40:18.460",
"Id": "57298",
"Score": "0",
"body": "@200_success: See? You didn't need to check `(data.push_back(s), true)` after all. :-)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T09:28:52.210",
"Id": "35333",
"ParentId": "35331",
"Score": "4"
}
},
{
"body": "<p>Let's start with this:</p>\n\n<pre><code>std::vector<Sexdoublet> import(std::istream &in) {\n std::vector<Sexdoublet> data;\n Sexdoublet s;\n do {\n in >> s;\n } while (in && (data.push_back(s), true));\n return data;\n}\n</code></pre>\n\n<p>As far as I can see, this appears to be equivalent to:</p>\n\n<pre><code>std::vector<Sexdoublet> import(std::istream &in) { \n return std::vector<Sexdoublet> {std::istream_iterator<Sexdoublet>(in),\n std::istream_iterator<Sexdoublet()};\n}\n</code></pre>\n\n<p>Given how simple this is, however, I'd question whether it's worth writing as a separate function at all. It's probably simpler to just initialize the target <code>vector</code> directly from the iterators and be done with it.</p>\n\n<p>Your code to write the data out:</p>\n\n<pre><code>std::for_each(data.begin(), data.end(), [](const Sexdoublet &s) {\n std::cout << s << std::endl;\n});\n</code></pre>\n\n<p>...doesn't seem like the way I'd do things either. I rarely find <code>std::for_each</code> useful, and this is no exception to that rule. In C++98/03, I'd use:</p>\n\n<pre><code>std::copy(data.begin(), data.end(), \n std::ostream_iterator<Sexdoublet>(std::cout, \"\\n\"));\n</code></pre>\n\n<p>In C++11, I'd generally prefer a range-based <code>for</code> loop:</p>\n\n<pre><code>for (auto const &s : data)\n std::cout << s << \"\\n\";\n</code></pre>\n\n<p>That ignores the larger situation though: we end up simply reading the data into the vector, then writing it back out from the vector to standard output. That being the case, we might as well skip the vector and copy directly from input to output:</p>\n\n<pre><code>std::copy(std::istream_iterator<Sexdoublet>(in),\n std::istream_iterator<Sexdoublet>(),\n std::ostream_iterator<Sexdoublet>(std::cout, \"\\n\"));\n</code></pre>\n\n<p>Note that using this eliminates the <code>import</code> function entirely. In the end, I think the copying really belongs in a separate function, so <code>main</code> basically just deals with command line arguments and error handling, something on this order:</p>\n\n<pre><code>bool copy(std::istream &is, std::ostream &os) {\n if (!is) \n return false;\n std::copy(std::istream_iterator<Sexdoublet>(is),\n std::istream_iterator<Sexdoublet>(),\n std::ostream_iterator<Sexdoublet>(os, \"\\n\"));\n return true;\n}\n\nint main(int argc, char **argv){\n std::vector<std::string> args(argv, argv+argc);\n if (args.size() > 1 && args[1] == \"-\")\n copy(std::cin, std::cout);\n else if (!copy(std::ifstream(args[1]), std::cout)) \n std::cerr << \"Error opening \" << args[1]\n << \": \" << strerror(errno) << \"\\n\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-05T01:08:22.263",
"Id": "60270",
"Score": "0",
"body": "Actually, the _goal_ is to import the data into a vector; printing the vector was done as an example to prove that it worked. Anyway, thanks for the iteration tips."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-05T01:57:30.030",
"Id": "60274",
"Score": "0",
"body": "@200_success: I thought that might be the case, which is why I still included the code to do that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-05T00:58:30.450",
"Id": "36673",
"ParentId": "35331",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "35333",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T08:35:12.773",
"Id": "35331",
"Score": "7",
"Tags": [
"c++",
"c++11",
"error-handling",
"io"
],
"Title": "Reading three rows of six tab-separated numbers"
}
|
35331
|
<p>I am a total novice to web development, but I am trying to be a WordPress developer and have been actively at it for some weeks now. All self-taught with the world's best tool as my aid: the internet. Anyway, I was hoping that you guys could look at my (no doubt: shoddy) code and tell me what you think I could do to make it better. I made a contact form using the WP plugin Contact Form 7... this is the HTML I used for the form:</p>
<pre><code><div id="three-column">
<div id="left">
<p>[text* Subject akismet:author placeholder "Subject"]</p>
<p>[email* Email akismet:author_email placeholder "Email"]</p>
<p>[textarea* Message placeholder "Your Message"]</p>
</div>
<div id="center">
<span>
</span>
</div>
<div id="right">
<p>[text* FirstName akismet:author placeholder "First Name"]</p>
<p>[text* LastName akismet:author placeholder "Last Name"]</p>
<p>[tel* Tel placeholder "Telephone"]</p>
<p>[submit "Send"]</p>
</div>
</div>
</code></pre>
<p>And now for the CSS...</p>
<pre><code>/* FORM */
#three-column{
width: 100%;
margin-bottom:75px 0px 0px 0px;
}
#three-column #left{
width: 47%;
float: left;
margin-right:0%;
}
#three-column #center{
margin:0% 2%;
float: left;
}
#three-column #right{
width: 47%;
float: left;
margin-left:0%;
}
#three-column input[type="text"], input[type="email"], input[type="tel"]{
border:none;
border:2px solid #4274A5;
font-size :20px;
border-radius: 5px;
width: 100%;
padding: 18px 3px 18px 10px;
font-family: 'Lovelo Black';
color: #4274A5;
margin-bottom:22px;
height:20px;
}
#three-column textarea {
font-size :20px;
position: relative;
color: #4274A5;
padding: 18px 3px 3px 10px;
border:2px solid #4274A5;
min-width: 100%;
max-width: 100%;
font-family: 'Lovelo Black';
margin-bottom:22px;
min-height:127px;
max-height:127px;
}
#three-column textarea:hover{
-webkit-box-shadow: 0px 0px 22px 1px rgba(66,116,165,0.6);
-moz-box-shadow: 0px 0px 22px 1px rgba(66,116,165,0.6);
box-shadow: 0px 0px 22px 1px rgba(66,116,165,0.6);
}
#three-column #right input[type="submit"]{
padding:18px 0px 18px 0px;
background: #fff;
color:#4274A5;
border: 2px solid #4274A5;
font-size: 20px;
margin-bottom:22px;
font-family: 'Lovelo Black';
width:50%;
height:60px;
}
#three-column #right input[type="submit"]:hover{
-o-transition:.7s;
-ms-transition:.7s;
-moz-transition:.7s;
-webkit-transition:.7s;
transition:.7s;
background:#4274A5;
color: #fff;
border: 2px solid #4274A5;
}
body input[type=text].wpcf7-not-valid, body input[type=email].wpcf7-not-valid, body input[type=tel].wpcf7-not-valid, body textarea.wpcf7-not-valid {
border: 2px solid #ec3c06!important;
}
body span.wpcf7-not-valid-tip {
display: block;
height:20px;
margin-bottom:-20px;
color: #ec3c06;
border: none;
position: relative;
top: -22px;
left: 10px;
padding: 0;
background: none;
font-size: 15px;
}
body div.wpcf7-validation-errors {
background: #ffe2e2;
border: 2px solid #ff8a8a;
color: #ec3c06;
}
body div.wpcf7-response-output {
margin: 10px 0;
padding: 20px;
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
border-radius: 5px;
}
body .wpcf7-mail-sent-ng {
background: #fff2e2;
border: 2px solid #ffbc8a;
color: #e17731;
}
body .wpcf7-mail-sent-ok {
background: #e8ffe2;
border: 2px solid #6fdf51;
color: #1ea524;
}
div.wpcf7-validation-errors {
visibility:hidden;
}
div.wpcf7-mail-sent-ok {
border: 2px solid #4274A5!important;
background: white!important;
color: #4274A5;
font-family: 'Lovelo Black';
font-size: 20px!important;
position:relative;
min-width:100%;
float: none;
clear:both;
-webkit-box-shadow: 0px 0px 22px 1px rgba(66,116,165,0.6);
-moz-box-shadow: 0px 0px 22px 1px rgba(66,116,165,0.6);
box-shadow: 0px 0px 22px 1px rgba(66,116,165,0.6);
}
</code></pre>
<p>Just to give you an idea, I'm trying to style my form after the contact form on this <a href="http://designova.net/themes/wordpress/prisma/" rel="nofollow">WP theme</a> (down torwards the bottom).</p>
<p>It's a nice contact box, but they don't allow for any adjustments on that theme, so I had to build and style my own. It also doesn't allow for akismet protection, so I was getting tons of spam emails.</p>
<p>Any advice would be very welcomed. I didn't use any media screen CSS to adjust the view for mobile sites because I attempted to make it fairly responsive, even as a two-column form, but if you think that would be optimal, please let me know.</p>
<p>PS - On the original form, they have this cool success message validation which I love... it sort of floats in from the top. Mine doesn't do that, I utilized the existing Ajax validation and just styled it to match the theme. Any advice as to how to replicate the original markup would be great. My guess is using jQuery which I know absolutely NOTHING about! </p>
<p>HTML Source for form:</p>
<pre><code><p style="text-align: left;"><div class="container-fluid ">
<div class="row-fluid">
<div class="container">
<div class="row">
<div class="wpcf7" id="wpcf7-f1305-p59-o1"><form action="/contact/#wpcf7-f1305-p59-o1" method="post" class="wpcf7-form" novalidate="novalidate">
<div style="display: none;">
<input type="hidden" name="_wpcf7" value="1305" />
<input type="hidden" name="_wpcf7_version" value="3.5.4" />
<input type="hidden" name="_wpcf7_locale" value="en_US" />
<input type="hidden" name="_wpcf7_unit_tag" value="wpcf7-f1305-p59-o1" />
<input type="hidden" name="_wpnonce" value="fa6e557936" />
</div>
<div id="three-column">
<div id="left">
<p><span class="wpcf7-form-control-wrap Subject"><input type="text" name="Subject" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" placeholder="Subject" /></span></p>
<p><span class="wpcf7-form-control-wrap Email"><input type="email" name="Email" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-email wpcf7-validates-as-required wpcf7-validates-as-email" aria-required="true" placeholder="Email" /></span></p>
<p><span class="wpcf7-form-control-wrap Message"><textarea name="Message" cols="40" rows="10" class="wpcf7-form-control wpcf7-textarea wpcf7-validates-as-required" aria-required="true" placeholder="Your Message"></textarea></span></p>
</div>
<div id="center">
<span><br />
</span>
</div>
<div id="right">
<p><span class="wpcf7-form-control-wrap FirstName"><input type="text" name="FirstName" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" placeholder="First Name" /></span></p>
<p><span class="wpcf7-form-control-wrap LastName"><input type="text" name="LastName" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" placeholder="Last Name" /></span></p>
<p><span class="wpcf7-form-control-wrap Tel"><input type="tel" name="Tel" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-tel wpcf7-validates-as-required wpcf7-validates-as-tel" aria-required="true" placeholder="Telephone" /></span></p>
<p><input type="submit" value="Send" class="wpcf7-form-control wpcf7-submit" /></p>
</div>
</div>
<div class="wpcf7-response-output wpcf7-display-none"></div></form></div>
</div>
</div>
</div>
</div></p>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T16:09:28.243",
"Id": "57306",
"Score": "1",
"body": "Can you provide the generated HTML? Template code isn't very useful outside of your project (ie. I can't run it in a site like jsfiddle.net or codepen.io to see how it works)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T08:57:42.337",
"Id": "57381",
"Score": "0",
"body": "I know this sounds bad, but I have no idea how to generate the HTML... :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T09:59:48.233",
"Id": "57389",
"Score": "0",
"body": "Cinnamon means what it looks like in the browser. Bring up the web page, view source, copy the relevant part."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T10:24:45.457",
"Id": "57392",
"Score": "0",
"body": "Thanks - I thought that's what he meant, but I was inspecting the element instead (using firebug) and couldn't see any valid source code... I'll add the code from the source view above (I believe) probably missing something though, knowing me."
}
] |
[
{
"body": "<p>One thing that I can see is that you are not consistent with the units you use for measurement on padding, margins you should be consistent with this as different browsers will display <code>%</code> and <code>px</code> differently. </p>\n\n<p>I have heard that you should always try to use <code>em</code> as your unit instead (no reference link for this so I will not go into this in depth)</p>\n\n<p>Whatever you want to do you, should always try to be consistent with the measurement that you use for these things.</p>\n\n<p>Padding and Margins should always be done in static units like <code>px</code> (I am finding it hard to elaborate the explicit reason with text) </p>\n\n<p>A 5% Margin on the left will change when someone zooms in or out, where as pixels won't change when you zoom in or out, meaning that the margin will stay relative to the zoom percentage. If you mismatch, you could end up with some blocks of code that get really big and some that get smaller when you zoom in or out on the browser.</p>\n\n<p>Another thing, a minimum width probably shouldn't be a percentage even if it is 100%. if you want it to be a minimum of <code>500px</code> put <code>500px</code>. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T16:07:07.420",
"Id": "57305",
"Score": "2",
"body": "There's no reason you have use px for margins/paddings over units like em, pt, cm, in, etc. Px resize with zooming just as much as any other unit does."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T16:10:20.843",
"Id": "57307",
"Score": "0",
"body": "@cimmanon: I agree with you, I prefer Pixels or `em`s, the point is that you should use something static instead of something dynamic like percentages"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T08:52:40.317",
"Id": "57380",
"Score": "0",
"body": "This is helpful to me, because on resize, even though things were looking mostly right, I did lose the margin. Thanks!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T14:54:49.277",
"Id": "35365",
"ParentId": "35335",
"Score": "2"
}
},
{
"body": "<pre class=\"lang-css prettyprint-override\"><code>#three-column input[type=\"text\"], input[type=\"email\"], input[type=\"tel\"]\n</code></pre>\n\n<p>I'm pretty sure should be</p>\n\n<pre><code>#three-column input[type=\"text\"], #three-column input[type=\"email\"], #three-column input[type=\"tel\"]\n</code></pre>\n\n<p>because your probably mean all inputs in #three-columns. The selectors after the commas don't get the #three-columns from the first one.</p>\n\n<hr>\n\n<p>On the other hand,</p>\n\n<pre><code>#three-column #left\n</code></pre>\n\n<p>for a selector is not necessary; just </p>\n\n<pre><code>#left\n</code></pre>\n\n<p>will do. Because IDs should be unique, there is no way you can have another element on the same page which also has the id <code>left</code>.</p>\n\n<hr>\n\n<p>Look out with giving things a <code>color</code> without also giving them a <code>background-color</code>. If the user of your webpage has different default settings than you, things like those will become unreadable.</p>\n\n<hr>\n\n<p>Font-families should always end with a generic font family keyword, so </p>\n\n<pre><code>font-family: 'Lovelo Black';\n</code></pre>\n\n<p>is not enough. Use something like </p>\n\n<pre><code>font-family: 'Lovelo Black', sans-serif;\n</code></pre>\n\n<p>for a fallback, otherwise you won't know how the browsers handle a situation where Lovelo Black can't be displayed.</p>\n\n<hr>\n\n<p>In </p>\n\n<pre><code>body input[type=text].wpcf7-not-valid, body input[type=email].wpcf7-not-valid, body input[type=tel].wpcf7-not-valid, body textarea.wpcf7-not-valid {\n border: 2px solid #ec3c06!important;\n</code></pre>\n\n<p>is the <code>!important</code> really necessary? If it is, it's good practice to precede the <code>!</code> with a space, otherwise some older browsers will get confused. But do try to make the CSS work without it.<br>\nAlso, starting the selector with <code>body</code> is superfluous, because inputs can't reside anywhere but in the body.</p>\n\n<hr>\n\n<pre><code>body span.wpcf7-not-valid-tip {\n display: block;\n</code></pre>\n\n<p>Does this absolutely need to be a <code>span</code>? It looks odd to have a span and then to change it into a block with CSS, while you can just as easily use a <code>div</code> and won't have to change it. (Of course, this depends on your HTML situation; you can't insert a <code>div</code> everywhere that you can put a <code>span</code>.)</p>\n\n<hr>\n\n<pre><code>box-sizing: border-box;\n-webkit-box-sizing: border-box;\n-moz-box-sizing: border-box;\n</code></pre>\n\n<p>should be sorted so that the unprefixed version is last.</p>\n\n<pre><code>-webkit-box-sizing: border-box;\n-moz-box-sizing: border-box;\nbox-sizing: border-box;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T08:51:18.563",
"Id": "57379",
"Score": "0",
"body": "That is brilliant stuff, so helpful. Thank you! As said, I'm a complete novice, so this is all good stuff."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T09:55:43.303",
"Id": "57388",
"Score": "0",
"body": "You're welcome. Hope I didn't come across as too harsh; in some cases it's not easy to put in words why things should be written a certain way, so I may sound like \"do this! do that!\" without enough of an explanation. I'm not teacher, so, sorry. If you have questions, just ask."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T10:29:12.143",
"Id": "57394",
"Score": "0",
"body": "No, not too harsh at all... I really am a fish out of water, so all help is welcome and to be honest, it all makes sense... you explained well. One thing I have wondered (because I've heard it before) is not to use !important if you don't have to... why is that? I can guess that it would be that you shouldn't HAVE to if you're coding correctly. In this case, my code is in a child theme, so it is inheriting a lot of values from a parent (perhaps the parent also has background values for the boxes with color... not sure), so the !important was needed because it wasn't working without it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T14:16:25.623",
"Id": "57408",
"Score": "0",
"body": "`!important` plays havoc with the normal cascading rules. Normally, you can always ensure that your style is applied, by taking care that the specificity is high enough, or your style comes after the style in the stylesheet you want to overrule, or, to play it safe, put your style in an inline `style` attribute. But `!important` throws all those conventions out of the window and applies itself regardless."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T14:17:29.177",
"Id": "57409",
"Score": "0",
"body": "In other words, it's is a dirty trick that you should only use as a last resort. In fact, the only excuse you can have is if you want to override a stylesheet that a) contains `!important` itself, and b) you cannot make changes to."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T08:28:43.073",
"Id": "35421",
"ParentId": "35335",
"Score": "7"
}
},
{
"body": "<p>First off, your markup is invalid. You have a paragraph containing block elements (div, other paragraphs), when they are only allowed to contain inline elements.</p>\n\n<p>The rest of your markup is less than optimal, to be polite. You have so many empty elements being used to simulate whitespace when there's absolutely no need.</p>\n\n<p>There are no labels used here at all. There are still plenty of popular browsers that do not support placeholder text, so the user is left wondering what to do. Even if the browser <em>does</em> support placeholders, the user loses sight of what field is what.</p>\n\n<p>This form does not adapt well to narrow viewports (eg. handheld devices).</p>\n\n<p>Here's a quick demo of how the form's markup/styles can be improved from a structural standpoint:</p>\n\n<p><a href=\"http://cssdeck.com/labs/gis9h2nm\" rel=\"nofollow\">http://cssdeck.com/labs/gis9h2nm</a></p>\n\n<pre><code><form action=\"/contact/#wpcf7-f1305-p59-o1\" method=\"post\" class=\"wpcf7-form\" novalidate=\"novalidate\">\n <input type=\"hidden\" name=\"_wpcf7\" value=\"1305\" />\n <input type=\"hidden\" name=\"_wpcf7_version\" value=\"3.5.4\" />\n <input type=\"hidden\" name=\"_wpcf7_locale\" value=\"en_US\" />\n <input type=\"hidden\" name=\"_wpcf7_unit_tag\" value=\"wpcf7-f1305-p59-o1\" />\n <input type=\"hidden\" name=\"_wpnonce\" value=\"fa6e557936\" />\n\n <fieldset class=\"contact-info\">\n <legend>Your Contact Information</legend>\n\n <label class=\"wpcf7-form-control-wrap Name\">Name <input type=\"text\" name=\"Name\" value=\"\" size=\"40\" class=\"wpcf7-form-control wpcf7-text wpcf7-validates-as-required\" aria-required=\"true\" placeholder=\"John Doe\" required /></label>\n <label class=\"wpcf7-form-control-wrap Email\">Email <input type=\"email\" name=\"Email\" value=\"\" size=\"40\" class=\"wpcf7-form-control wpcf7-text wpcf7-email wpcf7-validates-as-required wpcf7-validates-as-email\" aria-required=\"true\" placeholder=\"jdoe@example.com\" required /></label>\n <label class=\"wpcf7-form-control-wrap Tel\">Phone Number<input type=\"tel\" name=\"Tel\" value=\"\" size=\"40\" class=\"wpcf7-form-control wpcf7-text wpcf7-tel wpcf7-validates-as-required wpcf7-validates-as-tel\" aria-required=\"true\" placeholder=\"(555) 555-5555\" /></label>\n </fieldset>\n\n <fieldset class=\"message\">\n <legend>Your Message</legend>\n\n <label class=\"wpcf7-form-control-wrap Subject\">Subject <input type=\"text\" name=\"Subject\" value=\"\" size=\"40\" class=\"wpcf7-form-control wpcf7-text wpcf7-validates-as-required\" aria-required=\"true\" required /></label>\n <label class=\"wpcf7-form-control-wrap Message\">Message <textarea name=\"Message\" cols=\"40\" rows=\"5\" class=\"wpcf7-form-control wpcf7-textarea wpcf7-validates-as-required\" aria-required=\"true\" required></textarea></label>\n </fieldset>\n\n <input type=\"submit\" value=\"Send\" class=\"wpcf7-form-control wpcf7-submit\" />\n</form>\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>form {\n -webkit-columns: 17em;\n -moz-columns: 17em;\n columns: 17em;\n}\n\nfieldset {\n -webkit-column-break-inside: avoid;\n page-break-inside: avoid;\n break-inside: avoid;\n}\n\nfieldset.contact-info {\n min-height: 14em;\n}\n\nlabel {\n margin: .5em 0;\n display: table; \n}\n\nlabel:last-child {\n display: margin-bottom: 0;\n}\n\nlabel input, label textarea {\n display: table;\n width: 15em;\n}\n</code></pre>\n\n<p>You don't <em>need</em> to use a legend, but fieldsets are the ideal way to group similar form elements together.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T19:49:07.487",
"Id": "36311",
"ParentId": "35335",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T10:19:22.303",
"Id": "35335",
"Score": "6",
"Tags": [
"css",
"wordpress"
],
"Title": "Evaluate a Contact Form CSS"
}
|
35335
|
<p>I recently worked with an architect who structured his base class like this:</p>
<pre><code>public abstract class Base<T>
{
public abstract T Get(int id);
internal T InternalGet(int id, IRepository<T> repository)
{
// Do more magic
return repository.Get(id);
}
}
</code></pre>
<p>And then in the derived class, if you just want to use the base functionality, you'd have to..</p>
<pre><code>public class Derived : Base<T>
{
private readonly IProductRepository _repository; // Implements IRepository<Product>
// Ctor with dependency injection, this is good stuff!
public DerivedClass(IProductRepository repository)
{
_repository = repository;
}
public override Product Get(int id)
{
// ... explicitly call base functionality - NOT a call to base though!
return InternalGet(id, _repository);
}
}
</code></pre>
<p>Why not just pass the repository to the base class, and override when you need to?</p>
<pre><code>public abstract class Base<T>
{
private readonly IRepository<T> _repository;
protected Base<T>(IRepository<T> repository)
{
_repository = repository;
}
public virtual T Get(int id)
{
// Do magic
return _repository.Get(id);
}
}
</code></pre>
<p>And then in the derived class, if you don't want to use the base method, just override it.</p>
<pre><code>public class Derived: Base<Product>
{
private readonly IProductRepository _repo;
public Derived(IProductRepository repo) : base(repo)
{
_repo = repo;
}
public override Get(int id)
{
if(! customerIsBeingNice)
throw new GoAwayException();
return _repo.Get(id);
}
}
</code></pre>
<p>I think the architect was trying to avoid the <a href="http://en.wikipedia.org/wiki/Call_super">call super code smell</a>, but since we are not requiring a call to super - in fact it really should never happen, because if you override the method, you are supposed to implement the flow you want, whereas if you call super, you can't hook into the flow that easily.</p>
<p>Which of these is better/worse, and why? Any alternatives?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T11:49:16.920",
"Id": "57239",
"Score": "4",
"body": "This question appears to be off-topic because it is not **your** code that you are asking to have reviewed"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T12:26:41.063",
"Id": "57240",
"Score": "1",
"body": "Why don't you ask the architect? They are the only person who can actually answer the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T12:35:39.300",
"Id": "57241",
"Score": "0",
"body": "I am asking because I want to know if I should do this myself, if this is some sort of established design pattern, or if the guy was just weird. I can't ask him, because we lost contact with him."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T12:37:59.857",
"Id": "57256",
"Score": "0",
"body": "- in fact the code I posted was code I wrote as I wrote this question."
}
] |
[
{
"body": "<p>The problem with building a good base class is that ideally, you should know exactly what kind of functionality will the derived classes need from the base class.</p>\n\n<p>If you think they'll need more than is actually necessary, you'll write more code unnecessarily and it will also make the base class harder to use. On the other hand, if you think the derived classes will need less, your base class will be hard (or impossible) to use for those advanced scenarios.</p>\n\n<p>For example, in your specific case, imagine you would need to call the base <code>Get()</code> with different <code>IRepository</code>s. With your implementation, that's hard to do (though not impossible, you use a hack like <code>IRepository</code> wrapper where the wrapped <code>IRepository</code> can be switched, but ugh). With the architect's implementation, that's a trivial thing to do: just pass different <code>IRepository</code> to each call of <code>InternalGet()</code>.</p>\n\n<p>But again, choosing between the two depends on expectations of what the derived classes will need. If a scenario like I just described is unlikely, then your implementation is better, because it's simpler. But if that scenario happens, your implementation is clearly insufficient and the one from the architect is clearly better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T12:45:37.260",
"Id": "57274",
"Score": "0",
"body": "Considering that we have a derived implementation for each repository there is, it is unlikely that the base class will be called with 2 separate repositories - but I see where you are coming from."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T12:38:55.260",
"Id": "35346",
"ParentId": "35337",
"Score": "7"
}
},
{
"body": "<p>Svick gives a good explanation on why this pattern exists. It is used, when you are not sure which base functionality derived class might actually need. Using your variant makes <code>Base</code> class dependant on single <code>IProductRepository</code> injection, which might not be the case for every derived class (at least in architector's opinion). Meanwhile, your issues with this particular base class can be easily solved by adding another base class to this hierarchy:</p>\n\n<pre><code>public abstract class SingleRepositoryBase<T> : Base<T>\n{\n public override T Get(int id)\n {\n return InternalGet(id, _repository);\n }\n\n protected SingleRepositoryBase(IRepository<T> repository)\n {\n _repository = repository;\n }\n\n private readonly IRepository<T> _repository;\n}\n</code></pre>\n\n<p>This will nicely cover both cases, and in my experience - that is how this patterns normally evolves.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T13:10:42.140",
"Id": "35356",
"ParentId": "35337",
"Score": "2"
}
},
{
"body": "<p>Based on your code example I will say something is missing from picture, but I give it a try. I have a different view from you and architect.</p>\n\n<p>First some comments on architect code version:\nIn Base class I will make InternalGet method protected, not internal. This way it is visible to only derived classes no matter in what assembly (suppose your solution has many projects and you need to have derived classes in different projects).\nDerived class should be defined like Derived : Base< Product >, other wise you have a compile error (type T definition is missing). Looks like a typo mistake, this ring a bell to me something is missing from picture.</p>\n\n<p>Because in base class the abstract method Get(int id) is identical with Get(int id) in IRepository and because Get and InternalGet methods both are coupled to type T I will suggest to use Decorator pattern to decorate IRepository (I don't see how InternalGet can deal with a repository for a different type that method Get return). Also because the \"do more magic\" is in Base class looks like the magic is kind of generic implementation. I would give a try to a implementation with generics. Here is my suggestion:</p>\n\n<p>Decorator:</p>\n\n<pre><code> public class RepositoryDecorator<T> : IRepository<T>\n {\n private readonly IRepository<T> _decoreatedRepository;\n\n public RepositoryDecorator(IRepository<T> decoreatedRepository)\n {\n _decoreatedRepository = decoreatedRepository;\n }\n\n public T Get(int id)\n {\n // do more magic\n return _decoreatedRepository.Get(id);\n }\n }\n</code></pre>\n\n<p>Client class:</p>\n\n<pre><code> public class RepositoryClient\n {\n private readonly IRepository<Product> _productRepository;\n\n public RepositoryClient(IRepository<Product> decoreatedRepository)\n {\n _productRepository = new RepositoryDecorator<Product>(decoreatedRepository);\n }\n\n public void Do(int id)\n {\n // productRepository is a decorator, but it's implementation type is hidden \n Product product = _productRepository.Get(id);\n\n // use product\n }\n }\n</code></pre>\n\n<p>RepositoryDecorator implements IRepository interface, this is need it to expose the decorator with same type as the decorated repository.</p>\n\n<p>RepositoryDecorator can be generic. If \"do more magic\" is specific to type T than you can have a decorator for each particular T type (like one for Product).\nRepositoryClient use a RepositoryDecorator actually, in my example decorator is instantiated in client constructor, but this is implementation detail. Decorator can be created outside and injected in client constructor as a simply IRepository. Client would not know he is dealing with a decorator in reality.</p>\n\n<p>Again, my suggestion is based on your succinct code. Your requirement could be more complex, in that case it will lead you to many decorators (per decorated type T). </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T08:16:31.317",
"Id": "57368",
"Score": "0",
"body": "The Decorator pattern.. What exactly is it? To me it seems like a business logic layer. And yes, it was a typo. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T09:55:28.630",
"Id": "57387",
"Score": "0",
"body": "@Jeff Decorator pattern is also known as Wrapper. Intent of decorator pattern from GoF: \"Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.\" In your case I would say you need to statically add behavior to IRepository. For details about decorator take a look http://en.wikipedia.org/wiki/Decorator_pattern"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-17T15:28:50.763",
"Id": "57650",
"Score": "0",
"body": "The code was something I typed up here, so like I said it was a typo - I am wondering why he might have wanted to do it the way he did."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T10:02:23.557",
"Id": "58091",
"Score": "0",
"body": "@Jeff I suppose architect intention was to make InternalGet method more generic. But in my opinion it doesn't make sense because InternalGet and Get methods are coupled (by type T). This is why I see you don't need Base class. Also I \"see\" your architect solution as trying to solve a problem doesn't exist: prepare code for a more generic case that might come in future. If you are 100% sure you will need it soon than architect solution is good, otherwise use the simplest solution that fit your actual need and refactor later when you will need it."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T22:29:41.187",
"Id": "35386",
"ParentId": "35337",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "35346",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T11:12:31.010",
"Id": "35337",
"Score": "9",
"Tags": [
"c#",
"design-patterns",
"dependency-injection",
"inheritance"
],
"Title": "Why would I want to always have to explicitly call a \"base\" method if I just want to use base functionality?"
}
|
35337
|
<p>Trying to return the below values from an RSS feed. I have sorted out the RSS feed side of things but I am not sure if what I am doing is the best way to extract the data that I need. I have looked at beautifulsoup and regex's, re.search but not sure what is the best way to do this. </p>
<p>Values that I need; (both of these values change daily obviously)</p>
<p><strong>4 Nov 2013</strong></p>
<p><strong>LOW-MODERATE</strong></p>
<p>This is the cut down version of the full body of text that has the data i need to get from rss feed;</p>
<pre><code><p>Fire Danger Ratings<br />Bureau of Meteorology forecast issued at: Mon, 4 Nov 2013 05:30 AM</p>
<p>Central: LOW-MODERATE</p>
</code></pre>
<p>My code to extract the rss feed and data at the moment;</p>
<pre><code>import feedparser #https://wiki.python.org/moin/RssLibraries
cfa_rss_url = "http://www.cfa.vic.gov.au/restrictions/central-firedistrict_rss.xml"
d = feedparser.parse( cfa_rss_url )
#get the data from the first item only, as it is only updated daily.
data = d.entries[0].description
print (data)
print('---------')
getdate = re.compile('forecast issued at: (.*?)</p>')
getrating = re.compile('<p>Central: (.*?)</p>')
m = getdate.search(data)
n = getrating.search(data)
print(m.group(1))
print(n.group(1))
</code></pre>
<p>This is the FULL data that is returned;</p>
<pre><code> <p>Total Fire Ban Status<br />Today, Mon, 4 Nov 2013 is <strong>not</strong> currently a day of Total Fire Ban in the <strong>Central (includes Melbourne and Geelong)</strong> fire district.</p><p>Fire Danger Ratings<br />Bureau of Meteorology forecast issued at: Mon, 4 Nov 2013 05:30 AM</p><p>Central: LOW-MODERATE</p></p><img alt="" border="0" src="http://www.cfa.vic.gov.au/images/fdr/central/low-moderate.gif" /></p><p><img alt="" height="22" src="http://www.cfa.vic.gov.au/images/fdr/tfb_icon_msg.gif" width="22" /> Displays when Total Fire Ban in force<br /><span><a href="http://www.cfa.vic.gov.au/warnings-restrictions/restrictions-during-the-fire-danger-period">Restrictions may apply</a></span></p>
---------
Mon, 4 Nov 2013 05:30 AM
LOW-MODERATE
</code></pre>
<p>As you can see my code returns the correct values atm but is this the most efficient way of doing this or should I be using another command?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T05:08:40.790",
"Id": "57242",
"Score": "0",
"body": "And.. what's the question? What do you want us to find?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T05:17:31.410",
"Id": "57243",
"Score": "0",
"body": "Am I using the best way to return the values that I require? the format of the rss feed doesn't change, just those few values."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T05:18:58.190",
"Id": "57244",
"Score": "1",
"body": "I think that's a fine way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T05:32:52.377",
"Id": "57245",
"Score": "0",
"body": "@alKid Thx for that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T05:33:13.240",
"Id": "57246",
"Score": "0",
"body": "@burhan, didn't know of that site, will check it out."
}
] |
[
{
"body": "<p>You can do the whole thing with a single regexp:</p>\n\n<pre><code>import re\n\ndata = \"\"\"\n<p>Fire Danger Ratings\n<br />Bureau of Meteorology \nforecast issued at: Mon, 4 Nov 2013 05:30 AM</p>\n\n<p>Central: LOW-MODERATE</p> \n\"\"\"\n\nrgx = re.compile(\"(forecast issued at: |<p>Central: )(.*?)</p>\")\nresults = rgx.findall(data)\nprint results[0][1]\nprint results[1][1]\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>$ python rss_parse.py\nMon, 4 Nov 2013 05:30 AM\nLOW-MODERATE\n</code></pre>\n\n<p>If this only runs a time or two a day, pre-compiling the regex is not important. </p>\n\n<pre><code>...\nresults = re.findall(\"(forecast issued at: |<p>Central: )(.*?)</p>\", data)\nprint results[0][1]\nprint results[1][1]\n</code></pre>\n\n<p>We can simplify how the result is handled:</p>\n\n<pre><code>...\n[when, rating] = [x[1] for x in\n re.findall(\"(forecast issued at: |<p>Central: )(.*?)</p>\",\n data)]\nprint(\"%s\\n%s\" % (when, rating))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T15:03:32.753",
"Id": "48341",
"ParentId": "35339",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T04:59:35.633",
"Id": "35339",
"Score": "3",
"Tags": [
"python"
],
"Title": "extract string from body of text"
}
|
35339
|
<p>Is there a shorter or maybe a cleaner way of doing:</p>
<blockquote>
<p>Using your <code>is_prime?</code> method, write a new method, <code>primes</code> that takes a (non-negative, integer) number <code>max</code> and returns an array of all prime numbers less than <code>max</code>.</p>
</blockquote>
<pre><code>def is_prime?(max)
i = 2
while i < max
is_divisible = ((max % i) == 0)
if is_divisible
# divisor found; stop and return false!
return false
end
i += 1
end
# no divisors found
true
end
def primes(max)
primes_arr = []
i = 2
while i < max
if is_prime?(i)
# i is prime; add it to the array
primes_arr << i
end
i += 1
end
# return primes_arr
primes_arr
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-28T08:48:20.667",
"Id": "193921",
"Score": "0",
"body": "Yes, there is an algorithm that works 300x faster than one you described, see full details: http://stackoverflow.com/questions/26792960/why-doesnt-my-ruby-coding-for-finding-prime-numbers-work/32806718#32806718"
}
] |
[
{
"body": "<p>Here it is using <a href=\"http://www.ruby-doc.org/stdlib-1.9.3/libdoc/prime/rdoc/Prime.html#method-i-prime-3F\" rel=\"nofollow\"><code>Prime#prime?</code></a>:</p>\n\n<blockquote>\n <p>Suppose I want to get all the prime numbers less than <code>9</code></p>\n</blockquote>\n\n<pre><code>require 'prime'\n\na = (1..12).to_a\np a.select{|e| e.prime? and e < 9 }\n# >> [2, 3, 5, 7]\n</code></pre>\n\n<p>Here is a method</p>\n\n<pre><code>require 'prime'\n\ndef prime_below_max(a,max)\n a.select{|e| e.prime? and e < max }\nend\n\nary = (1..12).to_a\np prime_below_max(ary,9)\n# >> [2, 3, 5, 7]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T09:20:10.817",
"Id": "57250",
"Score": "0",
"body": "The OP is supposed to write the methods for one of the online Ruby quizzes, not take advantage of built-in classes. While this is shorter on the surface it skirts the issue of working with the OPs code to optimize it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T09:26:40.673",
"Id": "57251",
"Score": "0",
"body": "@theTinMan I thought OP asked us to provide a short and simple code...Now I got what was he looking for... Should I delete this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-17T19:42:04.927",
"Id": "57662",
"Score": "1",
"body": "`Prime.each(100).to_a` is even shorter"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T06:29:38.753",
"Id": "35341",
"ParentId": "35340",
"Score": "1"
}
},
{
"body": "<p>Same logic, a bit cleaner and more rubular:</p>\n\n<pre><code>def is_prime?(num)\n (2...num).each do |divisor|\n return false if num % divisor == 0\n end\n\n true\nend\n\ndef primes(max)\n primes = []\n\n (2...max).each do |num|\n primes << num if is_prime?(num)\n end\n\n primes\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T07:09:18.270",
"Id": "57252",
"Score": "0",
"body": "Would you happen to know a similar way of printing out the primes up to (max) number without the without using \"is_prime\" method?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T07:12:51.893",
"Id": "57253",
"Score": "0",
"body": "@ZeroOne something like this? <https://gist.github.com/micahbf/7299091>"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T07:19:09.210",
"Id": "57254",
"Score": "0",
"body": "https://gist.github.com/micahbf/7299091"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T06:31:33.830",
"Id": "35342",
"ParentId": "35340",
"Score": "1"
}
},
{
"body": "<p>I rewrote <code>is_prime?</code>. It's more robust (doesn't fail when <code>n < 2</code>) and has caching and basic tests.</p>\n\n<pre><code>require 'set'\n\n# Returns true if a number is found to be prime and caches it for quick lookup.\n# Uses the simple trial division method.\ndef is_prime?(n)\n @primes ||= Set.new # Prefer set over array because of constant-time checks.\n return true if @primes.include?(n)\n return false if n < 2\n\n (2...n).each do |i|\n return false if n % i == 0\n end\n\n @primes.add(n)\n true\nend\n\ndef run_tests\n tests = {\n -1 => false,\n 0 => false,\n 1 => false,\n 2 => true,\n 3 => true,\n 4 => false,\n 5 => true,\n 9 => false,\n 913 => false,\n 997 => true,\n 3571 => true,\n }\n\n tests.each do |num, is_prime|\n # Tests primality.\n if is_prime?(num) == is_prime\n print \"PASS: \"\n else\n print \"FAIL: \"\n end\n if is_prime then puts \"#{num} is prime\" else puts \"#{num} is not prime\" end\n\n # Tests caching of primes.\n if is_prime && @primes.include?(num)\n print \"PASS: \"\n elsif !is_prime && !@primes.include?(num)\n print \"PASS: \"\n else\n print \"FAIL: \"\n end\n if is_prime then puts \"#{num} should be cached\" else puts \"#{num} should not be cached\" end\n puts\n end\nend\n\nrun_tests\n</code></pre>\n\n<p>If you need a better primality test (in Ruby) I recommend the <code>Prime</code> class, or if that's not possible for whatever reason, implement the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow\">Sieve of Eratosthenes</a> algorithm.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-15T11:57:55.563",
"Id": "140525",
"Score": "0",
"body": "You only cache the fact that certain numbers are prime, but not the fact that other numbers are non-prime. That guarantees a low cache hit rate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-15T12:03:19.970",
"Id": "140526",
"Score": "0",
"body": "@200_success that's a good point, thanks for bringing that up. The set can be changed to a hash. The tradeoff is that it would be faster at the expense of taking up more space (which is usually worth it)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-15T12:10:17.540",
"Id": "140527",
"Score": "0",
"body": "Note that you can also speed up trial division by iterating up to `sqrt(n)`. E.g. `2.upto(Math.sqrt(n).to_i) do |i|`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-15T11:43:56.140",
"Id": "77590",
"ParentId": "35340",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "35342",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T06:24:08.547",
"Id": "35340",
"Score": "3",
"Tags": [
"ruby",
"primes"
],
"Title": "Printing out prime numbers from an array given a max number"
}
|
35340
|
<p>Let <code>a,b,c</code> be a boolean value. I need to print all values of expression <code>a && b && c</code>. I'm writing the class</p>
<pre><code>public class BooleanTriple{
private boolean a,b,c;
public BooleanTriple(boolean a, boolean b, boolean c){ this.a =a; this.b=b; this.c=c;}
/**
*Increments the value of triple with lexicographical ordering
*/
public void incr(){
if (!a) a=true;
else if(!b){
a= false;
b= true;
else if (!c){
a= false;
b= false;
c=true;
}
}
public boolean logProduct(){ return a && b && c;}
}
</code></pre>
<p>And Main class:</p>
<pre><code>public class Main{
BooleanTriple bTriple = new BooleanTriple(false,false,false);
public static void main(String[] args){
for (int i=0; i<8; i++){
System.out.println(bTriple.logProduct());
bTriple.incr();
}
}
}
</code></pre>
<p>But i think, that it's bad implementation. Can you correct me?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T15:57:58.263",
"Id": "57257",
"Score": "2",
"body": "`Does it work?`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T15:58:23.890",
"Id": "57258",
"Score": "0",
"body": "I don't understand exactly what you're trying to do... but is your program working correctly...?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T15:58:39.430",
"Id": "57259",
"Score": "0",
"body": "@Cruncher Yes, can it implements more generally?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T15:59:39.147",
"Id": "57260",
"Score": "0",
"body": "@DmitryFucintv Yes, there definitely exists an implementation for this, given an arbitrary number of booleans"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T16:01:05.000",
"Id": "57261",
"Score": "0",
"body": "@DmitryFucintv notice that in general, the first boolean that is false, you set to true, and all before it to false. This is easily generalised."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T16:01:33.990",
"Id": "57262",
"Score": "0",
"body": "By the way, I might add `if(a && b && c) return (a && b && c)` and skip out of the entire `if else` structure since the `if else` structure only handles cases where any of them are false."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T16:02:17.660",
"Id": "57263",
"Score": "0",
"body": "@nhgrif Yeah, the idea is that he is only looping it 8 (2^3, which is also easily generalised) times."
}
] |
[
{
"body": "<p>I'll give you a hint. Think of a && b && c as a 3 digit binary number </p>\n\n<p>So all possibles values will be:</p>\n\n<pre><code>a | b | c\n0 | 0 | 0\n0 | 0 | 1\n0 | 1 | 0\n0 | 1 | 1\n1 | 0 | 0\n1 | 0 | 1\n1 | 1 | 0\n1 | 1 | 1\n</code></pre>\n\n<p>As you can see, you want to flip c every time and check the value of a and b to determine what they will be. b will change any time c is 1 and a will change any time b and c are 1. This should be enough to give you a better implementation. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T16:05:51.677",
"Id": "57264",
"Score": "5",
"body": "You could also loop between 0 and 7. a will be `(i%8)/4`. b will be `(i%4)/2`. And c will be `(i%2)/1` :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T16:11:55.533",
"Id": "57265",
"Score": "0",
"body": "I never have thought about it like that. That's a really smart and simple way to do it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T16:12:48.100",
"Id": "57266",
"Score": "0",
"body": "Yep, it also allows you to jump to an arbitrary point in the ordering, and not depend on the previous iteration"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T16:02:54.140",
"Id": "35348",
"ParentId": "35347",
"Score": "1"
}
},
{
"body": "<p>I find recursive approach to be a better one, since you can easily adapt it for an arbitrary number of boolean variables. Here's a quick implementation just to give you an idea:</p>\n\n<pre><code>public class Triple {\n public static void main(String[] args) {\n Set<String> combinations = new HashSet<>();\n generateCombinations(\"\", combinations);\n System.out.println(combinations); // [010, 110, 111, 011, 000, 101, 001, 100]\n for (String combination : combinations)\n logProduct(combination);\n }\n\n private static void generateCombinations(String prefix, Set<String> dest) {\n if (prefix.length() == 3) {\n dest.add(prefix);\n } else {\n generateCombinations(prefix + \"0\", dest);\n generateCombinations(prefix + \"1\", dest);\n }\n }\n\n private static void logProduct(String input) {\n StringBuilder output = new StringBuilder();\n boolean result = true;\n for (int i = 0; i < input.length(); i++) {\n boolean next = input.charAt(i) != '0';\n result &= next;\n output.append(next);\n if (i != input.length() - 1)\n output.append(\" && \");\n else\n output.append(\" = \").append(result);\n }\n System.out.println(output.toString());\n }\n}\n</code></pre>\n\n<p>And the output sample is: <code>true && true && false = false</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T16:15:40.463",
"Id": "35349",
"ParentId": "35347",
"Score": "1"
}
},
{
"body": "<p>If you like to \"increment the boolean values\" similar to binary values this might help you:</p>\n\n<pre><code>public class dummy1 {\n\nstatic BooleanTriple bTriple = new BooleanTriple(false, false, false);\n\npublic static void main(String[] args) {\n for (int i = 0; i < 8; i++) {\n System.out.println(i + \" => \" + bTriple.logProduct());\n bTriple.incr();\n }\n}\n}\n\nclass BooleanTriple {\n\nprivate int value;\n\npublic BooleanTriple(boolean a, boolean b, boolean c) {\n value = (a ? 1 : 0) + (b ? 2 : 0) + (c ? 4 : 0);\n}\n\npublic void incr() {\n //if (value < 7) // if the increment should not \"loop\"\n value = ++value & 7;\n}\n\npublic boolean logProduct() {\n return value == 0b111; // 7\n}\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T16:25:23.500",
"Id": "57267",
"Score": "2",
"body": "What's the point of the `value = ++value & 7;`? This will cause 7 to still be 7 after incrementing. Did you mean `value = ++value % 7;`? By the way, using `++value` in an assignment statement to `value` is rather obtuse. I would just use `value+1`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T16:50:26.050",
"Id": "57268",
"Score": "0",
"body": "@Cruncher: The \" & 7\" should have been removed when i added the comment in the line above - since the questioner only mentioned 3 bool vars i assumed that is the \"default\" he meant. About the \"++value\": first the right side of equal sign is evaluated and then the result is assigned to left side of \"=\". So it is no error and incrementing is faster and results in shorter code than adding 1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T16:52:10.080",
"Id": "57269",
"Score": "0",
"body": "It's no error, but it's a little bit confusing. It's also not faster. This is what is happening. You are adding 1 to value. Assigning it to value, Using that value in the expression `value & 7` and then assigning the result to value. You assign to value twice here. (I don't know exactly how it translates to bytecote, my guess is that the compiler actually optimizes it to `value+1`)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T17:01:17.930",
"Id": "57270",
"Score": "0",
"body": "I guess we both do not have debugged the resulting code on assembler level. But as i know from my \"assembler times\" incrementing a value (by one) is just a single machine code instruction while an addition of an value needs to load the value (1), add it and store the result (3 opcodes). Anyway, as long as we agree that it is not an error we should close discussion about that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T18:27:19.313",
"Id": "57271",
"Score": "0",
"body": "@Michael Besteck: your code still needs to load and store the value as you still have an assignment of the form `value=expression`. If you admit that you don’t have a clue about the resulting code, then don’t add these “optimizations” to your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T17:26:49.490",
"Id": "57272",
"Score": "0",
"body": "@Holger: I have written a sort of test case for the problem\n(http://system33.de/temp/TestExecutionSpeed.java). That shows that my increment version has an execution time of 289820ms while the \"x+1\" version has an execution time of 291514ms for 10^11 executions. For that high number of executions both methods can be taken as effectively equal in execution time (mine seems faster). The level on which you are arguing does not take CPU architecture, microcode execution, cache effects, compiler optimization et. al. into account. You are thinking not on a real but on an only theoretical level."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T17:54:04.373",
"Id": "57273",
"Score": "0",
"body": "You are talking about performance but use constructs like `(new Date()).getTime()` instead of `System.nanoTime()`? I have the strong feeling that you optimize at the wrong places of your code… But anyway, I’m not talking about theoretical things, I *know* that there is no such thing than a special increment instruction for fields in Java bytecode (despite to local variables). Just disassemble the class file if you don’t believe it, both methods do the same besides the fact that the `++` creates an additional store operation. So it’s not surprising that your version is *slower* in most setups."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T16:21:34.003",
"Id": "35351",
"ParentId": "35347",
"Score": "0"
}
},
{
"body": "<p>Why not iterate over the boolean values <code>true</code> and <code>false</code> like this? </p>\n\n<pre><code> final boolean[] bools=new boolean[]{false,true};\n for (boolean a:bools)\n {\n for (boolean b:bools)\n {\n for (boolean c:bools)\n {\n System.out.println(\"a: \"+a+\" b: \"+b+\" c: \"+c+\": => \"+(a && b && c));\n\n }\n\n } \n\n }\n</code></pre>\n\n<p>Output will be:</p>\n\n<blockquote>\n <p>a: false b: false c: false: => false</p>\n \n <p>a: false b: false c: true: => false </p>\n \n <p>a: false b: true c: false: => false </p>\n \n <p>a: false b: true c: true: => false </p>\n \n <p>a: true b: false c: false: => false </p>\n \n <p>a: true b: false c: true: => false </p>\n \n <p>a: true b: true c: false: => false </p>\n \n <p>a: true b: true c: true: => true</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T15:11:03.540",
"Id": "57939",
"Score": "0",
"body": "Because it is not a very flexible way of doing it. Imagine you would want to change to using 6 bools instead, you would have to add 3 more for-loops."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T16:27:21.130",
"Id": "35352",
"ParentId": "35347",
"Score": "0"
}
},
{
"body": "<p>Here is a simple version done in one loop. I developed this independently of @Cruncher's comment, but please give him credit also.</p>\n\n<pre><code>public static void main(String[] args) {\n boolean a = false;\n boolean b = false;\n boolean c = false;\n\n for (int i = 0; i < 8; i++) {\n c = !c;\n if (i % 2 == 0)\n b = !b;\n if (i % 4 == 0)\n a = !a;\n System.out.println(\"A: \" + a + \", B: \" + b + \", C: \" + c + \" | value: \" + (a && b && c));\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T16:45:50.610",
"Id": "35353",
"ParentId": "35347",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T15:55:35.557",
"Id": "35347",
"Score": "1",
"Tags": [
"java"
],
"Title": "All values of boolean-triple"
}
|
35347
|
<p>I am having a slight issue here, i am trying to think of a faster way of finding two elements from 2 different lists that match. The problem is that if i have lists which both have 1000 elements ( rules ) and the very last one [index.1000] matches then in order to find it i have to loop through booth lists from top to bottom. What i have is fine and it works however its not very efficient. Could any one perhaps suggest a better way ? (if there is any ? )
<br></p>
<p>The loop in this meethod is where the iteration through the lists happen. For furthere reference below this method you will find what ContextRule and Context is.</p>
<pre><code>public ContextRule match(Context messageContext, ContextRuleList contextRules) {
ContextRule matchedContextRule = null;
for(ContextRule contextRule : contextRules) {
if(this.match(messageContext, contextRule)) {
matchedContextRule = contextRule;
break;
}
}
if(matchedContextRule == null) {
matchedContextRule = this.getDefaultContextRule();
}
return matchedContextRule;
}
</code></pre>
<p>match() method which does comparason.</p>
<pre><code>private boolean match(Context messageContext, ContextRule contextRule) {
return match(contextRule.getMessageContext().getUser(), messageContext.getUser())
&& match(contextRule.getMessageContext().getApplication(), messageContext.getApplication())
&& match(contextRule.getMessageContext().getService(), messageContext.getService())
&& match(contextRule.getMessageContext().getOperation(), messageContext.getOperation());
}
private boolean match(String value, String contextValue) {
return value.equals(ContextRuleEvaluator.WILDCARD) || value.equals(contextValue);
}
</code></pre>
<hr>
<p>Context ( which is an interface ) </p>
<pre><code>public interface Context {
public String getUser();
public void setUser(String user);
public String getApplication();
public void setApplication(String application);
public String getService();
public void setService(String service);
public String getOperation();
public void setOperation(String operation);
}
</code></pre>
<p>And finally ContextRule</p>
<pre><code>public interface ContextRule {
public Context getMessageContext();
public int getAllowedConcurrentRequests();
}
</code></pre>
<p>any help or suggestions appreciated.</p>
|
[] |
[
{
"body": "<p>Too long for a comment, so, your <code>match</code> function can be shortened to this:</p>\n\n<pre><code>public ContextRule match(Context messageContext, ContextRuleList contextRules) {\n for(ContextRule contextRule : contextRules) {\n if(this.match(messageContext, contextRule)) {\n return contextRule;\n }\n } \n\n // Found nothing, returning default.\n return this.getDefaultContextRule();\n}\n</code></pre>\n\n<p>This will not yield a massive performance improvement, but is easier to read.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T14:18:14.230",
"Id": "35364",
"ParentId": "35357",
"Score": "1"
}
},
{
"body": "<p>Can your context rules be precomputed into any sort of hierarchical match tree once at application initialization?</p>\n\n<pre><code>HashMap<String, HashMap<String, List<ContextRule>>> contextRuleMap\n\npublic boolean match (Context context, Map<String, Map<String, List<ContextRule>> contextRuleMap)\n{\n Map<String, List<ContextRule>> rulesByApplication = contextRuleMap[context.getUser()];\n\n for (ContextRule contextRule : rulesByApplication[context.getApplication()]) {\n // Existing logic for remaining 'match' of service and operation\n }\n\n return false;\n}\n</code></pre>\n\n<p>You can pre-compute your 'match tree' to as many 'levels deep' as you need to by User -> Application -> Service -> Operation to achieve the necessary performance.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T17:55:20.587",
"Id": "35370",
"ParentId": "35357",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "35370",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T13:19:09.800",
"Id": "35357",
"Score": "3",
"Tags": [
"java",
"performance"
],
"Title": "Trying to find a better way of finding something rather then looping through list from top to bottom."
}
|
35357
|
<p>The overall question is: I need feedback on the security of the idea and the script. Do I need to do more in raw code, or is this ok, taking into account my other information?</p>
<ol>
<li><p>Let's assume these following first:</p>
<ul>
<li>All images are stored on a subdomain (e.g. <code>images.example.com</code>)</li>
<li>The subdomain <code>images.example.com</code> does not have execute rights</li>
<li>The upload script is named upload.php and is located at <code>example.com</code></li>
<li>I run a virus scanner on <code>images.example.com</code> every day</li>
</ul></li>
<li><p>A simple upload script written in PHP:</p>
<pre><code>$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"images.example.com/" . randomName() .$_FILES["file"]["name"]);
}
}
}
else
{
echo "Invalid file";
}
</code></pre>
<p>The script is demonstrating my thoughts; nothing more.</p></li>
<li><p>So from what I understand now, all images uploaded cant do any harm to example.com, even if they contain <code>injected code</code>?</p></li>
<li><p>Do I not need to do a <code>exif</code> or <code>Fileinfo</code> check since I put the files on a subdomain?</p></li>
<li><p>I've assumed a lot of things. Did I miss anything?</p></li>
</ol>
|
[] |
[
{
"body": "<p>First thing I would consider is using functions so that it becomes easier readable.</p>\n\n<pre><code>function hasAllowedExtension($filename); // returns bool\nfunction isAllowedType($filetype); // returns bool\n</code></pre>\n\n<p>That way you can shorten the first lines to</p>\n\n<pre><code>$file = $_FILES[\"file\"];\nif (hasAllowedExtension($file[\"name\"]) && isAllowedType($file[\"type\"]) && $file[\"size\"] < 20000) {\n</code></pre>\n\n<p>which is much more readable.</p>\n\n<hr>\n\n<pre><code>$allowedExts = array(\"gif\", \"jpeg\", \"jpg\", \"png\");\n$temp = explode(\".\", $_FILES[\"file\"][\"name\"]);\n$extension = end($temp);\n</code></pre>\n\n<p><a href=\"http://php.net/manual/en/function.pathinfo.php\" rel=\"nofollow\">There are better and easier ways</a>:</p>\n\n<pre><code>$extension = pathinfo($_FILES[\"file\"][\"name\"], PATHINFO_EXTENSION);\n</code></pre>\n\n<hr>\n\n<p>Also consider making all of this into a function which you only either hand the name of the file <code>$_FILES[$filename]</code> or the file (from <code>$_FILES</code>) directly.</p>\n\n<hr>\n\n<pre><code>echo \"Invalid file\";\n</code></pre>\n\n<p>A <code>die</code> might be appropriate here. <code>die</code> will also print a message but has the added bonus that it immediately stops execution and it is easier to understand that this is really a stopper.</p>\n\n<pre><code>die(\"Invalid file.\");\n</code></pre>\n\n<hr>\n\n<p>I couldn't see any gaping holes in it except for only one thing: I can't remember and couldn't find out if <code>$_FILES[\"file\"][\"name\"]</code> is safe or not. So check if this value can contain path separators or not. And by check I mean, read the documentation carefully.</p>\n\n<hr>\n\n<p>Also it seems like you're checking for the file in a different location/under a different name than you actually save it as.</p>\n\n<pre><code>if (file_exists(\"upload/\" . $_FILES[\"file\"][\"name\"]))\n...\nmove_uploaded_file($_FILES[\"file\"][\"tmp_name\"],\n \"images.example.com/\" . randomName() .$_FILES[\"file\"][\"name\"]);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T14:21:48.103",
"Id": "57283",
"Score": "0",
"body": "Hey Bobby :) Do you have any comments on the security aspect of it all?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T14:46:06.767",
"Id": "57285",
"Score": "0",
"body": "Only that name could contain anything, otherwise it looks good to me (at least I don't see anything), as long as the server is correctly configured (does not allow uploads of 500MB or so). I don't know what `randomName()` returns, but better make sure that this never collides."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T14:50:22.900",
"Id": "57286",
"Score": "0",
"body": "Ok, so yea.. I was thinking uploads of 5-50MB max. randomName() is just a function that returns a random name to put infront of the original name. But i might even just do a totally random name."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T15:05:43.693",
"Id": "57287",
"Score": "1",
"body": "I don't see anything else, that doesn't meant that there isn't, though. Wait a moment, are you checking for the existence of `/uploaded/filename.ext` but then copying it to `/uploads/randomstuffFilename.ext`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T15:32:57.190",
"Id": "57296",
"Score": "0",
"body": "Ah the existence of a file on the subdomain.. forgot that :-) That will ofc have to be implemented :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T14:06:50.847",
"Id": "35363",
"ParentId": "35359",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "35363",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T13:38:47.623",
"Id": "35359",
"Score": "1",
"Tags": [
"php",
"security"
],
"Title": "Secure file upload example"
}
|
35359
|
<p>Using ARC, I'm calling the following function in an iOS app every time the app gets opened in the <code>applicationDidBecomeActive</code> function.</p>
<p>My concern is that it could create a memory leak because it's creating new instances of <code>UIViewControllers</code> every time the app gets opened from the background.</p>
<pre><code>- (void)showMainWindow{
NSLog(@"@Info @AppDelegate: Showing Main Window");
self.leftMenuViewController = nil;
self.rightMenuViewController = nil;
MenuViewController *tempLeft = [[MenuViewController alloc]initWithSide:@"left"];
MenuViewController *tempRight = [[MenuViewController alloc]initWithSide:@"right"];
self.leftMenuViewController = tempLeft;
self.rightMenuViewController = tempRight;
self.viewDeckController = [[IIViewDeckController alloc] initWithCenterViewController:self.webViewController
leftViewController:self.leftMenuViewController
rightViewController:self.rightMenuViewController];
self.window.rootViewController = self.viewDeckController;
[[NSNotificationCenter defaultCenter] postNotificationName:@"updateNavigationBar" object:nil];
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T09:49:14.900",
"Id": "57386",
"Score": "0",
"body": "I don't think so, though it might depend on if the view deck controller retains the web view controller. simple way to check though: run in instruments"
}
] |
[
{
"body": "<p>This code doesn't appear to leak. To be sure, however, you should use the <code>leaks</code> instrument to periodically check your code. </p>\n\n<p>To do such,</p>\n\n<ol>\n<li>Select Product -> Profile (or, ⌘ I)</li>\n<li>Choose `Leaks`</li>\n<li>Select Profile</li>\n<li>Exercise your app (i.e. go through all the options, background it, etc)</li>\n</ol>\n\n<p>For more information on using the leaks tool, you can checkout Ray Wenderlich's <a href=\"http://www.raywenderlich.com/2696/\" rel=\"nofollow\">Instruments Tutorial for iOS: How to Debug Memory Leaks</a>.</p>\n\n<p><b>Additional Notes:</b></p>\n\n<p>1) Unless you have a really good reason to, you shouldn't be setting <code>self.window.rootViewController</code> every time that the app returns to the foreground. Instead of calling <code>showMainWindow</code> from within <code>applicationDidBecomeActive</code>, you should probably move this code within <code>application:didFinishLaunchingWithOptions:</code>, which is the more common place to do initial app setup.</p>\n\n<p>Further, if you need a controller to know when the app has entered the foreground (I imagine that this is the reason you're actually doing this), you should have it register to receive notification of <code>UIApplicationWillEnterForegroundNotification</code>. I.e.</p>\n\n<pre><code>- (void)viewDidLoad\n{\n [super viewDidLoad];\n\n [[NSNotificationCenter defaultCenter] addObserver:self\n selector:@selector(YOUR_SELECTOR)\n name:UIApplicationWillEnterForegroundNotification\n object:nil];\n\n // ... whatever else you do here...\n}\n\n// Also make sure to unregister too\n- (void)dealloc\n{\n [[NSNotificationCenter defaultCenter] removeObserver:self];\n}\n</code></pre>\n\n<p>2) To make this code a bit more cleaner and easier to read, I would rewrite it like this:</p>\n\n<pre><code>- (void)showMainWindow \n{\n\n NSLog(@\"@Info @AppDelegate: Showing Main Window\");\n\n self.leftMenuViewController = [[MenuViewController alloc]initWithSide:@\"left\"];;\n self.rightMenuViewController = [[MenuViewController alloc]initWithSide:@\"right\"];;\n\n self.viewDeckController = [[IIViewDeckController alloc] initWithCenterViewController:self.webViewController\n leftViewController:self.leftMenuViewController\n rightViewController:self.rightMenuViewController];\n\n self.window.rootViewController = self.viewDeckController;\n [[NSNotificationCenter defaultCenter] postNotificationName:@\"updateNavigationBar\" object:nil];\n}\n</code></pre>\n\n<p>In such, you don't have to explicitly set <code>self.leftMenuViewController</code> and <code>self.rightMenuViewController</code> to <code>nil</code> or create the <code>temp</code> objects.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T23:22:57.567",
"Id": "37086",
"ParentId": "35360",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37086",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T13:51:11.897",
"Id": "35360",
"Score": "4",
"Tags": [
"objective-c",
"ios",
"memory-management"
],
"Title": "applicationDidBecomeActive: Am I causing a memory leak?"
}
|
35360
|
<p>I've implemented the following code which allows me to bolt modules of code on to my core library via the prototype chain. It's quite prescriptive so any user creating a module has to create an init method and also has to define a queue method:</p>
<p>(working fiddle: <a href="http://jsfiddle.net/wG9Pv/" rel="noreferrer">http://jsfiddle.net/wG9Pv/</a>)</p>
<pre><code>//Constructor
test = function() {
this.tester = 'The instance was successfully created';
};
//A core method
test.prototype.amethod = function() {
};
//Extend method which facilitates the module system
test.extend = function(name,plugin) {
test.prototype[name] = plugin.init;
//later do something with the queue method that's been fed in via the 'plugin' object
};
//Add a module
test.extend('method1', {
init: function(val) {
console.log(this.tester);
},
queue: function() {
},
render: function() {
}
});
//add another module
test.extend('method2',{
init: function() {
console.log('Init of the plugin has been fired');
},
draw : function() {}
});
var test = new test();
test.method1('boom!');
test.method2();
</code></pre>
<p>Now this all works well but is this a good way of achieving it? </p>
|
[] |
[
{
"body": "<p>Looks fine to me,</p>\n\n<p>I would consider making extend a property of prototype though.</p>\n\n<p>For nitpickings, I think</p>\n\n<pre><code>function Test() {\n this.tester = 'The instance was successfully created';\n};\n</code></pre>\n\n<p>is preferred to </p>\n\n<pre><code>test = function() {\n this.tester = 'The instance was successfully created';\n};\n</code></pre>\n\n<p>This ways developers will know to use <code>new</code> when using test.\nPlease read <a href=\"http://addyosmani.com/resources/essentialjsdesignpatterns/book/#constructorpatternjavascript\" rel=\"nofollow\">Learning JavaScript Design Patterns</a> for the cons of using the <code>new</code> keyword.</p>\n\n<p>You probably want to store the entire plugin object provided to <code>extend</code>, not just keep <code>init</code>.</p>\n\n<p>You probably want to throw an exception if the <code>plugin</code> does not have an <code>init</code> property.</p>\n\n<p>I am not sure if you realize that <code>method1</code> and <code>method2</code> are at the end of the script also \"core methods\"?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T16:25:49.137",
"Id": "35439",
"ParentId": "35367",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T16:23:01.313",
"Id": "35367",
"Score": "8",
"Tags": [
"javascript"
],
"Title": "A simple javascript plugin architecture"
}
|
35367
|
<p>As an exercise, I have implemented a linked queue whose <code>enqueue</code> and <code>dequeue</code> methods are synchronized. There is a <code>Producer</code> thread which keeps inserting elements into the queue as long as there are less than 10 items in it. When the queue is full, the thread waits. The second thread <code>Consumer</code> keep removing elements from queue as long as it is not empty. I would like to get a review of this code - is there any flaw? How could I improve it? </p>
<p>MyLinkedQueue.java</p>
<pre><code>public class MyLinkedQueue<T> implements Iterable<T> {
private Node first, last;
private int size = 0;
private static final int MAX_QUEUE_SIZE = 10;
public Iterator<T> iterator() { return new QueueIterator(); }
private class Node {
T item;
Node next;
}
public boolean isEmpty() { return first == null; }
public boolean isFull() { return MAX_QUEUE_SIZE == size(); }
public synchronized void enqueue(T item) throws InterruptedException {
while (isFull()) {
wait();
}
Node oldLast = last;
last = new Node();
last.item = item;
last.next = null;
if (isEmpty()) {
first = last;
} else {
oldLast.next = last;
}
notifyAll();
size++;
}
public synchronized T dequeue() throws InterruptedException {
while (0 == size()) {
wait();
}
T item = first.item;
first = first.next;
if (isEmpty()) { last = null; }
size--;
notifyAll();
return item;
}
public synchronized int size() { return size; }
private class QueueIterator implements Iterator<T> {
private Node current = first;
public boolean hasNext() { return current != null; }
public void remove() {}
public T next() {
T item = current.item;
current = current.next;
return item;
}
}
}
</code></pre>
<p>Producer.java</p>
<pre><code>public class Producer implements Runnable {
private static final int DELAY = 1000;
private MyLinkedQueue queue;
private int count;
public Producer(MyLinkedQueue queue, int count) {
this.queue = queue;
this.count = count;
}
public void run() {
try {
for (int i = 0; i < count; ++i) {
queue.enqueue(new Date().toString());
Thread.sleep(DELAY);
}
} catch(InterruptedException e) {
}
}
}
</code></pre>
<p>Consumer.java</p>
<pre><code>public class Consumer implements Runnable {
private static final int DELAY = 1000;
private MyLinkedQueue queue;
private int count;
public Consumer(MyLinkedQueue queue, int count) {
this.queue = queue;
this.count = count;
}
public void run() {
try {
for (int i = 0; i < count; ++i) {
queue.dequeue();
Thread.sleep(DELAY);
}
} catch(InterruptedException e) {
}
}
}
</code></pre>
<p>QueueThreadrunner.java</p>
<pre><code>public class QueueThreadrunner {
public static void main(String[] args) {
MyLinkedQueue queue = new MyLinkedQueue();
final int THREADS = 10;
final int REPETITIONS = 50;
for (int i = 1; i <= THREADS; ++i) {
Producer pr = new Producer(queue, REPETITIONS);
Consumer cr = new Consumer(queue, REPETITIONS);
Thread dt = new Thread(pr);
Thread wt = new Thread(cr);
dt.start();
wt.start();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T18:50:08.577",
"Id": "57320",
"Score": "1",
"body": "`public boolean isEmpty() { return first == null; }` needs to be synchronized otherwise it could have a stale version of `first`."
}
] |
[
{
"body": "<p>It is apparent that you have put some thought in to this implementation, and apart from the not-synchronized isEmpty() method, it all looks functional.</p>\n\n<p>I have some minor nit-picks though, and please bear in mind that these are just my opinion...</p>\n\n<p>I prefer to have the notifyAll method to be the last thing in a synchronized block, where possible... You have:</p>\n\n<pre><code>....\n }\n notifyAll();\n size++;\n}\n</code></pre>\n\n<p>I would always put the notifyAll() after the size++. This does not make a functional difference to the program, but it makes the logic more apparent (that <code>size++</code> will happen <strong>before</strong> any other thread can read the <code>size</code> value):</p>\n\n<pre><code>....\n }\n size++;\n notifyAll();\n}\n</code></pre>\n\n<p>As I say, this does not affect the logic of the code, but it does affect the readability.</p>\n\n<p>A second nit-pick I have is that you 'leak' logic from your synchronized blocks. What I mean by this, is that you should try to avoid any method calls from inside the block. When you call other methods from a block it becomes much easier to introduce synchronization bugs and deadlocks. Additionally, the methods you call are also synchronized, so you introduce a readability/complexity (and perhaps even a slight performance) issue by having nested synchronization calls.</p>\n\n<p>EDIT: I would add another nit-pick here which is you do not use 'final' enough. 'final' is a good hint to the optimizer in Java and it allows it to make smarter choices when inlining and otherwise rearranging/compiling your code</p>\n\n<p>Finally, I would choose just one mechanism to manage the empty/full condition of the queue. Currently you have a few: <code>isEmpty</code> depends on <code>first == null</code>; <code>isFull()</code> depends on <code>size == MAX_QUEUE_SIZE</code>; in your <code>enqueue(...)</code> you test for <code>isFull()</code> and <code>isEmpty()</code>; and in your <code>dequeue()</code> you test for <code>0 == size()</code> and <code>isEmpty()</code>. I would reduce all of these to tests on <code>size</code> only. That way there is only one condition that you need to mentally track when you read the code. </p>\n\n<p>So, if it were me, I would replace your code as follows:</p>\n\n<pre><code>public synchronized boolean isEmpty() { return size == 0; } // replace first == null\npublic synchronized boolean isFull() { return size == MAX_QUEUE_SIZE; } // replace size()\n\npublic synchronized void enqueue(final T item) throws InterruptedException { // add final\n while (size == MAX_QUEUE_SIZE) { // replace isFull() call.\n wait();\n }\n\n final Node oldLast = last; // add final\n last = new Node();\n last.item = item;\n last.next = null;\n\n if (size == 0) { // remove isEmpty()\n first = last;\n } else {\n oldLast.next = last;\n }\n size++; // move before notifyAll()\n notifyAll();\n} \n\npublic synchronized T dequeue() throws InterruptedException {\n while (size == 0) { // remove size() call.\n wait();\n }\n\n final T item = first.item; // add final\n first = first.next;\n\n size--; // move size-- up a bit to make the logic below more transparent\n if (size == 0) { // remove isEmpty() call\n last = null;\n }\n notifyAll();\n return item;\n}\n</code></pre>\n\n<p>Finally, if it really was me, I would recommend that you consider <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html\" rel=\"noreferrer\">ReentrantLocks</a> and <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Condition.html\" rel=\"noreferrer\">Conditions</a> to manage the queue.... There's a good example (almost identical to this exact problem) of how to do it <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Condition.html\" rel=\"noreferrer\">in the JavaDoc</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T20:17:48.600",
"Id": "35382",
"ParentId": "35371",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "35382",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T18:06:38.893",
"Id": "35371",
"Score": "6",
"Tags": [
"java",
"algorithm",
"multithreading",
"thread-safety"
],
"Title": "Thread safe enqueue and dequeue method in Queue"
}
|
35371
|
<p>This is the <code>CalculatorAdvanced</code> Kata from the Kata gem. I've just finished it and would love some feedback on my solution.</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>CalculatorAdvanced Kata
Add Method
Allow the expression to handle new lines between numbers
- example: "1\n2\n3" computes to 6
- example: "2,3\n4" computes to 9
- detail: Consecutive use of delimeters should raise an exception
- example: "1,\n2" or "1\n,2"
completed (Y|n):
Calling method with a negative number will give an exception
- detail: The exception should tell the user "negatives not allowed"
- detail: The exception will list the negative number that was in the string
- detail: The exception should list all negatives if there is more than one
completed (Y|n):
Diff and Product Method
should raise the same exceptions as the add method
- detail: Consecutive Delimiters
- detail: Negative Numbers
completed (Y|n):
Define Custom Delimeters
Allow the add method to accept a different delimiter
- detail: The line of the string will contain "//[delimeter]\n...
- detail: This line is optional and all previous tests should pass
- example: "//[;]\n1;2" computes to 3
- detail: "1;2" should raise an exception
completed (Y|n):
Allow the diff method to accept a different delimiter like add
- example: //[;]\n2;1 computes to 1
completed (Y|n):
Allow the prod method to accept a different delimiter like add
- example: //[;]\n2;1 computes to 2
completed (Y|n):
Allow the div method to accept a different delimiter like add
- example: //[;]\n3;2 computes to 1
completed (Y|n):
Allow the add method to handle multiple different delimeters
- example: multiple delimeters can be specified using "//[delimeter]...[delimeter]\n...
- example: "//[*][;]\n1*2;3" computes to 6
- example: "//[*][;][#]\n5*4;3#2" computes to -4
- example: "//[#][;][*]\n1*2#3;4,5\n6" computes to 21
completed (Y|n):
Allow the diff method to handle multiple different delimeters
- example: "//[*][;]\n1*2;3" computes to -4
completed (Y|n):
Allow the prod method to handle multiple different delimeters
- example: "//[*][;]\n1*2;3" computes to 6
completed (Y|n):
Allow the div method to handle multiple different delimeters
- example: "//[*][;]\n1*2;3" computes to 0
completed (Y|n):
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━┓
┃ Requirement ┃ Time ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫
┃ Allow the expression to handle new lines between numbers ┃ 00:37:20 ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫
┃ Calling method with a negative number will give an exception ┃ 00:20:55 ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫
┃ should raise the same exceptions as the add method ┃ 00:08:41 ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫
┃ Allow the add method to accept a different delimiter ┃ 00:22:51 ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫
┃ Allow the diff method to accept a different delimiter like add ┃ 00:06:04 ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫
┃ Allow the prod method to accept a different delimiter like add ┃ 00:01:49 ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫
┃ Allow the div method to accept a different delimiter like add ┃ 00:01:46 ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫
┃ Allow the add method to handle multiple different delimeters ┃ 00:55:48 ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫
┃ Allow the diff method to handle multiple different delimeters ┃ 00:00:54 ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫
┃ Allow the prod method to handle multiple different delimeters ┃ 00:00:38 ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╊━━━━━━━━━━┫
┃ Allow the div method to handle multiple different delimeters ┃ 00:00:43 ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┻━━━━━━━━━━┛
</code></pre>
</blockquote>
<p>And, here's the Class I created:</p>
<pre class="lang-ruby prettyprint-override"><code>class Calculatoradvanced
attr_reader :expr
def expr=(expression='')
@expr = expression
validate_expression
end
alias_method :initialize, :expr=
def add
@values.inject(&:+)
end
def diff
@values.inject(&:-)
end
def prod
@values.inject(&:*)
end
def div
@values.inject(&:/)
end
private
def validate_expression
if @expr =~ /,\n/ || @expr =~ /\n,/
raise "Consecutive Delimiters"
end
split_string = ",\n"
if match = @expr.match(/\/\/([^\n]*)\n(.*)/m)
delimeters, @expr = match.captures
delimeters = delimeters.split(/[\[\]]/)
delimeters.reject! { |delimeter| delimeter == '' }
split_string = "#{Regexp.escape(delimeters.join)}" + split_string
end
@values = @expr.split(/[#{split_string}]/).map(&:to_i)
@negatives = @values.select { |value| value < 0 }
if (@negatives && @negatives.any?)
raise "negatives not allowed: #{@negatives.join(', ')}"
end
end
end
</code></pre>
<p>I'm really unsatisfied with the test for Consecutive Delimiters. If anyone knows of a good way to make that test more flexible, I'd love to hear it.</p>
<p>Here are my specs:</p>
<pre class="lang-ruby prettyprint-override"><code>require 'spec_helper'
require 'calculatoradvanced'
describe Calculatoradvanced do
subject(:calc) { Calculatoradvanced.new(expression) }
context 'with an empty expression' do
let(:expression) { '' }
specify { expect { calc }.to_not raise_exception }
end
context 'with expression "1\n2\n3"' do
let(:expression) { "1\n2\n3" }
specify { expect { calc }.to_not raise_exception }
its(:add) { should eq(6) }
end
context 'with expression "2,3\n4"' do
let(:expression) { "2,3\n4" }
its(:add) { should eq(9) }
its(:expr) { should eq("2,3\n4") }
end
context 'with expression "1,\n2"' do
let(:expression) { "1,\n2" }
specify { expect { calc.add }.to raise_exception }
end
context 'with expression "1\n,2"' do
let(:expression) { "1\n,2" }
specify { expect { calc.add }.to raise_exception }
end
shared_examples_for 'expression validation' do
specify { expect { method }.to raise_exception(RuntimeError, /negatives not allowed/) }
specify { expect { method }.to raise_exception(RuntimeError, /-1, -2, -3/) }
end
context 'with expression "-1,-2\n-3"' do
let(:expression) { "-1,-2\n-3" }
context '.add' do
let(:method) { calc.add }
it_behaves_like 'expression validation'
end
context '.diff' do
let(:method) { calc.diff }
it_behaves_like 'expression validation'
end
context '.prod' do
let(:method) { calc.prod }
it_behaves_like 'expression validation'
end
end
context 'with expression "//[;]\n1;2"' do
let(:expression) { "//[;]\n1;2" }
its(:add) { should eq(3) }
end
context 'with expression "//[;]\n2;1"' do
let(:expression) { "//[;]\n2;1" }
its(:diff) { should eq(1) }
its(:prod) { should eq(2) }
end
context 'with expression "//[;]\n3;2"' do
let(:expression) { "//[;]\n3;2" }
its(:div) { should eq(1) }
end
context 'with expression "//[*][;]\n1*2;3"' do
let(:expression) { "//[*][;]\n1*2;3" }
its(:add) { should eq(6) }
its(:diff) { should eq(-4) }
its(:prod) { should eq(6) }
its(:div) { should eq(0) }
end
context 'with expression "//[*][;][#]\n5*4;3#2"' do
let(:expression) { "//[*][;][#]\n5*4;3#2" }
its(:diff) { should eq(-4) }
end
context 'with expression "//[#][;][*]\n1*2#3;4,5\n6"' do
let(:expression) { "//[#][;][*]\n1*2#3;4,5\n6" }
its(:add) { should eq(21) }
end
end
</code></pre>
|
[] |
[
{
"body": "<p>I am not going to re-write your code but give some pointers instead, I hope it's helpful:</p>\n\n<ul>\n<li>Those four methods (<code>add</code>, ...) do basically the same thing, why don't you abstract them?</li>\n<li><code>inject</code> accepts a symbol: <code>@values.inject(:+)</code></li>\n<li>split_string -> maybe this? <code>string.split(/[,$]/)</code></li>\n<li>Variable <code>delimeters</code> has three different values on the course of the method! Different values deserve different names.</li>\n<li><code>if @negatives</code>: That's an unnecessary check, <code>@negatives</code> is an array, so it will never be falsy (in Ruby: <code>nil</code>/<code>false</code>).</li>\n<li><code>@negatives.any?</code> If you are going to perform an <code>any?</code> operation, do it directly (with a block), don't do a <code>select</code> + <code>any?</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T17:14:51.037",
"Id": "57427",
"Score": "0",
"body": "thanks for the feedback. I'll try using the old `method_not_found` trick and then having a case statement for `add`, etc... I'm a bit prejudice against that pattern but ... this is just for fun so why not make sure I understand that pattern before rejecting it. Good catch on `inject()`. Re: `split_string`, it actually does need to be \"\\n\" and not \"$\". The newline character can occur multiple times in the string. `delimiters` is also an interesting case. I only want to final value so I'm stripping away unwanted characters in each line. I could try chaining the whole thing together ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T17:19:46.920",
"Id": "57429",
"Score": "0",
"body": "-- continued :) -- Re: @negatives, the reason I'm checking `@negatives && @negatives.any?` is that, if there are no negative numbers, `@negatives` will be nil. This will cause `@negatives.any?` to throw an error because `any?` isn't defined on the Nil class. Also, I'm using select to get an array of all negatives because I need to print all negative numbers in the exception. I hope that clarifies what I was thinking with the choices I've made. Please let me know if I'm missing something and there's a better way to satisfy the requirements. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T17:27:38.177",
"Id": "57431",
"Score": "0",
"body": "Re: Re: @negatives, you're right! `select` will return the empty array if it doesn't find anything so `@negatives.any?` is the only test that's needed there :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T18:20:41.960",
"Id": "57435",
"Score": "0",
"body": "please don't use `method_not_found`!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T18:48:40.410",
"Id": "57439",
"Score": "0",
"body": "lulz ... I know, I felt dirty doing it ;) What would you suggest to get the same effect (i.e. a case statement that maps the method to a symbol to pass to `inject`)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T19:47:55.707",
"Id": "57448",
"Score": "0",
"body": "You can use `define_method`, but I am not also a big fan of it. On second thought, it's 4 methods, i guess it's no big deal to have separate code..."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T11:18:37.580",
"Id": "35431",
"ParentId": "35372",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "35431",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T18:21:01.920",
"Id": "35372",
"Score": "2",
"Tags": [
"ruby",
"calculator",
"math-expression-eval",
"rspec"
],
"Title": "Advanced Calculator Kata"
}
|
35372
|
<p>I'm a mediocre programmer at best and am pretty terrible at JavaScript. But I have been tasked with creating a Google Maps application. This application is driven by a dynamic report with a Java layer on top of it. This Java layer spits out generated Google API JavaScript. </p>
<p>The problem I am running into is that I am attempting to plot a huge number of markers. I am already investigating how to set the markers map to null using AJAX. But I am wondering if someone could look at this code and tell me if anything is redundant. When my application is not restricted it could easily spit out 1000 of each of these blocks, which results in a ton of JavaScript. </p>
<p>Below is a sample run of my code:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>txtMark</title>
<style>
#map-canvas {
height: 500px;
width: 500px;
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var txtMark = {};
var circles = {};
var balloons = {};
var highPin = 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|008000';
var lowPin = 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FFFF00';
var medPin = 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FE7569';
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(38.873555, -77.295380),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
circles[0] = {
center: new google.maps.LatLng(38.873555, -77.295380),
id: 0,
addr: '00601',
r: 16093.4,
txt: '00601: Claims With Labor:322',
color: '#FE7569'
};
balloons[0] = {
center: new google.maps.LatLng(38.873555, -77.295380),
id: 0,
pin: lowPin,
addr: '00601',
txt: '00601: Claims With Part And Labor:139'
};
txtMark[0] = {
center: new google.maps.LatLng(38.873555, -77.295380),
id: 0,
style: 'FE7569',
addr: '139',
txt: '00601: Claims With Part Only:139'
};
var tInfo = new google.maps.InfoWindow();
for (i in txtMark) {
var tMark = new MarkerWithLabel({
position: txtMark[i].center,
map: map,
labelClass: "labels",
labelStyle: {
color: txtMark[i].style
},
labelContent: txtMark[i].addr,
icon: {}
});
google.maps.event.addListener(tMark, 'click', (function (tMark, i) {
return function () {
if (tInfo) {
infoWindow.close();
tInfo.close();
bInfo.close();
}
tInfo.setContent(txtMark[i].txt);
tInfo.setPosition(txtMark[i].center);
tInfo.open(map);
}
})(tMark, i));
}
var bMarker;
var bInfo = new google.maps.InfoWindow();
for (i in balloons) {
var balloonOptions = {
map: map,
id: balloons[i].id,
position: balloons[i].center,
icon: balloons[i].pin,
infoWindowIndex: i
};
bMarker = new google.maps.Marker(balloonOptions);
google.maps.event.addListener(bMarker, 'click', (function (bMarker, i) {
return function () {
if (bInfo) {
infoWindow.close();
tInfo.close();
bInfo.close();
}
bInfo.setContent(balloons[i].txt);
bInfo.setPosition(balloons[i].center);
bInfo.open(map);
}
})(bMarker, i));
}
var cityCircle;
var infoWindow = new google.maps.InfoWindow();
for (i in circles) {
var magnitudeOptions = {
strokeColor: circles[i].color,
fillColor: circles[i].color,
map: map,
center: circles[i].center,
radius: circles[i].r,
id: circles[i].id,
addr: circles[i].addr,
infoWindowIndex: i
};
cityCircle = new google.maps.Circle(magnitudeOptions);
google.maps.event.addListener(cityCircle, 'click', (function (cityCircle, i) {
return function () {
if (infoWindow) {
infoWindow.close();
tInfo.close();
bInfo.close();
}
infoWindow.setContent(circles[i].txt);
infoWindow.setPosition(cityCircle.getCenter());
infoWindow.open(map);
}
})(cityCircle, i));
}
}
google.maps.event.addDomListener(window, 'load', initialize)
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T21:09:09.087",
"Id": "57329",
"Score": "0",
"body": "To clarify… you expect that sometimes there may be `circles[0]`, `circles[1]`, … `circles[999]` as well as many `balloons[]` and `txtMark[]`? Do the `balloons[]` and `txtMark[]` always coincide in location?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T21:11:59.650",
"Id": "57331",
"Score": "0",
"body": "There will always be the same number of circles, balloons, and txtMark. They are related as in they are plotted on the same lat/long. But dont necessarily have anything in common besides that. But yes there may be cirles[999], balloons[999], txtMark[999], and even a polygon[999] once I get the data. I know its a huge amount of markers and I am working to make some enhancements with ajax calls to reduce plotted points that arent in view."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T21:14:04.167",
"Id": "57332",
"Score": "0",
"body": "But in your example, `circles[0]` is not in the same location as `balloons[0]` and `txtMark[0]`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T21:19:32.537",
"Id": "57335",
"Score": "0",
"body": "Oh I am sorry. I changed it to test something else out. Let me fix that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T15:23:58.630",
"Id": "57418",
"Score": "0",
"body": "Any suggestions?"
}
] |
[
{
"body": "<p>I can't really speak to performance issues, since there are too many unknowns. E.g. oes the user need 1000+ locations all at once? What is acceptable performance?<br>\nI will say that simply loading everything (<em>and</em> the kitchen sink) and plotting it all seems pretty inelegant. But coming up with a smarter solution would require knowledge of your problem domain.</p>\n\n<p>But I'll speak to the code a bit. First some basic JS remarks:</p>\n\n<ol>\n<li>Use an IIFE to isolate your code from the global scope. Right now, all your variables are global.</li>\n<li>Use arrays. You're using objects, and iterating with <code>for...in</code>, which is - I'm sorry to say - plain wrong for what you're trying to achieve</li>\n</ol>\n\n<p>As for structure: Judging by your exchange with 200_success in the comments, you will have <em>N</em> number of locations (lat/lng positions), and each of those will have a circle, a label and a balloon.</p>\n\n<p>In that case, use objects to encapsulate all that. Then take those objects, and stick those in a (proper) array. Right now, you're duplicating data across those three things, and you're \"manually\" tracking 3 different \"arrays\" that aren't really arrays. </p>\n\n<p>Here's the object structure I'd propose (I'll clean it up futher in a bit)</p>\n\n<pre><code>var locations = [ // an array!\n {\n id: 0, // I'm assuming the ID is tied to the lat/lng; not the individual circles/labels/balloons\n position: new google.maps.LatLng(38.873555, -77.295380),\n circle: {\n addr: '00601',\n r: 16093.4,\n txt: '00601: Claims With Labor:322',\n color: '#FE7569'\n },\n balloon: {\n pin: lowPin,\n addr: '00601',\n txt: '00601: Claims With Part And Labor:139'\n },\n txtMark: {\n style: 'FE7569',\n addr: '139',\n txt: '00601: Claims With Part Only:139'\n }\n },\n // more location objects here ...\n];\n</code></pre>\n\n<p>Now <code>locations[0]</code> will be an object containing everything to do with that particular point on the globe.</p>\n\n<p>But while we're at it, I highly suggest using different names for the \"items\": <code>circle</code>, <code>balloon</code> and <code>txtMark</code> do not describe the data, but their presentation. And that's a separate concern right now. Name data for <em>what</em> they represent, not <em>how</em> they are represented.</p>\n\n<p>I'll stick with your names for this, though, as I don't know what these things should rightly be called (though <code>partOnly</code>, <code>laborOnly</code> and <code>partAndLabor</code> seem like obvious candidates).</p>\n\n<p>Looking at the above, there's more repetition we can probably get rid of in the data objects.</p>\n\n<pre><code>{\n id: 0,\n position: new google.maps.LatLng(38.873555, -77.295380),\n address: '00601',\n style: 'A',\n circle: {\n radius: 16093.4,\n text: '00601: Claims With Labor:322'\n },\n balloon: {\n text: '00601: Claims With Part And Labor:139'\n },\n label: {\n text: '00601: Claims With Part Only:139'\n }\n}\n</code></pre>\n\n<p>I've cleaned up some names, but I'm also making some assumptions here:</p>\n\n<ol>\n<li><code>addr</code> is the same for all 3 even though your code has <code>139</code> as the <code>txtMark</code>'s address. Again, your conversation with 200_success makes me think this might be a typo.</li>\n<li>The \"style\" is the same for all things at one location. I.e. a circle color <code>#FE7569</code> implies a <code>lowPin</code> implies a <code>FE7569</code>-style label. Here, I've just called that style \"A\" (come up with a better name) and made it common to all 3.</li>\n</ol>\n\n<p>For the styles, I'd make a single object, like so:</p>\n\n<pre><code>var styles = {\n A: {\n color: \"#FE7569\",\n pin: \"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FFFF00\"\n },\n B: {\n color: ...\n pin: ...\n },\n // etc.\n}\n</code></pre>\n\n<p>So that's the data set, now for the logic. Instead of looping through 3 different objects, you now only have to loop though 1 array, so:</p>\n\n<pre><code>var i, l, location, style, label, circle, balloon,\n infoWindow = new google.maps.InfoWindow(); // you only need 1 window!\n\n// I'm leaving the map initilization out of it; just assume there's a `map` variable\n\n// generalized click handler\nfunction addClickHandler(item, content, position) {\n google.maps.event.addListener(item, 'click', function () {\n infoWindow.close();\n infoWindow.setContent(content);\n infoWindow.setPosition(position);\n infoWindow.open(map);\n });\n}\n\n// functions to add the items to the map\n\nfunction addCircle(location, style) {\n var circle = new google.maps.Circle({\n map: map,\n center: location.position,\n radius: location.circle.radius,\n strokeColor: style.color,\n fillColor: style.color,\n addr: location.address // do you actually need this for anything?\n });\n addClickHandler(circle, location.circle.text, location.position);\n}\n\nfunction addLabel(location, style) {\n var label = new MarkerWithLabel({\n map: map,\n position: location.position,\n labelClass: \"labels\",\n labelStyle: { color: style.color },\n labelContent: location.address,\n icon: null // I'm assuming you can just do this to avoid a default icon\n });\n addClickHandler(label, location.label.text, location.position);\n}\n\nfunction addBalloon(location, style) {\n var balloon = new google.maps.Marker({\n map: map,\n position: location.position,\n icon: style.pin\n });\n addClickHandler(balloon, location.balloon.text, location.position);\n}\n\n// loop through the array\nfor( i = 0, l = locations.length ; i < l ; i++ ) {\n location = locations[i];\n style = styles[location.style];\n addCircle(location, style);\n addLabel(location, style);\n addBalloon(location, style);\n}\n</code></pre>\n\n<p>It's not perfect, but it's better. I haven't tested it it though, but the point is really about structure, and the structure should be ok</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-18T17:31:23.493",
"Id": "57810",
"Score": "0",
"body": "Hey I really appreciate you taking the time to outline the options and clearly explain them. As you can tell I am not much of a javascript programer. I will look into each of the options you have outlined."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T12:54:13.893",
"Id": "35480",
"ParentId": "35374",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "35480",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T18:45:42.143",
"Id": "35374",
"Score": "0",
"Tags": [
"javascript",
"beginner",
"serialization",
"google-maps"
],
"Title": "Generating redundant data for Google Maps markers"
}
|
35374
|
<p><a href="http://wordpress.org/about/" rel="nofollow">http://wordpress.org/about/</a></p>
<p>WordPress is a blogging platform most commonly used with PHP and MySQL</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T19:05:39.560",
"Id": "35376",
"Score": "0",
"Tags": null,
"Title": null
}
|
35376
|
WordPress is a free and open source blogging tool and a content-management system (CMS) based on PHP and MySQL.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T19:05:39.560",
"Id": "35377",
"Score": "0",
"Tags": null,
"Title": null
}
|
35377
|
<p>I have a “featured projects” view that requires its subviews conform to a non-uniform grid: one narrow column with 3 items, then one wide column with 2 items, followed by another narrow column with 3 items. The width that is used for each subview is determined by the model’s <code>display</code> attribute. If there are any extra items in the collection, they are disregarded for the purposes of this view.</p>
<p>Here's the relevant portion of the code:</p>
<pre><code>class App.Views.FeaturedProjects extends Backbone.View
el: '#featured'
template: '<div class="column"></div>'
initialize: ->
...
@collection.on 'reset', @addAll, this
addOne: (item, el) =>
view = new App.Views.Project model: item
el.append view.render().el
addAll: ->
# … clear out existing subviews, then …
# separate collection into wide & narrow
narrow = @collection.where display: 'narrow'
wide = @collection.where display: 'wide'
# only display the grid if there are enough items to fill it
if narrow.length >= 6 and wide.length >= 2
column1 = $(@template).addClass('column-narrow')
column2 = $(@template).addClass('column-wide')
column3 = $(@template).addClass('column-narrow')
# 3 narrow / 2 wide / 3 narrow
@addOne(item, column1) for item in narrow[0..2]
@addOne(item, column2) for item in wide[0..1]
@addOne(item, column3) for item in narrow[3..5]
@$el.append(column1).append(column2).append(column3)
</code></pre>
<p>My current approach works, but is there a better way of handling something like this?</p>
<p><strong>EDIT</strong></p>
<p>I took Marco's suggestions a bit further and ended up with the following:</p>
<pre><code>class App.Views.FeaturedProjects extends Backbone.View
columnTemplate: '<div class="column"></div>'
defaults: ->
columns: [
{ type: 'narrow', itemsPer: 3 }
{ type: 'wide', itemsPer: 2 }
{ type: 'narrow', itemsPer: 3 }
]
initialize: (options) ->
@options = _.extend({}, @defaults(), options)
...
@collection.on 'reset', @addAll, this
addAll: ->
# … clear out existing subviews, then …
items = {}
valid = true
# get unique column types
uniqueColTypes = _.uniq _.pluck @options.columns, 'type'
# separate collection by column type and verify there are enough items of each type
for type in uniqueColTypes
items[type] = @collection.where display: type
valid = false if items[type].length < @minItems type
# display the grid
if valid
for column in @options.columns
columnHtml = $(@columnTemplate).addClass "column-#{column.type}"
itemsPer = column.itemsPer
@addOne items[column.type].shift(), columnHtml while itemsPer--
@$el.append(columnHtml)
# returns number of items with specified column type required to fill the grid
minItems: (type) ->
minItems = 0
minItems += col.itemsPer for col in _.where @options.columns, {type: type}
return minItems
</code></pre>
|
[] |
[
{
"body": "<p>This looks pretty good. My main suggestion for improvement would be we how you set and create the columns. I would try and make this more dynamic so the amount of columns can more easily change, and can be set from code using this view. </p>\n\n<p>To do this I'd create an array to represent the columns. Each column would have information about whether its narrow, or wide and then how many items it should have in it:</p>\n\n<pre><code>columns = [{type: 'narrow', itemsPer: 3}, {type: 'wide', itemsPer: 2}, \n {type: 'narrow', itemsPer: 3}]\n</code></pre>\n\n<p>And then process the array rather then have variables named for each column. This would also add the items to the columns so it can be done it one loop. I used \"shift\" to remove the first element of the array so the narrow collection could be used without referencing exact indexes, which would allow it to work for any amount of items per column. I also changed the structure of the narrow and wide variables so they are properties on a items object, which makes the referenced with the same column.type name. </p>\n\n<pre><code>items[narrow] = @collection.where display: 'narrow'\nitems[wide] = @collection.where display: 'wide' \n\nif narrow.length >= 6 and wide.length >= 2\n for column in columns \n columnHtml = $(@template).addClass('column-' + column.type)\n for i in range(column.itemsPer)\n @addOne(items[column.type].shift(), columnHtml)\n\n @$el.append(columnHtml)\n</code></pre>\n\n<p>Another thing, I found the template property to be confusing, because it was the template for each of the three columns where I expected it to be the template for the whole view (which would only be created once). I suggest naming it to something like \"columnTemplate\" </p>\n\n<pre><code>columnTemplate: '<div class=\"column\"></div>',\n</code></pre>\n\n<p>My code examples are in pseudo code, as I'm less familiar with CoffeeScript, but I think you can understand generally what I'm saying.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-18T18:12:48.137",
"Id": "35615",
"ParentId": "35378",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "35615",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T19:56:38.930",
"Id": "35378",
"Score": "2",
"Tags": [
"javascript",
"coffeescript",
"backbone.js"
],
"Title": "Backbone subviews with non-uniform layout"
}
|
35378
|
<p>dapper is a micro-ORM, offering core parameterization and materialization services, but (by design) not the full breadth of services that you might expect in a full ORM such as LINQ-to-SQL or Entity Framework. Instead, it focuses on making the materialization <em>as fast as possible</em>, with no overheads from things like identity managers - just "run this query and give me the (typed) data".</p>
<p>However, it retains support for materializing non-trivial data structures, with both horizontal (joined data in a single grid) and vertical (multiple grids) processing.</p>
<p>Quite possibly the fastest materializer available for .NET, and available here: <a href="http://code.google.com/p/dapper-dot-net/" rel="nofollow">code.google.com/p/dapper-dot-net/</a></p>
<h3>Getting Started with Dapper</h3>
<p>Dapper comprises of a single file, it lives on Google code: <a href="http://code.google.com/p/dapper-dot-net/source/browse/Dapper/SqlMapper.cs" rel="nofollow">SqlMapper.cs</a>. You can either include the file, as is, in your project. Or install it via <a href="http://stackoverflow.com/tags/nuget/info">nuget</a>. </p>
<p>Here is a <a href="http://www.youtube.com/watch?v=lT3QrMykGUY" rel="nofollow">video</a> with a simple example.</p>
<h3>A simple Hello World sample</h3>
<pre><code>using Dapper;
//...
using (var connection = new SqlConnection(myConnectionString))
{
connection.Open();
var posts = connection.Query<Post>("select * from Posts");
//... do stuff with posts
}
</code></pre>
<h3>CRUD operation</h3>
<p>Dapper provides a minimal interface between your database and your application. Even though the interface is minimal it still supports the full array of database operations. Create, Read, Update, Delete are fully supported. Using stored procedures or not. </p>
<p>See also: </p>
<ul>
<li><a href="http://stackoverflow.com/questions/5957774/performing-inserts-and-updates-with-dapper">http://stackoverflow.com/questions/5957774/performing-inserts-and-updates-with-dapper</a></li>
<li><a href="http://stackoverflow.com/questions/6387904/how-to-insert-an-ienumerablet-collection-with-dapper-dot-net">http://stackoverflow.com/questions/6387904/how-to-insert-an-ienumerablet-collection-with-dapper-dot-net</a></li>
<li><a href="http://stackoverflow.com/questions/5962117/is-there-any-way-using-dapper-with-sql-stored-procedure/5971847#5971847">http://stackoverflow.com/questions/5962117/is-there-any-way-using-dapper-with-sql-stored-procedure/5971847#5971847</a></li>
</ul>
<h3>The Multi Mapper</h3>
<p>Dapper allows you to automatically split a single row to multiple objects. This comes in handy when you need to join tables. </p>
<p>See also: </p>
<ul>
<li><a href="http://stackoverflow.com/questions/6001508/cant-get-multi-mapping-to-work-in-dapper">http://stackoverflow.com/questions/6001508/cant-get-multi-mapping-to-work-in-dapper</a></li>
<li><a href="http://stackoverflow.com/questions/7078478/dapper-multi-mapping-flat-sql-return-to-nested-objects">http://stackoverflow.com/questions/7078478/dapper-multi-mapping-flat-sql-return-to-nested-objects</a></li>
<li><a href="http://stackoverflow.com/questions/6146918/how-do-i-selecting-an-aggregate-object-efficiently-using-dapper">http://stackoverflow.com/questions/6146918/how-do-i-selecting-an-aggregate-object-efficiently-using-dapper</a></li>
</ul>
<h3>Performance</h3>
<p>A key feature of Dapper is performance. You can go through the performance of SELECT mapping over 500 iterations at <a href="https://github.com/SamSaffron/dapper-dot-net#performance-of-select-mapping-over-500-iterations---poco-serialization" rel="nofollow">this</a> link.</p>
<h3>.NET Framework support</h3>
<p>Dapper runs best on .NET 4.0 or later. It makes use of Dynamic features in the language and optional params. You can run Dapper on .NET 3.5 as well. There are no known ports that avoid dynamic method generation. There are no known ports to .NET 2.0. </p>
<p>Dapper also <a href="http://stackoverflow.com/questions/7934757/does-dapper-work-on-mono">works fine</a> in Mono</p>
<h3>Nuget package</h3>
<p>Dapper can most easily be installed through its <a href="http://www.nuget.org/packages/Dapper/" rel="nofollow">NuGet package</a>.</p>
<pre><code>Install-Package Dapper
</code></pre>
<h3>Extensions</h3>
<p>The Dapper solution includes the following extensions:</p>
<ul>
<li><strong>Dapper.Rainbow</strong></li>
<li><strong>Dapper.Contrib</strong></li>
<li><strong>Dapper.SqlBuilder</strong></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T19:56:46.540",
"Id": "35379",
"Score": "0",
"Tags": null,
"Title": null
}
|
35379
|
dapper is the micro-ORM for .NET developed and used by the stackoverflow team, focusing on raw performance as the primary aim.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T19:56:46.540",
"Id": "35380",
"Score": "0",
"Tags": null,
"Title": null
}
|
35380
|
<p>I'm trying to convert an <code>std::string</code> to an <code>int</code> with a default value if the conversion fails. C's <code>atoi()</code> is way too forgiving and I've found that <code>boost::lexical_cast</code> is quite slow in the case where the cast fails. I imagine it's because an exception is raised. I don't have C++11, so <code>stoi()</code> is out.</p>
<p>The Delphi function <code>StrToIntDef</code> is the ideal, and it's also available in C-Builder (where I'm working currently). But I want something more portable that works with <code>std::string</code>. </p>
<p>I've created the following function, which uses <code>atoi()</code> but first tests for error conditions. It also allows for leading and trailing spaces, which are harmless in my situation.</p>
<pre><code>int stringtoIntDef(const std::string & sValue, const int & DefaultValue) {
// convert a std::string to integer with a default value returned
// in the case where the string doesn't represent a valid integer
// - accepts leading or trailing spaces as valid
bool hasDigits = false;
bool TrailingSpace = false;
for (std::string::size_type k = 0; k < sValue.size(); ++k) {
if ((sValue[k] == ' ') || (sValue[k] == '\t')) {
TrailingSpace = hasDigits;
} else if ((sValue[k] == '0') || (sValue[k] == '1') || (sValue[k] == '2') || (sValue[k] == '3') ||
(sValue[k] == '4') || (sValue[k] == '5') || (sValue[k] == '6') || (sValue[k] == '7') ||
(sValue[k] == '8') || (sValue[k] == '9')) {
if (TrailingSpace) {
return DefaultValue;
} else {
hasDigits = true;
}
} else if ((sValue[k] == '-') && !hasDigits) {
hasDigits = true; // this protects against "--"
} else {
return DefaultValue;
}
}
return atoi(sValue.c_str());
}
</code></pre>
<p>In my testing, I've compared it against <code>StrToIntDef</code> and it is just as fast, but <code>lexical_cast</code> is much slower in the case where the default is returned. For 1000 iterations, <code>lexical_cast</code> took 5 seconds while the other 2 weren't measurable.</p>
<p>For my <code>lexical_cast</code> function, I've used this:</p>
<pre><code>try {
return boost::lexical_cast<int>(sValue);
}
catch (boost::bad_lexical_cast &) {
return DefaultValue;
}
</code></pre>
<p>Are there any gotchas I might have missed here?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T16:45:14.977",
"Id": "57424",
"Score": "1",
"body": "Hi, regarding [this suggested edit](http://codereview.stackexchange.com/review/suggested-edits/14356), feel free to add your *bullet-proof* solution as another answer - editing others' content is fine, but not for commenting and/or appending to their posts."
}
] |
[
{
"body": "<p>There's a few things that jump out at me both in your implementation and standard options you missed. A few (scattered) thoughts follow.</p>\n\n<hr>\n\n<p>Returning a default if you care about error checking doesn't make sense. How would you determine if conversion failed if there's not an integer available for use as a sentinel? You are basically doing the same thing <code>atoi</code> does except your default is flexible instead of <code>0</code>.</p>\n\n<hr>\n\n<p>Have you considered [<code>strtol</code>][1]? It's basically <code>atoi</code> with error checking capabilities. It's the fastest string to int converter you're likely going to get:</p>\n\n<pre><code>long string_to_long(const std::string& str, long default_value, int base = 10) {\n char* parse_end = NULL; //nullptr if C++11, though really you don't have to initialize this\n //since strol is guaranteed to initialize it. I just like to avoid\n //unitialized variables.\n long val = strtol(str.c_str(), &parse_end, base);\n if (parse_end == str.c_str() + str.size()) {\n return val;\n } else {\n return default_value;\n }\n}\n</code></pre>\n\n<p><strong>Note:</strong> <code>strtol</code> ignores leading whitespace. The function I've written above errors for trailing whitespace (or trailing anything). In other words, <code>\" 3\"</code> is fine, but <code>\"3 \"</code> would error.</p>\n\n<hr>\n\n<p>The idiomatic way to do this in C++ would be to use a string stream:</p>\n\n<pre><code>int string_to_int(const std::string& str, int def)\n{\n std::istringstream ss(str);\n int i;\n if (!(ss >> std::noskipws >> i)) {\n //Extracting an int failed\n return def;\n }\n char c;\n if (ss >> c) {\n //There was something after the int\n return def;\n }\n return i;\n}\n</code></pre>\n\n<p>In terms of performance, <code>strtol</code> will likely be faster than this. This does have a useful advantage though that it can be made highly generic with simple templating (this is the essential idea behind <code>boost::lexical_cast</code> actually, but this doesn't use exceptions):</p>\n\n<pre><code>template<typename ResultType>\nResultType lexical_cast(const std::string& str, const ResultType& default_value = ResultType()) {\n std::istringstream ss(str);\n ResultType result;\n if (!(ss >> std::noskipws >> result)) {\n return default_value;\n }\n char c;\n if (ss >> c) {\n return default_value;\n }\n return result;\n}\n</code></pre>\n\n<hr>\n\n<p>If you don't want to use exceptions, but you want to be able to detect errors, you're going to have to use a flag. You basically have two options of how to handle that. You can use a boolean flag and return the value, or you can use a boolean reference parameter and return the value. Which route you take really depends on how you want to use the code, but I would probably return the value. That lets you ignore errors if you want to, but it still doesn't force you to. I might do something like this:</p>\n\n<pre><code>template<typename ResultType>\nResultType lexical_cast(const std::string& str, bool& success) {\n std::istringstream ss(str);\n ResultType result;\n success = true;\n if (!(ss >> std::noskipws >> result)) {\n success = false;\n }\n char c;\n if (ss >> c) {\n success = false;\n }\n return result;\n}\n\ntemplate<typename ResultType>\nResultType lexical_cast(const std::string& str) {\n bool ignore;\n return lexical_cast<ResultType>(str, ignore);\n}\n</code></pre>\n\n<p>This gives you both options of detecting an error or ignoring one. You could even build more on top of this to have one that returns a default value:</p>\n\n<pre><code>template<typename ResultType>\nResultType lexical_cast(const std::string& str, const ResultType& default_value = ResultType()) {\n bool success;\n ResultType val(lexical_cast<ResultType>(str, ignore));\n if (success) {\n return val;\n } else {\n return default_value;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Don't check for classes of characters manually. Just use the <code>cctype</code> header's functions (<code>isspace</code>, <code>isdigit</code>, etc).</p>\n\n<hr>\n\n<p>You loop is way over complicated:</p>\n\n<pre><code>bool all_digit = true;\nfor (std::string::size_type i = 0, l = str.size(); i < l; ++i) {\n if (!std::isdigit(str[i])) { \n all_digit = false;\n break;\n }\n}\n\nif (all_digit) { ... }\n</code></pre>\n\n<p>Or, allowing leading/trailing whitespace:</p>\n\n<pre><code>std::string::size_t i = 0;\nconst std::string::size_t len = str.size();\nfor (; i < len && std::isspace(str[i]); ++i) { /* empty */ }\nfor (; i < len && std::isdigit(str[i]); ++i) { /* empty */ }\nfor (; i < len && std::isspace(str[i]); ++i) { /* empty */ }\nconst bool all_digits = (i == len);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T04:16:07.950",
"Id": "57357",
"Score": "0",
"body": "my loop is more complicated because its doing more. Your method doesn't handle leading and trailing spaces and it doesn't handle negatives. But I like the isdigit shortcut. strtol is more promising. I have included another version of the function in a separate answer using strtol."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T04:28:05.327",
"Id": "57358",
"Score": "0",
"body": "Thanks @Corbin, While I was writing my response you were editing your answer... The strtol based function is excellent. I came up with something similar. It doesn't work for trailing whitespace, but it handles overflow (or can). Performance wise its the same as mine and IntToStrDef. Only after a million iterations can I see a difference and then the Pascal function is still fastest! My version doesn't handle overflow, I noticed. And IntToStrDef doesn't handle trailing whitespace either. Historically it did."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T04:35:56.627",
"Id": "57359",
"Score": "0",
"body": "Regarding the use of a default return value, its very useful as a flag depending on the known context. My main use for it though is to prepare data for entry in a database. My database stores dummy values in integer channels as -2147483647, so I use that as the default and store invalid data as Dummies."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T05:11:56.753",
"Id": "57360",
"Score": "0",
"body": "@marcp Seems i misunderstood your function's functionality. I had assumed that leading and trailing whitespace were not considered valid components of integers. In particular, I assumed only 1 or more digits were valid. All of my example functions follow that logic. I will add a snippet to check for just digits or leading/trailing whitespace. Is trailing whitespace valid or not, by the way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T05:14:54.033",
"Id": "57361",
"Score": "0",
"body": "@marcp It sounds like that where you're storing -2^31 you might should be storing null. That sounds like a bit of an abuse of an integer field (hard to say without more context though). In your particular instance, a non-valid value might exist, but in the general case, it's not safe to assume (and CR is all about the general case :)). At the end of the day though, whatever works works. I would probably still go the route of implementing a defaulting one in terms of an error checking one though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T16:11:52.360",
"Id": "57420",
"Score": "0",
"body": "I've added a final bulletproof version of the function to your answer. Thanks for the illumination!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T00:29:06.080",
"Id": "35393",
"ParentId": "35388",
"Score": "8"
}
},
{
"body": "<p>As per @retailcoder's suggestion I'm adding the bulletproof version as a separate answer rather than edit @Corbin's answer.</p>\n\n<p>This function meets all the requirements and is quite a bit cleaner than my original. It is based on @Corbin's final suggestions.</p>\n\n<pre><code>int stringtoIntDef(const std::string & str, const int & DefaultValue) {\n int result = DefaultValue;\n std::size_t i = 0;\n const std::size_t len = str.size();\n for (; i < len && std::isspace(str[i]); ++i) { /* leading space */}\n if (str[i]=='-') ++i; /* allow negative symbol */\n if (i==len) { return result; } /* no digits */\n for (; i < len && std::isdigit(str[i]); ++i) { /* digits */}\n for (; i < len && std::isspace(str[i]); ++i) { /* trailing space */}\n if (i == len) {\n errno = 0;\n const char *s = str.c_str();\n char * p;\n result = strtol(s, &p, 0);\n if (errno != 0) {\n result = DefaultValue;\n }\n }\n return result;\n}\n</code></pre>\n\n<p>Interestingly it remains a fair bit slower than the Delphi function. Some sample results using GetTickCount(), which has a granularity of about 16, and 1 million iterations:</p>\n\n<pre><code> str time ok str time ok str time ok str time ok str time ok str time ok\nDelphi -25 0 yes 12 16 yes box 15 yes \" \" 15 yes inf 16 yes \"2 \" 16 no\nMy original -25 140 yes 12 109 yes box 31 yes \" \" 109 no inf 375 no \"2 \" 78 yes\nFinal -25 250 yes 12 234 yes box 93 yes \" \" 63 yes inf 561 yes \"2 \" 249 yes\n</code></pre>\n\n<p>where inf is some number large enough to cause overflow.</p>\n\n<p>Admittedly none of those times is very big for 1 million of anything. I just think its interesting that the Delphi function is SO efficient.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T17:31:30.877",
"Id": "57432",
"Score": "0",
"body": "Glad to see you managed to extract some use out of my incoherent ramblings :). As for the performance difference.... That's not surprising. The direct conversion function only requires one linear scan as it validates while it converts. This one requires two since it does validation then passes it to strtol for another linear pass. I would essentially expect this to take twice the speed in the typical case of a valid number."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T17:32:06.677",
"Id": "57433",
"Score": "0",
"body": "If you were willing to disallow trailing space (as Delphi does) then you could actually use strtol directly and save a pass (you would have to explicitly use base 10 to strtol or it would allow octal/hex)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T17:03:18.503",
"Id": "35440",
"ParentId": "35388",
"Score": "3"
}
},
{
"body": "<p>Based on @Corbin's last comment I've created another version that seems to be a bit faster and cleaner. I just strip any whitespace off the end before calling strtol. It also has the benefit of handling numbers with a different base, if I want it to.</p>\n\n<pre><code>int stringtoIntDef(const std::string & str, const int & DefaultValue) {\n // this function was developed iteratively on Codereview.stackexchange\n // with the assistance of @Corbin\n std::size_t len = str.size();\n while (std::isspace(str[len-1]))\n len--;\n if (len==0) return DefaultValue; \n errno = 0;\n char *s = new char[len + 1];\n std::strncpy(s, str.c_str(), len);\n char * p;\n int result = strtol(s, &p, 0);\n if ((*p!= '\\0') || (errno != 0)) {\n return DefaultValue;\n }\n delete s;\n return result;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T18:24:21.370",
"Id": "35444",
"ParentId": "35388",
"Score": "0"
}
},
{
"body": "<p>This is a follow up to your <a href=\"https://codereview.stackexchange.com/a/35444/7308\">second follow up</a>. I just have a few comments, and you have two bugs.</p>\n\n<ul>\n<li><code>stringtoIntDef</code> is a strange name. In particular, why are <code>Int</code> and <code>Def</code> capitalized but not <code>To</code>? I would go either full camelCase, or I would use the standard library convention of under_scores.</li>\n<li>You never <code>delete[]</code> <code>s</code> which means you have a memory leak.</li>\n<li>I actually meant in my comment that you could check the end pointer from <code>strtol</code> to see if all that follows is either nothing or 0. I should have been more specific. An example of this is below.</li>\n<li>If <code>cstdlib</code> was included (as it should be) rather than <code>stdlib.h</code>, then <code>strtol</code> needs to be <code>std::strtol</code>. The <code>cheader</code>-style headers guarantee declarations in the <code>std</code> namespace, but they do not guarantee declarations in the global namespace. (Every C++ implementation I've ever seen does both, but they not required to do the global namespace.)</li>\n<li>Define variables as late as possible. In other words, declare <code>result</code> when you're defining it to be <code>strtol</code>'s return value.</li>\n<li>If you don't want a variable to change after its initial value, make it <code>const</code>. This keeps you from accidentally changing the value, and it makes your intentions more clear to anyone who inherits the code.</li>\n<li>You must provide a base of 10 to strtol, not 0. 0 is the default and it means to try to parse a number as base 10 unless it's prefixed with either 0x (for hex) or 0 (for octal). Assuming you want just decimal, it <em>must</em> be 10.</li>\n<li>If you do want the default behavior, don't put the 0. Just let it default to 0. Default behavior and and an empty default value have a nice symmetry to them, and it allows for future change of what the default sentinel value is without breaking consuming code.</li>\n<li>Since it's never modified anywhere, <code>str</code> should be passed by constant reference, not reference.</li>\n<li>If you were going to copy the string (<em>don't!</em> memory allocation is both unnecessary here and is very slow compared to the rest of the operations we're using), I would take the string by value and modify the parameter. That would allow for moving in C++11, and it would conveniently handle the memory allocation for you. The (potentially major) downside to this approach would be that obviously invalid strings could cause a rather large copy. Imagine if you passed a string of pure whitespace. All that whitespace would be copied for nothing other than to get immediately removed.</li>\n<li>We both missed the case of an empty string. <code>strtol</code> output can be used to detect it (<code>begp == endp</code>), but neither of us checked for that :).</li>\n</ul>\n\n<hr>\n\n<p>I still disagree with your decision to hide the ability to check for errors, but if that's the route you want to take, I would do something like this:</p>\n\n<pre><code>int string_to_int(const std::string& str, const int& DefaultValue) {\n errno = 0;\n\n const char* str_beg = str.c_str();\n const char* str_end = str_beg + str.size();\n char* p = NULL;\n\n const int result = std::strtol(str.c_str(), &p, 10);\n\n if (p == str_beg) { return DefaultValue; }\n\n for (; p != str_end && std::isspace(*p); ++p) { /* eat trailing spaces */}\n\n if (p != str_end || errno != 0) {\n return DefaultValue;\n }\n\n return result;\n}\n</code></pre>\n\n<p>(This could probably be optimized quite a bit, but it would likely be compiler/system specific, and it would be tedious.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T22:37:19.940",
"Id": "57460",
"Score": "0",
"body": "Hello @Corbin, thanks for sticking with me! Regarding the name: stringtoIntDef was stringToIntDef to contrast with the Delphi function StrToIntDef because it uses strings as opposed to VCL Strings, but got mangled along the way. Your method of swallowing the trailing spaces is more elegant and doesn't require the copy (ie faster), BUT it fails on a string of spaces. Not sure how to remedy that. I've added a test for zero length after stepping backwards which fixes my null string problem, and made some of your other suggested edits."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T22:39:13.417",
"Id": "57461",
"Score": "0",
"body": "I don't understand your comment about cstdlib, if strtol is defined as part of stdlib, which is always included (in C++Builder, anyway) why would I insist on using the STL version? Are they different somehow?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T22:49:36.350",
"Id": "57462",
"Score": "0",
"body": "Back to the default value 'discussion', when I return iDUMMY (-2^31) I am in fact putting a NULL into the database, that's what the DB engine uses in this case. If I want to capture the error I just test the result for IDUMMY, but in most cases the NULL result is the most appropriate outcome for me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T23:13:56.263",
"Id": "57463",
"Score": "1",
"body": "@marcp I have updated my function to work with strings of spaces. cstdlib and std::strtol aren't the STL version (or more correctly the C++ standard library). They're just the C++ version. C++ makes a point to encapsulate as much as possible in the namespace std. `stdlib.h` puts names in the global namespace. `cstdlib` puts them in `std`. That's the only difference. My point though was that if you include `stdlib.h` `strtol` is correct. If you include `cstdlib` though, `std::strtol` is correct. As it's C++, the namespaced `cstdlib` should typically be preferred."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T23:18:36.663",
"Id": "57464",
"Score": "0",
"body": "As for the default: Your approach is fine for your specific use case. What if in the future though -2^31 is a valid integer to parse? Then suddenly you've lost your ability to detect errors. I feel that code should do what you want it to do, not a close approximation of what you want it to do. \"Try to parse an integer, or use a null value if that fails,\" and \"Try to parse an integer, default to -2^31. If the parsed value is -2^31, pretend it's NULL\" are very close for most situations, but they're not the same. It seems to fit your situation though (though I'm still skeptical of emulating null)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T23:44:23.483",
"Id": "57465",
"Score": "0",
"body": "I've accepted this as the answer. Its a sweet solution. Back to default - NULL IS -2^31 in my situation, its not pretending, but if iDUMMY is a valid integer to parse in a different scenario I will use a different default, or if there is no meaningful default I will use a different function. This function is for the case where the default is meaningful. It's obviously a useful concept for others as well, or it wouldn't be a standard function in Delphi & C++Bulder. cheers"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T21:50:54.350",
"Id": "35454",
"ParentId": "35388",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "35454",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T22:59:55.020",
"Id": "35388",
"Score": "6",
"Tags": [
"c++",
"converting",
"boost"
],
"Title": "Converting std::string to int without Boost"
}
|
35388
|
<p>How can I make this program run faster? On enter, I have a string from the console. For example:</p>
<pre><code>1 1 7 3 2 0 0 4 5 5 6 2 1
</code></pre>
<p>On exit, it will be</p>
<pre><code>6 20
</code></pre>
<p>Could you recommend a way to make this run faster?</p>
<pre><code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
ArrayList<Integer> _arr = new ArrayList<Integer>();
while((line=br.readLine())!= null){
StringTokenizer tok = new StringTokenizer(line);
while (tok.hasMoreTokens()) {
_arr.add((Integer.parseInt(tok.nextToken())));
}
}
Algorithm(_arr);
}
private static void Algorithm(ArrayList<Integer> arr) {
int ascLength = 1,
descLength = 1,
ascSequenceStart = 0,
descSequenceStart = 0,
ascLongest = 1,
descLongest = 1,
summa = 0,
tmp1, tmp2;
for (int i = 1; i<arr.size(); i++) {
tmp1 = arr.get(i-1);
tmp2 = arr.get(i);
if(tmp2>tmp1){
ascLength++;
descLength = 1;
} else if (tmp2<tmp1) {
descLength++;
ascLength = 1;
} else if (tmp1==tmp2){
descLength++;
ascLength++;
}
if (ascLength > ascLongest) {
ascLongest = ascLength;
ascSequenceStart = i - ascLength + 1;
}
if (descLength > descLongest) {
descLongest = descLength;
descSequenceStart = i - descLength + 1;
}
}
if (ascLongest > descLongest) {
for (int i = ascSequenceStart; i < (ascSequenceStart+ascLongest); i++) {
summa += arr.get(i);
}
System.out.print(String.valueOf(ascLongest)+" "+String.valueOf(summa));
} else {
for (int i = descSequenceStart; i < (descSequenceStart+descLongest); i++) {
summa += arr.get(i);
}
System.out.print(String.valueOf(descLongest)+" "+String.valueOf(summa));
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T00:21:42.240",
"Id": "57346",
"Score": "4",
"body": "Welcome to Code Review! Can you please describe what the program does?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T00:39:09.623",
"Id": "57347",
"Score": "0",
"body": "@Kevin: I wasn't sure how to edit the title, so hopefully this is good enough until more details are given."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T09:26:26.940",
"Id": "57383",
"Score": "0",
"body": "What's the assignment? What is the intended purpose of this? How come '1 1 7 3 2 0 0 4 5 5 6 2 1' turns into '6 20' ?"
}
] |
[
{
"body": "<p>Yeah, without giving too much away (this is obviously homework)....</p>\n\n<p>First though, the assumption I make is that the assignment is:</p>\n\n<ol>\n<li>find the length of the longest series of either increasing, or decreasing numbers</li>\n<li>sum the values in this longest sequence.</li>\n</ol>\n\n<p>There are two parts to this problem as well. The first part is getting the user input, and the second is identifying and processing the sequences. I will assume that you can process the user input adequately, and put it in an array of integer <code>int[] values = ...</code>. You use an <code>ArrayList<Integer></code> which is not, in my opinion, a great container for doing arithmetic on...</p>\n\n<p>This problem can be solved by managing three variables, and keeping a <code>maxlen</code> and <code>maxsum</code> total.</p>\n\n<p>First you need to ensure you have at least 2 items in your values array, and, assuming you do, you initialize your three variables:</p>\n\n<pre><code>boolean increasing = values[0] < values[1];\nint sum = values[0];\nint len = 1;\n\nint maxlen = len;\nint maxsum = sum;\n</code></pre>\n\n<p>OK, we set up the system where we expect the third value to be a continuation of the sequence.... and then we start the loop, starting from position 1 (the second item) in the values array:</p>\n\n<pre><code>for (int i = 1; i <= arrays.length; i++) {\n // check here to see if we are going in the same direction\n if ( (increasing && value[i] >= value[i -1]) || ( ...decreasing and next is smaller) ) {\n // we are going on in the same direction as before:\n // increase the length, and add value[i] to the sum.\n // if the length is larger than maxlen, then change maxlen and maxsum to len and sum\n } else {\n // the value at position i breaks the sequence.\n // reset len and sum to be 2 and the sum of this and the previous value\n\n // EDIT: 'Obviously' you record the change in direction!\n increasing = !increasing;\n\n }\n}\n\nSystem.out.printf(\"The longest sequence is %d values long, and has a sum of %d\\n\", maxlen, maxsum);\n</code></pre>\n\n<p>Without going in to too much detail, you can easily convert this algorithm to work at the same time as you process the user input.... there is no real reason why you have to first convert all the values to int first, and only then process them.... you can process them as they are entered.</p>\n\n<p>EDIT: I realize you may need to be smarter than I have suggested when setting up the variables initially... if the first values in the input are all the same then the algorithm above will assume the sequence is <code>not increasing</code> and will produce the wrong result. You need to find out the initial 'direction' of the sequence by looking for the first 'different' value</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T12:03:42.303",
"Id": "57397",
"Score": "0",
"body": "Thank you for ur answer. Problems will appear where sequence have more than 1 the same variables. For example, for \"0 0 1 1 2 2\" exit will be \"length - 6, summ - 6\", early i made exactly like you said. When 2 numbers like \" 0 0 \" appear, i need to keep INCREASE and DECREASE flags on...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T12:28:12.480",
"Id": "57398",
"Score": "0",
"body": "Apart from the very first numbers (which I have already mentioned), your concern about duplicates is not valid. Using `>=` for `increasing` and `<=` for `!increasing` will keep it right"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T12:47:02.907",
"Id": "57399",
"Score": "0",
"body": "You are right, but when in will be \" 0 0 1 1 2 2 3 3 3 2 1 1 1 0 0 0\" by ur program logic out will be \" 0 0 1 1 2 2 3 3 3\". A correct answer must be \" 3 3 3 2 1 1 1 0 0 0\" this sequence length is bigger on 1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T13:02:25.603",
"Id": "57403",
"Score": "0",
"body": "it's appear because in the same time we have parts of decreasing and increasing sequences"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T13:02:27.767",
"Id": "57404",
"Score": "0",
"body": "Perhaps there was something so 'obvious' I neglected to put it in to the comments... let me edit my answer...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T13:18:26.700",
"Id": "57406",
"Score": "0",
"body": "Some question about ArrayList. Before, i used Vector, defference in time is not very big. In any way - Vector and ArrayList fit the time frame. I cant use int[] because when i initialize 'int[] arr = new int[999999]' (10^7 - max length of in sequence) values in array will be '0'. But we dont know how many variables will be in input to fit array size... Mb im stupid or something else, but i need help in it. Need to improve performance of program, logic is OK."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T13:23:06.300",
"Id": "57407",
"Score": "0",
"body": "As I mentioned, it is possible (relatively easily) to convert 'my' method to not use an array or ArrayList at all. You can do the logic at the same time as you parse the user input. That will save **a lot** of memory"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T00:30:24.927",
"Id": "35394",
"ParentId": "35390",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T23:21:46.533",
"Id": "35390",
"Score": "0",
"Tags": [
"java",
"performance",
"strings",
"homework",
"console"
],
"Title": "Processing a string from the console"
}
|
35390
|
<p>I wrote a chatbot in Ruby for <a href="http://turntable.fm" rel="nofollow">turntable.fm</a>, a chatroom where users can listen to music together. It interacts with users in a room, who can type in specific keywords and get responses from it. It also enforces some rules. For example, if people playing music go AFK for too long, it will force them to stop playing music.</p>
<p>The chatbot's overall architecture is that it has a number of event handlers that respond to various changes in the chatroom's state. For example, it can respond to a user joining the room or someone posting to the room. (These handlers are provided using the Turntabler gem (<a href="http://rubygems.org/gems/turntabler" rel="nofollow">RubyGems</a>, <a href="https://github.com/obrie/turntabler" rel="nofollow">GitHub</a>).)</p>
<p>The problem I've run into is that there are pieces of code throughout the project that are logically related, but spread out throughout multiple event handlers. Is there some pattern that will let me refactor related pieces of code into the same class?</p>
<p>For example, one thing the chatbot does is keep track of a queue of users that want to play music when the room is full. When a spot to play music opens up, it makes sure that only the person at the front of the queue can get up.</p>
<p>To get this to work, I created a <a href="https://github.com/KevinNorth/Kevbot/blob/9435ccbaa1c725fd7f74fa1d36da2ffd27cd2014/src/queue/room_queue.rb" rel="nofollow"><code>RoomQueue</code></a> class that wraps an <code>Array</code> with queue management functions. Then I put the queue in a <a href="https://github.com/KevinNorth/Kevbot/blob/9435ccbaa1c725fd7f74fa1d36da2ffd27cd2014/src/kevbot_state.rb" rel="nofollow"><code>KevbotState</code></a> class, a questionable class that keeps track of objects representing the chatbot's state. The bot spins up one instance of <code>KevbotState</code> and passes it around liberally, meaning that its members smell to me like glorified global variables.</p>
<pre><code>require_relative 'queue/room_queue.rb'
# Keeps track of the current state of the robot.
# These are basically global variables. To keep the code half-way sane,
# I put them all into the same class. For example, this means that we
# pass the state around, avoiding singleton pattern code smells by
# directly accessing the variable's values.
class KevbotState
#...snip
# This keeps track of the DJ queue
attr_reader :room_queue
#...snip
def initialize(client)
@room_queue = RoomQueue.new
#...snip
end
end
</code></pre>
<p>Then, <a href="https://github.com/KevinNorth/Kevbot/blob/9435ccbaa1c725fd7f74fa1d36da2ffd27cd2014/src/main.rb" rel="nofollow">in the file that defines the event handlers</a>, there are multiple places that interact directly with this <code>RoomQueue</code>. (The main thing to get from the next code snippit is that there are a lot of places that manipulate the <code>RoomQueue</code>.)</p>
<pre><code>require 'turntabler'
require_relative "kevbot_state.rb"
#...snip
# Set up a connection to the room and hooks to the event handlers
Turntabler.run do
client = Turntabler::Client.new(ENV['EMAIL'], ENV['PASSWORD'],\
:room => ENV['ROOM'], :reconnect => true, :reconnect_wait => 30)
# This is the single instance of KevbotState that's used liberally in
# the rest of the program. It's frequently passed as a parameter to
# methods that might need to manipulate it.
state = KevbotState.new (client)
# Every ~30 seconds, I run some logic to enforce rules against going AFK.
# Some of this logic involves the RoomQueue
client.on :heartbeat do
room = client.room
#...snip
# Enforce that AFK users lose their positions in the queue.
queue = state.room_queue
unless queue.empty? && (room.djs.count < room.dj_capacity)
head = queue.peek
#...snip
end
end
#... snip
# When users leave the room, I remove them from the queue
client.on :user_left do |user|
state.room_queue.remove_user user
state.last_activity.delete user
state.sent_dj_reminders.delete user
end
client.on :user_booted do |user|
state.room_queue.remove_user user
end
# When a user attempts to start playing music, I make
# sure that they're at the front of the queue
client.on :dj_added do |user|
#...snip
room = client.room
queue = state.room_queue
if queue.can_user_dj? user
queue.remove_user user
else
user.remove_as_dj
#...snip
end
#...snip
end
#...snip
end
</code></pre>
<p>In addition, there are a couple of chat commands that users can enter that the chatbot will respond to by manipulating the queue. For example, this is the logic for a command to <a href="https://github.com/KevinNorth/Kevbot/blob/9435ccbaa1c725fd7f74fa1d36da2ffd27cd2014/src/commands/check_queue.rb" rel="nofollow">check the contents of the queue</a>. There are two other commands that also touch the <code>RoomQueue</code>.</p>
<pre><code>require_relative '../kevbot_state.rb'
require_relative 'command.rb'
class CheckQueueCommand
include Command
#...snip
def execute(parameter, user, client, state)
room = client.room
queue = state.room_queue
if queue.empty?
room.say "The queue is empty."
if (user.dj?) && (room.djs.size < room.dj_capacity)
room.say "Feel free to get on deck!"
end
else
room.say "The queue is: #{queue.check.join(', ')}"
end
end
#...snip
end
</code></pre>
<p>I don't like how the behavior that manipulates and enforces the queue is spread out throughout the chatbot. Are there any patterns I can use to consolidate all of this logic in one place? Also, is there a better place for me to put my <code>RoomQueue</code> than the <code>KevbotState</code>?</p>
<p><a href="https://github.com/KevinNorth/Kevbot/tree/9435ccbaa1c725fd7f74fa1d36da2ffd27cd2014" rel="nofollow">This is a stable commit in the project that uses the design I want feedback on.</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-17T17:37:53.107",
"Id": "57658",
"Score": "2",
"body": "I don't have much time to build an elaborate answer, but here's my two cents : first, much of the data you store in the state should be the responsibility of the room queue ; for instance, deck activity timers, etc. Looking from afar, I'd say your code also misses a User class that would store last activity time, afk time, etc. for ONE user, and be responsible to maintain timers, notify the user, etc. All in all, your code lacks well-defined entities that embody responsibilities. Maybe I'll have a closer look when i have time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-11T22:56:03.863",
"Id": "203594",
"Score": "0",
"body": "Quick note: All those `#...snip`s make me think this is off-topic. Could you paste in the full code? (Aside from that, this seems *super* cool! Does it still work?)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T00:19:09.043",
"Id": "35392",
"Score": "3",
"Tags": [
"ruby",
"design-patterns",
"event-handling"
],
"Title": "Encapsulating behavior spread across multiple event handlers"
}
|
35392
|
<p>Please review my strstr implementation. This is an interview question that does not allow the use of <code>strlen()</code>. Is there a better way than using a boolean below?</p>
<pre><code>#include <iostream>
#include <cstring>
char* my_strstr(char * s1, const char *s2)
{
if ( s1 == NULL || s2 == NULL )
return NULL;
size_t s2Size = 0;
const char *end = s2;
while (*end++)
++s2Size;
bool match;
while ( *s1 )
{
match = true;
for ( int i = 0; i < s2Size ; ++i )
{
if ( s1[i] != s2[i] )
{
match = false;
break;
}
}
if ( match )
return s1;
++s1;
}
return NULL;
}
const char* my_strstr(const char * s1, const char *s2)
{
return my_strstr(const_cast<char*>(s1),s2);
}
int main()
{
const char str[]= "This is a strstr test";
const char search[]= "strstr";
const char *result = my_strstr(str,search);
if ( result )
printf("original: %s\n item: %s\n found: %s\n", str, search, result );
}
</code></pre>
|
[] |
[
{
"body": "<p>Yep.</p>\n\n<p>You implemented the standard brute force implementation. </p>\n\n<p>Personally I think that is fine. For some silly reason though a lot of interviewers expect you to swat up on string manipulation for interviews and want you to know the non brute force versions off the top of your head. In my opinion if you know a clever versions exists is enough (because in real life I would Google \"efficient strstr implementation\") if you happen to know the name even better (because in real life you will find it faster).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T06:54:30.850",
"Id": "35406",
"ParentId": "35396",
"Score": "5"
}
},
{
"body": "<p>By counting the length of <code>s2</code>, you <strong>missed the point</strong> of this exercise. Technically, you didn't call <code>strlen()</code>, but you emulated it, which is arguably even worse. The point was to test your proficiency with pointers, and you failed this interview question. (Why not count the length? Because it's possible to do it without incurring the cost of that O(<em>n</em>) operation. The only time you need to walk along the entire length of <code>s2</code> is when a match is imminent.)</p>\n\n<p>The <code>strstr(3)</code> documentation probably calls the arguments <code>s1</code> and <code>s2</code>. However, I'll borrow a rare piece of wisdom from the <a href=\"http://php.net/strstr\">PHP documentation</a> and <strong>call the arguments <code>haystack</code> and <code>needle</code></strong>.</p>\n\n<p><strong>Don't use variables to control the execution flow.</strong> Prefer to use more active means such as <code>continue</code>, <code>break</code>, and <code>return</code>. If you have detected a match, what are you waiting for? Celebrate your success with an immediate <code>return</code>!</p>\n\n<p>Your <strong>imports</strong> are wrong. The only library function you call is <code>printf()</code>, so you should <code>#include <cstdio></code>.</p>\n\n<p>Here's a solution.</p>\n\n<pre><code>#include <cstdio>\n\nchar* my_strstr(char *haystack, const char *needle) {\n if (haystack == NULL || needle == NULL) {\n return NULL;\n }\n\n for ( ; *haystack; haystack++) {\n // Is the needle at this point in the haystack?\n const char *h, *n;\n for (h = haystack, n = needle; *h && *n && (*h == *n); ++h, ++n) {\n // Match is progressing\n }\n if (*n == '\\0') {\n // Found match!\n return haystack;\n }\n // Didn't match here. Try again further along haystack.\n }\n return NULL;\n}\n\nconst char* my_strstr(const char *haystack, const char *needle) {\n return my_strstr(const_cast<char *>(haystack), needle);\n}\n\nint main() {\n const char *str = \"This is a strstr test\";\n const char *search = \"strstr\";\n\n const char *result = my_strstr(str, search);\n\n if (result)\n printf(\"original: %s\\n item: %s\\n found: %s\\n\", str, search, result);\n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T06:58:52.820",
"Id": "35407",
"ParentId": "35396",
"Score": "12"
}
},
{
"body": "<p>I think interviewers like this task to see how you might be able to\ncode/design on your feet. How readable is your implementation?\nDid you use four variables and three loops when fewer are sufficient?\nDo you think in pointers or arrays? Do you really know C, or do you\nthink in some other language and translate it internally into C?\nIs your code pedantic, obtuse, obfuscated, sick or slick?\nDid you pay attention to the edge cases?</p>\n\n<pre><code>char * strstr(const char *haystack, const char *needle) { \n const char *a = haystack, *b = needle; \n for (;;) \n if (!*b) return (char *)str; \n else if (!*a) return NULL; \n else if (*a++ != *b++) { a = ++haystack; b = needle;} \n}\n</code></pre>\n\n<p>If the interviewer is willing to take a bet, then bet that you can write strstr\nwithout using any local variables or calling any other external routines.\nIf they take the bet, then try to up the bet by saying you can write it without\nusing any for or while or gotos. Produce the recursive version below.\nAgree that it is not efficient.</p>\n\n<pre><code>char * strstr(const char *haystack, const char *needle) {\n if (!*needle)\n return (char *)haystack;\n if (!*haystack) \n return NULL;\n if ((*haystack == *needle) && (strstr(haystack+1, needle+1) == haystack+1)) \n return (char *)haystack;\n return strstr(haystack+1, needle);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-11-29T23:21:04.263",
"Id": "279340",
"Score": "0",
"body": "Does it compile? The symbol `str` in statement `return (char *)str;` seems undefined..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T18:24:38.930",
"Id": "424015",
"Score": "0",
"body": "It should be haystack. Just a typo."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-27T16:19:11.743",
"Id": "45524",
"ParentId": "35396",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "35407",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T00:42:34.150",
"Id": "35396",
"Score": "7",
"Tags": [
"c++",
"strings",
"interview-questions"
],
"Title": "strstr implementation"
}
|
35396
|
<p>Please review my answer for this interview question:</p>
<pre><code>#include <iostream>
#include <vector>
std::vector<int> merge2Sorted ( std::vector<int> left, std::vector<int> right )
{
//finger matching algo
auto itLeft = left.begin();
auto itRight = right.begin();
auto itLeftEnd = left.end();
auto itRightEnd = right.end();
std::vector<int> result;
result.reserve(std::max(left.size(),right.size()));
while ( itLeft != itLeftEnd &&
itRight != itRightEnd )
{
if ( *itLeft < *itRight )
result.push_back( *itLeft++ );
else
result.push_back( *itRight++ );
}
// copy rest of left array
while ( itLeft != itLeftEnd )
result.push_back(*itLeft++);
// copy rest of right array
while ( itRight != itRightEnd )
result.push_back(*itRight++);
return result;
}
int main ()
{
std::vector<int> v1 = { 1,2,3,4,5,6,7,8,9,10 };
std::vector<int> v2 = { -1,-2,0,3,7,9,11,12 };
std::vector<int> v3 ( merge2Sorted ( v1, v2 ) );
for ( auto& i: v3 )
std::cout << i << std::endl;
}
</code></pre>
|
[] |
[
{
"body": "<p>Pass your parameters by const reference to avoid a copy:</p>\n\n<pre><code>std::vector<int> merge2Sorted(std::vector<int> const& left, std::vector<int> const& right)\n// ^^^^^^ ^^^^^^\n</code></pre>\n\n<p>You are not reservng enough</p>\n\n<pre><code>result.reserve(std::max(left.size(),right.size()));\n</code></pre>\n\n<p>The result size will eventually be the size of the sum of the two input arrays.</p>\n\n<pre><code>result.reserve(left.size() + right.size());\n</code></pre>\n\n<p>Your test for left and right can be simplified:</p>\n\n<pre><code>if ( *itLeft < *itRight )\n result.push_back( *itLeft++ );\nelse\n result.push_back( *itRight++ );\n}\n\n// Simplified\n// Though I am 50/50 on this one.\nresult.push_back( ( *itLeft < *itRight ) ? *itLeft++ : *itRight++);\n</code></pre>\n\n<p>No point in flushing the stream after every print:</p>\n\n<pre><code>std::cout << i << std::endl;\n\n ^^^^^^^^^^ prefer '\\n' unless you really want to force a flush.\n\nstd::cout << i << '\\n';\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T03:44:45.647",
"Id": "35402",
"ParentId": "35397",
"Score": "7"
}
},
{
"body": "<p>In addition to Loki's answer you can also simplify copying the rest of the left and right arrays like so:</p>\n\n<pre><code>// Copy rest of left and right vectors\nresult.insert(result.end(), itLeft, itLeftEnd);\nresult.insert(result.end(), itRight, itRightEnd);\n</code></pre>\n\n<p>Oh and if you were doing this in production and not for an interview you could instead use <code>std::merge</code>:</p>\n\n<pre><code>#include <algorithm>\n\nstd::vector<int> merge2Sorted ( const std::vector<int>& left, const std::vector<int>& right ) {\n std::vector<int> output;\n std::merge(left.begin(), left.end(), right.begin(), right.end(), std::back_inserter(output));\n return output;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T07:54:07.703",
"Id": "35410",
"ParentId": "35397",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "35402",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T01:01:50.620",
"Id": "35397",
"Score": "4",
"Tags": [
"c++",
"c++11",
"interview-questions",
"vectors",
"mergesort"
],
"Title": "Merge two sorted arrays together"
}
|
35397
|
<p>I'm learning backbone.js in parallel with unit testing. I've just made a simple model and wanted to unit test it. Do I have the right idea? I am simply making a model with some default values.</p>
<pre><code>Person = Backbone.Model.extend({
defaults: {
name: "fetus",
age: 0,
child: ''
},
initialize: function() {
console.log("Welcome to this world");
}
});
var test_Person = {};
var test_Person.Defaults = function() {
var person = new Person();
person.assertString(person.defaults.initialize,"Welcome to this world");
person.assertString(person.defaults.name,"fetus");
person.assertNum(person.defaults.age,0);
person.assertString(person.defaults.child,"");
}();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-31T17:24:19.697",
"Id": "111928",
"Score": "0",
"body": "I think that it's an awesome approach to learning Backbone, that is, to learn how to unit test it simultaneously as you learn it. Now, to take a step back, I don't think that you need to unit test this code. Why? Because having Backbone set some values to defaults is something that cannot go wrong. If you unit test that Backbone set the defaults then you are repeating yourself, you're just hardcoding the values in your unit test, too. IMHO, logic deserves unit tests. As an example, you can look at my post: http://codereview.stackexchange.com/questions/61629/unit-testing-backbone-model"
}
] |
[
{
"body": "<p>If your <code>Person</code> was initialized with a name other than \"fetus\", your test would fail.. but your test has <em>several reasons for failing</em> and that's what makes it not-so-good: that same test would also fail if a <code>Person</code> was \"born\" with a child (!) or if <code>age</code> defaulted to 1, or if the <em>welcome to this world</em> string was different.</p>\n\n<p>I've never written a unit test with JS, but I believe the following would apply:</p>\n\n<ul>\n<li><strong>Name</strong> your test method so that anybody (including non-technical) reading it (the name) knows exactly <em>what is being tested</em>.</li>\n<li><strong>Arrange</strong> the dependencies of your SUT (that's <em>System Under Test</em>). Set up /configure your mocks, define what the expected outcome should be.</li>\n<li><strong>Act</strong> upon your SUT (i.e. call the method you want to test). Pass in your mock dependencies, retrieve the \"actual\" result.</li>\n<li><strong>Assert</strong> - verify that you get expected results, i.e. make the test pass, or fail.</li>\n</ul>\n\n<p>In this particular case, I'm not sure what's being tested exactly - you're merely verifying that the <code>person</code> object was initialized with the expected default values? <em>I guess it's ok</em>.</p>\n\n<p>Unit tests should be testing that the code <em>does what it's supposed to be doing</em>.</p>\n\n<p>As I said I've never written a test with JS, so this example is C#:</p>\n\n<pre><code> [TestMethod]\n public void ShouldReplaceCommaWithEmptyStringInProductDescription()\n {\n // arrange\n var testDescription = \"Product,Description\";\n var data = GetValidMockRecord();\n var values = data.Split(',');\n values[11] = testDescription;\n data = string.Join(\",\", values);\n\n if (!testDescription.Contains(\",\")) Assert.Inconclusive(\"testDescription must contain at least one (1) comma (,).\");\n\n var sut = new EdiParser();\n var expected = testDescription.Replace(\",\", string.Empty);\n\n // act\n var result = sut.Parse(data);\n var actual = result.ProductDescription;\n\n // assert\n Assert.AreEqual(expected, actual);\n }\n</code></pre>\n\n<p>I don't think the language is a barrier: as you can see I'm asserting in my <em>arrange</em> section and making the test <em>inconclusive</em> if the test data would make the test, well, inconclusive. Then in the actual <em>assert</em> section I'm <strong>only testing one thing</strong>, and this is what <em>unit</em> testing is really about.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T16:28:42.943",
"Id": "57421",
"Score": "0",
"body": "Thanks this is really good information. So do you agree that my example does not really require a unit test. I mean the defaults are pretty obvious from looking at the code. Unless I said that the person object was supposed to be initialized with those exact default values, then I would have to write a unit test for that. Ah, now this is where unit testing starts to get confusing. So I guess it comes down to requirements with unit testing, I was reading up on TDD and that gave me the impression to unit test pretty much every function/object you write"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T16:34:30.373",
"Id": "57423",
"Score": "0",
"body": "I'm not much into TDD so maybe you read and understand the right thing. IMHO unit tests aim at protecting your program's logic against changes - let me explain: if changing the default value for a person's `age` from 0 to 1 could break something somewhere, then yes you should have a unit test that verifies that every `person` is initialized with an `age` of 0. But most of your tests should cover *methods* that implement some logic. Also make sure your tests are *shielded* from each other (they should be able to run independently, in any order)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T13:34:43.853",
"Id": "35436",
"ParentId": "35399",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "35436",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T02:24:38.430",
"Id": "35399",
"Score": "4",
"Tags": [
"javascript",
"unit-testing",
"backbone.js"
],
"Title": "First ever unit test. Am I headed in the right direction?"
}
|
35399
|
<p>Case 1_a:</p>
<pre><code> zip_file = file.sub(directory, '').sub!(/^\//, '')
zipfile.add( zip_file, file)
</code></pre>
<p>Case 1_b:</p>
<pre><code> zipfile.add(
file.sub(directory, '').sub!(/^\//, ''),
file)
</code></pre>
<p>Case 2 : If the String contains lots of parameters , I prefer write in an array.But I'm not sure to have a line break behind <strong>[</strong> is better, or not</p>
<pre><code> def run_remote_focus()
self.setup_remote_focus()
created_at=(Time.now.to_f*1000000).to_i.to_s
settings=[
"-i #{params[:remote_focu][:ip]}",
"-u #{params[:remote_focu][:username]}",
"-p #{params[:remote_focu][:password]}",
"-s #{params[:RemoteFocu].values.join(':')}",
"-m #{params[:af_type]}",
"-t #{params[:remote_focu][:tester]}",
"-n #{@remote_focu.id}",
"-c #{created_at}"
]
cmd=["ruby",
"-I #{@rf[:lib]}",
"#{@rf[:bin]}",
" #{settings.join(' ')}"
]
cmd_str=" #{cmd.join(' ').strip()} & "
</code></pre>
<p>Case 3 : I can not tell what is the problem, but it just seems weird</p>
<pre><code>@rf={
folder: "#{Rails.root}#{ENV["module_remote_focus_folder_path"]}",
bin: "#{Rails.root}#{ENV["module_remote_focus_bin_path"]}",
lib: "#{Rails.root}#{ENV["module_remote_focus_lib_path"]}"
}
@rf={folder: "#{Rails.root}#{ENV["module_remote_focus_folder_path"]}",
bin: "#{Rails.root}#{ENV["module_remote_focus_bin_path"]}",
lib: "#{Rails.root}#{ENV["module_remote_focus_lib_path"]}"}
</code></pre>
|
[] |
[
{
"body": "<p>Case 1_a. Don't mix pure functions (<code>sub</code>) with destructive functions (<code>sub!</code>). Whenever possible use pure methods:</p>\n\n<pre><code>zip_file = file.sub(directory, '').sub(/^\\//, '')\nzipfile.add(zip_file, file)\n</code></pre>\n\n<p>But can't you write simply?</p>\n\n<pre><code>zip_file = File.basename(file)\n</code></pre>\n\n<p>Case 1_b: I prefer to set variables. Giving names to things is good.</p>\n\n<p>Case 2 : It's ok. I also prefer to write a comma at the last element so it can be freely reordered. I'd also change the structure of <code>settings</code> so it's easier to write:</p>\n\n<pre><code>settings = [\n [\"-i\", params[:remote_focu][:ip]],\n [\"-u\", params[:remote_focu][:username]],\n ...\n].map { |opt, value| [opt, value].join(\" \") }\n</code></pre>\n\n<p>Case 3 : Use the same indentation style that you used for array. Also, use the library facilities, don't manipulate paths as strings (extremely prone to bugs):</p>\n\n<pre><code>@rf = {\n folder: File.join(Rails.root, ENV[\"module_remote_focus_folder_path\"]),\n ...\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T10:22:11.593",
"Id": "35427",
"ParentId": "35400",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T03:16:05.490",
"Id": "35400",
"Score": "4",
"Tags": [
"ruby"
],
"Title": "Coding style in Ruby format in an method and variable assign"
}
|
35400
|
<p>I have tried to comment my code as much as I can. If you have any questions about it, please feel free to ask. The code itself should have a lot of details and the comments mostly explain what is going on. The task description is in the code.</p>
<pre><code>#pragma config(Sensor, dgtl1, allowButton, sensorTouch)
#pragma config(Sensor, dgtl2, resetButton, sensorTouch)
#pragma config(Sensor, dgtl3, redLED1, sensorLEDtoVCC)
#pragma config(Sensor, dgtl4, contestantButton1, sensorTouch)
#pragma config(Sensor, dgtl5, redLED2, sensorLEDtoVCC)
#pragma config(Sensor, dgtl6, contestantButton2, sensorTouch)
#pragma config(Sensor, dgtl7, redLED3, sensorLEDtoVCC)
#pragma config(Sensor, dgtl8, contestantButton3, sensorTouch)
#pragma config(Sensor, dgtl9, resetLED, sensorLEDtoVCC)
#pragma config(Sensor, dgtl10, greenLEDStart, sensorLEDtoVCC)
//*!!Code automatically generated by 'ROBOTC' configuration wizard !!*//
/*
Project Title: Jeopardy Game
Team Members:
Date: 11/12/13
Section:
Task Description:
The Jeopardy game should be programmed to perform the following functions:
1. Alex has two buttons at his podium; a button that enables players to ring in once he has read the question or to ring in after someone misses the question (the green LED should light up to indicate the button has been pressed), and the other to reset the program.
2. Each contestant has their own signalling button when they ring in, their red light flashes with the flashes getting closer and closer together until it stays lit showing they are out of time.
3. After a contestant rings in, they should not be able to ring in again if they miss the question.
4. If no one answers the question or if someone gets the question right, the reset button should be hit to reset the program.
5. Wowing the teacher can be achieved if the green light acts as a timer for any contestant to ring in and if a player is locked out if they hold down their signalling button when Alex presses his enable button.
Hint: A thorough knowledge of functions is required.
Pseudo code:
After the question is read, Alex hits allowButton, this enables the contestants buttons
timer starts
Contestants hits their button,their button is disabled and red light starts flashing
reset button resets all the buttons and timers
*/
bool contestantsAllow;
bool badContestant1;
bool badContestant2;
bool badContestant3;
int y = 500;
void blinkLED(tSensors sensorPort)
{
ClearTimer(T2);
while(time1[T2] < 10000) //Performs body for 10 seconds (10000 Milliseconds
{
turnLEDOn(sensorPort);
waitInMilliseconds (y);
turnLEDOff(sensorPort);
waitInMilliseconds (y);
y = y *(5/10); //cuts wait time in half
}
}
task resetAll
{
while (1) //Keeps task running at all times
{
if (SensorValue[resetButton] == 1)//Resets all Sensors and Booleans
{
turnLEDOff (redLED1);
turnLEDOff (redLED2);
turnLEDOff (redLED3);
turnLEDOff (greenLEDStart);
SensorValue[contestantButton1] = 0;
SensorValue[contestantButton2] = 0;
SensorValue[contestantButton3] = 0;
SensorValue[allowbutton] = 0;
badContestant1 = false;
badContestant2 = false;
badContestant3 = false;
contestantsAllow = false;
turnLEDOn(resetLED);
wait (.5);
turnLEDOff(resetLED);
}
}
}
task main()
{
while(1)
{
StartTask(resetAll); //Starts the reset task so it is running in parallel with the main task
while (SensorValue[allowButton] == 0) //makes sure that the allowbutton isn't pressed
{
if (SensorValue[contestantButton1] == 1) //Checks to see if they have tried to answer before the question was finished
{
turnLEDOn(redLED1); //Visual that they can no longer answer
badContestant1 = true; //They are not allowed to answer if true
}
if (SensorValue[contestantButton2] == 1) //Checks to see if they have tried to answer before the question was finished
{
turnLEDOn(redLED2); //Visual that they can no longer answer
badContestant2 = true; //They are not allowed to answer if true
}
if (SensorValue[contestantButton3] == 1) //Checks to see if they have tried to answer before the question was finished
{
turnLEDOn(redLED3); //Visual that they can no longer answer
badContestant3 = true; //They are not allowed to answer if true
}
}
contestantsAllow = true; //Sets value to true so that contestants can answer the question
turnLEDOn(greenLEDStart); //Visual allowing them to answer the question
ClearTimer(T1);
while (time1[T1]<6000) //Starts timer, contestants 6 seconds
{
if (SensorValue[contestantButton1] == 1 && badContestant1 == false) //If they press their button and badcontestant is false then they can answer the question
{
badContestant2 = true; //locks other contestants out
badContestant3 = true; //locks other contestants out
{
ClearTimer(T2); //resets timer[T2]
while(time1[T2] < 10000) //Starts Timer for 10 seconds
blinkLED(redLED1);//runs function blinkLED
turnLEDOn(redLED2); //Visual showing that their turn is over
badContestant1 = true; //Contestant can't answer again
badContestant2 = false; //allows other contestants to answer
badContestant3 = false;//allows other contestants to answer
ClearTimer(T1); //Clears timer so that there is another 6 seconds added to the clock
}
}
else if (SensorValue[contestantButton2] == 1 && badContestant2 == false) //If they press their button and badcontestant is false then they can answer the question
{
badContestant1 = true; //locks other contestants out
badContestant3 = true; //locks other contestants out
{
ClearTimer(T2); //resets timer[T2]
while(time1[T2] < 10000) //Starts Timer for 10 seconds
blinkLED(redLED2);//runs function blinkLED
turnLEDOn(redLED2); //Visual showing that their turn is over
badContestant2 = true;//Contestant can't answer again
badContestant1 = false;//allows other contestants to answer
badContestant3 = false;//allows other contestants to answer
ClearTimer(T1); //Clears timer so that there is another 6 seconds added to the clock
}
}
else if (SensorValue[contestantButton3] == 1 && badContestant3 == false) //If they press their button and badcontestant is false then they can answer the question
{
badContestant2 = true; //locks other contestants out
badContestant1 = true; //locks other contestants out
ClearTimer(T2); //resets timer[T2]
while(time1[T2] < 10000) //Starts Timer for 10 seconds
blinkLED(redLED3);//runs function blinkLED
turnLEDOn(redLED3); //Visual showing that their turn is over
badContestant3 = true;//Contestant can't answer again
badContestant2 = false;//allows other contestants to answer
badContestant1 = false;//allows other contestants to answer
ClearTimer(T1); //Clears timer so that there is another 6 seconds added to the clock
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>Program design issues:</strong></p>\n\n<ul>\n<li><p>Do not ever use global variables. In this case, the variables <code>contestantsAllow</code> and so on should be declared locally in main, because there is no reason to have them in the global namespace.</p>\n\n<p>Had you been using a more object-oriented design, where for example everything related to sensors was put in a separate module (sensor.h + sensor.c etc), then variables that are only used by that module could be declared at file scope, but with the keyword <code>static</code>, thereby using the object-oriented concepts of private variables and encapsulation.</p></li>\n<li><p><code>y</code> should be given a meaningful name. It is a delay in miliseconds, why don't name it such? <code>led_delay_ms</code> for example.</p></li>\n<li><p>You lock up the whole CPU at 100% whenever you execute your delays. That may not be an issue in this case, but it will be in a larger program. Consider using polling or interrupts instead.</p></li>\n<li><p>Even though Jeopardy always come with exactly 3 competitors, consider rewriting the code so that it works with any amount of competitors. The 3 different badContestant variables should for example be stored in an array, to increase readability and make the program more generic: <code>bool badContestant [COMPETITORS];</code>. Same goes for <code>contestantButton</code> and so on. This will not only make your program more powerful, it also prevents you from having the same code at different places all over the program, making it easier to maintain.</p></li>\n</ul>\n\n<p><strong>Bugs:</strong></p>\n\n<ul>\n<li><p><code>y = y *(5/10);</code> performs a division on an integer, not a floating point. 5/10 is always 0. You need to learn the difference between integers and floats. You can probably fix this specific bug by changing the code to <code>y = (y*5) / 10;</code>.</p></li>\n<li><p>Variables shared between different tasks in a RTOS, or between the main code and an interrupt, or between threads, must always be declared as <code>volatile</code>. This will prevent potential bugs caused by code optimization, where the compiler does not realize that a particular variable is updated. In addition, you may need to protect such variables with semaphores, to achieve thread safety (volatile does not give thread-safe, atomic access).</p></li>\n<li><p>You don't seem to include stdbool.h. Is the code posted really complete? It shouldn't compile. If it does compile without that header, chances are you are compiling as C++, which is always a bad idea. C and C++ are quite different languages in many ways.</p></li>\n<li><p>This may or may not be a bug, but are you certain that the function <code>wait()</code> expects a floating point variable? Looks fishy to me.</p></li>\n</ul>\n\n<p><strong>Coding style:</strong></p>\n\n<ul>\n<li><p>It is a good habit of always using <code>{}</code> after each <code>if, for</code> or <code>while</code>. This will save you from a lot of accidental bugs.</p></li>\n<li><p>Your indention isn't consistent, making the code hard to read. Always indent with either 2 or 4 spaces (pick one style and stick to it). If you are using tab key for indention, make sure your IDE replaces tabs with spaces.</p></li>\n<li><p>Consider placing comments at a specific column whenever possible, like after 40 or 50 symbols. (There are indention programs that can do this for you, like <a href=\"http://universalindent.sourceforge.net/\" rel=\"nofollow\">UniversalIndent</a>.) Example:</p>\n\n<p>Instead of </p>\n\n<pre><code>ClearTimer(T2); //resets timer[T2]\nwhile(time1[T2] < 10000) //Starts Timer for 10 seconds\nblinkLED(redLED1);//runs function blinkLED\n</code></pre>\n\n<p>put comments like this:</p>\n\n<pre><code>ClearTimer(T2); //resets timer[T2]\nwhile(time1[T2] < 10000) //Starts Timer for 10 seconds\n blinkLED(redLED1); //runs function blinkLED\n</code></pre></li>\n<li><p>Avoid meaningless comments. Your comments should address what the program is doing, so that another C programmer can tell what it does. You should assume that the reader of your comments know the C language.</p>\n\n<p>An example of a good comment is <code>badContestant2 = true; //locks other contestants out</code>. It tells the reader what this code row will cause.</p>\n\n<p>An example of a bad comment is <code>blinkLED(redLED1); //runs function blinkLED</code>. Every C programmer knows that the code is a function call, so the comment is pointless. </p>\n\n<p>Also, if the code speaks for itself, you need not comment it. For example, <code>ClearTimer(T2);</code> speaks for itself. The comment <code>//resets timer[T2]</code> is superfluous.</p></li>\n<li><p>Never use \"magic numbers\" in the code. If you have something like <code>while (time1[T1]<6000)</code>, then nobody can tell what 6000 is supposed to mean, unless there is a comment. Instead, put the numeric constant in a <code>#define</code> or a <code>const</code> variable. For example you could write <code>while (time1[T1]< 6*SECOND)</code>. And then suddenly you can remove the comment too, because the code speaks for itself.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T12:55:35.163",
"Id": "57401",
"Score": "0",
"body": "Thank you so much, and the wait function is correct, and the program I use will compile the code without any issues. But do you think you could figure out an equation that is based off of timer2 for my blinking light function, so as the timer approaches 6 seconds ( I'm changing it from 10 seconds) the light will blink faster?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T13:42:09.683",
"Id": "57506",
"Score": "0",
"body": "Nice answer, +1. But are private variables and encapsulation really \"object-oriented concepts\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-18T07:18:57.313",
"Id": "57738",
"Score": "0",
"body": "@WilliamMorris Yes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-18T16:13:24.357",
"Id": "57796",
"Score": "0",
"body": "Mmm, I use both in C, but I never though I was being object orientated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T22:55:17.020",
"Id": "83454",
"Score": "0",
"body": "@WilliamMorris Encapsulation + Abstraction + Inheritance + Polymorphism = OOP ;)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T11:51:36.370",
"Id": "35432",
"ParentId": "35401",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T03:21:10.030",
"Id": "35401",
"Score": "1",
"Tags": [
"c",
"game"
],
"Title": "ROBOTC Jeopardy program"
}
|
35401
|
<p>I wrote some very basic R code.</p>
<p>This has at least two problems.</p>
<ol>
<li><p>It uses a very basic imperative-programming style instead of good R style.</p></li>
<li><p>It draws the result as an ellipse, not a circle. This effect is barely visible on RGui on Windows, but extremely visible in RStudio on Linux. [<strong>Edit:</strong> <em>rcs has mentioned that the asp parameter of the image command can fix this. Thanks, rcs.</em>]</p></li>
</ol>
<p>There are some debatable issues. For example, there is no good reason why I draw the radius at the distance that I do, so I consider this to be a "magic" number, and I try to avoid "magic numbers" in code because they cause maintenance problems. The number is in there because I don't think it's worthwhile specifying a user input or a function argument to control it.</p>
<pre><code>edge<-100
magicradius=.81
magicmargin=.01
width<-(2*edge)+1
x<-c(-edge:edge)
y<-c(-edge:edge)
squarelist<-c(1:((width^2)))
dim(squarelist)<-c(width, width)
counter<-0
for (i in 1:length(x)){
for (j in 1:length(y)){
counter<-counter+1
if( (((magicradius-magicmargin)*(edge))<sqrt( x[i]^2 + y[j]^2 ) )
&(((magicradius+magicmargin)*(edge))>sqrt( x[i]^2 + y[j]^2 ) ) ){
squarelist[counter]<-sqrt( x[i]^2 + y[j]^2)
} else {
squarelist[counter]<-0
}
}
}
gg<-matrix(squarelist,nrow=width,ncol=width)
image(gg)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T21:19:37.400",
"Id": "58469",
"Score": "1",
"body": "fix for Problem 2: `image(gg, asp=1)`"
}
] |
[
{
"body": "<p>A vectorized solution using <code>outer</code> (Outer Product of Arrays):</p>\n\n<pre><code>edge <- 100\nmagicradius <- .81\nmagicmargin <- .01\nwidth <- (2*edge) + 1\n\nx <- -edge:edge\ny <- -edge:edge\n\nmat <- outer(x, y, function(x,y) sqrt(x^2 + y^2))\nind <- mat > ((magicradius-magicmargin)*edge) &\n mat < ((magicradius+magicmargin)*edge)\nimage(ind, asp=1)\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/KkIks.png\" alt=\"enter image description here\"></p>\n\n<p>The aspect ratio in <code>image()</code> can be set with the <code>asp</code> argument (see the <em>Details</em> section in <code>?plot.window</code>)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T03:11:43.343",
"Id": "58829",
"Score": "0",
"body": "I had not been aware of the outer() syntax until now --thanks. The ind construction is obviously much easier to write than mine and should result in shorter code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T03:46:25.950",
"Id": "58837",
"Score": "0",
"body": "I have just tested the above code in rstudio and it produces unexpected results."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T06:37:40.020",
"Id": "58862",
"Score": "0",
"body": "The output produced by gg seems to be very different from the output produced by ind."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T08:03:10.143",
"Id": "58870",
"Score": "0",
"body": "my code produces exactly the same result as your example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T16:13:32.797",
"Id": "58906",
"Score": "0",
"body": "See here http://www.r-fiddle.org/#/fiddle/wk5fEVOu"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T08:12:45.240",
"Id": "35905",
"ParentId": "35404",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T06:34:31.220",
"Id": "35404",
"Score": "2",
"Tags": [
"r"
],
"Title": "Basic graphical R code draws an ellipse instead of a circle"
}
|
35404
|
<p>Here is the code that I am using on a website's contact form:</p>
<p>HTML file:</p>
<pre><code> <form name="ajax-form" id="ajax-form" action="php-file.php" method="post">
<label for="name">Name: *
<span class="error" id="err-name">please enter name</span>
</label>
<input name="name" id="name" type="text" />
<label for="email">E-Mail: *
<span class="error" id="err-email">please enter e-mail</span>
<span class="error" id="err-emailvld">e-mail is not a valid format</span>
</label>
<input name="email" id="email" type="text" />
<label for="message">Message:</label>
<textarea name="message" id="message"></textarea>
<button id="send">Submit</button>
<div class="error" id="err-form">There was a problem validating the form please check!</div>
<div class="error" id="err-timedout">The connection to the server timed out!</div>
<div class="error" id="err-state"></div>
</form>
<div id="ajaxsuccess"><h2>Successfully sent!!</h2></div>
</code></pre>
<p>PHP file (php-file.php):</p>
<pre><code><?php
$send_to = "contact@example.com";
$send_subject = "Ajax form ";
$f_name = cleanupentries($_POST["name"]);
$f_email = cleanupentries($_POST["email"]);
$f_message = cleanupentries($_POST["message"]);
$from_ip = $_SERVER['REMOTE_ADDR'];
$from_browser = $_SERVER['HTTP_USER_AGENT'];
function cleanupentries($entry) {
$entry = trim($entry);
$entry = stripslashes($entry);
$entry = htmlspecialchars($entry);
return $entry;
}
$message = "This email was submitted on " . date('m-d-Y') .
"\n\nName: " . $f_name .
"\n\nE-Mail: " . $f_email .
"\n\nMessage: \n" . $f_message .
"\n\n\nTechnical Details:\n" . $from_ip . "\n" . $from_browser;
$send_subject .= " - {$f_name}";
$headers = "From: " . $f_email . "\r\n" .
"Reply-To: " . $f_email . "\r\n" .
"X-Mailer: PHP/" . phpversion();
if (!$f_email) {
echo "no email";
exit;
}else if (!$f_name){
echo "no name";
exit;
}else{
if (filter_var($f_email, FILTER_VALIDATE_EMAIL)) {
mail($send_to, $send_subject, $message, $headers);
echo "true";
}else{
echo "invalid email";
exit;
}
}
?>
</code></pre>
<p>Is this code safe? How secure is the email address from users? Am I using best practices in this implementation?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T20:37:07.010",
"Id": "57542",
"Score": "1",
"body": "Does `cleanupentries` also clean up newlines? Otherwise it would be trivial to inject additional headers into the outgoing mail."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-17T06:45:14.297",
"Id": "57605",
"Score": "0",
"body": "@MischaArefiev You should post that as an answer (perhaps with a bit of explanation)."
}
] |
[
{
"body": "<p>Your code is safe as far as I can tell. You may consider adding some additional levels of spam checking though to stop invalid requests sooner. </p>\n\n<ol>\n<li>Use a token generated by your server when the form renders, pass that to php-file.php to check when processing the submission, if it isn't in your token list, it didn't come from your server. These tokens should only be used once before they are discarded. It will help you stop Cross Site Request Forgery attempts. It would mean having a storage medium to keep track of the tokens though, so it adds a little bit of overhead to the process. </li>\n<li>Honeypot field(s). These are just input fields that you hide with CSS so that a normal user would not fill them in. If they have a value when you process your script you should stop execution.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T22:39:14.180",
"Id": "35457",
"ParentId": "35405",
"Score": "2"
}
},
{
"body": "<p>As <code>htmlspecialchars</code> doesn't seem to clean up newlines in the code, and none of the other two functions does, it is possible to inject any number of headers into your outgoing messages.</p>\n\n<p>Consider this simple code:</p>\n\n<pre><code><?php\necho \"<pre>\\n\";\n$header = \"Hello!\\r\\nMalicious-Header: malicious/value\\r\\n\";\n\necho \"<pre>\\n\";\necho \"From: admin@example.com\\n\";\necho \"To: user@example.com\\n\";\necho \"Good-Header: \" . htmlspecialchars($header);\necho \"</pre>\\n\";\n?>\n</code></pre>\n\n<p>Its output is:</p>\n\n<pre><code>From: admin@example.com\nTo: user@example.com\nGood-Header: Hello!\nMalicious-Header: malicious/value\n</code></pre>\n\n<p>Depending on your installation, this may or may not be dangerous, but it is still a good habit to be aware of injection attacks. The general principle is: get rid of special characters not only from your input context but also from your output context. In your case, you place data into the context of RFC mail headers, and in headers, newlines are special characters.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-17T07:58:26.457",
"Id": "35524",
"ParentId": "35405",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "35524",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T06:53:56.100",
"Id": "35405",
"Score": "2",
"Tags": [
"php",
"security",
"ajax"
],
"Title": "Is this contact form safe?"
}
|
35405
|
<p>I have a Lua project that uses some syntax sugar described in <a href="http://lua-users.org/wiki/DecoratorsAndDocstrings" rel="nofollow">DecoratorsAndDocstrings</a>, near the bottom of the page. It looks like this:</p>
<pre class="lang-lua prettyprint-override"><code>random =
docstring[[Compute random number.]] ..
function(n)
return math.random(n)
end
</code></pre>
<p>Notice how the function definition is concatenated to the result of the function previous function call. I also have similar sugar like this:</p>
<pre class="lang-lua prettyprint-override"><code>something = foo.bar "Blah" { a = 1, b = 2 }
</code></pre>
<p>Basically, the idea is that instead of <code>foo.bar</code> taking two arguments (a string and a table), it only takes the first argument, and returns a function that finishes the operation (like a continuation). In the first example, instead of returning a function, we'd return a table with a <code>__concat</code> meta method.</p>
<p>I ended up with a handful of functions in my project that use syntax like this. The problem is: </p>
<ul>
<li>The code is not straightforward.</li>
<li>It's difficult to document properly.</li>
<li>Adding support for non-sugared calls compounds the previous two problems.</li>
</ul>
<p>So, I had the idea to just write them as normal functions, and create a "sweeten" function that takes two arguments: a function to "sweeten," and the number of args it wants. It returns a wrapper for the function. If you call the wrapper with at least the required number of arguments, it will simply tail-call the wrapped function. If you call it with less arguments, it will instead return a sort of "continuation table" with both <code>__call</code> and <code>__concat</code> metamethods set up as wrappers to the wrapper -- calling them will invoke the wrapper again with the previous args and the new args.</p>
<pre class="lang-lua prettyprint-override"><code>local function sweeten(fn, argc)
local wrapper
argc = tonumber(argc) or 2
local function unpack_plus(t, i, ...)
i = i or 1
if i <= #t then
return t[i], unpack_plus(t, i + 1, ...)
else
return ...
end
end
local function resume(t, ...)
return wrapper(unpack_plus(t, 1, ...))
end
local meta = { __call = resume, __concat = resume }
wrapper = function(...)
if select('#', ...) >= argc then
return fn(...)
else
return setmetatable({...}, meta)
end
end
return wrapper
end
</code></pre>
<p>To test if out, you can do something like:</p>
<pre class="lang-lua prettyprint-override"><code>function foo(a, b, c) print(a, b, c) end
function sweet_foo = sweeten(foo, 3)
sweet_foo "qwe" "asd" "zxc" -- prints stuff
</code></pre>
<p>I feel like I should be able to simplify <code>sweeten</code> and still get the same result. I'd especially like to get rid of <code>unpack_plus</code>, but I can't see a way to do it. Any thoughts?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T07:39:33.480",
"Id": "35408",
"Score": "4",
"Tags": [
"lua"
],
"Title": "Can this \"syntax sweetener\" be improved?"
}
|
35408
|
<p>I am making a filter to get posts by status that are saved by post metavalue in a Wordpress plugin. It is a question and answer system, where the question and answer are post objects.</p>
<pre><code> // Filter post where
function posts_where( $where ) {
global $wpdb, $dwqa_general_settings;
switch ( $this->filter['filter_plus'] ) {
case 'overdue' :
$overdue_time_frame = isset($dwqa_general_settings['question-overdue-time-frame']) ? $dwqa_general_settings['question-overdue-time-frame'] : 2;
$where .= " AND post_date < '" . date('Y-m-d H:i:s', strtotime('-'.$overdue_time_frame.' days') ) . "'";
case 'open':
// answered
$where .= " AND ID NOT IN (
SELECT `t1`.question FROM
( SELECT `{$wpdb->prefix}posts`.post_author, `{$wpdb->prefix}postmeta`.meta_value as `question`, `{$wpdb->prefix}posts`.post_date FROM `{$wpdb->prefix}posts` JOIN `{$wpdb->prefix}postmeta` ON `{$wpdb->prefix}posts`.ID = `{$wpdb->prefix}postmeta`.post_id WHERE `{$wpdb->prefix}posts`.post_type = 'dwqa-answer' AND ( `{$wpdb->prefix}posts`.post_status = 'publish' OR `{$wpdb->prefix}posts`.post_status = 'private' ) AND `{$wpdb->prefix}postmeta`.meta_key = '_question' ) as `t1`
JOIN
(SELECT `{$wpdb->prefix}postmeta`.meta_value as `question`, max(`{$wpdb->prefix}posts`.post_date) as `lastdate` FROM `{$wpdb->prefix}posts` JOIN `{$wpdb->prefix}postmeta` on `{$wpdb->prefix}posts`.ID = `{$wpdb->prefix}postmeta`.post_id WHERE post_type = 'dwqa-answer' AND ( `{$wpdb->prefix}posts`.post_status = 'publish' OR `{$wpdb->prefix}posts`.post_status = 'private' ) AND `{$wpdb->prefix}postmeta`.meta_key = '_question' GROUP BY `{$wpdb->prefix}postmeta`.meta_value) as t2
ON `t1`.question = `t2`.question AND `t1`.post_date = `t2`.lastdate
JOIN `{$wpdb->prefix}usermeta` ON `t1`.post_author = `{$wpdb->prefix}usermeta`.user_id
WHERE 1=1 AND `{$wpdb->prefix}usermeta`.meta_key = '{$wpdb->prefix}capabilities' AND (
`{$wpdb->prefix}usermeta`.meta_value LIKE '%administrator%'
OR `{$wpdb->prefix}usermeta`.meta_value LIKE '%editor%'
OR `{$wpdb->prefix}usermeta`.meta_value LIKE '%author%'
) ";
if( current_user_can('edit_posts' ) ) {
$where .= " AND ID NOT IN (
SELECT `{$wpdb->prefix}postmeta`.meta_value FROM
`{$wpdb->prefix}comments`
JOIN
( SELECT `{$wpdb->prefix}comments`.comment_ID, `{$wpdb->prefix}comments`.comment_post_ID, max( `{$wpdb->prefix}comments`.comment_date ) as comment_time FROM `{$wpdb->prefix}comments`
JOIN `{$wpdb->prefix}posts` ON `{$wpdb->prefix}comments`.comment_post_ID = `{$wpdb->prefix}posts`.ID
WHERE `{$wpdb->prefix}comments`.comment_approved = 1 AND `{$wpdb->prefix}posts`.post_type = 'dwqa-answer'
GROUP BY `{$wpdb->prefix}comments`.comment_post_ID ) as t1
ON `{$wpdb->prefix}comments`.comment_post_ID = t1.comment_post_ID AND `{$wpdb->prefix}comments`.comment_date = t1.comment_time
JOIN `{$wpdb->prefix}usermeta` ON `{$wpdb->prefix}comments`.user_id = `{$wpdb->prefix}usermeta`.user_id
JOIN `{$wpdb->prefix}postmeta` ON `{$wpdb->prefix}postmeta`.post_id = `{$wpdb->prefix}comments`.comment_post_ID
WHERE 1=1 AND `{$wpdb->prefix}usermeta`.meta_key = '{$wpdb->prefix}capabilities'
AND `{$wpdb->prefix}usermeta`.meta_value NOT LIKE '%administrator%'
AND `{$wpdb->prefix}usermeta`.meta_value NOT LIKE '%editor%'
AND `{$wpdb->prefix}usermeta`.meta_value NOT LIKE '%author%'
AND `{$wpdb->prefix}postmeta`.meta_key = '_question'
) ";
}
$where .= " )";
break;
case 'replied':
// answered
$where .= " AND ID IN (
SELECT `t1`.question FROM
( SELECT `{$wpdb->prefix}posts`.post_author, `{$wpdb->prefix}postmeta`.meta_value as `question`, `{$wpdb->prefix}posts`.post_date FROM `{$wpdb->prefix}posts` JOIN `{$wpdb->prefix}postmeta` ON `{$wpdb->prefix}posts`.ID = `{$wpdb->prefix}postmeta`.post_id WHERE `{$wpdb->prefix}posts`.post_type = 'dwqa-answer' AND ( `{$wpdb->prefix}posts`.post_status = 'publish' OR `{$wpdb->prefix}posts`.post_status = 'private' ) AND `{$wpdb->prefix}postmeta`.meta_key = '_question' ) as `t1`
JOIN
(SELECT `{$wpdb->prefix}postmeta`.meta_value as `question`, max(`{$wpdb->prefix}posts`.post_date) as `lastdate` FROM `{$wpdb->prefix}posts` JOIN `{$wpdb->prefix}postmeta` on `{$wpdb->prefix}posts`.ID = `{$wpdb->prefix}postmeta`.post_id WHERE post_type = 'dwqa-answer' AND ( `{$wpdb->prefix}posts`.post_status = 'publish' OR `{$wpdb->prefix}posts`.post_status = 'private' ) AND `{$wpdb->prefix}postmeta`.meta_key = '_question' GROUP BY `{$wpdb->prefix}postmeta`.meta_value) as t2
ON `t1`.question = `t2`.question AND `t1`.post_date = `t2`.lastdate
JOIN `{$wpdb->prefix}usermeta` ON `t1`.post_author = `{$wpdb->prefix}usermeta`.user_id
WHERE 1=1 AND `{$wpdb->prefix}usermeta`.meta_key = '{$wpdb->prefix}capabilities' AND ( `{$wpdb->prefix}usermeta`.meta_value LIKE '%administrator%'
OR `{$wpdb->prefix}usermeta`.meta_value LIKE '%editor%'
OR `{$wpdb->prefix}usermeta`.meta_value LIKE '%author%'
)
)";
break;
default:
# code...
break;
}
return $where;
}
</code></pre>
<p>Review my MySQL code to make sure it performs well.</p>
|
[] |
[
{
"body": "<p>I remember answering a question that was similar to this one, in that it also needed a stored procedure.</p>\n\n<p>this code could use several stored procedures. I don't know how sprocs work in MySQL but I assume that you can still code them.</p>\n\n<p>it looks to me like you are trying to write a lot of SQL Code in the PHP, you can do this but it is a waste of the PHP Server Resources, let the Database do the work it is supposed to be doing.</p>\n\n<p>you should be able to do the Case Statement in SQL as well. all of this should be SQL Code not SQL inside of PHP Logic.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T04:22:14.883",
"Id": "58063",
"Score": "0",
"body": "as i said that i am developing a wordrpess plugin, i can't change database of plugin's users, just write mysql query by php :-/"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-17T18:23:36.613",
"Id": "35544",
"ParentId": "35409",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T07:52:23.817",
"Id": "35409",
"Score": "2",
"Tags": [
"php",
"mysql",
"plugin",
"wordpress"
],
"Title": "Wordpress filter post by metavalue"
}
|
35409
|
<p>I have a script, which updates my table's column and writes an id to it.</p>
<p>I need to check whether the column is empty or not. If it is not, I add a <code>,</code>.</p>
<pre><code>$subs = mysql_fetch_array(mysql_query("SELECT subscribed_user_id FROM users WHERE user_id=".(int)$_GET['user']));
$subs_array = array();
$subs_array=explode(',', $subs['subscribed_user_id']);
if(!in_array($_COOKIE['user_id'], $subs_array))
{
if($subs['subscribed_user_id']=='')
{
$add='';
} else {
$add = $subs['subscribed_user_id'].',';
}
mysql_query("UPDATE users SET subers=subers+1, subscribed_user_id='".$add.$_COOKIE['user_id']."' WHERE user_id=".(int)$_GET['user']);
}
</code></pre>
<p>I have an idea: always add <code>,</code>. But when I select it, I don't use the full length of the array. But, for example <code>array.length-2</code>, I think that it is not OK and I need to know how I can improve this script.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T09:30:10.190",
"Id": "57384",
"Score": "1",
"body": "I don't really understand what you're trying to do? Just add a , if the column is not empty? Why? Your script is also prone to SQL injections."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T10:26:41.620",
"Id": "57393",
"Score": "0",
"body": "I believe the idea is to comma separate multiple values in a single column."
}
] |
[
{
"body": "<p>With regard to your question about adding <code>,</code>, just do</p>\n\n<pre><code>$new_user_id = $_COOKIE['user_id'];\n\nif ($subs['subscribed_user_id'] === '') {\n $new_user_id = $subs['subscribed_user_id'] . ',' . $new_user_id;\n}\n</code></pre>\n\n<p>With that said, the details of how you add the comma is not the issue here.</p>\n\n<p>I began rewriting the code, but since the db interactions make the code hard to test and work with, I honestly couldn't be bothered to properly finish it.</p>\n\n<p>You should </p>\n\n<ol>\n<li>Wrap the functionality in a actual <code>function</code> taking parameters to remove use of <code>$_</code> globals.</li>\n<li>Stop using the ancient and deprecated <a href=\"http://www.php.net/manual/en/ref.mysql.php\" rel=\"nofollow\"><code>mysql</code></a> extension. In fact, don't use (the much better) <a href=\"http://www.php.net/manual/en/book.mysqli.php\" rel=\"nofollow\"><code>mysqli</code></a> either, at the very least, adopt <a href=\"http://www.php.net/manual/en/ref.pdo-mysql.php\" rel=\"nofollow\"><code>PDO</code></a>, or better yet, a tool that removes the low level details of managing the DB.</li>\n<li>Fix the <a href=\"https://en.wikipedia.org/wiki/SQL_injection\" rel=\"nofollow\">injection vulnerability</a> in your update query.</li>\n<li>Consider whether you really should be comma separating values in the column. Perhaps you should instead add a new row?</li>\n</ol>\n\n<p>Some code I started writing, but didn't finish because I have better things to do than setting up the db I would need.</p>\n\n<pre><code>function update_user_id($user_id, $subs, $cookie) {\n $subs = mysql_fetch_array(mysql_query(\"SELECT subscribed_user_id FROM users WHERE user_id = \" . (int) $user_id));\n\n $subs_array = explode(',', $subs['subscribed_user_id']);\n\n if (!in_array($cookie['user_id'], $subs_array)) {\n $new_user_id = $cookie['user_id'];\n\n if ($subs['subscribed_user_id'] === '') {\n $new_user_id = $subs['subscribed_user_id'] . ',' . $new_user_id;\n }\n\n mysql_query(\"UPDATE users SET subers = subers + 1, subscribed_user_id = '\" . $new_user_id . \"' WHERE user_id = \". (int) $user_id);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T10:24:58.017",
"Id": "35428",
"ParentId": "35422",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "35428",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T08:50:47.713",
"Id": "35422",
"Score": "1",
"Tags": [
"php",
"mysql"
],
"Title": "How to improve my PHP adding script?"
}
|
35422
|
<p>I have this<code>Point</code> Class:</p>
<pre><code>public class Point
{
private final int CONSTANT_VALUE = 0;
private int _x;
private int _y;
public Point(int x, int y)
{
_x = x;
_y = y;
}
public Point(Point other)
{
_x = other._x;
_y = other._y;
}
public int getX()
{
return _x;
}
public int getY()
{
return _y;
}
public void setX(int x)
{
if (x < 0)
_x = CONSTANT_VALUE;
else
_x = x;
}
public void setY(int y)
{
if (y < 0)
_x = CONSTANT_VALUE;
else
_y = y;
}
public void move (int dX, int dY)
{
int newXValue = _x + dX;
int newYValue = _y + dY;
if (newXValue >= 0 || newYValue >= 0)
{
_x = _x + dX;
_y = _y + dY;
}
}
}
</code></pre>
<p>And City Class:</p>
<pre><code>public class City
{
private String _cityName;
private Point _cityCenter;
private Point _centralStation;
private long _numOfResidents;
private int _noOfNeighborhoods;
private final long RESIDENTS_CONST_VALUE = 0;
private final int NEIGHBORHOODS_CONST_VALUE = 1;
public City(String cityName, Point cityCenter,
Point centralStation, long numOfResidents, int noOfNeighborhoods)
{
_cityName = cityName;
_cityCenter = cityCenter;
_centralStation = centralStation;
if (numOfResidents < 0)
_numOfResidents = RESIDENTS_CONST_VALUE;
else
_numOfResidents = numOfResidents;
if (noOfNeighborhoods <= 0)
_noOfNeighborhoods = NEIGHBORHOODS_CONST_VALUE;
else
_noOfNeighborhoods = noOfNeighborhoods;;
}
public City(City other)
{
_cityName = other._cityName;
_cityCenter = new Point(other._cityCenter);
_centralStation= new Point(other._centralStation);
_numOfResidents = other._numOfResidents;
_noOfNeighborhoods = other._noOfNeighborhoods;
}
public String getCityName()
{
return _cityName;
}
public Point getCityCenter()
{
return _cityCenter;
}
public Point getCentralStation()
{
return _centralStation;
}
public long getNumOfResidents()
{
return _numOfResidents;
}
public int getNoOfNeighborhoods()
{
return _noOfNeighborhoods;
}
public void setCityName(String cityName)
{
_cityName = cityName;
}
public void setCityCenter(Point cityCenter)
{
_cityCenter = cityCenter;
}
public void setCentralStation(Point centralStation)
{
_centralStation = centralStation;
}
public void setNumOfResidents(long numOfResidents)
{
_numOfResidents = numOfResidents;
}
public void setNoOfNeighborhoods(int noOfNeighborhoods)
{
_noOfNeighborhoods = noOfNeighborhoods;
}
public String toString()
{
return "City Name: " + _cityName + "\n" +
"City Center: " + _cityCenter + "\n" +
"Central Station: " + _centralStation + "\n" +
"Number of Residents: " + _numOfResidents + "\n" +
"Number of Neighborhoods: " + _noOfNeighborhoods;
}
public boolean addResidents(long residentsUpdate)
{
long newResidentAmount = _numOfResidents + residentsUpdate;
if (newResidentAmount < 0)
{
_numOfResidents = 0;
return false;
}
else
{
_numOfResidents = newResidentAmount;
return true;
}
}
public void moveCentralStation(int deltaX,int deltaY)
{
_centralStation.move(deltaX, deltaY);
}
public double distanceBetweenCenterAndStation()
{
return _cityCenter.distance(_centralStation);
}
public City newCity(String newCityName, int dX, int dY)
{
Point newCityCenterPoint = new Point(_cityCenter);
newCityCenterPoint.move(dX, dY);
Point newCityCentralStationPoint = new Point(_centralStation);
newCityCentralStationPoint.move(dX, dY);
return new City(
newCityName,
newCityCenterPoint,
newCityCentralStationPoint,
0,
1);
}
}
</code></pre>
<p>My question:</p>
<ol>
<li><p>Point class: method public Point(Point other) - do i need to write this i other way to avoid aliasing ?</p></li>
<li><p>what about the rest get and set method from both <code>Point</code> and <code>City</code> classes ? i need to write it in other way or this is OK ?</p></li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T10:10:43.537",
"Id": "57390",
"Score": "0",
"body": "I personally prefer the short if, if the code is so short: `_x = x < 0 ? CONSTANT_VALUE : x;`, but this is a matter of taste. But By the way, CONSTANT_VALUE is not defined anywhere, so you should define it and give it a meaningful name."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T10:41:24.737",
"Id": "57395",
"Score": "3",
"body": "why are you prefixing \"_\" with the variables ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T11:03:41.387",
"Id": "57396",
"Score": "0",
"body": "Kinjal: This is my homework and this the way i have to define it @user hichaeretaqua: CONSTANT_VALUE added, i forgot it"
}
] |
[
{
"body": "<ul>\n<li><p>There looks to be a bug in <code>setY</code>: it assigns to <code>_x</code> instead of <code>_y</code>.</p></li>\n<li><p>This code can avoid aliasing problems on small classes like <code>Point</code> by making them immutable. That is, remove the <code>setX</code> and <code>setY</code> methods from <code>Point</code>. Any time a change needs to be made to a point, construct a new <code>Point</code> entirely.</p></li>\n</ul>\n\n<p><code>moveCentralStation</code> then becomes:</p>\n\n<pre><code>class Point {\n ...\n Point makeMovedPoint(int deltaX, int deltaY) {\n return new Point(_x + deltaX, _y + deltaY);\n }\n ...\n}\n\nclass City {\n ...\n void moveCentralStation(int deltaX, int deltaY) {\n _centralStation = _centralStation.makeMovedPoint(deltaX, deltaY);\n }\n ...\n}\n</code></pre>\n\n<p><code>City</code> can be made immutable in a similar fashion. However, that might end up crossing a line and make things less maintainable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T10:23:59.873",
"Id": "57391",
"Score": "0",
"body": "Point move added, i cannot remove setX and setY methods from Point because that what i need to write (homework) and i cannot add new method except what define in my homework"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T10:09:08.683",
"Id": "35426",
"ParentId": "35424",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T09:55:08.827",
"Id": "35424",
"Score": "2",
"Tags": [
"java"
],
"Title": "Aliasing in Set and Get?"
}
|
35424
|
<p>I would like to know if my chosen layout is HTML5 standards compliant, or if I'm using the heading tags incorrectly (or any other tag for that matter)?</p>
<p><strong>Main Header</strong></p>
<ul>
<li><code><h1></code> for website name</li>
<li><code><h2></code> for webpage name</li>
<li><code><h3></code> for website slogan, or should this be <code><span></code> with styling?</li>
</ul>
<p><strong>Main Content/Sidebar Content</strong></p>
<ul>
<li><code><h2></code> for every first heading in each <code><section></code> element (because a level 1 heading is too large), or should this really be <code><h1></code> with specific styling; e.g. <code>.panel-ws section h1</code>?</li>
<li><code>.first</code> removes unwanted top margin.</li>
<li><code>.panel-ws</code> adds whitespace (padding).</li>
</ul>
<h2>Example Code Extracts (OLD; Updated Below!)</h2>
<pre><code><header id="page-header" role="banner">
<div id="logo"></div>
<div id="header-text">
<h1>Website Name</h1>
<h2>Page Title</h2>
<h3>Slogan</h3>
</div>
</header>
<main id="content" role="main">
<div class="panel-ws">
<section id="name1">
<h2 class="first">Content 1</h2>
<p>Lorem ipsum...</p>
<p>Lorem ipsum...</p>
</section>
<section id="name2">
<h2>Content 2</h2>
<p>Lorem ipsum...</p>
<p>Lorem ipsum...</p>
</section>
<section id="name3">
<h2>Content 3</h2>
<p>Lorem ipsum...</p>
<p>Lorem ipsum...</p>
</section>
</div>
</main>
<aside id="sidebar" role="complementary">
<div class="panel-ws">
<section id="sidename1">
<h2 class="first">Side content 1</h2>
<p>Lorem ipsum...</p>
<p>Lorem ipsum...</p>
</section>
<section id="sidename2">
<h2>Side content 2</h2>
<p>Lorem ipsum...</p>
<p>Lorem ipsum...</p>
</section>
</div>
</aside>
#header-text h1
#header-text h2
#header-text h3
.panel-ws section h2
.first
</code></pre>
<h2>Example Code Extracts (UPDATED!)</h2>
<pre><code><header id="page-header" role="banner">
<div id="logo"></div>
<div id="header-text">
<h1>Website Name</h1>
<p>Slogan</p>
</div>
</header>
<main id="content" role="main">
<div class="panel-ws">
<header id="page-title-container">
<h1 id="page-title">Page Title</h1>
</header>
<section id="name1">
<h1>Content 1</h1>
<p>Lorem ipsum...</p>
<p>Lorem ipsum...</p>
</section>
<section id="name2">
<h1>Content 2</h1>
<p>Lorem ipsum...</p>
<p>Lorem ipsum...</p>
</section>
<section id="name3">
<h1>Content 3</h1>
<p>Lorem ipsum...</p>
<p>Lorem ipsum...</p>
</section>
</div>
</main>
<aside id="sidebar" role="complementary">
<div class="panel-ws">
<section id="sidename1">
<h1>Related Content 1</h1>
<p>Lorem ipsum...</p>
<p>Lorem ipsum...</p>
</section>
<section id="sidename2">
<h1>Related Content 2</h1>
<p>Lorem ipsum...</p>
<p>Lorem ipsum...</p>
</section>
</div>
</aside>
#header-text h1
#header-text p
.panel-ws #page-title-container #page-title
.panel-ws section h1
.panel-ws section h2
.panel-ws section h3
</code></pre>
|
[] |
[
{
"body": "<p>In HTML5 <code>h1</code> elements can be treated as relative to their semantic container, so it is not bad practice to have an <code>h1</code> as the main page header text <em>and</em> further <code>h1</code>'s for each <code>section</code>, <code>aside</code>, <code>article</code>, etc.</p>\n\n<p>As you've mentioned you would naturally style this with something like <code>section h1 { ... }</code>. I'd recommend making this more general and not depending on <code>.panel-ws</code> because you may want to hang it off <code>main</code> and <code>aside</code> instead to allow for different header text styling in each?</p>\n\n<p>I found a similar question on stackoverflow which you might want to check out too... </p>\n\n<p><a href=\"https://stackoverflow.com/questions/7405282/how-to-properly-use-h1-in-html5\">https://stackoverflow.com/questions/7405282/how-to-properly-use-h1-in-html5</a></p>\n\n<p>For the webpage name and slogan, you could group <code>h1</code> and <code>h2</code> elements inside a parent <code>hgroup</code> to ensure that html readers don't parse the slogan as an implicit second level of content.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-18T05:27:47.540",
"Id": "57717",
"Score": "0",
"body": "Thank you Stephen; you answered my original question. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T12:07:06.800",
"Id": "35434",
"ParentId": "35425",
"Score": "3"
}
},
{
"body": "<h3>Site heading</h3>\n\n<p>This is not correct:</p>\n\n<pre><code><div id=\"header-text\">\n <h1>Website Name</h1>\n <h2>Page Title</h2>\n <h3>Slogan</h3>\n</div>\n</code></pre>\n\n<p>Using <code>h1</code> for the website heading is good.</p>\n\n<p>But your page heading (<code>h2</code>), which typically is the main content heading, shouldn’t come there, as now everything else in scope of this page heading, not the site heading. The page heading should be part of the <code>main</code> element, and also part of a sectioning content element (<code>article</code> or <code>section</code>).</p>\n\n<p>The slogan should never be a heading (in previous HTML5 version, you could have used a heading together with the <code>hgroup</code> element, but this element is now obsolete). Typically it would be a <code>div</code> or, if appropriate, a <code>p</code>.</p>\n\n<h3>Content headings</h3>\n\n<p>It doesn’t matter if you use <code>h1</code> or <code>h2</code> (or any other appropriate level) for a sectioning content’s main heading. Always using <code>h1</code> would allow you to move sections without having to adjust the heading levels.</p>\n\n<h3>The sidebar</h3>\n\n<p>If the <code>aside</code> content is related to the whole website, it should be in scope of the site heading. If it’s related to the specific page only (i.e., the main content), it should be in scope of the page heading (that means: it should be a child of the content’s sectioning element).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T02:42:02.103",
"Id": "57483",
"Score": "0",
"body": "I've changed the position of the page title and also swapped the slogan to a `<p>` element. In response to the sidebar, its content is going to be related to the contents of the `<main>` element. For example, in `#content` I have the device specifications for the LG Nexus 5, and in the `#sidebar`, I would have all devices related to the Nexus 5, such as the Nexus 4, Nexus 10, Nexus 7, other top-tier LG phones, etc. Also, all first headings start with `<h1>`, and I'm going to follow the model of resetting this with each `<section>` or `<article>` element."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T03:06:06.027",
"Id": "57492",
"Score": "0",
"body": "@DylRicho: Regarding your page heading: you should use a `section` (or `article`, if you think it’s appropriate) explicitly, for example instead of the `div.panel-ws`. This one would include all your sub-sections (`name1`, `name2`, …) then. This, of course, only works if the page heading is appropriate for all these sub-sections. If not, your structure should be changed. -- For discussing these things it would be best to see an example with real content, as the heading outline depends on the actual content."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T16:07:35.660",
"Id": "57511",
"Score": "0",
"body": "[Here](http://v9.dylricho.com/temp/) be a semi-real example of this layout in action. The placement of the page title has me undecided as I did like it better in the banner section, even if it doesn't have to be a heading element."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T16:16:26.950",
"Id": "57512",
"Score": "0",
"body": "@DylRicho: In this example, \"HTC One S (Z520E)\" would be a child section of \"Device Specifications\" -- is this intended? I feel like \"HTC One S (Z520E)\" should be the page heading (= a `section` containing all the other content `section` elements) instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T16:26:10.683",
"Id": "57514",
"Score": "0",
"body": "\"Device Specifications\" was intended to be the page heading as it describes the category of the page, while \"HTC One S (Z520E)\" is supposed to be a subheading as it stems off from the page heading, in order to create a breadcrumb trail."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T16:29:42.593",
"Id": "57515",
"Score": "0",
"body": "@DylRicho: I see. Usually you don’t reproduce the full category tree in the heading outline. The `title` element may contain references to the top-categories, but the page heading should reflect the actual content on that page, not a top category of that content. Anyway, even if you stay with your current headings, \"HTC One S (Z520E)\" is not heading to the following sub-sections, because they are on the *same* level, instead of being included in the `#device-rank`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T16:55:52.223",
"Id": "57516",
"Score": "0",
"body": "Would me altering the \"Device Specifications\" heading to \"HTC One S (Z520E) Specifications\" (and then removing the \"HTC One S (Z520E)\" heading) help? I still did prefer the heading above the slogan, however. Is there a reason why the HTML `<hx>` structuring must be so strict/frustrating to follow?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T17:16:13.553",
"Id": "57517",
"Score": "0",
"body": "@DylRicho: If you want to follow [HTML5’s outline algorithm](http://www.w3.org/TR/2013/CR-html5-20130806/sections.html#outlines), yes. You can play around with this [outliner](http://gsnedders.html5.org/outliner/) to see what outline your page creates. It should make sense. Think of the outline as a kind of table of contents: every heading should exactly describe what the following content is about, with the correct nesting/hierarchy. As a general rule: use `section`/`article` for the main content, which include this main content’s heading and the whole content (e.g., sub-sections)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-17T03:47:19.417",
"Id": "57566",
"Score": "0",
"body": "I think it's probably [as good as I'm going to get it](http://gsnedders.html5.org/outliner/process.py?url=http%3A%2F%2Fv9.dylricho.com%2Ftemp%2F) right now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-17T04:26:55.113",
"Id": "57567",
"Score": "0",
"body": "I've just read up on [HTML5 Doctor](http://html5doctor.com/outlines/) about untitled elements in the outline, and it states that it's recommended that \"each element have a heading, even `<aside>` and `<nav>`.\" And I can hide the headings if I don't want them visible via CSS `display:none`. I could do that, if necessary? I was concerned about the untitled elements in the outline, until I read that you could hide them and it would still be okay."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-17T11:42:19.320",
"Id": "57632",
"Score": "0",
"body": "@DylRicho: It’s recommended to have a heading, but it’s not required! And yes, you may hide them via CSS (but make sure that they are still get read by screen readers; otherwise they’d be superfluous )."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-17T11:45:47.273",
"Id": "57633",
"Score": "0",
"body": "How does [the document outline](http://gsnedders.html5.org/outliner/process.py?url=http%3A%2F%2Fv9.dylricho.com%2Ftemp%2F) look now? Is that better or worse?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-17T11:54:22.830",
"Id": "57635",
"Score": "0",
"body": "@DylRicho: Overall pretty good. I’d only change small things now, e.g.,: \"Date and Time\" doesn’t deserve an own section; \"Social Interaction and Accessibility Tools\" shouldn’t be assembled; I wouldn’t give the footer and the breadcrumbs explicit headings (they probably don’t mean much to visitors). Oh, and `footer` in a `footer` is not allowed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-17T15:51:17.023",
"Id": "57652",
"Score": "0",
"body": "In regards to the accessibility, I was just trying to provide a little better compatibility with assistant devices for impaired users. By removing \"Page Footer\" wouldn't that mess up the 'recent content' headings too?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-17T17:47:01.583",
"Id": "57660",
"Score": "0",
"body": "@DylRicho: No, the footer would simply be untitled in the outline. But thanks to it being a `footer`, assistive technology may \"know\" that it’s a footer. But all this is now far away from your original question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-18T05:26:44.957",
"Id": "57716",
"Score": "0",
"body": "I see. Thank you for all the help. I have no further issues. :)"
}
],
"meta_data": {
"CommentCount": "16",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T01:03:41.890",
"Id": "35460",
"ParentId": "35425",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "35460",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T10:06:55.770",
"Id": "35425",
"Score": "4",
"Tags": [
"html",
"css",
"html5"
],
"Title": "Is there anything incorrect about this layout, semantically or otherwise?"
}
|
35425
|
<p>I am working on a Windows project using C++03 (C++11 is not an option), and without using Boost. I have several resources that are accessed by multiple threads at various times - a queue, for example, with data added by one thread and removed by another. Individual methods of the involved classes generally perform locking internally. However in some cases I need to lock the entire resource to perform a sequence of actions without another thread getting in the way.</p>
<p>Without the phrases "use Boost" and "use C++11", does the posted code for RAII-style locking of a resource look correct and safe, or is there something I've missed?</p>
<p>To this end I have written a simple RAII-style locking class, so that the following can be performed:</p>
<blockquote>
<pre><code>void somefunction(void) {
GetLock<LockableClass> lock(queue);
...
}
</code></pre>
</blockquote>
<p>Here the only requirement of <code>LockableClass</code> is that is has <code>Lock()</code> and <code>Unlock()</code> methods. Specialisations of the class are provided for <code>CRITICAL_SECTION</code>, etc.</p>
<p>However, in the case of there being several queues, only some of which need to be locked at one time, I would like the following to be possible:</p>
<blockquote>
<pre><code>void somefunction(void) {
list<GetLock<LockableClass> > locks;
for (vector<LockableClass>::iterator its = queues.begin(); queues.end() != its; ++its)
if (some_condition)
locks.push_back(GetLock<LockableClass>(*its));
...
}
</code></pre>
</blockquote>
<p>In order to achieve this I've added a copy-constructor to <code>GetLock</code>. This creates the requirement that any lockable object has to have some kind of reference counting. It also limits me to using a <code>std::list</code> as the container for the locks - at least in my version of Visual Studio (2008 - yes, yes, I know). <code>std::vector</code> appears to default-construct, then assign.</p>
<p>The following is the code for <code>GetLock</code>, along with a specialisation for <code>CRITICAL_SECTION</code>:</p>
<pre><code>template <typename TLOCKABLE>
class GetLock {
private:
TLOCKABLE& lock;
GetLock();
public:
GetLock(TLOCKABLE& plock) : lock(plock) {
lock.Lock();
}
GetLock(TLOCKABLE* plock) : lock(*plock) {
lock.Lock();
}
GetLock(const GetLock<TLOCKABLE>& plock) : lock(plock.lock) {
lock.Lock();
}
~GetLock(void) {
lock.Unlock();
}
};
template <>
class GetLock<CRITICAL_SECTION> {
private:
CRITICAL_SECTION& lock;
GetLock();
public:
GetLock(CRITICAL_SECTION& plock) : lock(plock) {
EnterCriticalSection(&lock);
}
GetLock(const GetLock<CRITICAL_SECTION>& plock) : lock(plock.lock) {
EnterCriticalSection(&lock);
}
~GetLock(void) {
LeaveCriticalSection(&lock);
}
};
// There is also a specialisation for HANDLE, to cope with mutexes...
// This presents its own issues as HANDLE is used everywhere in Windows,
// but differentiating between a Mutex and something else is a question
// for StackOverflow.
</code></pre>
<p>Does the code look safe? Is there something I've missed? Is making the assumption of using recursively-lockable objects a foolhardy thing to do? What could I do better?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T14:31:05.860",
"Id": "57412",
"Score": "0",
"body": "`std::vector appears to default-construct, then assign`. No It copy constructs into place. Because you have already created the object before the `push_back` is called."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T17:24:05.243",
"Id": "57430",
"Score": "0",
"body": "Usually when you have multiple lockable objects. You want to acquire them in a specific order (order to avoid deadlock). TO do this you must also release locks that you previously held if they are not acquired in the correct order."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T10:08:05.620",
"Id": "57923",
"Score": "0",
"body": "@LokiAstari: You're right regarding the `push_back`, but it seems that `std::vector` requires `op=` to be declared too, which is where my original code failed. I've updated my question with the \"final\" code, which I think works quite well. And yes, normally you may need to lock in a specific order, but for my purpose it's not so necessary... just that they all be locked prior to \"some process\"."
}
] |
[
{
"body": "<p>first I suggest you use <em>pointers</em> to keep the mutex reference; this makes it possible to have a non-owning state when the pointer is 0 (the state when default initialized)</p>\n\n<p>also you created a <strong>copy constructor</strong> and a <strong>destructor</strong>, so you still need a <strong>copy assignment</strong> to properly follow rule of 3 (or at least disable it)</p>\n\n<pre><code>GetLock<TLOCKABLE>& operator=(const GetLock<TLOCKABLE>& plock) {\n if(plock.lock != lock){\n GetLock<TLOCKABLE> tmp(plock); \n swap(tmp);\n\n }\n return *this;\n}\n</code></pre>\n\n<p>however this keeps the assumption that the lock is recursively-lockable, but as an optimization it won't reacquire and release when the locks are the same </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T13:08:21.157",
"Id": "57405",
"Score": "0",
"body": "Ah yes, I forgot about at least declaring `operator=`. And I'm not sure why I went with a reference, but changing to a pointer would allow your code above, and hence allow putting locks into a `vector` (if I allow default construction). Good stuff, thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T14:28:44.617",
"Id": "57411",
"Score": "0",
"body": "@icabod: Just change the internal representation to pointer. Maintain the interface that passes by reference."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T17:19:35.207",
"Id": "57428",
"Score": "0",
"body": "@ratchet You should use copy and swap idium for assignment operator. Its exception safe while this is not. If `lock->Lock()` throws then you fail to call `tmp->Unlock()`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-18T10:13:46.120",
"Id": "57760",
"Score": "0",
"body": "@LokiAstari: Good call on the copy-swap... the whole point of this class is to be exception safe. If I'm swapping to a pointer to the lockable object, then it makes copy-swap simple. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-18T10:19:53.773",
"Id": "57761",
"Score": "0",
"body": "@icabod yeah then the entire if block will be just `GetLock<TLOCKABLE> tmp(plock); swap(tmp);` with swap just swapping the lock pointers (which is exception safe)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T11:55:28.650",
"Id": "35433",
"ParentId": "35430",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "35433",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T11:08:07.337",
"Id": "35430",
"Score": "2",
"Tags": [
"c++",
"locking",
"winapi",
"c++03",
"raii"
],
"Title": "RAII-style lockable objects"
}
|
35430
|
<p>Let's say I have a collection of expensive-to-generate objects stored in an IEnumerable: </p>
<pre><code>IEnumerable<Expensive> expensiveObjects = CreateExpensiveIEnumerable();
</code></pre>
<p>Now I will iterate over everything in <code>expensiveObjects</code> and afterwards, I want to know if it was empty.</p>
<p>Here is how I am doing that currently.</p>
<pre><code>var count = 0;
foreach(var e in expensiveObjects)
{
count++;
//other processing
}
if (count == 0)
{
//do something
}
</code></pre>
<p>This works fine, but I'm asking here as a fishing expedition to figure out if there are any clever ways to implement this functionality without either:</p>
<ul>
<li>iterating over at least part of the collection twice by using the <code>Any()</code> method</li>
<li>Performing a <code>ToList()</code> up-front on my collection</li>
</ul>
<p>Any other suggestions or should I just stick with a simple counting variable?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T18:26:41.597",
"Id": "57436",
"Score": "0",
"body": "I'm confused, you say the objects are “stored” in the `IEnumerable` but you also don't want to iterate it twice, which looks like the objects are generated each time. So which one is it? Could you describe the characteristics on the `IEnumerable` in more detail?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T18:30:40.553",
"Id": "57438",
"Score": "0",
"body": "Sorry for any confusion, let's say CreateExpensiveIEnumerable() generates its return values through a `yield return` statement, does that help?"
}
] |
[
{
"body": "<p>It depends on the type that's implementing your <code>IEnumerable</code>. Per <a href=\"https://stackoverflow.com/questions/13738329/how-does-tolist-on-an-ienumerable-work\">this Jon Skeet SO answer</a>, calling <code>.ToList()</code> doesn't automatically mean an enumeration.</p>\n\n<p>I'd make sure <code>expensiveObjects</code> is some <code>IList</code>, and if that's the case I'd call <code>.ToList()</code> up-front, using the <code>Count</code> property instead of incrementing a <code>count</code> variable during the enumeration.</p>\n\n<pre><code>var items = expensiveObjects as IList<Expensive> ?? expensiveObjects.ToList();\n</code></pre>\n\n<p>Now if <code>expensiveObjects</code> is some \"pure\" <code>IEnumerable</code>, I believe this would effectively iterate the items, so it <em>could</em> be more efficient to increment a <code>count</code> variable as you're iterating.</p>\n\n<p>The best way to find out, ...is to try & profile both ways :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T19:15:14.480",
"Id": "57443",
"Score": "0",
"body": "In my example, this is a \"pure\" `IEnumerable`, so based on your answer, I'd be best off with my current approach."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T19:29:42.513",
"Id": "57445",
"Score": "0",
"body": "I would *think* so, but profiling/timing both alternatives (or being more knowledgeable about these subtleties than I am :s) would be the best way to find out for sure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T21:43:10.580",
"Id": "57457",
"Score": "0",
"body": "@ledbutter Why not generate them into a `List<T>`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T22:24:04.920",
"Id": "57459",
"Score": "1",
"body": "because then they would all be in memory at once, and I'd rather not do that"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T18:33:30.670",
"Id": "35445",
"ParentId": "35442",
"Score": "1"
}
},
{
"body": "<p>I think your approach is reasonable if you don't want (or can't) have the whole collection in memory. One minor change: if you don't need the count, just whether the collection was empty or not, use a simple <code>bool</code>:</p>\n\n<pre><code>bool any = false;\n\nforeach(var e in expensiveObjects)\n{\n any = true;\n\n //other processing\n}\n\nif (any)\n{\n //do something\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T21:51:45.267",
"Id": "35455",
"ParentId": "35442",
"Score": "5"
}
},
{
"body": "<p>One alternative would be to enclose this logic into an extension method:</p>\n\n<pre><code>static bool ForEach<T>(this IEnumerable<T> source, Action<T> action)\n{\n bool any = false;\n\n foreach (var x in source)\n {\n any = true;\n\n action(x);\n }\n\n return any;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>bool any = expensiveObjects.ForEach(e => /* other processing */);\n\nif (any)\n{\n //do something\n}\n</code></pre>\n\n<p>But I think that in this specific case, this doesn't make much sense and using normal <code>foreach</code> with additional variable is the better solution.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T21:22:27.953",
"Id": "35495",
"ParentId": "35442",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "35455",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T17:55:38.170",
"Id": "35442",
"Score": "3",
"Tags": [
"c#",
"ienumerable"
],
"Title": "Check IEnumerable Count"
}
|
35442
|
<p>I want you to look the following code for validating dictionary schemas. There are some libraries out there that do the same thing, but I just wanted to write my own for fun and not to overload my current project with a big third party library.</p>
<p>Feel free to comment regarding code optimization, duplication, API design and the testing part.</p>
<p>You can see the API usage in the test snippet.</p>
<pre><code>class ValidationError(Exception):
def __init__(self, *args, **kwargs):
super(ValidationError, self).__init__()
class Schema(object):
"""
Schema class to validate the structure of dic objects.
Accepts a dict of Attr's and validates their type, a validation function, etc.
usage: Schema({'name': Attr(str, validator=lambda x: len(x) > 0),
'age': Attr(int, lambda x: x > 0)})
To denote a nested dict you use it like this Attr(schema=Schema({...}))
"""
def __init__(self, attrs):
self._attrs = attrs
def bind(self, data):
if isinstance(data, dict):
self._data = data
return self
raise TypeError('data parameter is not a dict')
def validate(self, data=None):
"""
returns True if the bound data is valid to the schema
raises an exception otherwise
"""
if data:
self.bind(data)
for key in self._attrs.keys():
attr = self._attrs[key]
if not attr.is_optional and not key in self._data:
raise ValidationError('Required attribute {0} not present'.format(key))
if key in self._data:
attr.validate(self._data[key])
return True
class Attr(object):
"""
Class to be used inside a Schema object.
It validates individual items in the target dict,
usage: Attr(int, validatos=some_func)
"""
def __init__(self, t=None, optional=False, validator=None, schema=None):
self._t = t
self._optional = optional
self._validator = validator
self._schema = schema
@property
def is_schema(self):
return isinstance(self._schema, Schema)
@property
def is_optional(self):
return self._optional
@property
def validator(self):
return self._validator
@validator.setter
def validator(self, val):
self._validator = val
def validate(self, data):
if self._schema:
if not isinstance(self._schema, Schema):
raise TypeError('{0} is not instance of Schema'.format(data))
return self._schema.validate(data)
elif not isinstance(data, self._t):
raise TypeError('{0} is not instance of {1}'.format(data, self._t))
if self.validator and not self.validator(data):
raise ValidationError('attribute did not pass validation test')
return True
</code></pre>
<p>If you think some test are missing just tell it.</p>
<pre><code>import unittest
class TestAttr(unittest.TestCase):
def test_validates_type(self):
attr = Attr(int)
self.assertTrue(attr.validate(1), 'The attribute should be valid')
attr = Attr(int)
self.assertRaises(TypeError, attr.validate, '1')
def test_validates_validator(self):
attr = Attr(int, validator=lambda x: x > 1)
self.assertTrue(attr.validate(2), 'The attribute should be valid')
self.assertRaises(ValidationError, attr.validate, 0)
class TestSchema(unittest.TestCase):
def test_flat_schema(self):
schema = Schema({'name': Attr(str),
'age': Attr(int, validator=lambda x: x > 0),
'awesome': Attr(bool, optional=True, validator=lambda x: x == True)})
valid = {'name': 'python', 'age': 19, 'awesome': True}
self.assertTrue(schema.validate(valid), 'schema should be valid')
# omit optional
valid = {'name': 'python', 'age': 19}
self.assertTrue(schema.validate(valid), 'schema should be valid')
invalid = {'name': 'python'}
self.assertRaises(ValidationError, schema.validate, invalid)
# validate optional if present
invalid = {'name': 'python', 'age': 19, 'awesome': False}
self.assertRaises(ValidationError, schema.validate, invalid)
def test_nested_schema(self):
address = Schema({'street': Attr(str, validator=lambda x: len(x) > 0),
'number': Attr(int)})
schema = Schema({'name': Attr(str),
'age': Attr(int, validator=lambda x: x > 0),
'address': Attr(schema=address)})
valid_address = {'street': 'pip', 'number': 2}
invalid_address = {'street': '', 'number': 5}
valid_data = {'name': 'python', 'age': 4, 'address': valid_address}
invalid_data = {'name': 'python', 'age': 4, 'address': invalid_address}
self.assertTrue(schema.validate(valid_data), 'schema should be valid')
self.assertRaises(ValidationError, schema.validate, invalid_data)
</code></pre>
|
[] |
[
{
"body": "<h3>1. Error messages</h3>\n\n<p>The biggest problem with this code is that the error messages are useless. If the purpose is to validate data structures, then you have to think about what happens when validation fails. How easily are users going to be able to track down the cause of the problem?</p>\n\n<ol>\n<li><p>So imagine that you are validating some data using a schema that you got from some library:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> from somewhere import schema\n>>> data = dict(m=0)\n>>> schema.validate(data)\nTraceback (most recent call last):\n ...\nValidationError: attribute did not pass validation test\n</code></pre>\n\n<p>Now what? Why didn't the attribute pass the validation test? What are you supposed to do?</p>\n\n<p>The message really needs to explain what the problem is, for example this would be much better:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>ValidationError: 0 is not a valid month (use 1=January to 12=December)\n</code></pre>\n\n<p>So the <code>Attr</code> class needs some way of generating good error messages. For example, maybe the constructor could take a function that generates the message:</p>\n\n<pre><code>Attr(int, validator=lambda m:1 <= m <= 12,\n message=\"{} is not a valid month (use 1=January to 12=December)\".format)\n</code></pre>\n\n<p>(There are other ways of doing this which I'm sure you can think of.)</p></li>\n<li><p>Let's suppose you've implemented the suggestion above, and we try it out:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> data = dict(a=0, b=0, c=0)\n>>> schema.validate(data)\nTraceback (most recent call last):\n ...\nValidationError: 0 is not a valid month (use 1=January to 12=December)\n</code></pre>\n\n<p>Oh. Which attribute was the invalid month? Was it <code>a</code>, <code>b</code> or <code>c</code>? In order to be any use to the developer, the error message needs to include the attribute name:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>ValidationError: b=0 is not a valid month (use 1=January to 12=December)\n</code></pre></li>\n<li><p>But the attribute name on its own is not enough when you are validating a nested structure:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> data = dict(coordinates=dict(a=0, b=0, c=0), date=dict(a=0, b=0, c=0))\n>>> schema.validate(data)\nTraceback (most recent call last):\n ...\nValidationError: b=0 is not a valid month (use 1=January to 12=December)\n</code></pre>\n\n<p>The error message needs to include the complete path through the data structure to the erroneous attribute, perhaps like this:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>ValidationError: date.b=0 is not a valid month (use 1=January to 12=December)\n</code></pre></li>\n</ol>\n\n<h3>2. Other commentary</h3>\n\n<ol>\n<li><p>The validator doesn't fail if there are attributes that are present in the data but missing in the schema. For example, shouldn't this fail validation:</p>\n\n<pre><code>>>> schema = Schema({})\n>>> schema.validate(dict(a=1))\nTrue\n</code></pre></li>\n<li><p>You added some documentation, but it's very sketchy. It's really not good enough to say, \"You can see the API usage in the test snippet.\" Did you learn to use Python by <a href=\"http://hg.python.org/cpython/file/932db179585d/Lib/test\" rel=\"nofollow\">reading the unit tests</a>? If not, how can you in all fairness expect users of your class to do that?</p>\n\n<p>For example, what does a <code>Schema</code> object represent? What is its purpose? Can you give us a use case? Can you provide some examples? What does the <code>bind</code> method do? In the <code>validate</code> method, what's the role of the <code>data</code> argument? In the <code>Attr</code> constructor, what's the meaning of the <code>t</code>, <code>optional</code>, and <code>schema</code> arguments? And so on.</p></li>\n<li><p>There are some mistakes in the examples (there's a missing <code>validator=</code> in one place, and a typo <code>validatos</code> in another). If you used the <a href=\"http://docs.python.org/3/library/doctest.html\" rel=\"nofollow\"><code>doctest</code> module</a> to make your examples runnable, then you would have found and fixed these mistakes.</p></li>\n<li><p>In <code>ValidationError.__init__</code>, if you're just going to call the superclass's method, there's no point in defining the method at all. Just write:</p>\n\n<pre><code>class ValidationError(Exception):\n pass\n</code></pre></li>\n<li><p>What is the purpose of the <code>bind</code> method? It allows the caller to divide the validation process into two steps: first, bind <code>data</code> to a schema object; second, call <code>.validate()</code> with no argument to do the actual validation. But what does this achieve over calling <code>.validate(data)</code>?</p></li>\n<li><p>By testing <code>isinstance(data, dict)</code> you limit the kinds of object that can validated. The only methods on <code>data</code> you actually call are <code>__contains__</code>, <code>__iter__</code> and <code>__getitem__</code>, so it would be better to test against <a href=\"http://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping\" rel=\"nofollow\"><code>collections.abc.Mapping</code></a> rather than <code>dict</code>.</p></li>\n<li><p>A dictionary with no keys converts to Boolean as <code>False</code>, so instead of writing:</p>\n\n<pre><code>if data:\n self.bind(data)\n</code></pre>\n\n<p>(which would go wrong when <code>data={}</code>) you should write:</p>\n\n<pre><code>if data is not None:\n self.bind(data)\n</code></pre></li>\n<li><p>Instead of:</p>\n\n<pre><code>for key in self._attrs.keys():\n attr = self._attrs[key]\n</code></pre>\n\n<p>you should write:</p>\n\n<pre><code>for key, attr in self._attrs.items():\n</code></pre>\n\n<p>(or <code>.iteritems()</code> in Python 2). This avoids an unnecessary lookup, and in Python 2 also avoids the unnecessary allocation of a list of keys.</p></li>\n<li><p>In these lines:</p>\n\n<pre><code>if not attr.is_optional and not key in self._data:\n raise ValidationError('Required attribute {0} not present'.format(key))\nif key in self._data:\n attr.validate(self._data[key])\n</code></pre>\n\n<p>you look up <code>key</code> in <code>self._data</code> three times. This seems a waste. Turn the logic round and look up the key just once:</p>\n\n<pre><code>try:\n attr.validate(self._data[key])\nexcept KeyError:\n if not attr.is_optional:\n raise ValidationError(...)\n</code></pre></li>\n<li><p>It seems inelegant to me for the <code>is_optional</code> logic to be in the <code>Schema</code> class. Shouldn't this be in the <code>Attr</code> class?</p></li>\n<li><p>When you've removed the <code>bind</code> method, you'll see that the only method left on the class is the <code>validate</code> method. So I think it would be simpler to name the class <code>Validator</code> and use the <code>__call__</code> method instead. (This has the advantage that you no longer need the special-case <code>schema</code> argument to the <code>Attr</code> constriuctor.)</p></li>\n<li><p>Having a property <code>Attr.validator</code> with getter and setter seems pointless because these are only ever called from within the <code>Attr</code> class. The <code>Attr.is_schema</code> property is pointless because it is never used.</p></li>\n<li><p>Having a property <code>Attr.is_optional</code> seems pointless: why not just use an attribute?</p></li>\n<li><p>Having a special case for <code>Attr(schema=Schema(...))</code> is unnecessary: one can just write <code>Attr(validator=Schema(...).validate)</code>. Or if you take my suggestion above about using the <code>__call__</code> method, you'd be able to just write <code>Attr(validator=Schema(...))</code>.</p></li>\n<li><p>The <code>t</code> argument to the <code>Attr</code> constructor would be better named <code>classinfo</code> to match the name of the second argument to <a href=\"http://docs.python.org/3/library/functions.html#isinstance\" rel=\"nofollow\"><code>isinstance</code></a>. Since it's an optional argument, it should default to <code>object</code> (rather than <code>None</code>), so that if you don't specify it, the test passes rather than fails.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T17:40:42.837",
"Id": "35486",
"ParentId": "35446",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "35486",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T18:50:50.850",
"Id": "35446",
"Score": "1",
"Tags": [
"python",
"unit-testing"
],
"Title": "Remove duplication in python code for dict schema validation"
}
|
35446
|
<p>I'm experimenting with std::future, but haven't found any materials that deal with the usecase I have in mind and was hoping someone could either confirm or deny the validity of the approach excerpted below:</p>
<pre><code>class Thing {
private:
std::string mValue;
public:
Thing() : mValue( "" ) {}
void set(const std::string& s)
{
mValue = s;
reverse( mValue.begin(), mValue.end() );
}
const std::string& getValue() const
{
return mValue;
}
};
int main(int argc, const char * argv[])
{
Thing* tA = new Thing();
Thing* tB = new Thing();
Thing* tC = new Thing();
auto tLambda = [](const string& iStr, Thing* oThing) -> Thing* {
oThing->set( iStr );
return oThing;
};
future<Thing*> tA1 = async( launch::async, tLambda, "This is a test...A", tA );
future<Thing*> tB1 = async( launch::async, tLambda, "This is a test...B", tB );
future<Thing*> tC1 = async( launch::async, tLambda, "This is a test...C", tC );
future<Thing*> tA2 = async( launch::async, tLambda, tA1.get()->getValue(), tA );
future<Thing*> tB2 = async( launch::async, tLambda, tB1.get()->getValue(), tB );
future<Thing*> tC2 = async( launch::async, tLambda, tC1.get()->getValue(), tC );
cout << tA2.get()->getValue() << endl;
cout << tB2.get()->getValue() << endl;
cout << tC2.get()->getValue() << endl;
return 0;
}
</code></pre>
<p>In essence, I'd like to use <code>std::future</code> to update a pre-existing object's member variables rather than initializing and returning a new object (as is shown in most <code>std::future</code> examples I've seen). In the example above, the model seems a little suspect. I would love to hear any thoughts on the best way to achieve this sort of functionality. Ultimately, I would like to embed this in a thread-pool sort of context. </p>
<p>(Note: On another user's suggestion, <a href="https://stackoverflow.com/questions/20005276/using-stdfuture-to-manipulate-objects-in-c11">this is reposted from Stack Overflow</a>).</p>
|
[] |
[
{
"body": "<p>There are two things that concern me in the code you offer:</p>\n\n<ul>\n<li>The Thing instances pointed to by <code>tA</code>, <code>tB</code>, <code>tC</code> are leaked. In this case it looks like it would be trivial to address this by stack allocating them, and passing their address to the <code>async</code> calls: <code>Thing tA;</code> <code>async( ... , &tA);</code></li>\n<li>The cross thread synchronization dependencies are not explicitly addressed. Instead it's all implicit by the way the code is written. Any mistake in the code to lead to data races. For example if in creating <code>tB2</code> it called the wrong <code>get()</code> or pass the wrong <code>Thing*</code>, not only would it be the wrong value, but it might race.</li>\n</ul>\n\n<p>I spent some time trying to figure out if proposed functionality such as <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3328.pdf\" rel=\"nofollow\">Resumable Functions (pdf)</a> would allow this to be nicer, and while I expect resumable functions would help in more general code, in your code I think a bigger problem is the factoring. Namely, since nothing uses the middle state, the code passed to the future should encompass both operations.</p>\n\n<pre><code>auto tLambdaBoth = [](const string& iStr, Thing* oThing) -> Thing* {\n auto pthing = tLambda(iStr, oThing);\n return tLambda(pthing->getValue(), oThing);\n}\n</code></pre>\n\n<p>And writing this showed me a new angle on my second misgiving. The original code mixed uses of the original pointer and the pointer returned by <code>tLambda</code>. We know that they currently are the same pointer, but assuming that could restrict your options later. In <code>tLambdaBoth</code> I'd rather see <code>return tLambda(pthing->getValue(), pthing);</code> so why not the same in the original code?</p>\n\n<p>So we can address both points together by avoiding new, and then never reusing the original object; instead it always uses the pointer that's returned from the future:</p>\n\n<pre><code>Thing tA, tB, tC;\n\n// launch futures\nstd::vector<std::future<Thing*>> fut1;\nfut1.emplace_back(async(launch::async, tLambda, \"This is a test...A\", &tA));\nfut1.emplace_back(async(launch::async, tLambda, \"This is a test...B\", &tB));\nfut1.emplace_back(async(launch::async, tLambda, \"This is a test...C\", &tC));\n\n// launch second set; using values clearly no longer in flight\nstd::vector<std::future<Thing*>> fut2;\nfor (auto& fut : fut1)\n{\n auto pthing = fut.get();\n fut2.emplace_back(async(launch::async, tLambda, pthing->getValue(), pthing));\n}\n\n// report results\nfor (auto& fut : fut2)\n{\n cout << fut.get()->getValue() << endl;\n}\n</code></pre>\n\n<p>While I definitely like this a lot better, I'm not sure I understand your use case well enough to say whether this addresses it. Perhaps you should digest what I'm saying here, and then clarify your use case if this did not address what you were trying to determine about the validity of your approach.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-18T14:32:26.143",
"Id": "57784",
"Score": "0",
"body": "Thanks so much for this in-depth response. The approach you demonstrate fits nicely into the use case I have in mind."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T16:18:43.310",
"Id": "35483",
"ParentId": "35448",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "35483",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T19:32:55.033",
"Id": "35448",
"Score": "3",
"Tags": [
"c++",
"c++11"
],
"Title": "Using std::future to manipulate objects in C++11"
}
|
35448
|
Prolog is the most commonly used logic programming language. It supports non-deterministic programming through backtracking and pattern matching through unification.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T20:26:58.077",
"Id": "35451",
"Score": "0",
"Tags": null,
"Title": null
}
|
35451
|
<p>This is a program for converting Roman numerals to their decimal equivalents. There must be a better way of distinguishing between, for example, 'IV' and 'VI', than what I have currently written.</p>
<pre><code>#include <iostream>
#include <string>
using namespace std;
class romanType{
public:
romanType();
romanType(string s);
~romanType();
void setRoman(string); //Set the Roman numeral from user entries.
int romanToDecimal(); //Convert the Roman numeral(string) to Decimal value.
void printDecimal(); //Display the decimal value.
void printRoman(); //Display the Roman numeral value.
private:
string romanNum;
int decimalNum = 0;
};
romanType::romanType()
{
romanNum = 1;
}
romanType::~romanType()
{
}
void romanType::setRoman(string troll)
{
romanNum = troll;
}
int romanType::romanToDecimal()
{
for (int i = 0; i < romanNum.length(); i++)
{
if (romanNum[i] == 'I')
decimalNum++;
if (romanNum[i] == 'V')
{
if (i > 0 && romanNum[i - 1] == 'I')
decimalNum -= 2;
decimalNum += 5;
}
if (romanNum[i] == 'X')
{
if (i > 0 && romanNum[i - 1] == 'I')
decimalNum -= 2;
decimalNum += 10;
}
if (romanNum[i] == 'L')
{
if (i > 0 && romanNum[i - 1] == 'X')
decimalNum -= 20;
decimalNum += 50;
}
}
cout << decimalNum << endl;
return decimalNum;
}
int main()
{
string numerals;
do{
cout << "Enter roman numerals: ";
cin >> numerals;
romanType Rom;
Rom.setRoman(numerals);
Rom.romanToDecimal();
} while (true);
system("PAUSE");
}
</code></pre>
<p><strong>Sample output:</strong></p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Enter roman numerals: IX
9
Enter roman numerals: XI
11
Enter roman numerals: XIX
19
Enter roman numerals: XX
20
Enter roman numerals: LVIII
58
Enter roman numerals: LXXXVIII
88
Enter roman numerals: LXVI
66
Enter roman numerals: LXIV
64
Enter roman numerals:
</code></pre>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T21:49:23.423",
"Id": "57458",
"Score": "1",
"body": "perhaps you should look at Enum"
}
] |
[
{
"body": "<ul>\n<li><p><strong>Try not to use <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\"><code>using namespace std</code></a> and <a href=\"https://stackoverflow.com/questions/1107705/systempause-why-is-it-wrong\"><code>system(\"PAUSE\")</code></a>.</strong></p>\n\n<p>The former is okay for shorter programs or toy programs, or when used in local scope as opposed to global (such as within a function).</p>\n\n<p>The latter is best avoided as it is problematic while safer and more portable alternatives are in existence, such as <code>std::cin.get()</code>. It's also non-portable and only works with Windows.</p></li>\n<li><p>In certain environments (or depending on personal preference), new user-defined types should be capitalized and objects should be lowercase.</p>\n\n<pre><code>NewType objOfNewType;\n</code></pre></li>\n<li><p>Prefer an initializer list here:</p>\n\n<pre><code>NewType::NewType() : dataMember1(/* value */) {}\n</code></pre>\n\n<p>Although this may not make a huge difference in your code, it's still good to know about it when writing larger programs. It is best when initializing objects (especially when the arguments are of the same name) and <em>necessary</em> when initializing constants.</p></li>\n<li><p>As you're not using the destructor, you can leave it out. The compiler will make one for you that does any of the default cleanup.</p></li>\n<li><p>You shouldn't do this in the class declaration:</p>\n\n<pre><code>int decimalNum = 0;\n</code></pre>\n\n<p>You should instead put that into the initializer list as mentioned above:</p>\n\n<pre><code>// entries are separated by commas\n// can also be listed on separate lines\nclassName::className() : member1(0), member2(0) {}\n</code></pre></li>\n<li><p>You have declared <code>printRoman()</code>, but have not defined it. Better yet, overload <code>operator<<</code> for your class and leave out that empty declaration.</p>\n\n<p>Declare in header:</p>\n\n<pre><code>friend std::ostream& operator<<(std::ostream&, Class const&);\n</code></pre>\n\n<p>Define in source:</p>\n\n<pre><code>std::ostream& operator<<(std::ostream& out, Type const& obj)\n{\n return out << obj.typeMember;\n}\n</code></pre>\n\n<p>Print it out:</p>\n\n<pre><code>NewType objOfNewType;\nstd::cout << objOfNewType;\n</code></pre></li>\n<li><p><a href=\"https://stackoverflow.com/questions/1181079/stringsize-type-instead-of-int\"><code>int</code> is not a good loop counter type here</a>:</p>\n\n<pre><code>for (int i = 0; i < romanNum.length(); i++) {}\n</code></pre>\n\n<p><code>romanNum</code> is of type <code>std::string</code>, so you should use <a href=\"http://en.cppreference.com/w/cpp/types/size_t\" rel=\"nofollow noreferrer\"><code>std::string::size_type</code></a>. This will ensure that you can loop through <em>any</em> string size while not being limited by <code>int</code>'s size.</p>\n\n<p>Better yet, use its iterators instead (using a range-based <code>for</code>-loop in C++11):</p>\n\n<pre><code>for (auto& iter : romanNum)\n{\n if (iter == 'I')\n decimalNum++;\n}\n</code></pre>\n\n<p>Another alternative (if you don't have C++11 and cannot use the above):</p>\n\n<pre><code>for (std::string::iterator = romanNum.begin(); iter != romanNum.end(); ++iter)\n{\n if (*iter == 'I')\n decimalNum++;\n}\n</code></pre></li>\n<li><p>Prefer not to pass-by-value here:</p>\n\n<pre><code>void romanType::setRoman(string troll)\n{\n romanNum = troll;\n}\n</code></pre>\n\n<p>As you're not modifying <code>troll</code>, prefer to pass by constant reference (<code>const</code> and <code>&</code>). This will avoid unneeded copying, thereby also increasing performance. It's best only for non-native types (such as <code>std::string</code>), so disregard it for any of the <a href=\"http://en.cppreference.com/w/cpp/language/types\" rel=\"nofollow noreferrer\">native ones</a>.</p>\n\n<p>Example (in different forms):</p>\n\n<pre><code>void func(const std::string& str) {}\n</code></pre>\n\n<p></p>\n\n<pre><code>void func(std::string const& str) {}\n</code></pre></li>\n<li><p><code>do-while</code> loops are usually considered less-readable than <code>while</code> loops. However, you don't need a <code>while</code> loop here as that would require adding another user input before the loop.</p>\n\n<p>Instead, I'd recommend the \"infinite loop\" <code>for (;;)</code>:</p>\n\n<pre><code>for (;;)\n{\n std::cout << \"This message will print forever!\\n\";\n std::cout << \"But please do end this eventually!\\n\\n\";\n\n bool keepGoing = true;\n if (!keepGoing) break; // or return\n}\n</code></pre>\n\n<p>As described, this will keep looping until the loop is ended (usually with a <code>break</code>, <code>return</code>, or <code>return X</code> if non-<code>void</code>). You'll just need a conditional that will decide when the loop should end.</p></li>\n<li><p>Prefer to use variables as close in scope as possible:</p>\n\n<pre><code>std::cout << \"Input: \";\nint input;\nstd::cin >> input;\n</code></pre></li>\n<li><p>This is unneeded:</p>\n\n<pre><code>romanType Rom;\nRom.setRoman(numerals);\n</code></pre>\n\n<p>You're invoking the default destructor (no arguments) while calling the mutator.</p>\n\n<p>Instead, the object should be constructed right away with <code>numerals</code>:</p>\n\n<pre><code>romanType Rom(numerals);\n</code></pre>\n\n<p>Beyond that, you won't need a mutator in your program. They can also be bad for encapsulation, but that's another topic. For now, focus on proper object construction while <em>only</em> using necessary implementations. Keep your code as concise as possible.</p>\n\n<p>Note that my previous point about the initializer list was for example purposes. In this case, you'll need to add an argument to the list.</p>\n\n<pre><code>NewType::NewType(ArgType arg) : member1(arg) {}\n</code></pre>\n\n<p>With this in place:</p>\n\n<pre><code>NewType objOfNewType(5); // will compile\nNewType objOfNewType; // will not compile\n</code></pre>\n\n<p>In your program, the latter should still happen as the conversion process shouldn't work with no input given to the object. You <em>can</em> also keep your existing default constructor, allowing the latter to still work. But there may be no need for a default value if you want the user to give input.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T00:45:49.070",
"Id": "57466",
"Score": "0",
"body": "Thanks! \nI realized it was an infinite loop, I did it intentionally because I was in the process of debugging something. The final program will ask the user if he/she wants to convert another numeral."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T00:51:41.033",
"Id": "57468",
"Score": "0",
"body": "@Justin: That's fine. It does still help to know about the different loops when putting them to real use."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-17T08:19:14.790",
"Id": "57622",
"Score": "0",
"body": "You have suggested to do `for (;;) { ... if (!keepGoing) break; }` - if you do have a flag then wouldn't it be better to do `while(keepgoing) { ... }`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-17T08:48:10.563",
"Id": "57624",
"Score": "0",
"body": "@ChrisWue: Yes, perhaps. This was mainly an example, and I assume the OP would just need a simple loop like this."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T22:08:20.033",
"Id": "35456",
"ParentId": "35453",
"Score": "17"
}
},
{
"body": "<p>Jamal has some good comments on general coding style. To address the other part of your question though, here's an alternative way of implementing the conversion from a Roman Numeral string to an integer which is more general and also cleaner IMO:</p>\n\n<pre><code>int fromRoman(const string& x) {\n auto first = crbegin(x);\n const auto last = crend(x);\n\n auto decimalDigitFromRoman = [&](char unit, char five, char ten) {\n int num = 0;\n for (; first != last && *first == unit; ++first) ++num;\n while (first != last && (*first == ten || *first == five)) {\n num += *first == ten ? 10 : 5;\n for (++first; first != last && *first == unit; ++first) --num;\n }\n return num;\n };\n\n int num = 0, pow = 1;\n for (auto syms : {\"IVX\", \"XLC\", \"CDM\"}) {\n num += decimalDigitFromRoman(syms[0], syms[1], syms[2]) * pow;\n pow *= 10;\n }\n\n return num;\n}\n</code></pre>\n\n<p><a href=\"http://ideone.com/mhHldk\">Live version</a>.</p>\n\n<p>This function handles the \"standard\" forms and also most of the <a href=\"https://en.wikipedia.org/wiki/Roman_numerals#Alternative_forms\">\"alternative\" forms</a> described on the Wikipedia page.</p>\n\n<p>[<strong>Edited</strong> to add explanation below]</p>\n\n<p>There's a few observations that lead to the approach used here. </p>\n\n<p>First, we can look at a Roman numeral as a special kind of decimal number where the 'digits' can be 0-n characters long and 'digits' of different powers are written with different symbols. So the number 321 (3x100 + 2x10 + 1x1) is written <code>CCC'XX'I</code> (3x100 + 2x10 + 1x1) (we don't write the separating <code>'</code>s). For the decimal digits 0-9 in least significant position the Roman numeral 'digits' are: <code>''(0)(an empty string), 'I'(1), 'II'(2), 'III'(3), 'IV'(4), 'V'(5), 'VI'(6), 'VII'(7), 'VIII'(8), 'IX'(9)</code>. </p>\n\n<p>Second, 'digits' of each power of 10 are written the same way, just using different symbols. For each power of 10, we have a 'unit' symbol, a 'five' symbol and a 'ten' symbol. For 10^0 these are <code>I,V,X</code>, for 10^1 they are <code>X,L,C</code>, for 10^2, <code>C,D,M</code>. The system doesn't extend to 10^3.</p>\n\n<p>Third, to parse a 'digit' forwards is tricky since we don't know for a given 'unit' symbol whether it is additive or subtractive without looking ahead (this is the problem that makes your code a bit tricky). Parsing backwards however we only need our previously seen context to interpret a symbol. If we see a 'five' or 'ten' symbol as our first symbol in a digit parsing backwards, subsequent 'unit' symbols for our current power are subtractive. Otherwise 'unit' symbols are additive until we hit a non-unit which marks the beginning of a subsequent 'digit'.</p>\n\n<p>We can now understand the code above. The lambda <code>decimalDigitFromRoman</code> parses a single Roman numeral 'digit' given the symbols for 'unit', 'five' and 'ten' by stepping backwards through the string using a reverse iterator. The loop below the lambda parses a sequence of Roman numeral 'digits' by calling the lambda in sequence for each set of symbols and multiplying by the corresponding power of 10. The sum is the integer value of the Roman numeral string.</p>\n\n<p>These rules as expressed in the code handle most of the edge cases automatically. Alternative forms like 'IIII' rather than 'IV' for 4 conveniently just fall out of the same rules when expressed appropriately. When we get to the 1000s we can just keep adding <code>M</code>s to the beginning of the number.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-21T03:02:25.430",
"Id": "105217",
"ParentId": "35453",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "35456",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-15T21:15:30.323",
"Id": "35453",
"Score": "15",
"Tags": [
"c++",
"homework",
"converting",
"roman-numerals"
],
"Title": "Roman numerals to decimal"
}
|
35453
|
<p><a href="http://www.microsoft.com/com/default.mspx" rel="nofollow">Component Object Model (COM)</a> specifies an architecture, a binary standard, and a supporting infrastructure for building, using, and evolving component-based applications. </p>
<p>Some of the core features of COM are: </p>
<ul>
<li>A remoting infrastructure</li>
<li>The use of interface-based programming </li>
<li>A threading model </li>
<li>The ability to write language independent components.</li>
</ul>
<p>COM is the foundation of technologies such as OLE, ActiveX and COM+.</p>
<p>COM predates .NET and although .NET has replaced some of the features that developers use COM for it is still a crucial technology and the foundation of most inter application communication on Windows. </p>
<p><strong>External links</strong> </p>
<ul>
<li><a href="http://www.microsoft.com/com/" rel="nofollow">Microsoft COM Technologies</a> </li>
<li><a href="http://www.polberger.se/components/read/com.html" rel="nofollow">A concise technical overview of COM</a> </li>
<li><a href="http://www.innovatia.com/software/papers/com.htm" rel="nofollow">The COM/DCOM Glossary</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T01:37:48.677",
"Id": "35464",
"Score": "0",
"Tags": null,
"Title": null
}
|
35464
|
Component Object Model (COM) is a component technology from Microsoft, featuring remoting, language independence and interface-based programming.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T01:37:48.677",
"Id": "35465",
"Score": "0",
"Tags": null,
"Title": null
}
|
35465
|
<p>I'm writing yet another MVC framework just for learning purposes and I would like you to review my code. Whenever I'm coding, I have that feeling that my code is horrible and is not the most efficient way to achieve something.</p>
<p>Right now the request class takes a URL path from <code>ORIG_PATH_INFO</code> or from <code>PATH_INFO</code> and explodes it into segments. Then I can easily retrieve controllers/actions/parameters from within my router class.</p>
<p><strong>request.php</strong></p>
<pre><code><?php
namespace framework\core;
class Request
{
/**
* Stores requested page.
*
* @var array
*/
private $segments = array();
/**
* Get requested page and explode it to segments.
*
* @param string $protocol
*/
public function __construct($protocol)
{
if($protocol != 'PATH_INFO' and $protocol != 'ORGI_PATH_INFO'){
throw new InvalidArgumentException('URI protocol was not setup correctly.');
}
$uri = (isset($_SERVER[$protocol])) ? $_SERVER[$protocol] : '';
$this->segments = explode('/', rtrim($uri, '/'));
array_shift($this->segments);
}
/**
* Return all segments.
*
* @return array
*/
public function getAll()
{
return $this->segments;
}
/**
* Get requested controller.
*
* @return mixed
*/
public function getController()
{
if(isset($this->segments[0])){
return strtolower($this->segments[0]);
}else{
return false;
}
}
/**
* Get requested action.
*
* @return mixed
*/
public function getAction()
{
if(isset($this->segments[1])){
return strtolower($this->segments[1]);
}else{
return false;
}
}
/**
* Get requested parameters.
*
* @return mixed
*/
public function getParams()
{
if(isset($this->segments[2])){
return array_slice($this->segments, 2);
}else{
return false;
}
}
}
</code></pre>
<p>And now the router class which matches controllers/methods automatically. (Right now it's pretty basic, but later I'm planning on adding predefined routes and maybe REST)</p>
<p><strong>router.php</strong></p>
<pre><code><?php
namespace framework\core;
class Router
{
/**
* Prefix which will be appended to the class method.
*
* @var constant
*/
const actionPrefix = 'action';
/**
* Router configuration data.
*
* @var array
*/
private $config = array();
/**
* Request class object.
*
* @var object
*/
private $request;
/**
* Controller to be called.
*
* @var string
*/
private $controller;
/**
* Action to be called.
*
* @var string
*/
private $action;
/**
* Parameters which will be passed to
* the controller.
*
* @var array
*/
private $params = array();
/**
* Store configuration and request object.
*
* @param array $config
* @param \framework\core\Request $request
*/
public function __construct($config, Request $request)
{
$this->config = $config;
$this->request = $request;
}
/**
* Match url to controllers/actions and pass parameters if available.
*/
public function dispatch()
{
$this->validateController();
$this->validateAction();
if(!$this->controllerExists() || !$this->actionExists()){
require_once(APP_PATH . 'error' . DS . 'error_404.php');
exit();
}
$controller = 'application\\controllers\\' . $this->controller;
$obj = new $controller;
if(!$this->paramsExists()){
call_user_func(array($obj, $this->action));
}else{
call_user_func_array(array($obj, $this->action), $this->params);
}
}
/**
* Check if user requested specific controller, if not
* then load the default one.
*
* @return boolean
*/
private function validateController()
{
$controller = $this->request->getController();
if($controller != false && $controller != ''){
$this->controller = $controller;
return true;
}
$this->controller = $this->config['DEFAULT_CONTROLLER'];
}
/**
* Check if user requested a specific action, if not
* then load the default action.
*
* @return boolean
*/
private function validateAction()
{
$action = $this->request->getAction();
if($action != false && $action != ''){
$this->action = self::actionPrefix . $action;
return true;
}
$this->action = self::actionPrefix . $this->config['DEFAULT_ACTION'];
}
/**
* Check of the requested controller exists in controllers
* directory.
*
* @return boolean
*/
private function controllerExists()
{
$path = APP_PATH . 'controllers' . DS . $this->controller . '.php';
if(file_exists($path)){
return true;
}
return false;
}
/**
* Check to see if action is callable or not.
*
* @return boolean
*/
private function actionExists()
{
if(is_callable(array('application\\controllers\\' . $this->controller, $this->action))){
return true;
}
return false;
}
/**
* Figure out if we have to pass additional parameters
* to the requested controller.
*
* @return boolean
*/
private function paramsExists()
{
if($this->request->getParams())
{
$this->params = $this->request->getParams();
return true;
}
return false;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>From quick glance I see a lot of logic in the constructor, usually not recommended. </p>\n\n<p>I would also avoid hard-coded indices for segments and use regular expressions to parse the URLs. Basically the less hard-coded strings are in the code, the better. </p>\n\n<p>You can place them together with all your constants and settings in a separate Config class or JSON. Then you can quickly change those settings and the code becomes more re-usable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-17T20:46:55.757",
"Id": "35548",
"ParentId": "35478",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "35548",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T12:02:55.997",
"Id": "35478",
"Score": "5",
"Tags": [
"php",
"mvc",
"url-routing"
],
"Title": "PHP router class"
}
|
35478
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.