body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I wrote this code for a dynamic stack and would like to know what would be better if done differently.</p>
<p>It can increase memory by a percentage and/or fixed value when needed. It can also be set to not increase automatically at all, so slots are only allocated by the user.</p>
<p>The stack is just a structure holding any data type, so it can change what kind of data is stored without deallocating memory.</p>
<p><strong>Header definitions</strong></p>
<pre><code>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define MINIMUM_ELEMENT_SIZE (1)
#define MULTIPLIER (1.00)
#define EXPANSION_AMOUNT (8)
typedef struct {
void *content;
size_t element_size;
size_t count;
size_t slots;
float multiplier;
size_t expansion_amount;
} Stack;
</code></pre>
<p><strong>Some inline functions to do very simple things</strong></p>
<pre><code>static inline void *memory_from_position(Stack *stack, size_t position) __attribute__((always_inline));
static inline size_t required_memory_for_slots(Stack *stack, size_t n_slots) __attribute__((always_inline));
static inline size_t how_many_slots_can_fit(size_t memory_size, size_t slot_size) __attribute__((always_inline));
static inline size_t available_slots(Stack *stack) __attribute__((always_inline));
//Return memory address based on position supplied, starts at 0, no error
//checking, caller must be sure the position is in range
static inline void *memory_from_position(Stack *stack, size_t position)
{
return stack->content + stack->element_size * position;
}
//Return how much memory n_slots would occupy
static inline size_t required_memory_for_slots(Stack *stack, size_t n_slots)
{
return stack->element_size * n_slots;
}
//Return how many slots can fit into memory
static inline size_t how_many_slots_can_fit(size_t memory_size, size_t slot_size)
{
return memory_size / slot_size;
}
//Return how many slots there are left
static inline size_t available_slots(Stack *stack)
{
return stack->slots - stack->count;
}
</code></pre>
<p><strong>Main functions</strong></p>
<pre><code>//Allocate and initialize stack
Stack *new_stack(size_t element_size)
{
if(element_size < MINIMUM_ELEMENT_SIZE){
return NULL;
}
Stack *temp = malloc(sizeof(Stack));
if(temp == NULL){
return NULL;
}
temp->content = NULL;
temp->element_size = element_size;
temp->count = 0;
temp->slots = 0;
temp->multiplier = MULTIPLIER;
temp->expansion_amount = EXPANSION_AMOUNT;
return temp;
}
void delete_stack(Stack *stack)
{
free(stack->content);
free(stack);
}
//Keep stack structure, free contents
void release_stack_resources(Stack *stack)
{
free(stack->content);
clear_stack(stack);
stack->content = NULL;
stack->slots = 0;
}
void clear_stack(Stack *stack)
{
stack->count = 0;
}
//Use an already allocated stack to hold a new data type, keep old multiplier and
//expansion amount, a few bytes may become unusable until a memory operation
//is performed, always succeed
void repurpose_stack(Stack *stack, size_t new_element_size)
{
//Calculate available memory
size_t available_memory = required_memory_for_slots(stack, stack->slots);
//Update slots count and stack
clear_stack(stack);
stack->slots = how_many_slots_can_fit(available_memory, new_element_size);
stack->element_size = new_element_size;
}
//Return multiplier set, must be positive
float set_stack_multiplier(Stack *stack, float new_multiplier)
{
if(new_multiplier >= 0){
stack->multiplier = new_multiplier;
}
return stack->multiplier;
}
//Can be set to 0
void set_stack_expansion_amount(Stack *stack, size_t expansion_amount)
{
stack->expansion_amount = expansion_amount;
}
//Allocate memory for more slots and return new memory location
void *add_slots(Stack *stack, size_t new_slots)
{
void *temp = realloc(stack->content, required_memory_for_slots(stack, stack->slots + new_slots));
if(temp == NULL){
return NULL;
}
stack->content = temp;
stack->slots += new_slots;
return temp;
}
//Remove slots whether they are empty or not, if the number is greater than
//the amount of slots, it removes all. Return pointer to stack or NULL
Stack *remove_slots(Stack *stack, size_t amount)
{
//Handle special case of removing all slots
if(amount >= stack->slots){
release_stack_resources(stack);
return stack;
}
//Regular usage
size_t slots_to_keep = stack->slots - amount;
void *temp = realloc(stack->content, required_memory_for_slots(stack, slots_to_keep));
if(temp == NULL){
return NULL;
}
//Update stack info
stack->content = temp;
stack->slots = slots_to_keep;
//Set back count if its overflowing
if(stack->count > stack->slots){
stack->count = stack->slots;
}
return stack;
}
//Expand stack memory by a percentage or fixed amount, whichever is greater
static void *expand_stack_memory(Stack *stack)
{
//If both multiplier and expansion amount evaluate to 0 slots, the stack cannot expand
//automatically, then a call to add_slots must be made to enable the stack to work
size_t new_slots = (float)stack->slots * stack->multiplier;
if(new_slots < stack->expansion_amount){
new_slots = stack->expansion_amount;
}
if(new_slots == 0){
return NULL;
}
return add_slots(stack, new_slots);
}
//Element must have size identical to element_size or stack will break
void *push(Stack *stack, void *element)
{
//Check if there's space, try to allocate more if there isn't
if(available_slots(stack) == 0 && expand_stack_memory(stack) == NULL){
return NULL;
}
//Copy element to stack and return its location
return memcpy(memory_from_position(stack, stack->count++), element, stack->element_size);
}
void *pop(Stack *stack)
{
return (stack->count > 0) ? memory_from_position(stack, --stack->count) : NULL;
}
//Look what element is at n_levels deep without removing it, 0 being the top element
void *peek(Stack *stack, size_t n_levels)
{
if(n_levels >= stack->count){
return NULL;
}
return memory_from_position(stack, stack->count - 1 - n_levels);
}
//Shrink allocated memory to fit current elements, return stack or NULL
Stack *shrink_stack_to_fit(Stack *stack)
{
size_t remove_total = stack->slots - stack->count;
return (remove_total > 0) ? remove_slots(stack, remove_total) : stack;
}
//Might be useful for printing all data or collecting it without removing
void stack_iterate(Stack *stack, void(*callback)(void*))
{
for(size_t i = 0; i < stack->count; ++i){
callback(memory_from_position(stack, stack->count - 1 - i));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T00:31:53.973",
"Id": "63397",
"Score": "0",
"body": "Looks professional. Good job."
}
] |
[
{
"body": "<p>Very Nice.<br>\nOnly small stuff</p>\n\n<ol>\n<li><p>Why <code>(float)</code> in <code>size_t new_slots = (float)stack->slots * stack->multiplier;</code>?</p></li>\n<li><p>Given <code>sizeof size_t</code> may not equal <code>sizeof float</code>, suggest grouping like types in <code>struct</code></p>\n\n<pre><code>typedef struct {\n void *content;\n size_t element_size;\n ...\n size_t expansion_amount;\n float multiplier;\n} Stack;\n</code></pre></li>\n<li><p>Since <code>new_stack()</code> may return NULL, note the other main functions are not protected from dereferencing NULL. Protection is not a hard requirement here - more about design philosophy about should main level routine have NULL protection? Your call.</p></li>\n<li><p>Minor: Could use a float in the define to emphasize the value will be used as a <code>float</code>.<br>\n<code>#define MULTIPLIER (1.00f)</code></p></li>\n<li><p>(I assume your header is at global scope.) Since <code>typedef struct { ... } Stack</code> is <em>only</em> used by an application as a pointer, could use an anonymous pointer to insure information hiding.</p></li>\n<li><p>The defines may be useful to an application as defaults parameters. There, they could appear at global scope, so use less generic names.</p>\n\n<pre><code>#define Stack_MINIMUM_ELEMENT_SIZE (1)\n#define Stack_MULTIPLIER (1.0f)\n#define Stack_EXPANSION_AMOUNT (8)\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T05:23:26.813",
"Id": "38098",
"ParentId": "38085",
"Score": "2"
}
},
{
"body": "<p>Why add the parentheses in your macro constants? This provides no benefit and may cause typos to compile (e.g. <code>(fabs MULTIPLIER - 5) / EXPANSION_AMOUNT;</code> when you meant to write <code>fabs(MULTIPLIER - 5) / EXPANSION_AMOUNT;</code>).</p>\n\n<p>Remove <code>__attribute__((always_inline))</code>. Compilers these days are very good at optimizing, and overriding their decisions will almost never lead to better code. With these functions, the compiler will almost always inline them anyway, but there may be rare occasions when it determines that it is faster to produce code with function calls.</p>\n\n<p>Your <code>new_stack</code> function is odd to me; it doesn't allocate <code>content</code>, and in fact allocates an object on the heap whose size is known at runtime when it may be more appropriate to allocate it on the stack! I'd pass it more parameters than just <code>element_size</code>, and have a separate <code>init_stack</code> function that initializes a stack that is passed in by reference in case the stack structure is allocated on the stack instead of the heap.</p>\n\n<p>Actually, I would rename all of the functions in this library; since C has no namespaces, function names in a library ought to have library-specific names: <code>stack_new</code>, <code>stack_push</code>, <code>stack_pop</code>, etc.</p>\n\n<p>You may want <code>slots</code> to be a derived value instead of a primary value, and instead store the size of the buffer in bytes. As it is,</p>\n\n<pre><code>Stack* s = new_stack(10);\nadd_slots(s, 10);\nprintf(\"Slots: %d\\n\", s->slots);\nrepurpose_stack(s, 15);\nrepurpose_stack(s, 10);\nprintf(\"Slots: %d\\n\" s->slots);\nrepurpose_stack(s, 91);\nrepurpose_stack(s, 10);\nprintf(\"Slots: %d\\n\" s->slots);\n</code></pre>\n\n<p>will print out \"10\\n9\\n0\\n\", not \"10\\n10\\n10\\n\".</p>\n\n<p>I recommend adding an assertion to <code>remove_slots</code>:</p>\n\n<pre><code>assert(amount <= stack->slots);\n</code></pre>\n\n<p>It is a programming error to remove more slots than actually exist in the data structure. This will be compiled out when optimizing, but may help find bugs while debugging.</p>\n\n<p>Similarly, consider adding assertions in <code>push</code> and <code>pop</code> that check bounds.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T06:08:24.387",
"Id": "38099",
"ParentId": "38085",
"Score": "4"
}
},
{
"body": "<p>Your code looks nice. I only have two comments.</p>\n\n<p>Firstly, both <code>peek</code> and <code>pop</code> give the caller access to locations on the stack, rather than copying stack data back to a variable in the caller's scope. This is not robust as the caller could easily stack something else and thereby overwrite these locations. </p>\n\n<p>Secondly, my usual refrain of adding <code>const</code> to function parameters where possible.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T19:17:06.433",
"Id": "38126",
"ParentId": "38085",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "38099",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T19:25:32.323",
"Id": "38085",
"Score": "6",
"Tags": [
"c",
"stack"
],
"Title": "Dynamic stack implementation"
}
|
38085
|
<p>I wrote this JS code with some jQuery and got a one-click-text-selection. Maybe someone can improve this code, because I think it's not "clean" and short engough ;) But I don't want to use an input field. Let me know if you have some ideas!</p>
<pre><code>function SelectText(element) {
var doc = document,
text = doc.getElementById(element),
range,
selection;
if (doc.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}
$(function() {
$('p').click(function () {
SelectText('autoselect');
});
});
</code></pre>
<p>And this is the HTML part:</p>
<pre><code><div id="autoselect">
<p>Some cool text!</p>
</div>
</code></pre>
<p><a href="http://jsfiddle.net/QLvxL/1/">Here's</a> the code in a fiddle.</p>
|
[] |
[
{
"body": "<p>You can further improve this by <a href=\"http://jsbin.com/oXetAcI/4/edit\" rel=\"nofollow\">making it a jQuery plugin</a> instead to make it reusable across any element.</p>\n\n<p><a href=\"http://gs.statcounter.com/#browser-ww-monthly-200807-201510\" rel=\"nofollow\">non-IE browsers, combined, account for ~60% of users at the time of writing</a>. This means 60% of the time, the two conditions are evaluated since you check for IE first. Instead, reverse the conditions to get it right on the first check 60% of the time.</p>\n\n<pre><code>$.fn.OneClickSelect = function () {\n return $(this).on('click', function () {\n\n // In here, \"this\" is the element\n\n var range, selection;\n\n if (window.getSelection) {\n selection = window.getSelection();\n range = document.createRange();\n range.selectNodeContents(this);\n selection.removeAllRanges();\n selection.addRange(range);\n } else if (document.body.createTextRange) {\n range = document.body.createTextRange();\n range.moveToElementText(this);\n range.select();\n }\n });\n};\n\n// Apply to these elements\n$('p, #all-select').OneClickSelect();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T16:22:10.350",
"Id": "63425",
"Score": "0",
"body": "You have always good ideas! Thank you! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-13T19:57:11.033",
"Id": "176960",
"Score": "0",
"body": "How did you know 60% of users are using non-IE browsers? [IE has been the dominant browser in the market.](http://www.netmarketshare.com/browser-market-share.aspx?qprid=1&qpcustomb=0&qpsp=2013&qpnp=3&qptimeframe=Y)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T04:07:26.473",
"Id": "38096",
"ParentId": "38089",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "38096",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T21:40:05.720",
"Id": "38089",
"Score": "5",
"Tags": [
"javascript",
"jquery",
"performance"
],
"Title": "Select text with just one click"
}
|
38089
|
<p>I've created a variable order Markov chain built on top of a tree, but I can't train on datasets >1MB worth of text without running out of memory. I'm sure the tree can be replaced by something else more efficient, but I'm struggling with figuring that out. I've heard a linked list might work, but I'm not sure how.</p>
<p>Below is the <code>AddString</code> method for variable order chains (of characters).</p>
<pre><code>public void AddString(string s)
{
// Construct the string that will be added.
StringBuilder sb = new StringBuilder(s.Length + 2 * (MarkovOrder));
sb.Append(StartChar, MarkovOrder);
sb.Append(s);
sb.Append(StopChar, MarkovOrder);
for (int i = 0; i < sb.Length; ++i)
{
// Get the order 0 node
Node parent = root.AddChild(sb[i]);
//add N-grams
for (int j = 1; j <= MarkovOrder && j + i < sb.Length; j++)
{
Node child = parent.AddChild(sb[j + i]);
parent = child;
}
}
}
</code></pre>
<p>(code base found <a href="https://github.com/mtbarta/Markov_Chain/blob/master/Markov.cs">here</a>)</p>
<p>This code bloats my memory with every order up to the defined order, and I'm not sure how I'd alter it to only store one order without it completely breaking down. I'd like to do something like </p>
<pre><code>markov = new markovChain(order = 3);.
</code></pre>
<p>I've been playing around with algorithms that can store a chain of order (i.e.) 4 without going through the other orders. These implementations aren't performing as well, and I keep resorting to several lists that make node creation complex for me.
(<a href="https://gist.github.com/mtbarta/8127895">https://gist.github.com/mtbarta/8127895</a>)</p>
<p>I'm not sure what structure to use so that I can generate a chain at a given order without bloating memory use. Can I implement a linked list that stores a list of following nodes? Does that ruin the point of a linked list while bloating my memory anyway? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T11:26:35.660",
"Id": "63489",
"Score": "0",
"body": "Can you git a source files and/or startup code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T11:34:47.737",
"Id": "63491",
"Score": "0",
"body": "I can't donload FairyTales.txt etc..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T23:49:13.947",
"Id": "63586",
"Score": "0",
"body": "I uploaded the training data files to github. Just throw them in your debug folder and the program will start."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T06:58:35.813",
"Id": "63760",
"Score": "0",
"body": "Are you shure the code is not running? It runs almost perfectly and I really can't find breaking changes to debug"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T07:00:48.417",
"Id": "63761",
"Score": "0",
"body": "modelOrder = 21, genOrder =5: #christmas\n\"Dick Wilkins, squab and a wife among this time the\ncase was all that would sure,\" replied, he died from the floors bell, dong, and\nlove!\" said the generous iron gate. A frost agitated him here, and plunge it und\ner us handsome one anonymous \"Christmas-day and let the chimes, and endeavouring\n down feeling of the lord spot--say St. Passing, you been a mother works in a tw\nine reason what damaged\nas the two."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T07:11:07.043",
"Id": "63762",
"Score": "0",
"body": "#christmas\nYou may--the plump sister. He thought, and swarthy, several gainst accessity of\ntime of\nits mysters, as though, and come, following when the Ghost, \"do yours with the b\noard, and how do you had fiery\nwere quite dark to me?\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T19:11:45.553",
"Id": "63961",
"Score": "1",
"body": "It runs, but I'm wondering if it can be optimized since the tree stores every order. If I use a larger training file, I run out of memory."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T12:44:32.147",
"Id": "65773",
"Score": "0",
"body": "of cause but this is the price for non effective data strictures you provide. optimization is to use sharing"
}
] |
[
{
"body": "<blockquote>\n <p>I'm sure the tree can be replaced by something else more efficient, but I'm struggling with figuring that out. I've heard a linked list might work, but I'm not sure how.</p>\n</blockquote>\n\n<p>Perhaps use the SortedList class instead of the Dictionary class.</p>\n\n<p>For example, <a href=\"http://blog.bodurov.com/Performance-SortedList-SortedDictionary-Dictionary-Hashtable/\" rel=\"nofollow noreferrer\">this blog entry</a> says,</p>\n\n<blockquote>\n <p>Best memory footprint we see in the SortedList, followed by Hashtable, SortedDictionary and the Dictionary has highest memory usage. Despite all that, we have to note, that the differences are not significant and unless your solution requires extreme sensitivity about the memory usage you should consider the other two parameters: time taken for the insert operations and time taken for searching a key as more important.</p>\n</blockquote>\n\n<p>Other optimizations might include:</p>\n\n<ul>\n<li>Don't allocate Node.Children until/unless the AddChild method is called.</li>\n<li>Use the Dictionary constructor which lets you specify the initial capacity (and specify a very low initial capacity)</li>\n<li>Add a <code>KeyValuePair<char,Node> OnlyChild</code> member to Node, and use it (instead of creating Dictionary) when the first child is added (delete it and create a dictionary when the second child is added) to optimize the case where a Node has only exactly one child</li>\n</ul>\n\n<p>Beware that the above are 'micro-optimizations' which don't change the algorithm; changing the algorithm (I don't understand <a href=\"https://codereview.stackexchange.com/questions/38092/optimizing-variable-order-markov-chain-implementation#comment65773_38092\">Artur Mustafin's comment</a>) might result in bigger savings.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T01:10:19.337",
"Id": "43832",
"ParentId": "38092",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T00:33:03.023",
"Id": "38092",
"Score": "7",
"Tags": [
"c#",
"algorithm",
"memory-optimization",
"markov-chain"
],
"Title": "Optimizing variable order Markov Chain Implementation"
}
|
38092
|
<p>I'm looking for corrections, optimizations, general code review, etc.</p>
<pre><code>final class TreeData<T> {
private T item;
private boolean left;
private boolean right;
public TreeData(T item) {
this.item = item;
}
public T getData () {
return item;
}
public boolean getLeft() {
return left;
}
public void setLeft(boolean left) {
this.left = left;
}
public boolean getRight() {
return right;
}
public void setRight(boolean right) {
this.right = right;
}
public boolean isLeaf () {
return !left && !right;
}
}
/**
* There are 2 common approaches over the internet:
*
* 1. Preorder deserialization.
* Cost: (2 * nodeSize * (n + 1))
*
* 2. PreOrder and Inorder deserialization
* Cost: (2 * nodeSize * (n))
*
* 3. Object based (wrap node inside an object, with a boolean
* Cost: (1 * (nodeSize + boolean + 8(object overhead)) * n )
*
* The third option triumphs iff:
* (nodeSize + boolean + 8) < (2 * nodeSize)
* boolean + 8 < nodeSize
* 1 + 8 < nodeSize
*
* When a node is saves as an Integer, then the nodeSize is (4 + 8 => 12)
* So
* 9 < 12.
* Thus works :)
*
* OR:
*
* Simply consider a single tree with 1 node, of type Int.
* Pre + Inorder is = 2 * (8(int object) + 4(actual value)) * 1 => 24
* Object with boolean = 1 * (8(wrapper object) + 12(int object) + 2) * 1 => 22.
*
*
* Complexity: O(n)
*
*/
public final class SerializeDeserializeBinarytree<T> {
TreeNode<T> root;
public SerializeDeserializeBinarytree(List<T> items) {
if (items == null) throw new NullPointerException("the items cannot be null");
create(items);
}
/** construction using parent child relation that left child is 2i + 1 and right is 2i + 2 */
@SuppressWarnings("unchecked")
private void create (List<T> items) {
assert items != null;
root = new TreeNode<T>(null, items.get(0), null);
final Queue<TreeNode<T>> queue = new LinkedList<TreeNode<T>>();
queue.add(root);
final int half = items.size() / 2;
for (int i = 0; i < half; i++) {
if (items.get(i) != null) {
final TreeNode<T> current = queue.poll();
final int left = 2 * i + 1;
final int right = 2 * i + 2;
if (items.get(left) != null) {
current.left = new TreeNode<T>(null, items.get(left), null);
queue.add(current.left);
}
if (right < items.size() && items.get(right) != null) {
current.right = new TreeNode<T>(null, items.get(right), null);
queue.add(current.right);
}
}
}
}
private static class TreeNode<T> {
TreeNode<T> left;
T item;
TreeNode<T> right;
TreeNode (TreeNode<T> left, T item, TreeNode<T> right) {
this.left = left;
this.item = item;
this.right = right;
}
}
public List<TreeData<T>> serialize () {
if (root == null) {
throw new NoSuchElementException("The root should be non-null");
}
List<TreeData<T>> objectList = new ArrayList<TreeData<T>>(countNodes(root));
preorderSerialize(root, objectList);
return Collections.unmodifiableList(objectList);
}
private int countNodes(TreeNode<T> root) {
assert root != null;
if (root != null) {
return countNodes(root.left) + countNodes(root.right) + 1;
}
return 0;
}
private boolean preorderSerialize(TreeNode<T> node, List<TreeData<T>> objectList ) {
assert root != null;
assert objectList != null;
if (node != null) {
TreeData<T> treeData = new TreeData<T>(node.item);
objectList.add(treeData);
treeData.setLeft(preorderSerialize (node.left, objectList));
treeData.setRight(preorderSerialize (node.right, objectList));
return true;
}
return false;
}
private class CounterContainer {
private int counterContainer;
public CounterContainer(int counterContainer) {
this.counterContainer = counterContainer;
}
public void increment() {
counterContainer++;
}
public int getCounter () {
return counterContainer;
}
}
public void deserialize (List<TreeData<T>> treeDatas) {
if (treeDatas == null) throw new NullPointerException("The treeData should not be null");
root = preOrderDeserialize (treeDatas, new CounterContainer(0));
}
private TreeNode<T> preOrderDeserialize (List<TreeData<T>> treeDatas, CounterContainer cc) {
assert treeDatas != null;
assert cc != null;
TreeData<T> treeData = treeDatas.get(cc.getCounter());
TreeNode<T> node = new TreeNode<T>(null, treeData.getData(), null);
if (treeData.isLeaf()) return node;
if (treeData.getLeft()) {
cc.increment();
node.left = preOrderDeserialize(treeDatas, cc);
}
if (treeData.getRight()) {
cc.increment();
node.right = preOrderDeserialize(treeDatas, cc);
}
return node;
}
public List<T> preOrderIterator () {
final List<T> preOrderList = new ArrayList<T>();
if (root == null) throw new NoSuchElementException("The root should be non-null");
preOrder(root, preOrderList);
return preOrderList;
}
private void preOrder (TreeNode<T> node, List<T> preOrderList) {
assert preOrderList != null;
if (node != null) {
preOrderList.add(node.item);
preOrder(node.left, preOrderList);
preOrder(node.right, preOrderList);
}
}
public static void main(String[] args) {
/**
* 1
* 2 3
* 4 n 6 n
*/
Integer[] arr2 = { 1, 2, 3, 4, null, 6 };
SerializeDeserializeBinarytree<Integer> sdbt = new SerializeDeserializeBinarytree<Integer>(Arrays.asList(arr2));
for (TreeData<Integer> treeData : sdbt.serialize()) {
System.out.print(treeData.getData() + ":");
}
System.out.println();
sdbt.deserialize(sdbt.serialize());
for (Integer node : sdbt.preOrderIterator()) {
System.out.print(node + ":");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T12:24:09.030",
"Id": "63418",
"Score": "1",
"body": "\"Serialization\" usually means to turn an object into a machine-readable string representation or byte stream. Do you mean \"traversal\" and \"reconstruction\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T18:55:45.973",
"Id": "63437",
"Score": "0",
"body": "Yes, well, my code is one step short of it. my missing step would be to use object output stream to convert list into byte stream"
}
] |
[
{
"body": "<p>If your goal is to serialize the tree, then you want to repeatedly append node representations to a <code>StringBuilder</code> or write them to an <code>OutputStream</code>. For space efficiency, it would be better to do so a node at a time, rather than to build up the entire list.</p>\n\n<p>Therefore, instead of using a <code>List<TreeData<T>></code> as the intermediate data structure, you should create an <code>PreOrderIterator<TreeData<T>></code>, <code>InOrderIterator<TreeData<T>></code>, etc.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T19:52:29.193",
"Id": "38130",
"ParentId": "38100",
"Score": "1"
}
},
{
"body": "<p>A minor bug: You get an <code>IndexOutOfBoundsException</code> for an empty list in <code>SerializeDeserializeBinarytree.create(List<T> items)</code>. You don't have a comment stating you need to input a list containing at least something. Consider returning <code>IllegalArgumentException</code> and adding a comment.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-17T11:18:15.230",
"Id": "63146",
"ParentId": "38100",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T06:37:50.260",
"Id": "38100",
"Score": "1",
"Tags": [
"java",
"optimization",
"tree",
"serialization"
],
"Title": "Serializing/deserializing binary tree in most space-efficient way"
}
|
38100
|
<p>I want to optimize my Apriori algorithm for speed:</p>
<pre><code>from itertools import combinations
import pandas as pd
import numpy as np
trans=pd.read_table('output.txt', header=None,index_col=0)
def apriori(trans, support=0.01, minlen=1):
ts=pd.get_dummies(trans.unstack().dropna()).groupby(level=1).sum()
collen, rowlen =ts.shape
#-------------Max leng (not used)
#tssum=ts.sum(axis=1)
#maxlen=int(tssum.loc[tssum.idxmax()])
pattern = []
for cnum in range(minlen, rowlen+1):
for cols in combinations(ts, cnum):
patsup = ts[list(cols)].all(axis=1).sum()
patsup=float(patsup)/collen
pattern.append([",".join(cols), patsup])
sdf = pd.DataFrame(pattern, columns=["Pattern", "Support"])
results=sdf[sdf.Support >= support]
return results
</code></pre>
<p><strong>When you input a dataframe of transactions:</strong></p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>>>> trans
1 2 3 4
0
11 a b c NaN
666 a d e NaN
10101 b c d NaN
1010 a b c d
414147 b c NaN NaN
10101 a b d NaN
1242 d e NaN NaN
101 a b c NaN
411 c d e NaN
444 a b c NaN
[10 rows x 4 columns]
</code></pre>
</blockquote>
<p><strong>It will yield:</strong></p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Ap=apriori(trans)
print Ap
>>>
Pattern Support
0 a 0.6
1 b 0.7
2 c 0.7
3 d 0.6
4 e 0.3
5 a,b 0.5
6 a,c 0.4
7 a,d 0.3
8 a,e 0.1
9 b,c 0.6
10 b,d 0.3
12 c,d 0.3
13 c,e 0.1
14 d,e 0.3
15 a,b,c 0.4
16 a,b,d 0.2
18 a,c,d 0.1
20 a,d,e 0.1
21 b,c,d 0.2
24 c,d,e 0.1
</code></pre>
</blockquote>
<p>I want to know if this can be optimized further so that it can run faster on large datasets. I also want to know if there a way to use purely Pandas without combinations from itertools. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T19:42:31.487",
"Id": "83282",
"Score": "0",
"body": "You may want to check out pyFIM for an alternative approach: http://www.borgelt.net/pyfim.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-22T04:49:07.627",
"Id": "295292",
"Score": "0",
"body": "how your output.txt dataset looks"
}
] |
[
{
"body": "<p>First off, this is just a part of the Apriori algorithm. Here, you're just finding frequent itemsets. Apriori continues to find association rules in those itemsets.</p>\n\n<p>Also, using <code>combinations()</code> like this is not optimal. For example, if we know that the combination <code>AB</code> does not enjoy reasonable support, we do not need to consider any combination that contains <code>AB</code> anymore (<code>ABC</code>, <code>ABD</code>, etc. will all be infrequent as well). Your algorithm does not take this into consideration.</p>\n\n<p>This means that your algorithm will check all the possible combinations (2<sup>n</sup>, where n is the number of possible items), while in fact we can prune the search tree as above and reduce this complexity drastically (depending on the density of the dataset).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-27T15:20:52.087",
"Id": "112047",
"ParentId": "38101",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T07:02:59.787",
"Id": "38101",
"Score": "6",
"Tags": [
"python",
"algorithm",
"numpy",
"pandas",
"data-mining"
],
"Title": "Apriori algorithm using Pandas"
}
|
38101
|
<p>An interviewer asked me to write clean Java code for clockwise and counterclockwise spiral matrix traversal.</p>
<p>e.g. <code>{{1,2,3}, {7,8,9}}</code> becomes <code>{1,2,3,9,8,7}</code> and <code>{1,7,8,9,3,2}</code></p>
<p>I've tried many methods and wrote down the below code while keeping in mind that it should be as clean as possible. But I am not sure it is the right answer. Please evaluate it.</p>
<p>Note: I've removed comments and test cases to reduce text size.</p>
<pre><code>public abstract class MatrixTraverse {
private TraverseDirection traverseDirection;
private int matrixCount;
private int row;
private int upLimit;
private int col;
private int downLimit;
private int leftLimit;
private int rightLimit;
public abstract void traverseUp();
public abstract void traverseLeft();
public abstract void traverseDown();
public abstract void traverseRight();
public MatrixTraverse(final TraverseDirection traverseDirection) {
this.traverseDirection = traverseDirection;
}
public void init(int[][] matrix) {
final int rowSize = matrix.length;
final int colSize = matrix[0].length;
upLimit = 0;
downLimit = matrix.length - 1;
leftLimit = 0;
rightLimit = matrix[0].length - 1;
matrixCount = rowSize * colSize;
row = 0;
col = 0;
}
public int[] traverseMatrix(int[][] matrix) {
init(matrix);
final int[] retTraveserdMatrix = new int[matrixCount];
for (int index = 0; index < matrixCount; index++) {
retTraveserdMatrix[index] = matrix[row][col];
switch (traverseDirection) {
case RIGHT :
traverseRight();
break;
case DOWN :
traverseDown();
break;
case LEFT :
traverseLeft();
break;
case UP :
traverseUp();
break;
default :
break;
}
}
return retTraveserdMatrix;
}
protected void moveDown() {
traverseDirection = TraverseDirection.DOWN;
}
public void moveRight() {
traverseDirection = TraverseDirection.RIGHT;
}
protected void moveLeft() {
traverseDirection = TraverseDirection.LEFT;
}
protected void moveUp() {
traverseDirection = TraverseDirection.UP;
}
public void decrementRow() {
--row;
}
public boolean isUpLimitExceed() {
return (row < upLimit);
}
public void incrementLeftLimit() {
++leftLimit;
}
public void incrementCol() {
++col;
}
public void incrementRow() {
++row;
}
public boolean isLeftLimitExceed() {
return (col < leftLimit);
}
public void decrementCol() {
--col;
}
public void decrementDownLimit() {
--downLimit;
}
public void decrementRightLimit() {
--rightLimit;
}
public boolean isDownLimitExceed() {
return (row > downLimit);
}
public boolean isRightLimitExceed() {
return (col > rightLimit);
}
public void incrementUpLimit() {
++upLimit;
}
}
public class MatrixTraverseClock extends MatrixTraverse {
public MatrixTraverseClock() {
super(TraverseDirection.RIGHT);
}
public void traverseUp() {
decrementRow();
if (isUpLimitExceed()) {
incrementRow();
incrementCol();
incrementLeftLimit();
moveRight();
}
}
public void traverseLeft() {
decrementCol();
if (isLeftLimitExceed()) {
incrementCol();
decrementRow();
decrementDownLimit();
moveUp();
}
}
public void traverseDown() {
incrementRow();
if (isDownLimitExceed()) {
decrementRow();
decrementCol();
decrementRightLimit();
moveLeft();
}
}
public void traverseRight() {
incrementCol();
if (isRightLimitExceed()) {
decrementCol();
incrementRow();
incrementUpLimit();
moveDown();
}
}
}
public class MatrixTraverseCounterClock extends MatrixTraverse {
public MatrixTraverseCounterClock() {
super(TraverseDirection.DOWN);
}
public void traverseUp() {
decrementRow();
if (isUpLimitExceed()) {
incrementRow();
decrementCol();
decrementRightLimit();
moveLeft();
}
}
public void traverseLeft() {
decrementCol();
if (isLeftLimitExceed()) {
incrementCol();
incrementRow();
incrementUpLimit();
moveDown();
}
}
public void traverseDown() {
incrementRow();
if (isDownLimitExceed()) {
decrementRow();
incrementCol();
incrementLeftLimit();
moveRight();
}
}
public void traverseRight() {
incrementCol();
if (isRightLimitExceed()) {
decrementCol();
decrementRow();
decrementDownLimit();
moveUp();
}
}
}
For Testing
final int[][] inputMatrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
final int[] expectedResult = {1, 2, 3, 6, 9, 8, 7, 4, 5};
final MatrixTraverse matrixTraverse = new MatrixTraverseClock();
Assert.assertArrayEquals(expectedResult,
matrixTraverse.traverseMatrix(inputMatrix));
final int[] expectedResult1 = {1, 4, 7, 8, 9, 6, 3, 2, 5};
final MatrixTraverse matrixTraverse = new MatrixTraverseCounterClock();
Assert.assertArrayEquals(expectedResult1,
matrixTraverse.traverseMatrix(inputMatrix));
</code></pre>
|
[] |
[
{
"body": "<p>A few remarks about your <strong>object-oriented design</strong>:</p>\n\n<ul>\n<li>It's odd that the <code>matrixCount</code> and <code>up/down/left/rightLimit</code>s are part of the state of the object, but <code>matrix</code> itself isn't.</li>\n<li>I think <code>matrix</code> should be an instance variable along with all the others — in which case it should be passed into the constructor, not <code>traverseMatrix()</code>.</li>\n<li>Alternatively, <em>all</em> of the variables would be <em>local</em> variables in <code>traverseMatrix(int[][])</code>. But that would be an excessively complex method. I don't recommend this.</li>\n<li>Class names should be nouns; method names should be verbs. I would rename <code>MatrixTraverse</code> and <code>traverseMatrix()</code> to <code>MatrixTraverser</code> and <code>traverse()</code>, respectively.</li>\n<li>You could consider this object an <code>Iterator</code>. I've written it that way in the solution below. Then you could have a convenience method called <code>traverse()</code> that repeatedly calls <code>next()</code> and assembles the whole array.</li>\n</ul>\n\n<p>The main problem with your solution is lack of generality: up/down/left/right are each treated as special cases, so <strong>all of your code appears in quadruplicate</strong>.</p>\n\n<p>You seem to have defined a <code>TraverseDirection</code> enum, which was not included in your post. I'll assume that it's just a dumb enum of four elements. You should make the enum more helpful.</p>\n\n<p>We have an abstract base class, an enum, a clockwise iterator subclass, and an anticlockwise iterator subclass. For code organization, I would make the latter three static inner classes within the first. Inner classes would also save you from the repetitive naming (<code>MatrixTraverse</code>, <code>TraversalDirection</code>, <code>MatrixTraverseClock</code>, <code>MatrixTraverseCounterClock</code>).</p>\n\n<p>An outline of the solution could be:</p>\n\n<pre><code>public abstract class MatrixTraverser implements Iterator<Integer> {\n protected static enum Direction {\n UP (-1, 0),\n RIGHT (0, +1),\n DOWN (+1, 0),\n LEFT (0, -1);\n\n public final int rowIncr, colIncr;\n\n /**\n * +1 if it represents \"positive\" movement; -1 if \"negative\" movement\n */\n public final int signum;\n\n private Direction(int rowIncr, int colIncr) {\n this.rowIncr = rowIncr;\n this.colIncr = colIncr;\n this.signum = this.rowIncr + this.colIncr;\n }\n }\n\n //////////////////////////////////////////////////////////////////////\n\n public static class Clockwise extends MatrixTraverser {\n public Clockwise(int[][] matrix) {\n super(matrix, Direction.RIGHT);\n }\n\n @Override\n protected Direction nextDirection(Direction direction) {\n switch (direction) {\n case RIGHT: return Direction.DOWN;\n case DOWN: return Direction.LEFT;\n case LEFT: return Direction.UP;\n case UP: return Direction.RIGHT;\n }\n assert false;\n throw new IllegalArgumentException();\n }\n }\n\n //////////////////////////////////////////////////////////////////////\n\n public static class AntiClockwise extends MatrixTraverser {\n public AntiClockwise(int[][] matrix) {\n super(matrix, Direction.DOWN);\n }\n\n @Override\n protected Direction nextDirection(Direction direction) {\n switch (direction) {\n case DOWN: return Direction.RIGHT;\n case RIGHT: return Direction.UP;\n case UP: return Direction.LEFT;\n case LEFT: return Direction.DOWN;\n }\n assert false;\n throw new IllegalArgumentException();\n }\n }\n\n public MatrixTraverser(int[][] matrix, Direction direction) {\n ...\n }\n\n public int[] traverse() {\n ...\n }\n\n ...\n}\n</code></pre>\n\n<p>Each subclass of <code>MatrixTraverser</code> does the minimum necessary to specialize the general solution.</p>\n\n<p>Oh, and here's the test case. Note that you can use it either as an iterator or call a convenience function to fetch the entire path at once.</p>\n\n<pre><code>public static void main(String[] args) {\n int[][] m = {{ 0, 1, 2, 3},\n { 4, 5, 6, 7},\n { 8, 9, 10, 11},\n {12, 13, 14, 15}};\n\n MatrixTraverser t = new MatrixTraverser.Clockwise(m);\n while (t.hasNext()) {\n System.out.print(t.next() + \" \");\n }\n System.out.println();\n\n int[] spiral = new MatrixTraverser.AntiClockwise(m).traverse();\n System.out.println(java.util.Arrays.toString(spiral));\n}\n</code></pre>\n\n<p>At this point, you could try to fill in the blanks. Or, read on to see what I came up with.</p>\n\n<hr>\n\n<pre><code>private final int[][] matrix;\nprivate int row, col;\nprivate int itemsRemaining;\nprivate Direction direction;\nprivate int[] limits = new int[Direction.values().length];\n\npublic MatrixTraverser(int[][] matrix, Direction direction) {\n this.matrix = matrix;\n this.direction = direction;\n this.itemsRemaining = matrix.length * matrix[0].length;\n\n this.limits[Direction.DOWN.ordinal()] = matrix.length - 1;\n this.limits[Direction.RIGHT.ordinal()] = matrix[0].length - 1;\n\n // Stay out of row 0 or col 0 on the next round of the spiral\n this.limits[this.prevDirection(direction).ordinal()] = 1;\n}\n\n@Override\npublic void remove() {\n throw new UnsupportedOperationException();\n}\n\n@Override\npublic boolean hasNext() {\n return this.itemsRemaining > 0;\n}\n\n@Override\npublic Integer next() {\n this.itemsRemaining--;\n int n = this.matrix[this.row][this.col];\n this.advance();\n return n;\n}\n\nprivate void advance() {\n int rowIncr = this.direction.rowIncr;\n int colIncr = this.direction.colIncr;\n this.row += rowIncr;\n this.col += colIncr;\n\n if ( (rowIncr < 0 && row == limits[Direction.UP.ordinal()]) ||\n (rowIncr > 0 && row == limits[Direction.DOWN.ordinal()]) ||\n (colIncr < 0 && col == limits[Direction.LEFT.ordinal()]) ||\n (colIncr > 0 && col == limits[Direction.RIGHT.ordinal()]) ) {\n this.limits[this.direction.ordinal()] -= this.direction.signum;\n this.direction = this.nextDirection(this.direction);\n }\n}\n\nprotected abstract Direction nextDirection(Direction direction);\n\nprivate Direction prevDirection(Direction direction) {\n for (Direction d : Direction.values()) {\n if (this.nextDirection(d) == direction) {\n return d;\n }\n }\n assert false;\n throw new IllegalArgumentException();\n}\n\npublic int[] traverse() {\n int[] ret = new int[this.itemsRemaining];\n int i = 0;\n while (this.hasNext()) {\n ret[i++] = this.next();\n }\n return ret;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T12:26:09.163",
"Id": "63419",
"Score": "0",
"body": "thanks for your valuable comments. I also updated sample."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T11:23:04.910",
"Id": "38108",
"ParentId": "38104",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38108",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T08:17:05.117",
"Id": "38104",
"Score": "3",
"Tags": [
"java",
"interview-questions",
"matrix"
],
"Title": "Clockwise and counterclockwise spiral matrix traversal"
}
|
38104
|
<p>Can someone tell me if my code is too long for what it does?</p>
<pre><code>package Tests;
import java.util.Random;
import java.util.Scanner;
public class DuelMain {
public static void main(String[] args) {
Random battle = new Random();
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
int hero, match, restart;
Duel valon = new Duel();
Duel rintar = new Duel();
Duel zersious = new Duel();
Duel balrock = new Duel();
Duel hawkeye = new Duel();
Duel yusef = new Duel();
valon.attack = 6;
valon.defense = 0;
valon.health = 19;
rintar.attack = 8;
rintar.defense = 1;
rintar.health = 16;
zersious.attack = 5;
zersious.defense = 2;
zersious.health = 18;
balrock.attack = 10;
balrock.defense =0;
balrock.health = 15;
hawkeye.attack = 7;
hawkeye.defense = 1;
hawkeye.health = 17;
yusef.attack = 13;
yusef.defense = 2;
yusef.health = 10;
System.out.println("Choose your HERO");
System.out.println("Press 1 for the Mage Lord Valon Press 2 for the Warrior Rintar");
System.out.println("Attack 6 Attack 8");
System.out.println("Defense 0 Defense 1");
System.out.println("Health 19 Health 16");
System.out.println("");
System.out.println("");
System.out.println("Press 3 for the Paladin Prince Zersious Press 4 for the Orc Balrock");
System.out.println("Attack 5 Attack 10");
System.out.println("Defense 2 Defense 0");
System.out.println("Health 18 Health 15");
System.out.println("");
System.out.println("");
System.out.println("Press 5 for the Elf Hawkeye Press 6 for the Dragon Summoner Yusef");
System.out.println("Attack 7 Attack 13");
System.out.println("Defense 1 Defense 2");
System.out.println("Health 17 Health 10");
hero = input.nextInt();
if(hero == 1){System.out.println("You have chosen Lord Valon!");
for(hero = 1;;){
System.out.println("Your battle is against....");
System.out.println("");
match = 1+battle.nextInt(5);
if(match == 1){
System.out.println("Rintar!");
System.out.println("");
valon.attack1 = 8;
valon.defense1 = 1;
valon.health1 = 16;
valon.calculateWinner();
}else if(match == 2){
System.out.println("Prince Zersious!");
System.out.println("");
valon.attack1 = 5;
valon.defense1 = 2;
valon.health1 = 18;
valon.calculateWinner();
}else if(match == 3){
System.out.println("Balrock!");
System.out.println("");
valon.attack1 = 10;
valon.defense1 = 0;
valon.health1 = 15;
valon.calculateWinner();
}else if(match == 4){
System.out.println("Hawkeye!");
System.out.println("");
valon.attack1 = 7;
valon.defense1 = 1;
valon.health1 = 17;
valon.calculateWinner();
}else if(match == 5){
System.out.println("Yusef!");
System.out.println("");
valon.attack1 = 13;
valon.defense1 = 2;
valon.health1 = 10;
valon.calculateWinner();}
System.out.println("");
System.out.println("Fight again?");
System.out.println("1 for Yes");
System.out.println("2 for No");
restart = input.nextInt();
if(restart == 1){
System.out.println("");
}else if(restart == 2){
System.out.println("Thank you for playing!");
break;}
}
}
if(hero == 2){System.out.println("You have chosen Rintar!");
for(hero = 2;;){
System.out.println("Your battle is against....");
System.out.println("");
match = 1+battle.nextInt(5);
if(match == 1){
System.out.println("Lord Valon!");
System.out.println("");
rintar.attack1 = 6;
rintar.defense1 = 0;
rintar.health1 = 19;
rintar.calculateWinner();
}else if(match == 2){
System.out.println("Prince Zersious!");
System.out.println("");
rintar.attack1 = 5;
rintar.defense1 = 2;
rintar.health1 = 18;
rintar.calculateWinner();
}else if(match == 3){
System.out.println("Balrock!");
System.out.println("");
rintar.attack1 = 10;
rintar.defense1 = 0;
rintar.health1 = 15;
rintar.calculateWinner();
}else if(match == 4){
System.out.println("Hawkeye!");
System.out.println("");
rintar.attack1 = 7;
rintar.defense1 = 1;
rintar.health1 = 17;
rintar.calculateWinner();
}else if(match == 5){
System.out.println("Yusef!");
System.out.println("");
rintar.attack1 = 13;
rintar.defense1 = 2;
rintar.health1 = 10;
rintar.calculateWinner();}
System.out.println("");
System.out.println("Fight again?");
System.out.println("1 for Yes");
System.out.println("2 for No");
restart = input.nextInt();
if(restart == 1){
System.out.println("");
}else if(restart == 2){
System.out.println("Thank you for playing!");
break;}
}
}
if(hero == 3){System.out.println("You have chosen Prince Zersious!");
for(hero = 3;;){
System.out.println("Your battle is against....");
System.out.println("");
match = 1+battle.nextInt(5);
if(match == 1){
System.out.println("Lord Valon!");
System.out.println("");
zersious.attack1 = 6;
zersious.defense1 = 0;
zersious.health1 = 19;
zersious.calculateWinner();
}else if(match == 2){
System.out.println("Rintar!");
System.out.println("");
zersious.attack1 = 8;
zersious.defense1 = 1;
zersious.health1 = 16;
zersious.calculateWinner();
}else if(match == 3){
System.out.println("Balrock!");
System.out.println("");
zersious.attack1 = 10;
zersious.defense1 = 0;
zersious.health1 = 15;
zersious.calculateWinner();
}else if(match == 4){
System.out.println("Hawkeye!");
System.out.println("");
zersious.attack1 = 7;
zersious.defense1 = 1;
zersious.health1 = 17;
zersious.calculateWinner();
}else if(match == 5){
System.out.println("Yusef!");
System.out.println("");
zersious.attack1 = 13;
zersious.defense1 = 2;
zersious.health1 = 10;
zersious.calculateWinner();}
System.out.println("");
System.out.println("Fight again?");
System.out.println("1 for Yes");
System.out.println("2 for No");
restart = input.nextInt();
if(restart == 1){
System.out.println("");
}else if(restart == 2){
System.out.println("Thank you for playing!");
break;}
}
}
if(hero == 4){System.out.println("You have chosen Balrock!");
for(hero = 4;;){
System.out.println("Your battle is against....");
System.out.println("");
match = 1+battle.nextInt(5);
if(match == 1){
System.out.println("Lord Valon!");
System.out.println("");
balrock.attack1 = 6;
balrock.defense1 =0;
balrock.health1 = 19;
balrock.calculateWinner();
}else if(match == 2){
System.out.println("Prince Zersious!");
System.out.println("");
balrock.attack1 = 5;
balrock.defense1 =2;
balrock.health1 = 18;
balrock.calculateWinner();
}else if(match == 3){
System.out.println("Rintar!");
System.out.println("");
balrock.attack1 = 8;
balrock.defense1 =1;
balrock.health1 = 16;
balrock.calculateWinner();
}else if(match == 4){
System.out.println("Hawkeye!");
System.out.println("");
balrock.attack1 = 7;
balrock.defense1 =1;
balrock.health1 = 17;
balrock.calculateWinner();
}else if(match == 5){
System.out.println("Yusef!");
System.out.println("");
balrock.attack1 = 13;
balrock.defense1 =2;
balrock.health1 = 10;
balrock.calculateWinner();}
System.out.println("");
System.out.println("Fight again?");
System.out.println("1 for Yes");
System.out.println("2 for No");
restart = input.nextInt();
if(restart == 1){
System.out.println("");
}else if(restart == 2){
System.out.println("Thank you for playing!");
break;}
}
}
if(hero == 5){System.out.println("You have chosen Hawkeye!");
for(hero = 5;;){
System.out.println("Your battle is against....");
System.out.println("");
match = 1+battle.nextInt(5);
if(match == 1){
System.out.println("Lord Valon!");
System.out.println("");
hawkeye.attack1 = 6;
hawkeye.defense1 = 0;
hawkeye.health1 = 19;
hawkeye.calculateWinner();
}else if(match == 2){
System.out.println("Prince Zersious!");
System.out.println("");
hawkeye.attack1 = 5;
hawkeye.defense1 = 2;
hawkeye.health1 = 18;
hawkeye.calculateWinner();
}else if(match == 3){
System.out.println("Balrock!");
System.out.println("");
hawkeye.attack1 = 10;
hawkeye.defense1 = 0;
hawkeye.health1= 15;
hawkeye.calculateWinner();
}else if(match == 4){
System.out.println("Rintar!");
System.out.println("");
hawkeye.attack1 = 8;
hawkeye.defense1 = 1;
hawkeye.health1 = 16;
hawkeye.calculateWinner();
}else if(match == 5){
System.out.println("Yusef!");
System.out.println("");
hawkeye.attack1 = 13;
hawkeye.defense1 = 2;
hawkeye.health1 = 10;
hawkeye.calculateWinner();}
System.out.println("");
System.out.println("Fight again?");
System.out.println("1 for Yes");
System.out.println("2 for No");
restart = input.nextInt();
if(restart == 1){
System.out.println("");
}else if(restart == 2){
System.out.println("Thank you for playing!");
break;}
}
}
if(hero == 6){System.out.println("You have chosen Yusef!");
for(hero = 6;;){
System.out.println("Your battle is against....");
System.out.println("");
match = 1+battle.nextInt(5);
if(match == 1){
System.out.println("Lord Valon!");
System.out.println("");
yusef.attack1 = 6;
yusef.defense1 = 0;
yusef.health1 = 19;
yusef.calculateWinner();
}else if(match == 2){
System.out.println("Prince Zersious!");
System.out.println("");
yusef.attack1 = 5;
yusef.defense1 = 2;
yusef.health1 = 18;
yusef.calculateWinner();
}else if(match == 3){
System.out.println("Balrock!");
System.out.println("");
yusef.attack1 = 10;
yusef.defense1 = 0;
yusef.health1 = 15;
yusef.calculateWinner();
}else if(match == 4){
System.out.println("Rintar!");
System.out.println("");
yusef.attack1 = 8;
yusef.defense1 = 1;
yusef.health1 = 16;
yusef.calculateWinner();
}else if(match == 5){
System.out.println("Hawkeye!");
System.out.println("");
yusef.attack1 = 13;
yusef.defense1 = 2;
yusef.health1 = 10;
yusef.calculateWinner();}
System.out.println("");
System.out.println("Fight again?");
System.out.println("1 for Yes");
System.out.println("2 for No");
restart = input.nextInt();
if(restart == 1){
System.out.println("");
}else if(restart == 2){
System.out.println("Thank you for playing!");
break;}
}
}
}
}
package Tests;
import java.util.Random;
public class Duel {
Random battle = new Random();
int newHealth, newHealth1;
int outcome, outcome1, outcome2, outcome3;
int attack, attack1;
int defense, defense1;
int health, health1;
void calculateWinner(){
do{ outcome = attack - defense1;
newHealth1 = health1 - outcome;
System.out.println("Your attack does " + outcome + " damage!");
System.out.println("");
System.out.println("Enemy Health");
System.out.println(newHealth1);
System.out.println("");
outcome2 = attack1 - defense;
newHealth = health - outcome2;
System.out.println("Enemies attack does " + outcome2 + " damage!");
System.out.println("");
System.out.println("Your Health");
System.out.println(newHealth);
if(newHealth1 > 0 && newHealth > 0){
outcome = attack - defense1;
outcome1 = 2 * outcome;
newHealth1 = health1 - outcome1;
System.out.println("Your attack does " + outcome + " damage!");
System.out.println("");
System.out.println("Enemy Health");
System.out.println(newHealth1);
outcome = attack1 - defense;
outcome1 = 2 * outcome;
newHealth = health - outcome1;
System.out.println("");
System.out.println("Enemies attack does " + outcome2 + " damage!");
System.out.println("");
System.out.println("Your Health");
System.out.println(newHealth);
if(newHealth1 > 0 && newHealth > 0){
outcome = attack - defense1;
outcome1 = 3 * outcome;
newHealth1 = health1 - outcome1;
System.out.println("Your attack does " + outcome + " damage!");
System.out.println("");
System.out.println("Enemy Health");
System.out.println(newHealth1);
outcome = attack1 - defense;
outcome1 = 3 * outcome;
newHealth = health - outcome1;
System.out.println("");
System.out.println("Enemies attack does " + outcome2 + " damage!");
System.out.println("");
System.out.println("Your Health");
System.out.println(newHealth);
if(newHealth1 > 0 && newHealth > 0){
outcome = attack - defense1;
outcome1 = 4 * outcome;
newHealth1 = health1 - outcome1;
System.out.println("Your attack does " + outcome + " damage!");
System.out.println("");
System.out.println("Enemy Health");
System.out.println(newHealth1);
outcome = attack1 - defense;
outcome1 = 4 * outcome;
newHealth = health - outcome1;
System.out.println("");
System.out.println("Enemies attack does " + outcome2 + " damage!");
System.out.println("");
System.out.println("Your Health");
System.out.println(newHealth);
if(newHealth1 > 0 && newHealth > 0){
outcome = attack - defense1;
outcome1 = 5 * outcome;
newHealth1 = health1 - outcome1;
System.out.println("Your attack does " + outcome + " damage!");
System.out.println("");
System.out.println("Enemy Health");
System.out.println(newHealth1);
outcome = attack1 - defense;
outcome1 = 5 * outcome;
newHealth = health - outcome1;
System.out.println("");
System.out.println("Enemies attack does " + outcome2 + " damage!");
System.out.println("");
System.out.println("Your Health");
System.out.println(newHealth);}
}
}
}
}while(newHealth1 > 0 && newHealth > 0);
if(newHealth1 <= 0 && newHealth > 0){
System.out.println("You win!");}
if(newHealth <= 0 && newHealth1 > 0){
System.out.println("You lose!");}
if(newHealth <= 0 && newHealth1 <= 0){
System.out.println("Draw!");}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-05T17:31:21.613",
"Id": "292246",
"Score": "1",
"body": "I just want to say if you've only been coding for a few days, I'm impressed. Yes there's a *lot* you can do to improve the verbosity and maintainability of this code, but having a working piece of software with this level of complexity in just a few days is something to be proud of. Keep it up!"
}
] |
[
{
"body": "<p>Yes it could be much smaller and therefore more easy to read.</p>\n\n<p>For example, you quite often set the fields:\n <code>attack, defense, health</code>. This could be moved to a method which sets them all three at once. </p>\n\n<pre><code> public setValues(int attack, int defense, int health){\n this.attack = attack;\n this.defense = defense;\n this.health = health;\n }\n</code></pre>\n\n<p>Also you could define a constructor which takes these three values.</p>\n\n<pre><code>/**Constructor which initializes: attack, defense, health*/\npublic Duel(int attack, int defense, int health){\n this.setValues(attack, defense, health);\n}\n</code></pre>\n\n<p>You can also improve the block <code>System.out.println(\"Choose your HERO\"); ...</code> by extracting a method, which prints the values of a hero.</p>\n\n<p>Not shorter but better style:\nuse <code>switch(match)</code> instead of<br>\n<code>if(match== ..) ... else if(match == ..) ...</code></p>\n\n<p>And there is quite a lot of other code which looks like copy and paste and should be extracted to methods.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T10:07:09.213",
"Id": "38106",
"ParentId": "38105",
"Score": "7"
}
},
{
"body": "<p>Generally, if you have multiple lines repeating a lot with minor or no changes, you want to make them into a function or a class. Especially, if you plan on extending them later.</p>\n\n<p>Also, you'd want to design your classes more carefully. It would make a lot more sense to create a Character class, that has a name, attack, health and defense. Then since a duel is a fight between two characters, you could just have two Character variables inside of it, instead of two integers for health, attack etc.</p>\n\n<p>A class is essentially a combination of variables (data) and functions that work with these variables. You can save a lot of lines by creating functions for all your printing.</p>\n\n<p>For instance if you make a Character class, you could fill it with data using either a function or a constructor - <a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html\">http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html</a> - that would enable you to do all the setting up in a single line:</p>\n\n<pre><code>public Character(int attack, int defense, int health)\n{\n this.attack = attack;\n this.defense = defense;\n this.health = health;\n}\n</code></pre>\n\n<p>Called as:</p>\n\n<pre><code>Character valon = new Character(6, 0, 19);\n</code></pre>\n\n<p>To print a character's stats, you could then make another function inside the Character class:</p>\n\n<pre><code>public void printStats()\n{\n System.out.println(\"Attack \" + this.attack);\n // other stats\n}\n</code></pre>\n\n<p>And just call it whenever you want to show the stats:</p>\n\n<pre><code>valon.printStats();\n</code></pre>\n\n<p>Same concepts can be applied inside the Duel class: you could have a Round class that represents A attacking B and B attacking A back. Or even an Attack class that would further split this round to two attacks.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T12:06:23.160",
"Id": "63417",
"Score": "8",
"body": "Good, except that `Character` would be an unfortunate name for a class, as it clashes with `java.lang.Character`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T10:53:21.760",
"Id": "38107",
"ParentId": "38105",
"Score": "9"
}
},
{
"body": "<p>there are a couple of things that I noticed, and I don't think that anyone else touched on these, but they are very important for a beginner in any language.</p>\n\n<ol>\n<li><p>indentation</p>\n\n<ul>\n<li><p>this includes ending brackets. make sure that your ending brackets are like this:</p>\n\n<pre><code> }\n }\n }\n}\n</code></pre>\n\n<p>And not like this</p>\n\n<pre><code>}\n}\n}\n}\n</code></pre></li>\n<li><p>your code should look like this</p>\n\n<pre><code>public class ClassName {\n int variable1;\n int variable2;\n int variable3;\n\n void methodName() {\n\n /* Do Stuff */\n }\n}\n</code></pre></li>\n<li>everything inside of <code>if</code> statements should also be indented.</li>\n</ul></li>\n<li><p><code>do while</code> loops. lot's of people don't like them, you should turn the <code>do while</code> loop inside of <code>calculateWinner()</code> into a <code>while(newHealth1 > 0 && newHealth > 0)</code> </p></li>\n</ol>\n\n<hr>\n\n<p><strike> upon reaching this point I have realized that this code doesn't work.</p>\n\n<p>all of your NPC and Player objects are type <code>Duel</code> and <code>Duel</code> is where the <code>calculateWinner</code> method is located, but it doesn't take any input parameters that would suggest that it is expected to interact with another <code>Duel</code> object and </strike></p>\n\n<p>What you need is more classes,</p>\n\n<ol>\n<li><p>player class, made up of</p>\n\n<ul>\n<li><code>Duel</code> object (<em>you should probably rename</em>)</li>\n<li>your Battle Engine (<em>method</em>)</li>\n<li>might want to include a <code>challenge</code> method as well</li>\n</ul></li>\n<li><p>Enemy class (you may not need this depending on how you set up your player class)</p></li>\n<li><p>Duel class needs to be changed significantly</p></li>\n</ol>\n\n<p>I haven't put much time into this, because there is a lot of <code>if then</code> nonsense going on in this code that can be cleaned up. </p>\n\n<hr>\n\n<p>I am not sure why you are doing this either</p>\n\n<pre><code> if(hero == 5){System.out.println(\"You have chosen Hawkeye!\");\n for(hero = 5;;){ ...\n</code></pre>\n\n<p>the way that the rest of the code is written it should be <code>while</code> statement written like this</p>\n\n<pre><code>int restart = 1; //for clarity\nif(hero == 5)\n{\n System.out.println(\"You have chosen Hawkeye!\");\n\n while (restart == 1)\n {\n /* rest of code */\n System.out.println(\"Fight again?\");\n System.out.println(\"1 for Yes\");\n System.out.println(\"2 for No\");\n restart = input.nextInt();\n }\n}\n</code></pre>\n\n<p>and you should be validating user input as well, what if they input <code>3</code>?</p>\n\n<hr>\n\n<p>This answer seems really scattered to me, but it's early in the morning.</p>\n\n<p>you should take the advice of the other two answers first (<em>MrSmith42's answer and Paprik's answer</em>), then read through this answer (hopefully it will make more sense that way)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T15:01:08.093",
"Id": "38118",
"ParentId": "38105",
"Score": "8"
}
},
{
"body": "<p>First, I'd like to start off by saying that if you've really only been coding in Java a few days -- well done. For \"a few days'\" worth of experience, having code that compiles and does what you want it to (and expect it to) is the most important thing. That being said, this <em>is</em> a code review site, so some suggestions....</p>\n\n<h2>The combatants</h2>\n\n<p>As others have mentioned, my first change would be to create a class to hold data for each participant of the Duel. The basic information for each participant is their name, and integer values for their attack, defense, and health. Since naming this class 'Character' would be in conflict with <code>java.lang.Character</code>, I figure \"Player\" would be a good name:</p>\n\n<pre><code>public class Player {\n private String name;\n private int attack;\n private int defense;\n private int health;\n\n // Contructor, getters, and setters here\n}\n</code></pre>\n\n<p>Now we can create a Player object for each combatant:</p>\n\n<pre><code>Player valon = new Player(\"Valon\", 6, 0, 19);\n</code></pre>\n\n<p>Since a \"Duel\" will continue until one player is \"dead\", I'd add a utility method for determining if a player is dead (or alive, in this case.) This will allow us to change the criteria in the future in a more simple way:</p>\n\n<pre><code>// in the Player class\npublic boolean isAlive() {\n return health > 0;\n}\n</code></pre>\n\n<p><strong>Why?</strong> In object-oriented programming, a single \"concept\" is defined by a class, which defines its data fields and methods. Here, we are taking the \"concept\" of a player and putting the logic for each player into a single, well-defined object. Now the Player object for Hawkeye knows everything there is to know about Hawkeye, and it is no longer scattered throughout the code. If we want to make Hawkeye a little weaker by changing his attack value, we now only need to change it in all places instead of tracking down all the places in the code where we define him as a combatant.</p>\n\n<h2>The fight</h2>\n\n<p>From reading the code, it looks like a \"duel\" is supposed to proceed by each player attacking the other until one player is dead. That is, Player 1 attacks Player 2. Then Player 2 attacks Player 1. And so on. A Player's damage is defined as their \"attack\" value minus their opponent's \"defense\" value. The damage is then subtracted from the defender's health value. The duel continues until one or both players are \"dead\". Since the code allows for \"draws\", which appears intentional, then both the attack and the counter attack (player 1 attacks player 2, player 2 attacks player 1) happen in the same round, and only after both attacks are completed does the round end and the end conditions get checked.</p>\n\n<p>The duel logic can therefore be consolidated into a small method that takes only two Player variables, the duel participants. (Here I left them named \"you\" and \"enemy\" but it's really not important.)</p>\n\n<pre><code>public void duel(Player you, Player enemy) {\n do {\n attack(you, enemy);\n attack(enemy, you);\n\n } while (you.isAlive() && enemy.isAlive());\n\n if (you.isAlive()) {\n System.out.println(\"You win!\");\n } else if (enemy.isAlive()) {\n System.out.println(\"You lose!\");\n } else {\n System.out.println(\"Draw!\");\n }\n}\n</code></pre>\n\n<p>I have extracted the \"attack\" code into a single method called <code>attack</code>. This method models the act of one Player attacking another Player, and it prints the result.</p>\n\n<pre><code>private void attack(Player attacker, Player defender) {\n\n int damage = Math.max(0, attacker.getAttack() - defender.getDefense());\n int health = defender.getHealth() - damage;\n\n System.out.println(attacker.getName() + \"'s attack does \" + damage + \" damage!\\n\");\n System.out.println(defender.getName() + \"'s Health\\n\");\n System.out.println(health);\n\n defender.setHealth(health); \n}\n</code></pre>\n\n<p>There is one very important thing to note here, and that is damage calculation. Previously the code didn't take into account the possibility that the defender's defense value could be higher than the attacker's attack value, which would result in negative damage. Since having health go up after an attack made no sense, called the <code>Math.max</code> method and passed it a 0, so that if the calculated damage was negative, to default to zero.</p>\n\n<p>(Another thing to note is that the concept of \"you\" and \"your enemy\" went away here and instead the attacker and defender are referred to by name. So instead of \"Your attack does 20 damage!\" it'll now print \"Hawkeye's attack does 20 damage!\") </p>\n\n<p><strong>Why?</strong> A Duel is a self-contained action between two Players, so it should be separate from the Player class itself. When we moved the logic for each combatant's stats and names into the Player object, we effectively anonymized the concept of a duel here as well. It no longer matters who \"you\" are and who your \"enemy\" is, but rather what two combatants are participating. This way we can simplify our code greatly and model an \"attack\" in a player-agnostic fashion.</p>\n\n<h2>The arena</h2>\n\n<p>Now that we've defined how a duel is performed, we need to take a step back and consider this class that we just modified.</p>\n\n<p>As we've defined it, a duel is an action, something that happens. It makes sense to model it as a method. If we have Valon and Hawkeye, and we want them to duel, we call <code>duel</code> and pass the method the parameters for those players: <code>duel(valon, hawkeye)</code>.</p>\n\n<p>The question now becomes, who is the arbiter of the combatants? That is, where is this \"library\" of all the available fighters defined? Furthermore, where does this <code>duel</code> method live?</p>\n\n<p>The answer the both these questions is one and the same: the \"duel\" happens in an \"arena\". Furthermore, all the combatants gather at the \"arena\". So it makes sense that instead of having the class named <code>Duel</code>, the class is named <code>Arena</code> instead. Furthermore, when we construct a new Arena, we can create our gallery of available fighters as well.</p>\n\n<p>I figure that since we're identifying each fighter by name, we can store our fighters in a <code>Map</code> object, using the name as the key. If you're new to Java you may not have heard of this data structure, but <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Map.html\">Maps</a> are a supremely useful way of creating a set of \"key-value\" pairs. </p>\n\n<p>Here is a class-level variable to hold the combatants, plus a constructor to populate that variable. I've also added a method to \"get\" a combatant by name; I will explain why after the code.</p>\n\n<pre><code>public class Arena { // formerly Duel\n private Map<String, Player> combatants;\n\n public Arena() {\n // initialize the combatants\n combatants = new HashMap<String, Player>();\n\n Player valon = new Player(\"Valon\", 6, 0, 19);\n Player rintar = new Player(\"Rintar\", 8, 1, 16);\n Player zersious = new Player(\"Zersious\", 5, 2, 18);\n Player balrock = new Player(\"Balrock\", 10, 0, 15);\n Player hawkeye = new Player(\"Hawkeye\", 7, 1, 17);\n Player yusef = new Player(\"Yusef\", 13, 2, 10);\n\n combatants.put(\"Valon\", valon);\n combatants.put(\"Rintar\", rintar);\n combatants.put(\"Zersious\", zersious);\n combatants.put(\"Balrock\", balrock);\n combatants.put(\"Hawkeye\", hawkeye);\n combatants.put(\"Yusef\", yusef);\n }\n\n public Player getCombatant(String name) {\n Player combatant = combatants.get(name);\n\n if (combatant == null) {\n System.out.println(\"No combatant with name \" + name + \" was found!\");\n return null;\n } else {\n return new Player(combatant.getName(), combatant.getAttack(), combatant.getDefense(), combatant.getDefense());\n }\n }\n\n // attack and duel methods go here\n}\n</code></pre>\n\n<p>There are two reasons for the <code>getCombatant</code> method. One is not applicable entirely now, but something to keep in mind for the future. The other actually is applicable in this immediate use case.</p>\n\n<p>Effectively, what <code>getCombatant</code> does is look for a Player with the provided name. If it can't find that Player -- eg. if the map has no key with that name -- then it prints out an error message and returns a null object. If it does find the player, it does not return that same object, but returns a <em>copy</em> of that object. The reasons for returning a copy are:</p>\n\n<ol>\n<li>This game allows for multiple duels to happen. However, the <code>duel</code> and <code>attack</code> methods work by \"winding down\" the health of the character until one or both players have zero or less health. At this point, your combatants are dead. So if you decide to have a new duel, you'll somehow need to reset those combatants' health. By always pulling a \"fresh\" version of the combatant (by returning a copy instead of the original), the Arena will always provide you a Player with their full health.</li>\n<li>If this game were multi-threaded, we'd be concerned about the safe publication of shared objects. Clearly, this is not a concern in this particular implementation, and the original post clearly says their coding level is novice, but this would be the other reason to include a copy-and-return action in this situation.</li>\n</ol>\n\n<h1>The menu (main method)</h1>\n\n<p>At this point, I don't have much to say about the menu and the main method. Certainly you'll want to consider Malachi's point about input validation. </p>\n\n<p>But with the structure proposed here, the flow of the main method would go something like this:</p>\n\n<ol>\n<li>Create a new Arena object, to instantiate the Players. <code>Arena arena = new Arena();</code></li>\n<li>Prompt the user for the first player's identity. Fetch that player from the arena. <code>Player player1 = arena.getCombatant(\"Rintar\");</code></li>\n<li>Prompt the user for the second player's identity. Fetch that player from the arena. <code>Player player2 = arena.getCombatant(\"Yusef\");</code></li>\n<li>Fight! <code>arena.duel(player1, player2);</code></li>\n<li>Ask the user if they want to fight again. If they do, loop back to step #2. Otherwise, exit.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-25T19:48:25.287",
"Id": "67279",
"Score": "0",
"body": "[belated] Welcome to CR! That's an awesome first post, stick around, we can't have enough answers like this!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-05T17:32:19.073",
"Id": "292247",
"Score": "0",
"body": "Incredible answer, nicely done."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T00:39:01.693",
"Id": "38143",
"ParentId": "38105",
"Score": "17"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T09:54:11.813",
"Id": "38105",
"Score": "11",
"Tags": [
"java",
"beginner",
"game"
],
"Title": "Battle game simulation"
}
|
38105
|
<p>I'm in doubts what approach to take here, please have a look on the code below:</p>
<pre><code>private void processBarCodeResponse(String decodedQrCode) {
JSONObject jsonObject = JsonUtil.composeJsonObject(decodedQrCode);
SalePoint salePoint = parseSalePoint(jsonObject);
if (salePoint == null) return; // handle null value here
saveSalePoint(salePoint);
}
private SalePoint parseSalePoint(JSONObject jsonObject) {
SalePoint salePoint = new SalePoint();
try {
salePoint.type = jsonObject.getString("type");
salePoint.url = jsonObject.getString("url");
salePoint.salePointId = jsonObject.getString("salePointId");
} catch (JSONException e) {
Logger.logError(TAG, "jsonObject " + jsonObject.toString() + " wasn't parsed " +
"correctly");
return null; // point of concern
}
return salePoint;
}
</code></pre>
<p>For the sake of readability I moved the <code>try/catch</code> block to the <code>parseSalePoint()</code> method, but then if parsing fails I'm enforced to return <code>null</code> from the method and check for <code>null</code> value in <code>processBarCodeResponse()</code> method. Wouldn't it be right to just handle the <code>JSONException</code> in <code>processBarCodeResponse()</code> method and stop its execution once it is thrown?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T19:21:55.210",
"Id": "63441",
"Score": "2",
"body": "This question is on the very edge of being primarily opinion based. I am not voting to close but I am downvoting because of the way the question is formulated."
}
] |
[
{
"body": "<p>I think the right thing to do would be to move the exception handler into <code>processBarCodeResponse()</code>.</p>\n\n<pre><code>private void processBarCodeResponse(String decodedQrCode) {\n JSONObject jsonObject = JsonUtil.composeJsonObject(decodedQrCode);\n try {\n SalePoint salePoint = parseSalePoint(jsonObject);\n saveSalePoint(salePoint);\n } catch (JSONException e) {\n // You don't need to call .toString() explicitly\n Logger.logError(TAG, \"jsonObject \" + jsonObject + \" wasn't parsed correctly\");\n }\n\n}\n\nprivate SalePoint parseSalePoint(JSONObject jsonObject) throws JSONException {\n SalePoint salePoint = new SalePoint();\n salePoint.type = jsonObject.getString(\"type\");\n salePoint.url = jsonObject.getString(\"url\");\n salePoint.salePointId = jsonObject.getString(\"salePointId\");\n return salePoint;\n}\n</code></pre>\n\n<p>Your brace indentation was a bit weird; I hope that was just a result of pasting the code into this website.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T12:19:21.933",
"Id": "38110",
"ParentId": "38109",
"Score": "4"
}
},
{
"body": "<p>A possibly useful pattern here can be the <a href=\"http://en.wikipedia.org/wiki/Null_Object_pattern\">Null Object</a>-pattern.</p>\n\n<p>Instead of returning <code>null</code>, return a \"null SalePoint\". Perhaps something like <code>new SalePoint();</code>, or <code>new SalePoint(\"some special url\");</code>. Then make your <code>saveSalePoint</code> method do nothing if the SalePoint has a special url indicating that it's null. </p>\n\n<p>Another option is to return <code>null</code> from your <code>parseSalePoint</code> method as you are currently doing and then simply return from the <code>saveSalePoint</code> method if the argument is null which will remove the null check from <code>processBarCodeResponse</code>.</p>\n\n<p>Honestly, I can't tell you which option you should use or not. I can only present you with alternatives. Personally I like Null Object pattern a lot, but it doesn't always makes much sense to use that pattern.</p>\n\n<p>By the way, why isn't <code>SalePoint</code> immutable? Instead of first creating a SalePoint object and then setting it's values one by one, read the values into variables and call a constructor which takes type, url, salePointId as arguments and get rid of the accessible properties (make them private, and also get rid of the setter-methods if you have any)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T15:25:43.383",
"Id": "63422",
"Score": "0",
"body": "Simon, `SalePoint` object is just a DTO, it encapsulates values parsed from a `String`, I don't even have getters and setters for it, just public variables in it, that's all. What benefits could I get if I made it immutable?\nI can't use Null Object pattern because as I said `SalePoint` does nothing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T16:27:47.353",
"Id": "63426",
"Score": "0",
"body": "@Eugene Do you have any benefit from *not* having it immutable? You *could* refactor to make a `save` method inside your `SalePoint` object so you call `salePoint.save(possibleAdditionalParameters)`. It's up to you of course, I don't know all your code and even if I did I can't tell you how to do it, I'm just saying what you *could* do."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T14:59:28.150",
"Id": "38117",
"ParentId": "38109",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T11:44:22.403",
"Id": "38109",
"Score": "1",
"Tags": [
"java",
"exception-handling"
],
"Title": "What's better: return null or handle the Exception?"
}
|
38109
|
<p>Rails AR. validate one field, with 4 validators & 2 condition block</p>
<pre><code>validates :inn,
presence: { if: -> { user.is_a?(Client) } },
inn: { if: -> { user.is_a?(Client) } },
uniqueness: { if: -> { user.is_a?(Client) } },
absence: { if: -> { user.is_a?(Department) } }
</code></pre>
<p>Could I have some tips on refactoring this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T13:44:48.300",
"Id": "63494",
"Score": "2",
"body": "`inn` as an option of `validates`?"
}
] |
[
{
"body": "<p>You can try something like this (obviously names can be shorter):</p>\n\n<pre><code>if_user_is_a = ->(klass) { { if: -> { user.is_a?(klass) } } }\nvalidates :inn, presence: if_user_is_a[Client], ..., absence: if_user_is_a[Department]\n</code></pre>\n\n<p>or</p>\n\n<pre><code>if_user_is_a = ->(klass) { { if: -> { user.is_a?(klass) } } }\nif_user_is_a_client = if_user_is_a[Client]\n...\nvalidates :inn, presence: if_user_is_a_client, ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-09T05:34:10.463",
"Id": "64993",
"Score": "0",
"body": "It seems better, but maybe is it something better than that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-21T23:49:33.190",
"Id": "66725",
"Score": "0",
"body": "It seems there isn't any better than that. Regards!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T03:47:42.413",
"Id": "38377",
"ParentId": "38112",
"Score": "1"
}
},
{
"body": "<p>You can try to use a method instead of repeat yourself 4 times</p>\n\n<p>Something like:</p>\n\n<pre><code>validates :inn,\n presence: { inn_meth { Client } },\n inn: { inn_meth { Client } },\n uniqueness: { inn_meth { Client} },\n absence: { inn_meth{ Department } }\n\ndef inn_meth\n if: -> { user.is_a?(yield) }\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-13T00:13:33.150",
"Id": "80390",
"ParentId": "38112",
"Score": "0"
}
},
{
"body": "<p>Why don't you split both conditions into 2 diffrent validations? I think it's cleaner and easier to read (ie more maintenable).</p>\n\n<pre><code>validates :inn, presence: true, uniqueness: true, if: :user_is_client #no idea about that `inn` option on your example\nvalidates :inn, absence: true, if: :user_is_department\n\ndef user_is_client\n user.is_a?(Client)\nend\n\ndef user_is_department\n user-is_a?(Department)\nend\n</code></pre>\n\n<p>Personally, I prefer to be more verbose some times. Also, I think this way conditions are checked only once each, the other way each condition is checked for each validation since rails has to evaluate all blocks.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T02:58:20.590",
"Id": "219969",
"ParentId": "38112",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "38377",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T12:35:40.080",
"Id": "38112",
"Score": "1",
"Tags": [
"ruby",
"ruby-on-rails",
"validation"
],
"Title": "Rails validating with condition block"
}
|
38112
|
<p>I've encountered a problem that I have to solve using <code>dynamic_cast</code> to invoke different functions, depending on the type of class State family.</p>
<p>I was re-factoring a Parser I wrote before, from a freaking nested class State inside Parser so that I could separate them and extract common parts using templates.</p>
<p>Here is a minimal model to illustrate the problem. It is not the code from the project, so I do not separate out the implementation here.</p>
<p><strong>Parser.h</strong></p>
<p><code>Operation()</code> to dispatch <code>OperationStateXX()</code> based on type of current state <code>mState</code></p>
<pre><code>#ifndef PARSER_H
#define PARSER_H
#include "ParserStates.hxx"
class Arg;
class Parser
{
public:
private:
const ParserBaseState* mState;
void
Transit(const ParserBaseState &state)
{ mState = &state; }
void
Operation(const Arg &arg)
{
if (dynamic_cast< const ParserState<ParserStates::State1>* >(mState))
{
OperationState1(arg);
}
}
void
OperationState1(const Arg &arg)
{
// if (someCase)
// {
// Transit(ParserState<ParserStates::State2>::GetInstance());
// }
}
};
#endif
</code></pre>
<p><strong>ParserStates.hxx</strong></p>
<p>Defines several State the Parser may have, each State uses Singleton Pattern since I think specific State have multiple instance does not make sense.</p>
<p>I know Singleton pattern is controversial, but it seems fit what I think this model
should be here. However, I met "static virtual" problem in C++ while fix the model in the middle.</p>
<pre><code>#ifndef PARSER_STATES
#define PARSER_STATES
struct ParserStates
{
struct State1 { typedef bool ParserStateTrait; };
struct State2 { typedef bool ParserStateTrait; };
struct State3 { typedef bool ParserStateTrait; };
};
class ParserBaseState
{
protected:
virtual ~ParserBaseState() {}
};
template < typename T >
class ParserState
: public ParserBaseState
{
public:
static ParserState< T > &
GetInstance()
{
static ParserState< T > instance;
return instance;
}
private:
typedef typename T::ParserStateTrait ParserStateTrait;
ParserState() {}
ParserState(const ParserState< T > &other);
const ParserState< T > & operator=(const ParserState< T > &other);
};
#endif
</code></pre>
<p>In this design, adding State is easy. Change and information in Parser is totally unaware in State, which is quite nice I think.</p>
<p>But it does explicit use <code>dynamic_cast</code> to switch type in States. </p>
<p>To avoid that, I need use some virtual function in <code>ParserState</code>, which is what polymorphism is for. But how do I invoke proper function in Parser from State without passing information Arg and let State access private function <code>OperationStateXX</code>? </p>
<p>Maybe there's no such silver bullet, but I would like to ask for some design advice. </p>
<p>I want to improve myself, so any other C++ advice (not limited to) about template and efficiency of this design is also welcome.</p>
<p><strong>Edit1</strong></p>
<p>At work so I can elaborate more now.</p>
<p><code>Parser</code> need to parse a file composed of lines of commands, here are some commands of
interest, like</p>
<pre><code>CommandA (follow by some other tokens)
CommandB (follow by some other tokens)
CommandC (not interested)
</code></pre>
<p>The followings of CommandA and CommandB need to match syntax rule of their own.</p>
<p>CommandB must occur after CommandA. Therefore I need State like StateHasA and StateHasAAndB. There may have some not interested commands like CommandC.</p>
<p>The <code>ParserStates</code> are similar to above <strong>ParserStates.hxx</strong></p>
<p><strong>Parser.h</strong></p>
<pre><code>#ifndef INCLUDED_PARSER
#define INCLUDED_PARSER
#include <string>
#include "ParserStates.hxx"
class Parser
{
public:
Parser();
~Parser();
void Parse(const std::string &fileName);
private:
const ParserBaseState* mState;
Data mData;
private:
void ReadLine(const std::string &line, int lineNumber);
void ReadLineStateInitial(const std::string &line, int lineNumber);
void ReadLineStateHasA(const std::string &line, int lineNumber);
void ReadLineStateHasAAndB(const std::string &line, int lineNumber);
void Transit(const ParserBaseState &state);
void ParseCommandA(const std::string &line);
void ParseCommandB(const std::string &line);
};
#endif
</code></pre>
<p><strong>Parser.cpp</strong></p>
<pre><code>#include "Parser.h"
#include <fstream>
#include <iostream>
#include <boost/regex.hpp>
namespace
{
const std::string syntaxA = "..."; //regex that line of CommandA should obey.
const std::string syntaxB = "..."; //regex that line of CommandB should obey.
}
void
Parser::
Parse(const std::string &fileName)
{
std::ifstream file;
file.open(fileName.c_str(), std::ios::in);
if (!file)
{
std::cout << "Some error message." << std::endl;
}
std::string line;
int lineNumber = 0;
while (std::getline(file, line))
{
++lineNumber;
DoSomePreProcessing(line);
ReadLine(line, lineNumber);
}
}
void
Parser::
ReadLine(const std::string &line, int lineNumber)
{
if (dynamic_cast< const ParserState< ParserStates::Initial >* >(mState))
{
ReadLineStateInitial(line, lineNumber);
return;
}
if (dynamic_cast< const ParserState< ParserStates::HasA>* >(mState))
{
ReadLineStateHasA(line, lineNumber);
return;
}
if (dynamic_cast< const ParserState< ParserStates::HasAAndB>* >(mState))
{
ReadLineStateHasAAndB(line, lineNumber);
return;
}
}
void
Parser::
ReadLineInitial(const std::string &line, int lineNumber)
{
if (boost::regex_match(line, boost::regex(syntaxA))
{
ParseCommandA(line);
Transit(ParserState< ParserStates::HasA >::GetInstance());
return;
}
if (boost::regex_match(line, boost::regex(syntaxB))
{
std::cout << "Some error message hint user syntax error in file." << std::endl;
return;
}
// and other cases...
}
void
Parser::
ReadLineHasA(const std::string &line, int lineNumber)
{
if (boost::regex_match(line, boost::regex(syntaxB))
{
ParseCommandB(line);
Transit(ParserState< ParserStates::HasAAndB >::GetInstance());
return;
}
// and other cases...
}
void
Parser::
ParseCommandA(const std::string &line)
{
CaptureContentCommandA(line, mData);
}
</code></pre>
<p>The <code>ReadLineXX</code> functions also have combinatorial problem: for each commands I need to
suport, all functions need to be modified.</p>
<p>@ChrisWue</p>
<p>To let the States do transition, is that means I need to pass context information and let States do logic of parsing context? I think the logic like function
<code>ReadLineStateXX()</code> should be in <code>Parser</code>, but the transition logic should be in <code>States</code>, which is what I failed in design.</p>
<p>The previous nested States design for comparison:</p>
<p><strong>Parser.h</strong></p>
<pre><code>#ifndef INCLUDED_PARSER
#define INCLUDED_PARSER
#include <string>
class Parser
{
public:
Parser();
~Parser();
void Parse(const std::string &fileName);
private:
class State
{
public:
virtual ~State() {}
virtual void ReadLine(Parser &parser, const std::string &line, int lineNumber) = 0;
protected:
void Transit(Parser &parser, const State &state)
{ parser.Transit(state); }
void ParseCommandA(Parser &parser, const std::string &line, int lineNumber);
{ parser.ParseCommandA(line, lineNumber); }
//... and each function in Parser that need delegate to.
};
class StateInitial
: public State
{
public:
static StateInitial &
GetInstance()
{
static StateInitial instance;
return instance;
}
//Equivalent to current ReadLineStateInitial() function.
void ReadLine(Parser &parser, const std::string &line, int lineNumber);
private:
StateInitial();
DISALLOW_COPY_AND_ASSIGN(StateInitial);
};
//And all other States, that's why I use template now.
//So all concrete StateXX using interface State can invoke private function in
//Parser, and State need define delegate functions.
friend class State;
const State* mState;
Data mData;
private:
void Transit(const State &state);
void ParseCommandA(const std::string &line);
void ParseCommandB(const std::string &line);
};
#endif
</code></pre>
<p>The usage is in implementation of <code>Parse()</code></p>
<pre><code>mState->ReadLine(*this, line, lineNumber);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T16:01:26.073",
"Id": "63424",
"Score": "0",
"body": "It is impossible to review this code: It is fake code (and appears not to compile), not the code you want reviewed. For problems like these, the specifics of the code are important, as your question does not have a one-size-fits-all answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T17:09:45.533",
"Id": "63429",
"Score": "0",
"body": "I don't understand about the compile part, I compiled in company project and I rewrite and tested above code home using Code::Blocks, the only missing part is using `Operation()` in some other implementation of `Parser`. I think that is obvious so omitted."
}
] |
[
{
"body": "<p>Maybe it's a result of your simplification for the example but your <code>ParserState</code> looks like an over-engineered enum to me. What do you gain from it over using an <code>enum</code> and a <code>switch</code> for the current state?</p>\n\n<p>In general whenever you need to check for the specific type in order to execute some specific logic then your abstraction is probably flawed from an OO point of view.</p>\n\n<p>One design I've chosen in the past for more complicated parser is to have the state execute the transition. Something along these lines (does not compile just showing the idea):</p>\n\n<pre><code>class IState\n{\n public:\n virtual IState* Transition(std::string& token) = 0;\n virtual bool IsFinalState() = 0;\n}\n\nclass InitState : IState\n{\n ...\n}\n\nclass SomeState : IState\n{\n ...\n}\n\nclass FinalState : IState\n{\n ...\n}\n\nclass Tokenizer\n{\n public:\n Tokenizer(const std::string& input) { ... }\n std::string NextToken() { ... } \n bool HasToken() { ... }\n}\n\nclass Parser\n{\n public:\n\n void Parse(const std::string& input)\n {\n Tokenizer tokenizer(input);\n\n IState* currentState = new InitState();\n\n while (!currentState->IsFinalState() && tokenizer.HasToken())\n {\n IState* newState = currentState->Transition(tokenizer.NextToken());\n delete currentState;\n currentState = newState;\n }\n }\n}\n</code></pre>\n\n<p>So the states themselves execute the code required for the transition into the next state given the current token. You can also pass around a context object if required.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T04:15:56.987",
"Id": "63871",
"Score": "0",
"body": "I didnt aware that this is the answer of my issue! I figure out something similar and just realize it. What I need is state provide virtual interface."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T00:55:56.337",
"Id": "38144",
"ParentId": "38114",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38144",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T13:16:17.860",
"Id": "38114",
"Score": "3",
"Tags": [
"c++",
"object-oriented",
"singleton",
"state-machine"
],
"Title": "How do I avoid explicit type switching when operation based on state?"
}
|
38114
|
<p>I am working on a little project to visualize the algorithm for the Traveling Salesman Problem. I have cities, which are movable objects painted with AWT and Swing. Also I can make a connection between two cities in the form of a undirected edge. Each city should have at least one connection between another city.</p>
<p>In my current solution every city has an <code>ArrayList</code> of the connected city. But I am afraid that this is not the optimal solution.
I would like to hear some comments about my code in general and improvements for my explained solution.</p>
<p>PS: I know that there are lots of external libraries, but I want to solve that problem without using any external libraries.</p>
<p><strong>The City Panel</strong></p>
<pre><code>public class CityPanel extends JPanel implements MouseListener, MouseMotionListener {
public final static int UNIT = 16;
public final static int GRIDWIDTH = 3 * UNIT;
public final static int PANELWIDTH = 12 * GRIDWIDTH;
public final static int PANELHEIGHT = 12 * GRIDWIDTH;
private boolean connect;
private boolean connectClick;
private Mediator mediator;
private CityList cityList = new CityList();
private CityList bestTrail = new CityList();
private City marked;
private boolean move;
private int pressX;
private int pressY;
private Graphics2D g2;
public CityPanel(Mediator mediator) {
this.setPreferredSize(new Dimension(PANELWIDTH, PANELHEIGHT));
this.setBorder(BorderFactory.createLineBorder(Color.BLACK));
this.mediator = mediator;
this.mediator.registerCityPanel(this);
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
//Painting methods
private void paintGrid() {
g2.setColor(Color.LIGHT_GRAY);
for(int i = 0; i < PANELWIDTH; i += GRIDWIDTH) {
this.g2.drawLine(i,0,i,PANELHEIGHT);
this.g2.drawLine(0,i,PANELHEIGHT,i);
}
}
private void paintCities() {
g2.setColor(Color.BLUE);
for (int i = 0; i < cityList.size(); i++) {
paintEdge(cityList.get(i));
paintCity(cityList.get(i));
}
if (marked != null) {
paintEdge(marked);
}
}
private void paintCity(City city) {
int rimX = city.getRimX();
int rimY = city.getRimY();
int x = city.getPos().x();
int y = city.getPos().y();
g2.setColor(city.getColor());
box(rimX, rimY, City.WIDTH, true);
write(String.valueOf(city.getId()), x, y);
if (marked == city) {
g2.setColor(Color.GREEN);
} else {
g2.setColor(Color.WHITE);
}
box(rimX, rimY, City.WIDTH, false);
}
private void paintConnections() {
for (int i = 0; i < this.cityList.size(); i++) {
for (int k = i+1; k < this.cityList.size(); k++) {
paintConnection(this.cityList.get(i), this.cityList.get(k));
}
}
}
private void paintConnection(City city1, City city2) {
if (city1.contains(city2)) {
g2.setColor(Color.GRAY);
g2.drawLine(city1.getPos().x(), city1.getPos().y(),
city2.getPos().x(), city2.getPos().y());
}
}
private void paintEdge(City city) {
g2.setColor(Color.CYAN);
if (city == marked) {
g2.setColor(Color.YELLOW);
}
}
private void box(int x, int y, int width, boolean b) {
if(b) {
g2.fillOval(x, y, width, width);
}
else
g2.drawOval(x, y, width, width);
}
private void write(String name, int x, int y) {
g2.setFont(new Font("Calibri", Font.PLAIN, City.WIDTH/2));
g2.setColor(Color.WHITE);
final FontMetrics fm = g2.getFontMetrics();
final int strWidth = SwingUtilities.computeStringWidth(fm, name);
g2.drawString(name, (int) (x - strWidth/2), (int) (y + fm.getMaxAscent()/2));
}
private void paintDescriptions() {
for (int i = 0; i < this.cityList.size(); i++) {
City city1 = this.cityList.get(i);
for (int k = 0; k < city1.getConnections().size(); k++) {
City city2 = city1.getConnections().get(k);
Pos pos = getCenterOfLine(city1, city2);
String dist = String.valueOf(this.cityList.getDistance(city1, city2));
g2.setColor(Color.GRAY);
g2.setFont(new Font("Calibri", Font.PLAIN, City.WIDTH/3));
final FontMetrics fm = g2.getFontMetrics();
final int strWidth = SwingUtilities.computeStringWidth(fm, dist);
g2.drawString(dist, pos.x() - strWidth/2, pos.y());
}
}
}
private void paintBestTrail() {
for (int i = 1; i < this.bestTrail.size(); i++) {
City a = this.bestTrail.get(i-1);
City b = this.bestTrail.get(i);
g2.setColor(Color.RED);
g2.drawLine(a.getPos().x(), a.getPos().y(), b.getPos().x(), b.getPos().y());
}
}
//other methods
public void addCities(int number) {
this.cityList.clear();
for (int i = 1; i <= number; i++) {
this.cityList.add(new City(i));
}
this.repaint();
}
public void connectAllCities() {
for (int i = 0; i < this.cityList.size(); i++) {
for (int k = i+1; k < this.cityList.size(); k++) {
this.cityList.get(i).addConnection(this.cityList.get(k));
this.cityList.get(k).addConnection(this.cityList.get(i));
}
}
repaint();
}
public void showConnections() {
for (int i = 0; i < this.cityList.size(); i++) {
System.out.print("City " + this.cityList.get(i).getId() + ":\t");
for (int k = 0; k < this.cityList.get(i).getConnections().size(); k++) {
System.out.print(this.cityList.get(i).getConnections().get(k).getId() + "\t");
}
System.out.println();
}
System.out.println();
}
public void setConnect(boolean connect) {
this.connect = connect;
}
public Pos getCenterOfLine(City city1, City city2) {
Pos pos1 = city1.getPos();
Pos pos2 = city2.getPos();
int newX = (pos2.x() - pos1.x()) / 2 + pos1.x();
int newY = (pos2.y() - pos1.y()) / 2 + pos1.y();
return new Pos(newX, newY, true);
}
private boolean isStartable() {
boolean b = true;
for (City city : this.cityList) {
if (city.getConnections().size() == 0)
b = false;
}
return this.cityList.size() != 0 && b;
}
public void setBestTrail() {
this.bestTrail.clear();
CityList temp = (CityList) this.cityList.clone();
Random rand = new Random();
for (int i = 0; i < temp.size(); i++) {
int r = rand.nextInt(this.cityList.size()-i);
this.bestTrail.add(temp.get(r));
temp.remove(r);
}
}
//MouseListener methods
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
this.g2 = (Graphics2D) g;
this.g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
this.g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
this.paintGrid();
this.paintConnections();
this.paintCities();
if (connectClick) {
g2.setColor(Color.GRAY);
g2.drawLine(this.marked.getPos().x(), this.marked.getPos().y(),
this.pressX, this.pressY);
}
paintDescriptions();
paintBestTrail();
this.mediator.enableStartButton(isStartable());
}
@Override
public void mouseClicked(MouseEvent e) {
if(SwingUtilities.isRightMouseButton(e)) {
if(this.cityList.isOccupied(new Pos(e.getX(), e.getY()), null)) {
cityList.remove(cityList.getMarked(e.getX(), e.getY()));
repaint();
} else {
cityList.add(new City(cityList.size() + 1, e.getX(), e.getY()));
repaint();
}
} else
showConnections();
}
@Override
public void mousePressed(MouseEvent e) {
if (marked != null) {
if (this.connect) {
this.connectClick = true;
}
this.move = true;
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (this.connectClick) {
City city = this.cityList.getMarked(e.getX(), e.getY());
if (city != null) {
city.addConnection(this.marked);
this.marked.addConnection(city);
}
}
this.move = false;
this.connectClick = false;
this.connect = false;
this.repaint();
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseDragged(MouseEvent e) {
if (this.connectClick) {
this.pressX = e.getX();
this.pressY = e.getY();
} else {
int maxHeight = CityPanel.PANELHEIGHT - City.WIDTH / 2;
int minHeight = City.WIDTH / 2;
int maxWidth = CityPanel.PANELWIDTH - City.WIDTH / 2;
int minWidth = CityPanel.WIDTH / 2;
if (e.getX() > maxWidth || e.getX() < minWidth || //Checks if Mouse is out of Panelrange, the field is Occupied, or if move=false
e.getY() > maxHeight || e.getY() < minHeight ||
this.cityList.isOccupied(new Pos(e.getX(), e.getY()), marked) ||
!move)
return;
this.marked.setPos(new Pos(e.getX(), e.getY()));
}
repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
if (this.move || this.connectClick)
return;
City neu = this.cityList.getMarked(e.getX(), e.getY());
if (this.marked != neu) {
this.marked = neu;
this.repaint();
}
}
}
</code></pre>
<p><strong>The City Class</strong></p>
<pre><code>public class City {
private int id;
private Pos pos;
public static int WIDTH = (int) (0.75 * CityPanel.GRIDWIDTH);
private Color color = Color.BLACK;
private ArrayList<City> connections = new ArrayList<City>();
private Random r = new Random();
public City(int id) {
this.id = id;
System.out.println("City " + id);
this.pos = new Pos();
}
public City(int id, int x, int y) {
this.id = id;
this.pos = new Pos(x,y);
}
public boolean isMarked(int x, int y) {
return (distFromCenter(x, y) < this.WIDTH/2);
}
public double distFromCenter(int x, int y) {
int dx = Math.abs(pos.x() - x);
int dy = Math.abs(pos.y() - y);
return Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
}
public int getRimX() {
return this.pos.x() - this.WIDTH / 2;
}
public int getRimY() {
return this.pos.y() - this.WIDTH / 2;
}
public void addConnection(City city) {
if (!this.connections.contains(city))
this.connections.add(city);
}
public void removeConnection(City city) {
this.connections.remove(city);
}
public boolean contains(City city) {
return this.connections.contains(city);
}
public Pos getPos() {
return this.pos;
}
public void setPos(Pos pos) {
this.pos = pos;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public Color getColor() {
return this.color;
}
public ArrayList<City> getConnections() {
return this.connections;
}
}
</code></pre>
<p><strong>The CityList Class</strong></p>
<pre><code>public class CityList extends ArrayList<City> {
private double[][] distances;
private Random r = new Random();
public CityList() {
}
public boolean isOccupied(Pos pos, City marked) {
for (int i = 0; i < this.size(); i++) {
if(get(i).getPos().equals(pos) && !get(i).equals(marked))
return true;
}
return false;
}
public City getMarked(int x, int y) {
for (int i = size() - 1; i >= 0; i--) {
if (get(i).isMarked(x, y)) {
return get(i);
}
}
return null;
}
public int getDistance(City a, City b) {
int x = Math.abs(a.getPos().x() - b.getPos().x());
int y = Math.abs(a.getPos().y() - b.getPos().y());
double dist = Math.sqrt(Math.pow(x,2) + Math.pow(y,2));
return (int) Math.round(dist / CityPanel.UNIT);
}
public boolean add(City city) {
while (this.isOccupied(city.getPos(), city)) {
city.setPos(new Pos());
}
return super.add(city);
}
public boolean remove(City city) {
for (City c : city.getConnections()) {
c.removeConnection(city);
}
boolean b = super.remove(city);
for (int i = 0; i < this.size(); i++) {
this.get(i).setId(i+1);
}
return b;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You might change from <code>ArrayList</code> to <code>HashMap</code>. That will give you better performance for large numbers of cities (for small numbers of cities, the overhead of using a HashMap can be more than what you gain over using the ArrayList).</p>\n\n<p>I would also suggest adding a new variable to your <code>CityList</code> - a new HashMap that is indexed by <code>Pos</code>. Then your <code>isOccupied</code> function becomes:</p>\n\n<pre><code>public boolean isOccupied(Pos pos, City marked) {\n //returns true only if there is a Pos p in the map so p.equals(marked.getPos()) is true.\n return posMap.containsKey(marked.getPos());\n}\n</code></pre>\n\n<p>Why?</p>\n\n<p>In <code>CityPanel</code>, <code>paintCities</code> needs to iterate across all cities\n<code>paintConnections</code> needs to iterate across all connections, i.e. doubly iterate across your cities (this will be O(n^2) in the best case).\n<code>paintDescriptions</code> will be the same.\n<code>addCities</code> calls <code>add()</code> once for each city being generated. So it's O(n * complexity of <code>add()</code>)</p>\n\n<p>In <code>City</code>, <code>addConnection</code> calls <code>contains()</code> and <code>add()</code> - this will be O(n) because of <code>contains()</code>\n<code>removeConnection</code> calls <code>remove()</code> on the list of connections.\n<code>contains</code> is O(n) with an <code>ArrayList</code>.</p>\n\n<p><code>CityList</code> really only has a problem with <code>isOccupied</code>; it has to iterate through the entire list (so it's O(n)) in order to give an answer.\n<code>add</code> relies on isOccupied\n<code>remove</code> calls <code>removeConnection()</code> on every city in the list, i.e. O(n * cost of <code>remove</code>)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T19:51:17.067",
"Id": "38191",
"ParentId": "38120",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T16:18:53.690",
"Id": "38120",
"Score": "7",
"Tags": [
"java",
"beginner",
"algorithm",
"gui",
"traveling-salesman"
],
"Title": "Visualization of the Traveling Salesmen Problem"
}
|
38120
|
<p>I'm just beginning web design, and I've come up with this code to scroll to a place in the same page. </p>
<p>I don't know if this can or should be improved much longer, so I'm asking for any tips that can make this code better. </p>
<p>I know it's messy, but I will clean it later. I just want to know if there's a better method.</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function(){
$('#Tecnologia').click(function(){
$(".ConHome").css('transition','all 0.4s ease');
$(".ConHome").css('transform','translateY(-50em)');
$("#BlankSpaceMenu").css('transition','all 0.4s ease');
$('#BlankSpaceMenu').css('transform','translateY(-50em)');
$(".ConTech").css('transition','all 0.4s ease');
$(".ConTech").css('transform','translateY(-50em)');
$(".TopHeader").css('transition','all 0.4s ease');
$(".TopHeader").css('border-bottom-color','rgba(0,0,255,1)');
})})</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#BlankSpaceMenu{
position:relative;
height:7em;
width:100%;
background-color:rgba(0,0,255,1);
z-index:9;
}
.Container{
position:relative;
color:rgba(255,255,255,1);
}
.TopHeader{
position:fixed;
background-color:rgba(255,153,0,1);
color:rgba(255,255,255,1);
height:7em;
width:100%;
z-index:10000;
border-bottom:rgba(0,0,0,1) dashed 10px;
}
.ConHome{
position: relative;
background-color: rgba(0,0,0,1);
color: rgba(255,255,255,1);
height: 50em;
width: 100%;
z-index:10;
}
.ConTech{
position: relative;
background-color:rgba(0,0,255,1);
color:rgba(255,255,255,1);
height: 50em;
width: 100%;
z-index:8;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<body>
<section class="Container">
<header class="TopHeader">
<nav id="NavBar">
<a id="Tecnologia">Tecnologia</a>
</nav>
</header>
<article class="ConHome">
....
</article>
<section id="BlankSpaceMenu">
</section>
<article class="ConTech">
...
</article>
</section>
</body></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T18:20:43.260",
"Id": "63435",
"Score": "0",
"body": "Is there are reason why you wouldn't want to move the whole `.Container` that contains `#Tecnologia` instead?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T03:33:24.937",
"Id": "63462",
"Score": "1",
"body": "Why not just toggle a class on and off and do your transitions in CSS?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T19:22:16.453",
"Id": "63556",
"Score": "0",
"body": "@200_success I did that once on another site. I'm trying to use a new perspective this time..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T19:28:45.990",
"Id": "63559",
"Score": "0",
"body": "@elclanrs I've tried that but the transitions weren't smooth enough... I've got a tip to shrink the code, using CSS selectors efficiently (that actually was a reply to this same question). You know those scrolls where the menu is fixed and the page goes up when you click the link? I wonder if there's a way to do that using the minimum coding possible..."
}
] |
[
{
"body": "<p>You should declare these styles into classes, and use jQuery to toggle the classes. That way, you have good \"separation of concerns\". You end up with a smaller base code.</p>\n\n<p>Additionally, one should not use the <code>all</code> for transition. It's bad for performance. Ideally, one should just indicate what property to transition.</p>\n\n<p>There's also <a href=\"http://mobile.smashingmagazine.com/2012/06/21/play-with-hardware-accelerated-css/\" rel=\"nofollow\">this neat trick that forces CSS to be hardware-accelerated</a>. However, you should use it carefully. I read that there's drawbacks to excessive use, and instead of performance gains, you lose performance.</p>\n\n<p>With what I know, here's how you can optimize that animation code:</p>\n\n<p>CSS:</p>\n\n<pre><code>#BlankSpaceMenu.transition, \n.ConHome.transition, \n.ConTech.transition,\n.TopHeader.transition{\n transition : all 0.4 ease\n}\n\n#BlankSpaceMenu.transform,\n.ConHome.transform,\n.ConTech.transform{\n transform : translateY(-50em)\n}\n\n.TopHeader.transform{\n border-bottom-color : rgba(0,0,255,1)\n}\n</code></pre>\n\n<p>JS:</p>\n\n<pre><code>$(function () {\n\n // Cache the set, assuming they don't change.\n var animationSet = $('.ConHome, #BlankSpaceMenu, .ConTech, .TopHeader');\n\n $('#Tecnologia').click(function () {\n animationSet.addClass('transition transform');\n });\n\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-26T19:31:00.077",
"Id": "67404",
"Score": "0",
"body": "Hi Joseph! Thanks for the help. I liked specially the JS trick. That helped me save some lines of code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T03:55:29.243",
"Id": "38378",
"ParentId": "38123",
"Score": "4"
}
},
{
"body": "<p>As an addition to Joseph's answer some thoughts on your HTML/CSS.</p>\n\n<p><strong>HTML:</strong></p>\n\n<ul>\n<li>You use the <code>section</code> element as a container for your main content. This inappropriate. There is a HTML5 element just for that purpose: <code><main></code>. \n<ul>\n<li><a href=\"http://html5doctor.com/the-main-element/\" rel=\"nofollow\">HTML5 doctor: main element</a></li>\n<li><a href=\"http://html5doctor.com/the-section-element/\" rel=\"nofollow\">HTML5 doctor: section element</a></li>\n</ul></li>\n<li>You have an empty <code>section</code> element in between some articles. What is its purpose?</li>\n</ul>\n\n<p><strong>CSS:</strong></p>\n\n<ul>\n<li>I recommend you not using ID's for navigation items. Do you know about CSS specificity? The main culprit of ID's is their higher specificity. This means a rule <code>#Tecnologica</code> can't be overwritten by <code>.TopHeader a</code>.</li>\n<li><p>You have quite a big problem with using <code>rgba()</code> with no transparency at all. <strong>Don't do this!</strong> Basically all browsers (rgba() will just ignore this declaration and therefor won't have a change in colors.</p>\n\n<p>If you have a declaration like <code>rgba(255,255,255,1)</code> you just need to change it to its hex format: <code>#fff</code>.</p></li>\n<li><p>Also since writing hex-based color values is short as opposed to <code>rgb()</code> just use the hex values for colors if you don't need transparency.</p></li>\n<li>Why are you using the <code>position</code> property so much? What are you trying to achieve? Can you give us a little demo?</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-26T19:37:22.687",
"Id": "67406",
"Score": "0",
"body": "Hello @kleinfreund! Thanks for the comments. About the section element, I really didn't know the main element, guess I've never paid attention to it. I was trying to use the other empty sections as targets for a scroll animation, but that didn't work quite well and I ended up using a the jQuery slide function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-26T19:50:07.360",
"Id": "67408",
"Score": "0",
"body": "About the CSS: Alphas are for background images I was planning to use. Positions, well, I was trying to make a website with fixed header and footer, and, when the user clicks the link, the pages would switch in between them, I had trouble with making them fit the end of the header."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-26T19:51:23.507",
"Id": "67409",
"Score": "0",
"body": "About the color declarations, is it faster to use #fff or rgb(255,255,255)? (just a curiosity)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-25T09:05:03.833",
"Id": "40033",
"ParentId": "38123",
"Score": "4"
}
},
{
"body": "<p>Another adition to Joseph answer</p>\n\n<p>You don't really need to set the transition property in the CSS <em>at the moment</em>.</p>\n\n<p>If you are not planning to make the changes in the element not transitioned at any time (and in your posted code you aren't), just leave the </p>\n\n<pre><code>transition: transform 0.4s ease; \n</code></pre>\n\n<p>declaration permanently in the CSS.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-25T10:59:01.510",
"Id": "40035",
"ParentId": "38123",
"Score": "3"
}
},
{
"body": "<p>I skimmed the answers and I haven't seen anyone mention this yet.</p>\n\n<p>Please <strong>INDENT YOUR CODE</strong></p>\n\n<p>You need to indent your code, right now it is hard to read.</p>\n\n<p>Take a look at this compared to your code</p>\n\n<pre><code><body>\n <section class=\"Container\">\n <header class=\"TopHeader\">\n <nav id=\"NavBar\">\n <a id=\"Tecnologia\">Tecnologia</a>\n </nav>\n </header>\n <article class=\"ConHome\">\n .... \n </article>\n <section id=\"BlankSpaceMenu\">\n </section>\n <article class=\"ConTech\">\n ...\n </article>\n </section>\n</body>\n</code></pre>\n\n<p><strong>CSS</strong></p>\n\n<pre><code>#BlankSpaceMenu{\n position:relative;\n height:7em;\n width:100%;\n background-color:rgba(0,0,255,1);\n z-index:9;\n}\n.Container{\n position:relative;\n color:rgba(255,255,255,1);\n}\n.TopHeader{\n position:fixed;\n background-color:rgba(255,153,0,1);\n color:rgba(255,255,255,1);\n height:7em;\n width:100%;\n z-index:10000;\n border-bottom:rgba(0,0,0,1) dashed 10px;\n}\n.ConHome{\n position: relative;\n background-color: rgba(0,0,0,1);\n color: rgba(255,255,255,1);\n height: 50em;\n width: 100%;\n z-index:10;\n}\n.ConTech{\n position: relative;\n background-color:rgba(0,0,255,1);\n color:rgba(255,255,255,1);\n height: 50em;\n width: 100%;\n z-index:8;\n}\n</code></pre>\n\n<p><strong>jQuery</strong></p>\n\n<pre><code>$(document).ready(function(){\n $('#Tecnologia').click(function(){\n $(\".ConHome\").css('transition','all 0.4s ease');\n $(\".ConHome\").css('transform','translateY(-50em)');\n $(\"#BlankSpaceMenu\").css('transition','all 0.4s ease');\n $('#BlankSpaceMenu').css('transform','translateY(-50em)');\n $(\".ConTech\").css('transition','all 0.4s ease');\n $(\".ConTech\").css('transform','translateY(-50em)');\n $(\".TopHeader\").css('transition','all 0.4s ease');\n $(\".TopHeader\").css('border-bottom-color','rgba(0,0,255,1)');\n })\n})\n</code></pre>\n\n<ol>\n<li>Much more readable</li>\n<li>Easier to debug</li>\n<li>When(if) you switch to Python (or VB) where there are no line terminators it is mandatory to use indentation (or Newlines) so that the compiler knows what is going on.</li>\n<li>If you need your JavaScript minified for some reason, get an application to do it for you, so that you don't fall into bad coding habits.</li>\n<li>Other people will be able to read your code with no issues if you keep similar formatting to the standards.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T16:50:24.253",
"Id": "41569",
"ParentId": "38123",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38378",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T17:42:24.240",
"Id": "38123",
"Score": "4",
"Tags": [
"beginner",
"jquery",
"html",
"css",
"animation"
],
"Title": "Animated scrolling to a place in the same webpage"
}
|
38123
|
<p>I've created this PHP script to print a batch of usernames with encrypted passwords locally on my computer because the user/pass format is always the same.</p>
<blockquote>
<p>username = username</p>
<p>password = username + "admin"</p>
<p>example = homer / homeradmin</p>
</blockquote>
<p>Then paste them into two different .htpasswd file and upload to an public Apache server to password-protect a directory and a directory within it.</p>
<p><strong>Is there a better way to write the code below?</strong></p>
<pre><code><?php
// Password to be encrypted for a .htpasswd file
$user1 = 'admin';
$user2 = 'g';
$user3 = 'homer';
$user4 = 'marge';
$user5 = 'bart';
$user6 = 'lisa';
$user7 = 'maggie';
$user8 = 'dog';
//Admin
$admin1 = 'admin';
$admin2 = '23!bseEsF@';
$admin3 = 'homeradmin';
$admin4 = 'margeadmin';
$admin5 = 'bartadmin';
$admin6 = 'lisaadmin';
$admin7 = 'maggieadmin';
$admin8 = 'dogadmin';
// Encrypt password
$pass1 = crypt($user1, base64_encode($user1));
$pass2 = crypt($user2, base64_encode($user2));
$pass3 = crypt($user3, base64_encode($user3));
$pass4 = crypt($user4, base64_encode($user4));
$pass5 = crypt($user5, base64_encode($user5));
$pass6 = crypt($user6, base64_encode($user6));
$pass7 = crypt($user7, base64_encode($user7));
$pass8 = crypt($user8, base64_encode($user8));
$adminpass1 = crypt($admin1, base64_encode($admin1));
$adminpass2 = crypt($admin2, base64_encode($admin2));
$adminpass3 = crypt($admin3, base64_encode($admin3));
$adminpass4 = crypt($admin4, base64_encode($admin4));
$adminpass5 = crypt($admin5, base64_encode($admin5));
$adminpass6 = crypt($admin6, base64_encode($admin6));
$adminpass7 = crypt($admin7, base64_encode($admin7));
$adminpass8 = crypt($admin8, base64_encode($admin8));
?>
<!doctype html>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Encrypt</title>
<meta name="viewport" content="width=device-width">
<head>
</head>
<body>
<p>
<?php
// Print encrypted password
echo $user1 . ":" . $pass1 . "<br/>";
echo $user2 . ":" . $pass2 . "<br/>";
echo $user3 . ":" . $pass3 . "<br/>";
echo $user4 . ":" . $pass4 . "<br/>";
echo $user5 . ":" . $pass5 . "<br/>";
echo $user6 . ":" . $pass6 . "<br/>";
echo $user7 . ":" . $pass7 . "<br/>";
echo $user8 . ":" . $pass8 . "<br/>";
?>
</p>
<p>
<?php
echo $admin1 . ":" . $adminpass1 . "<br/>";
echo $admin2 . ":" . $adminpass2 . "<br/>";
echo $admin3 . ":" . $adminpass3 . "<br/>";
echo $admin4 . ":" . $adminpass4 . "<br/>";
echo $admin5 . ":" . $adminpass5 . "<br/>";
echo $admin6 . ":" . $adminpass6 . "<br/>";
echo $admin7 . ":" . $adminpass7 . "<br/>";
echo $admin8 . ":" . $adminpass8 . "<br/>";
?>
</p>
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T18:30:38.250",
"Id": "63436",
"Score": "1",
"body": "this is off-topic for this site in that it is asking for code to be written, we don't do that here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T19:18:52.863",
"Id": "63438",
"Score": "0",
"body": "@Malachi This question seems to just be written differently. I believe the existing code here works and that it is desperately in need for a review. I interpret the question as \"Is there a way I can make this better, with less code?\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T19:19:43.180",
"Id": "63439",
"Score": "0",
"body": "I don't see any traces of the .htaccess stuff though, and we won't help you write that, @Conor. I hope someone will help you write the existing code in a better way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T19:21:31.533",
"Id": "63440",
"Score": "0",
"body": "I am thinking that you need to create some arrays, and then loop through the arrays, I will look at it a bit later, but I have to look up all the syntax, I am thinking **linked arrays** ( *I think that is the term I want* )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T19:22:01.400",
"Id": "63442",
"Score": "1",
"body": "@SimonAndréForsberg: If so, it could be edited to reflect that. As it's worded, it sounds like a request for code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T19:33:06.787",
"Id": "63445",
"Score": "1",
"body": "@SimonAndréForsberg I have the .htaccess files already pointed to these .htpasswd files on the server. Everything works fine, just need to be pointed in the right direction on how to write this code more efficiently."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T19:39:35.157",
"Id": "63446",
"Score": "0",
"body": "I edited the bolded part of the question to better reflect what it is about"
}
] |
[
{
"body": "<p>the first thing that came to my mind to make this cleaner was an array or rather several arrays.</p>\n\n<p>maybe something like this:</p>\n\n<pre><code>$user = array('admin','g','homer','marge','bart','lisa','maggie','dog');\n$admin = array('admin','23!bseEsF@','homeradmin','margeadmin','bartadmin','maggieadmin','dogadmin');\n\n$password = array(8); //my syntax may be wrong here\n$adminPassword = array(8); //my syntax may be wrong here\n\nfor ($x=0; $x < count($user); x$++)\n{\n $password[$x] = crypt($user[$x], base64_encode($user[$x]));\n $adminPass[$x] = crypt($admin[$x], base64_encode($admin[$x]));\n}\n</code></pre>\n\n<p>And then your Echo's would look like this.</p>\n\n<pre><code>echo $user1 . \":\" . $pass1 . \"<br/>\";\nfor ($y=0; $y < count($user); $y++)\n{\n echo $user[$y] . \":\" . $pass[$y] . \"<br/>\";\n}\nfor ($z=0; $z < count($admin); $z++)\n{\n echo $admin[$z] . \":\" . $adminPass[$z] . \"<br/>\";\n}\n</code></pre>\n\n<p>The only way that this works is if all the arrays are the same length and arrays in PHP are base 0. otherwise you have to change the for declarations a little bit.</p>\n\n<hr>\n\n<p>Again I say that my Syntax may not be perfect or even well formed, but this is much cleaner than what you have. </p>\n\n<p><em>Syntax not Guaranteed</em> </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T18:59:52.950",
"Id": "63551",
"Score": "0",
"body": "@Conor, your welcome. having them in an array really helps. but you have to make sure they are in the right order"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T16:24:58.357",
"Id": "38179",
"ParentId": "38124",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38179",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T18:20:09.863",
"Id": "38124",
"Score": "3",
"Tags": [
"php",
"cryptography"
],
"Title": "Need Loops for PHP Username/Pass Encryption Script"
}
|
38124
|
<p>In this code, I'm overriding the sorter and matcher for <a href="http://getbootstrap.com/2.3.2/javascript.html#typeahead" rel="nofollow">Twitter-Bootstrap's Typeahead</a> functionality. The reason for the override is to allow state (technically Jurisdiction) abbreviations to be used to match the full state name. I've reduced the length of the source array in this example for brevity, but a full version is available on <a href="http://jsfiddle.net/sciencepharaoh/YsULX/" rel="nofollow">this fiddle</a>. I also decided to make it so that duplicate entries could not be made.</p>
<p>I went out of my way to make JSHint like my code, but I'd basically like any suggestions. This is my first time doing something like this and I'm relatively new with Javascript anyway. The only things I'm not interested in is white space as I simply formatted this based upon JSFiddle's TidyUp function, the css (as I didn't create it), and suggestions to override highlighter as I don't see the need.</p>
<p>Note: In production the number of inputs is dynamic, which is why I am selecting them each time.</p>
<p>If you need to view the Typeahead source code to understand my overrides, you can download it <a href="http://getbootstrap.com/2.3.2/assets/js/bootstrap-typeahead.js" rel="nofollow">here</a></p>
<h2>HTML for Example</h2>
<pre><code><input class="jurisdiction">
<br/>
<input class="jurisdiction">
<br/>
<input class="jurisdiction" value="Alberta">
</code></pre>
<h2>Javascript</h2>
<pre><code>var myTypeAhead = ! function ($) { // To make JSHint happy
var states = [{ //shortened for brevity
name: 'Alabama',
abbreviation: 'AL'
}, {
name: 'Alberta',
abbreviation: 'AB'
}],
stateNames = [],
overrides = {
matcher: matcherOverride,
sorter: sorterOverride
},
usedStateNames = getUsedStateNames();
//Populate stateNames
$.each(states, function () {
stateNames.push(this.name);
});
function getState(stateName) {
return $.grep(states, function (e) {
return e.name === stateName;
})[0];
}
function matcherOverride(item) {
var state = getState(item);
var query = this.query.toLowerCase();
// true if entered value contained in state name or abbreviation
return ~state.name.toLowerCase().indexOf(query) ||
~state.abbreviation.toLowerCase().indexOf(query);
}
function sorterOverride(items) {
//Orders state names based upon match type
var beginswith = [],
caseSensitive = [],
caseInsensitive = [],
abbreviationMatch = [],
item = items.shift(),
state,
lcQuery = this.query.toLowerCase();
while (item) {
state = getState(item);
if (state && !state.abbreviation.toLowerCase().indexOf(lcQuery)) {
abbreviationMatch.push(state.name);
} else if (!item.toLowerCase().indexOf(lcQuery)) {
beginswith.push(item);
} else if (~item.indexOf(this.query)) {
caseSensitive.push(item);
} else {
caseInsensitive.push(item);
}
item = items.shift();
}
return abbreviationMatch.concat(beginswith, caseSensitive, caseInsensitive);
}
function UpdateDataSource(e) {
//$(e).typeahead(overrides).data('typeahead').source = getDataSourceArray();
$(e).typeahead(overrides).data('typeahead').source = getDataSourceArray(e.value);
}
function getDataSourceArray(currentValue) {
usedStateNames = removeArray(usedStateNames, [currentValue]);
return removeArray(stateNames, usedStateNames);
}
function removeArray(original, toRemove) {
return $.grep(original, function (a) {
return !~$.inArray(a, toRemove);
});
}
function getUsedStateNames() {
var usedStateNames = [];
$('.jurisdiction').each(function () {
usedStateNames.push(this.value);
});
return usedStateNames;
}
$(document).on("focus", ".jurisdiction", function () {
UpdateDataSource(this);
});
$(document).on("change", ".jurisdiction", function () {
//Disallow repeats or unlisted values
if (!~stateNames.indexOf(this.value) || ~usedStateNames.indexOf(this.value)) {
this.value = "";
}
});
$(document).on("blur", ".jurisdiction", function () {
usedStateNames.push(this.value);
});
}(window.jQuery);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T12:16:57.163",
"Id": "76453",
"Score": "0",
"body": "which bootstrap version are you using ?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T18:23:12.430",
"Id": "38125",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"beginner",
"twitter-bootstrap"
],
"Title": "Overriding sorter and matcher in Bootstrap Typeahead"
}
|
38125
|
<p><a href="http://getbootstrap.com/" rel="nofollow">Bootstrap</a> is a front-end framework from Twitter designed to kickstart the front-end development of webapps and sites. Among other things, it includes base CSS and HTML for typography, icons, forms, buttons, tables, layout grids, navigation along with custom-built jQuery plug-ins and support for responsive layouts.</p>
<p>It is tested and supported in the major modern browsers, such as the latest versions of Safari, Google Chrome, Firefox 5+, and Internet Explorer 7+. Mobile browsers are supported by Bootstrap versions 2.0 and later.</p>
<p>Starting with version 2.0, the default download package contains cumulative JavaScript and CSS files. If you're looking for the uncompiled <a href="http://lesscss.org/" rel="nofollow">LESS</a> source files, documentation and example templates, you can download them from the <a href="https://github.com/twbs/bootstrap" rel="nofollow">project's GitHub page</a>.</p>
<p>There are two major version of the framework:</p>
<ul>
<li><a href="http://getbootstrap.com/2.3.2/" rel="nofollow">Bootstrap 2.3.2</a> </li>
<li><a href="http://getbootstrap.com/getting-started/#download" rel="nofollow">Bootstrap 3</a></li>
</ul>
<p>It was licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0" rel="nofollow">Apache 2 License</a>, but is now dual-licensed under both the <a href="http://en.wikipedia.org/wiki/MIT_License" rel="nofollow">MIT License</a> and Apache 2 License, after <a href="https://github.com/twbs/bootstrap/issues/2054" rel="nofollow">this</a> issue was closed.</p>
<ul>
<li><a href="http://getbootstrap.com/" rel="nofollow">Website and style guide</a></li>
<li><a href="http://blog.getbootstrap.com/" rel="nofollow">The Official Twitter Bootstrap Blog</a></li>
<li><a href="http://bootstrapdocs.com/" rel="nofollow">BootstrapDocs</a></li>
<li><a href="http://glyphicons.com/" rel="nofollow">Bootstrap Icons</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T19:29:06.963",
"Id": "38127",
"Score": "0",
"Tags": null,
"Title": null
}
|
38127
|
<p>I've created an admin login area for an application I am planning to code, and I've used the following login.html page to let the user type in his data (I left out parts like "id", "placeholder" etc. to make it shorter):</p>
<pre><code><form method="post" action="login.php">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Login" name="submit">
</form>
</code></pre>
<p>The form is processed as is, no JavaScript interfering here. The login.php then looks like this:</p>
<pre><code><?php
if (isset($_POST['password']) && isset($_POST['userName'])) {
if ($_POST['password'] == "myPassword" && $_POST['userName'] == "myUsername") {
if (!session_id()) {
session_start();
$_SESSION['logon'] = true;
header('Location: admin_area.php');
die();
}
} else if ($_POST["password"] == "" || $_POST["userName"] == "") {
echo "Please enter both a username and a password! You are sent back in 3 seconds";
echo "<meta http-equiv='refresh' content='3;url=login.html'>";
} else {
echo "Wrong username and/or password! You are set back in 3 seconds";
echo "<meta http-equiv='refresh' content='3;url=login.html'>";
}
} else {
echo "This is a restricted area, you have to log in!";
echo "<meta http-equiv='refresh' content='3;url=login.html'>";
}
?>
</code></pre>
<p>The admin_area.php file, which the user is then being redirected to, has the following short placeholder code:</p>
<pre><code><?php
if (!session_id()) session_start();
if (!$_SESSION['logon']) {
echo "This is a restricted area, you have to log in!";
echo "<meta http-equiv='refresh' content='3;url=login.html'>";
} else {
echo "<script src='//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js'></script>";
echo "<script type='text/javascript' src='session_destroy.js'></script>";
echo "Hello World!";
echo "<br>";
echo "<input type='button' id='exit_button' value='Exit' onclick='window.open(\"\", \"_self\", \"\"); window.close();'>";
}
?>
</code></pre>
<p>The essential part of the session_destroy.js file on this page contains this code snippet:</p>
<pre><code>$(window).on("beforeunload", function() {
$.get("session_destroy.php");
return "You have left the page. Your session has been terminated.";
});
</code></pre>
<p>And finally, the session_destroy.php, which should terminate all session data, contains the following lines (taken from the PHP manual):</p>
<pre><code><?php
if (!session_id()) session_start();
if (!$_SESSION['logon']) {
echo "This is a restricted area, you have to log in!";
echo "<meta http-equiv='refresh' content='3;url=login.html'>";
} else {
$_SESSION = array();
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
session_destroy();
header('Location: login.html');
}
?>
</code></pre>
<p>Now this "construct" seems to be working just fine. I am wondering if there are some improvements on these lines, as I have researched everything myself and I am not sure how "secure" and correct these methods might be.</p>
<p>I am thinking of possible security improvements to the form-processing and session-handling / destroying. Are there any areas in which I should do more research?</p>
|
[] |
[
{
"body": "<p>Tha major security issue I see is that you do not have any limiting or logs for wrong/success attempts. One can use automated brute force attacks trying all day/night long to guess your username and password. If lack of success, at least you might have your app slowed down, because of the billion requests.</p>\n\n<p>As you requested, I tried to add some code examples around my suggestion:</p>\n\n<pre><code><?php\n\n//the db interaction is pseudo code, because it depends on the API you are using\n/**\n * \n * @param int $success : 0 for fail, 1 for success\n */\nfunction logAttempt($success) {\n $user = $db->escape($_POST['userName']);\n $pass = $db->escape($_POST['password']);\n $session_id = session_id();\n if (!in_array($success, array(0, 1))) {\n return false;\n }\n $db->query(\"INSERT INTO `log_attempts` \n (`user`, `pass`, `ip`, `session_id`, `success`, `tried_on`)\n VALUES\n ('$user', '$pass', '{$_SERVER['REMOTE_ADDR']}', '$session_id', '$success', NOW());\n \");\n return $db->affected_rows > 0;\n}\n\nfunction isAttemptsLimitExceeded() {\n $max_attempts = 5;\n $session_id = session_id();\n $res = $db->query(\"SELECT \n COUNT(*) AS cnt\n FROM \n `log_attempts`\n WHERE\n `session_id` = '$session_id' AND\n `tried_on` > DATE_SUB(NOW(), INTERVAL 24 HOUR) AND\n `success` = '0';\n \");\n $row = $db->fetch($res);\n if ($row['cnt'] >= $max_attempts) {\n return true;\n }\n return false;\n}\n\nfunction banFailedLogins() {\n if(isAttemptsLimitExceeded()) {\n $db->query(\"INSERT INTO `blacklist`\n (`ip`, `banned_on`)\n VALUES\n ('{$_SERVER['REMOTE_ADDR']}', NOW()\");\n }\n return $db->affected_rows > 0;\n}\n\nfunction clearBans() {\n $db->query(\"DELETE from `blacklist` WHERE `ip` = '{$_SERVER['REMOTE_ADDR']}';\");\n return $db->affected_rows > 0;\n}\n\n//check for expired bans?\nfunction canAcess() {\n $ban_expire = 24; // hours\n $res = $db->query(\"SELECT \n COUNT(*) AS cnt \n FROM \n `blacklist` \n WHERE \n `ip` = '{$_SERVER['REMOTE_ADDR']}' AND\n `banned_on` > DATE_SUB(NOW(), INTERVAL $ban_expire HOUR);\n \");\n $row = $db->fetch($res);\n if ($row['cnt'] > 0) {\n return false;\n }\n else {\n clearBans();\n return true;\n }\n}\n\nif (!canAcess()) {\n die(\"You are banned for failed login attempts\");\n}\n if (isset($_POST['password']) && isset($_POST['userName'])) {\n if ($_POST['password'] == \"myPassword\" && $_POST['userName'] == \"myUsername\") {\n if (!session_id()) {\n session_start();\n $_SESSION['logon'] = true;\n logAttempt(1); //log successfull attempt\n header('Location: admin_area.php');\n die();\n }\n } else if ($_POST[\"password\"] == \"\" || $_POST[\"userName\"] == \"\") {\n echo \"Please enter both a username and a password! You are sent back in 3 seconds\";\n logAttempt(0); //log failed attempt\n banFailedLogins();\n echo \"<meta http-equiv='refresh' content='3;url=login.html'>\";\n } else {\n echo \"Wrong username and/or password! You are set back in 3 seconds\";\n logAttempt(0); //log failed attempt\n banFailedLogins();\n echo \"<meta http-equiv='refresh' content='3;url=login.html'>\";\n }\n } else {\n echo \"This is a restricted area, you have to log in!\";\n echo \"<meta http-equiv='refresh' content='3;url=login.html'>\";\n }\n\n?>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T21:10:07.233",
"Id": "63453",
"Score": "0",
"body": "Thanks for the great suggestion Royal Bg.\nMay I ask, what sort of limitation for login attempts you suggest? Would a (clear) captcha login be enough to make sure that no bots hammer the login form, or do you recommend something else? Thanks again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T21:13:47.687",
"Id": "63454",
"Score": "0",
"body": "You can use database. Log the attempts there. If for certain session there are more than X attempts - add in a blacklist table and ban for Y hours."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T21:28:05.560",
"Id": "63456",
"Score": "0",
"body": "Do you maybe have a source for me, where I can check up and learn this technique? I get the basic Idea, I am just not that proficient with handling sessions (and as you mentioned \"attempts for one certain session\") yet. Thank you again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T21:58:56.617",
"Id": "63457",
"Score": "0",
"body": "session_id() is enough. You can insert everytime an user tries to login the session_id. Once there are 5 failed logins with th e same session_id - ban the user. You can change session_id() with IP for example. I added some code"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T23:35:14.477",
"Id": "63461",
"Score": "0",
"body": "Thanks a lot for the explanation and the code Royal. This is a great help. I am going to translate your example into my pages tomorrow."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T19:55:22.017",
"Id": "38131",
"ParentId": "38129",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38131",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T19:46:56.827",
"Id": "38129",
"Score": "4",
"Tags": [
"javascript",
"php",
"security",
"session"
],
"Title": "Possible improvements on admin login area?"
}
|
38129
|
<p>How can I reduce the amount of repetitive code in my Android app? A lot of the code seems to be doing the same thing twice. I think that there is a more compact way to do this. </p>
<p>What are some ways that I can reduce lines of code in this program?<br>
Is there a better way that I could write this program? I think that I am taking more steps than necessary. </p>
<p>The code is for <a href="https://play.google.com/store/apps/details?id=com.kerseykyle.easyhash" rel="nofollow">this app</a>.</p>
<pre><code>package com.kerseykyle.easyhash;
import java.security.MessageDigest;
import android.os.Build;
import android.os.Bundle;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Share();
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("text/plain".equals(type)) {
handleSendText(intent); // Handle text being sent
}
}
EditText myTextBox = (EditText) findViewById(R.id.input);
myTextBox.setSingleLine(true);
myTextBox.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onTextChanged(CharSequence s, int start, int before,
int count) {
String md5hash = CreateHash(s.toString(), "MD5");
TextView md5 = (TextView) findViewById(R.id.md5);
md5.setText(md5hash);
md5.setTextIsSelectable(true);
String sha1hash = CreateHash(s.toString(), "SHA-1");
TextView sha1 = (TextView) findViewById(R.id.sha1);
sha1.setText(sha1hash);
sha1.setTextIsSelectable(true);
String sha256hash = CreateHash(s.toString(), "SHA-256");
TextView sha256 = (TextView) findViewById(R.id.sha256);
sha256.setText(sha256hash);
sha256.setTextIsSelectable(true);
String sha512hash = CreateHash(s.toString(), "SHA-512");
TextView sha512 = (TextView) findViewById(R.id.sha512);
sha512.setText(sha512hash);
sha512.setTextIsSelectable(true);
}
});
}
public static String CreateHash(String data, String function) {
try {
MessageDigest digest = MessageDigest.getInstance(function);
byte[] hash = digest.digest(((String) data).getBytes("UTF-8"));
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if (hex.length() == 1)
hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public void Share() {
TextView md5 = (TextView) findViewById(R.id.md5);
md5.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText myTextBox = (EditText) findViewById(R.id.input);
String md5hash = CreateHash(myTextBox.getText().toString(),
"MD5");
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, md5hash);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
});
TextView sha1 = (TextView) findViewById(R.id.sha1);
sha1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText myTextBox = (EditText) findViewById(R.id.input);
String sha1hash = CreateHash(myTextBox.getText().toString(),
"SHA-1");
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, sha1hash);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
});
TextView sha256 = (TextView) findViewById(R.id.sha256);
sha256.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText myTextBox = (EditText) findViewById(R.id.input);
String sha256hash = CreateHash(myTextBox.getText().toString(),
"SHA-256");
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, sha256hash);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
});
TextView sha512 = (TextView) findViewById(R.id.sha512);
sha512.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText myTextBox = (EditText) findViewById(R.id.input);
String sha512hash = CreateHash(myTextBox.getText().toString(),
"SHA-512");
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, sha512hash);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
});
{
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
void handleSendText(Intent intent) {
String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
if (sharedText != null) {
EditText input = (EditText) findViewById(R.id.input);
input.setText(sharedText);
String md5hash = CreateHash(sharedText, "MD5");
TextView md5 = (TextView) findViewById(R.id.md5);
md5.setText(md5hash);
md5.setTextIsSelectable(true);
String sha1hash = CreateHash(sharedText, "SHA-1");
TextView sha1 = (TextView) findViewById(R.id.sha1);
sha1.setText(sha1hash);
sha1.setTextIsSelectable(true);
String sha256hash = CreateHash(sharedText, "SHA-256");
TextView sha256 = (TextView) findViewById(R.id.sha256);
sha256.setText(sha256hash);
sha256.setTextIsSelectable(true);
String sha512hash = CreateHash(sharedText, "SHA-512");
TextView sha512 = (TextView) findViewById(R.id.sha512);
sha512.setText(sha512hash);
sha512.setTextIsSelectable(true);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T07:51:08.587",
"Id": "63474",
"Score": "1",
"body": "You should remove `// TODO Auto-generated method stub` as soon as you put any code in the method. It's just there to help you to find the method."
}
] |
[
{
"body": "<p>This type of problem is conveniently solved with a <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow noreferrer\">Strategy Pattern</a>. But, first things first:</p>\n\n<ul>\n<li>you should search for efficient ways to convert bytes to hexadecimal-string values. This <a href=\"https://stackoverflow.com/questions/9655181/convert-from-byte-array-to-hex-string-in-java\">is a great solution I like</a>....</li>\n<li>Unless you have no choice (you are using Patterns/Matchers) you should always use <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html\" rel=\"nofollow noreferrer\">StringBuilder</a> instead of <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html\" rel=\"nofollow noreferrer\">StringBuffer</a></li>\n<li>The method <code>CreateHash</code> should not have a capital-letter to start with, it should rather be <code>createHash</code></li>\n</ul>\n\n<p>As for the Strategy Pattern.... In this case, you can create a class that listens for the text change, and updates the signature in the linked TextView. The same class listens for on-click on the TextView too. The class could have the signature</p>\n\n<pre><code>public abstract class HashDigestDisplay implements TextWatcher, OnClickListener {\n private final TextView view;\n private final MessageDigest digest;\n\n public HashDigestDisplay (TextView target, String digestName) throws NoSuchAlgorithmException {\n this.view = target;\n this.digest = MessageDigest.getInstance(digestName);\n this.view.setOnClickListener(this);\n }\n\n public void afterTextChanged(Editable s) {\n }\n\n public void beforeTextChanged(CharSequence s, int start, int count,\n int after) {\n }\n\n private String myDigest(String input) {\n digest.reset(); \n byte[] hash = digest.digest(input.getBytes(\"UTF-8\"));\n return bytesToHex(hash);\n }\n\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n public void onTextChanged(CharSequence s, int start, int before, int count) {\n view.setText(myDigest(s.toString()));\n view.setTextIsSelectable(true);\n }\n\n @Override\n public void onClick(View v) {\n // TODO Auto-generated method stub\n EditText myTextBox = (EditText) findViewById(R.id.input);\n String hash = myDigest(myTextBox.getText().toString());\n Intent sendIntent = new Intent();\n sendIntent.setAction(Intent.ACTION_SEND);\n sendIntent.putExtra(Intent.EXTRA_TEXT, hash);\n sendIntent.setType(\"text/plain\");\n startActivity(sendIntent);\n\n }\n}\n</code></pre>\n\n<p>You can see the pattern that is emerging above. Obviously there are issues in the onClick method, but this is from copy/pasting your code.</p>\n\n<p>Now, what you do in your <code>onCreate()</code> setup method is simply:</p>\n\n<pre><code>myTextBox.addTextChangedListener(\n new HashDigestDisplay((TextView) findViewById(R.id.md5), \"MD5\"));\nmyTextBox.addTextChangedListener(\n new HashDigestDisplay((TextView) findViewById(R.id.sha1), \"SHA-1\"));\n....\n</code></pre>\n\n<p>After that, the system should be self-managing.</p>\n\n<p>You only have one copy of the code, and the only things different about it are the name of the Digest and the target of the TextView.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T20:50:33.590",
"Id": "38137",
"ParentId": "38132",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T19:55:58.783",
"Id": "38132",
"Score": "4",
"Tags": [
"java",
"android",
"cryptography"
],
"Title": "Reducing repetitive Android code"
}
|
38132
|
<p>Drupal questions should involve code review as per the <a href="https://codereview.stackexchange.com/help/on-topic">Help Center</a>, otherwise they should be posted on <a href="https://drupal.stackexchange.com/">Drupal Answers SE</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T20:48:16.077",
"Id": "38135",
"Score": "0",
"Tags": null,
"Title": null
}
|
38135
|
Drupal is an open source CMS framework written in PHP.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T20:48:16.077",
"Id": "38136",
"Score": "0",
"Tags": null,
"Title": null
}
|
38136
|
<p>Looking for code review, suggestions for improvement, best practices etc.</p>
<p>The problem definiton is</p>
<blockquote>
<p><strong>Jump Game</strong> </p>
<p>Given an array start from the first element and reach the last by jumping. The jump length can be at most the value at the
current position in the array. Optimum result is when u reach the goal
in minimum number of jumps. </p>
<p>For example </p>
<p>Given array <code>A</code> = {2,3,1,1,4} </p>
<p>possible ways to reach the end (index list) </p>
<p>i) 0,2,3,4 (jump 2 to index 2, then jump 1 to index 3 then 1 to index
4) </p>
<p>ii) 0,1,4 (jump 1 to index 1, then jump 3 to index 4) </p>
<p><strong>Since second solution has only 2 jumps it is the optimum result</strong>.</p>
</blockquote>
<p>Original post can be found at <a href="http://www.careercup.com/question?id=10130965" rel="nofollow">CarrerCup</a>.</p>
<pre><code>/**
* http://www.careercup.com/question?id=10130965
*
* Complexity: O(n2)
*/
public final class JumpGame {
private JumpGame() {}
public static Collection<Integer> checkAnswer (int[] a) {
int[] jumpLength = new int[a.length];
int[] prevIndex = new int[a.length];
for (int i = 1; i < a.length; i++) {
int min = Integer.MAX_VALUE;
for (int j = 0; j < i; j++) {
int diff = i - j; // calculate differences in array indexes
// if jump is possible && if this the shortest jump from the start
if ((a[j] >= diff) && (jumpLength[j] < min)) {
min = jumpLength[j] + 1;
jumpLength[i] = min;
prevIndex[i] = j;
}
}
}
List<Integer> list = new ArrayList<Integer>();
int ctr = a.length - 1;
while (ctr > 0) {
list.add(ctr);
ctr = prevIndex[ctr];
}
list.add(0);
Collections.reverse(list);
return Collections.unmodifiableCollection(list);
}
public static void main(String[] args) {
int[] a1 = {2,3,1,1,4};
System.out.print("Expected: 0:1:4, Actual: ");
for (Integer i : checkAnswer (a1)) {
System.out.print(i + ":");
}
System.out.println();
int[] a2 = {3, 1, 10, 1, 4};
System.out.print("Expected: 0:3:4, Actual: ");
for (Integer i : checkAnswer (a2)) {
System.out.print(i + ":");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T15:39:08.227",
"Id": "63628",
"Score": "1",
"body": "This is a off-topic, but I saw that you are not accepting a lot of answers to your questions. I answered the question nevertheless. However, please note that this is still a beta community where its life and death depends on the reputation growth of its users. If you find the time, please go through your old questions and accept answers to those questions that you feel are answered sufficiently. This will also increase the chance of your questions being answered in the future, such that you have something of marking answers, as well. However, do not feel presured to accept answers either."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T20:03:54.633",
"Id": "63653",
"Score": "0",
"body": "`This is a off-topic, but I saw that you are not accepting a lot of answers to your questions.` - I apologize for this, however, I do accept answers once I review them completely. It is completely on my mind, and sooner or later all answers would be accepted. Thanks for patience, I am aware its on my plate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T22:14:47.403",
"Id": "63660",
"Score": "0",
"body": "Of course, I just wanted to make sure you knew. Thank you!"
}
] |
[
{
"body": "<p><strong>Coding style</strong></p>\n\n<p>Anytime when programming, but especially when you implement an algorithm, choose variable names that are a little more verbose. When you come back to your code after some time and you want to apply some changes to your implementation, you will at first only see a blend of some <code>i</code> and <code>j</code> which are meaningless names you probably have used in other algorithms, as well. Therefore, your first question will be: What did these variables mean again in this particular context? And other readers - like me - will ask themself the same question. </p>\n\n<p>Rather use speaking names such as for example <code>jumpBaseIndex</code> for <code>i</code>. (You might want to find an even better name, this is just me brain storming. I am neither a fan of abbreviations, but this is something you could argue about. However, do not forget: <a href=\"http://hingedjournal.wordpress.com/2013/05/08/code-is-poetry-but-poetry-is-not-code/\" rel=\"nofollow\">Code is poetry</a>.</p>\n\n<p><strong>Object-oriented design</strong></p>\n\n<p>At some point, you might want to extend your program (you never know) and then it is a good thing to apply object-orientation instead of offering a bunch of static methods. Do not worry about efficiency. The JVM will optimize the object-allocation away if your code becomes time-critical. Why not offer an API like that:</p>\n\n<pre><code>public final class JumpGame {\n\n private final int[] jump;\n\n public JumpGame(int[] jump) {\n this.jump = jump;\n }\n\n public List<Integer> checkAnswer(int[] a) {\n // implementation comes here\n }\n</code></pre>\n\n<p>This also allows you to add extensions such as for example an implementation that validates your input value.</p>\n\n<p><strong>Return type</strong></p>\n\n<p>You are creating a result with a <code>List</code> with a particular order but you are returning a <code>Collection</code> instead. A <code>Collection</code> does not have an explicit ordering since it could also be represented by a <code>Set</code>. Your result however requires such an ordering. Since you are as a matter of fact returning a <code>List</code>, this order is preserved but it is not communicated to your API's user.</p>\n\n<p><strong>Return value immutability</strong></p>\n\n<p>As long as you are not caching results, I do not see a point of returning an immutable <code>List</code> (see above) as a result. When you return the <code>List</code> you give up <em>object ownership</em> to the method's caller which will be the only code entity making use of this object. It should be up to this entity to decide on the result's immutability. In general, immutable collections are poorly implemented in Java since their immutability is not reflected by the collection's type. This might suprise the user of your object. </p>\n\n<p>However, if you added caching to your solution (which you can since you chose an object-oriented aproach, see above), you should indeed wrap the list by calling <code>Collections#unmodifiableList(List)</code> in order to allow handing this object over to several callers. However, you must make this explicit in your method's javadoc.</p>\n\n<p><strong>Used <code>List</code> implementation</strong></p>\n\n<p>I would recommend you to use a <code>LinkedList</code> instead of an <code>ArrayList</code> to record the result. You only append to the end of that list but you never read a value from it while computing your result. At the same time, you do not know the size of the final result. If you want to further process the result and therefore require an <code>ArrayList</code>, you should at least give an estimate for the size of the array such as its upper bound of <code>a.length</code>. (Concerning <code>a</code>, rather find a better name, see above.)</p>\n\n<p><strong>Use shorter methods</strong></p>\n\n<p>Using shorter methods allows you to segment your code into logical units. This makes your code better readable. Your <em>core</em> method could look something like:</p>\n\n<pre><code>public static List<Integer> checkAnswer (int[] jump) {\n return asJumpTargetList(computePreviousIndex(jump));\n}\n\nprivate static int[] computePreviousIndex(int[] jump) {\n // first code segment comes here\n}\n\nprivate static List<Integer> asJumpTargetList(int[] previousIndex) {\n // second code segment comes here\n}\n</code></pre>\n\n<p>As a good indicator, check if you use a lot of empty lines for grouping your code. If this is true, you should probably have used different methods instead and compose calls to these methods to get your result and it is time for some refactoring.</p>\n\n<p><strong>Algorithm efficiency</strong></p>\n\n<p>Your problem can be solved quite easily in linear time (<code>O(n)</code>). The idea behind this algorithm is the following:</p>\n\n<p>From each <code>index</code>, you can reach <code>allowedJumps[index]</code> fields. It is best to jump as far as possible. However, if you cannot reach the <code>finalIndex</code> in a single jump, a short jump can be advantegous if it allows you to jump further in the next round than jumping to a higher index. This is true (if and only if)</p>\n\n<pre><code>allowedJumps[index_a] > allowedJumps[index_b] + (index_b - index_a)\n</code></pre>\n\n<p>where <code>index_b > index_a</code>. This can only be true if the optimal target <code>index_c</code> after jumping to <code>index_a</code> holds <code>index_c</code> > <code>index_b</code> for all possible values of <code>index_b</code>. Therefore, any possible jump target is considered at most once what yields a complexity of <code>O(n)</code>. I'll spare you a mathematical proof which is however quite trivial and follows the same idea.</p>\n\n<p>This is my suggestion for an efficient (<code>O(n)</code>) implementation where I added some console output instead of comments in order to allow you a better understanding of the computation.</p>\n\n<pre><code>import java.util.List;\nimport java.util.LinkedList;\n\npublic class JumpGame {\n\n public static void main(String[] args) { \n JumpGame firstJumpGame = new JumpGame(new int[] {2, 3, 1, 1, 4});\n System.out.println(firstJumpGame.findShortestPath());\n\n System.out.println();\n\n JumpGame secondJumpGame = new JumpGame(new int[] {3, 1, 10, 1, 4});\n System.out.println(secondJumpGame.findShortestPath());\n\n System.out.println();\n\n // Check for special cases:\n\n JumpGame thirdJumpGame = new JumpGame(new int[] {1, 1});\n System.out.println(thirdJumpGame.findShortestPath());\n\n System.out.println();\n\n JumpGame forthJumpGame = new JumpGame(new int[] {1});\n System.out.println(forthJumpGame.findShortestPath());\n }\n\n private final int[] jump;\n\n public JumpGame(int[] jump) {\n this.jump = jump; \n }\n\n public List<Integer> findShortestPath() {\n List<Integer> result = new LinkedList<Integer>();\n result.add(0);\n int current = 0, nextRelevantTarget = 1;\n System.out.println(\"I need to jump my way through indices 0 to \" \n + (jump.length - 1));\n while(current + jump[current] < jump.length - 1) {\n System.out.println(\"I am at \" + current + \" and could jump up to \" \n + (current + jump[current]));\n int currentMaximumReach = 0, currentBestTarget = 0;\n for(int jumpTarget = nextRelevantTarget; \n jumpTarget <= current + jump[current]; jumpTarget++) {\n int targetMaximumReach = Math.min(jump.length - 1, jumpTarget + jump[jumpTarget]);\n currentMaximumReach = Math.max(currentMaximumReach, targetMaximumReach);\n System.out.println(\"When jumping to \" + jumpTarget \n + \" I could jump up to \" + targetMaximumReach);\n if(targetMaximumReach == currentMaximumReach) {\n currentBestTarget = jumpTarget;\n System.out.println(\" -> This is my current best guess\");\n }\n }\n nextRelevantTarget = current + jump[current] + 1;\n current = currentBestTarget;\n result.add(current);\n System.out.println(\" => I am therefore jumping to \" + current);\n System.out.println(\" From there, I will at least jump to \" \n + nextRelevantTarget);\n }\n result.add(jump.length - 1);\n return result; \n }\n}\n</code></pre>\n\n<p>Note that I did not apply all suggested optimizations in order to keep the code concise.</p>\n\n<p><strong>Prefer unit tests over example code</strong></p>\n\n<p>Instead of demonstrating the capabilities of your code by a main method, rather add unit tests. Unit tests are more concice and allow you to express directly what you are expecting (also they can be run automatically. Here is an example using <a href=\"http://junit.org/\" rel=\"nofollow\">JUnit</a>:</p>\n\n<pre><code>@Test\npublic void testAlgorithmCorrectness() {\n assertEquals(Arrays.asList(0, 1, 4), checkAnswer(new int[] {2, 3, 1, 1, 4}));\n assertEquals(Arrays.asList(0, 3, 4), checkAnswer(new int[] {3, 1, 10, 1, 4}));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T15:33:04.170",
"Id": "38222",
"ParentId": "38142",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "38222",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T00:02:01.383",
"Id": "38142",
"Score": "3",
"Tags": [
"java",
"dynamic-programming"
],
"Title": "Jump game in Java"
}
|
38142
|
<p>Below is a generic code for parsing strings (read from file for example) and converting them to .java types, such as primitives (and their wrappers), java.io.File, Enum etc. There is also possible to register custom made <code>TypeParser</code>'s, for non-standard java types (Or provide a static factory method named: valueOf(String) in your class.).</p>
<ol>
<li>Is the usage of generics done in a correct way? </li>
<li>Is the registration mechanism of custom made <code>TypeParser</code>'s made with best practices way? </li>
<li>Is the usage of the Builder pattern done the right way? </li>
<li>Any other comments?</li>
</ol>
<hr>
<pre><code>package com.github.drapostolos.typeparser;
public interface TypeParser<T> {
T parse(String value);
}
</code></pre>
<hr>
<pre><code>package com.github.drapostolos.typeparser;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
class DefaultTypeParsers {
static List<TypeParser<?>> list() {
List<TypeParser<?>> result = new ArrayList<TypeParser<?>>();
for(Class<?> c : DefaultTypeParsers.class.getDeclaredClasses()){
if(TypeParser.class.isAssignableFrom(c)){
TypeParser<?> instance;
try {
instance = (TypeParser<?>) c.newInstance();
result.add(instance);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
return result;
}
static class BooleanTypeParser implements TypeParser<Boolean> {
@Override
public Boolean parse(final String value0) {
String value = value0.trim().toLowerCase();
if(value.equals("true") || value.equals("1")){
return Boolean.TRUE;
} else if(value.equals("false") || value.equals("0")){
return Boolean.FALSE;
}
String message = "\"%s\" is not parsable to a Boolean.";
throw new IllegalArgumentException(String.format(message, value0));
}
}
static class CharacterTypeParser implements TypeParser<Character>{
@Override
public Character parse(String value) {
if(value.length() == 1){
return Character.valueOf(value.charAt(0));
}
String message = "\"%s\" must only contain a single character.";
throw new IllegalArgumentException(String.format(message, value));
}
}
static class ByteTypeParser implements TypeParser<Byte> {
@Override
public Byte parse(String value) {
return Byte.valueOf(value.trim());
}
}
static class IntegerTypeParser implements TypeParser<Integer>{
@Override
public Integer parse(String value) {
return Integer.valueOf(value.trim());
}
}
static class LongTypeParser implements TypeParser<Long>{
@Override
public Long parse(String value) {
return Long.valueOf(value.trim());
}
}
static class ShortTypeParser implements TypeParser<Short>{
@Override
public Short parse(String value) {
return Short.valueOf(value.trim());
}
}
static class FloatTypeParser implements TypeParser<Float>{
@Override
public Float parse(String value) {
return Float.valueOf(value);
}
}
static class DoubleTypeParser implements TypeParser<Double>{
@Override
public Double parse(String value) {
return Double.valueOf(value);
}
}
static class FileTypeParser implements TypeParser<File>{
@Override
public File parse(String value) {
return new File(value.trim());
}
}
static class StringTypeParser implements TypeParser<String>{
@Override
public String parse(String value) {
return value;
}
}
}
</code></pre>
<hr>
<pre><code>package com.github.drapostolos.typeparser;
import java.util.HashMap;
import java.util.Map;
public final class StringToTypeParserBuilder {
private final static Map<Class<?>, TypeParser<?>> defaultTypeParsers = new HashMap<Class<?>, TypeParser<?>>();
private final static Map<Class<?>, Class<?>> wrapperToPrimitiveMapper = new HashMap<Class<?>, Class<?>>();
private Map<Class<?>, TypeParser<?>> typeParsers;
static {
wrapperToPrimitiveMapper.put(Boolean.class, boolean.class);
wrapperToPrimitiveMapper.put(Byte.class, byte.class);
wrapperToPrimitiveMapper.put(Short.class, short.class);
wrapperToPrimitiveMapper.put(Character.class, char.class);
wrapperToPrimitiveMapper.put(Integer.class, int.class);
wrapperToPrimitiveMapper.put(Long.class, long.class);
wrapperToPrimitiveMapper.put(Float.class, float.class);
wrapperToPrimitiveMapper.put(Double.class, double.class);
for(TypeParser<?> typeParser : DefaultTypeParsers.list()){
Class<?> type = Util.extractTypeParameter(typeParser);
defaultTypeParsers.put(type, typeParser);
if(wrapperToPrimitiveMapper.containsKey(type)){
// add primitive version, example int.class, boolean.class etc.
defaultTypeParsers.put(wrapperToPrimitiveMapper.get(type), typeParser);
}
}
}
StringToTypeParserBuilder() {
// Initialize with the default typeParsers
typeParsers = new HashMap<Class<?>, TypeParser<?>>(defaultTypeParsers);
}
public StringToTypeParserBuilder unregisterTypeParser(Class<?> type){
if(type == null) {
throw new NullPointerException(Util.nullArgumentErrorMsg("type"));
}
typeParsers.remove(type);
return this;
}
public StringToTypeParserBuilder registerTypeParser(TypeParser<?> typeParser){
if(typeParser == null) {
throw new NullPointerException(Util.nullArgumentErrorMsg("typeParser"));
}
typeParsers.put(Util.extractTypeParameter(typeParser), typeParser);
return this;
}
public <T> StringToTypeParserBuilder registerTypeParser(Class<T> type, TypeParser<? extends T> typeParser){
if(typeParser == null) {
throw new NullPointerException(Util.nullArgumentErrorMsg("typeParser"));
}
if(type == null) {
throw new NullPointerException(Util.nullArgumentErrorMsg("type"));
}
typeParsers.put(type, typeParser);
return this;
}
public StringToTypeParser build(){
return new StringToTypeParser(new HashMap<Class<?>, TypeParser<?>>(typeParsers));
}
}
</code></pre>
<hr>
<pre><code>package com.github.drapostolos.typeparser;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
public final class StringToTypeParser {
private static final StringToTypeParser defaultTypeParser = newBuilder().build();
private final Map<Class<?>, TypeParser<?>> typeParsers;
public static StringToTypeParserBuilder newBuilder() {
return new StringToTypeParserBuilder();
}
public static <T> T parse(String value, Class<T> type){
return defaultTypeParser.parseType(value, type);
}
StringToTypeParser(HashMap<Class<?>, TypeParser<?>> typeParsers) {
this.typeParsers = typeParsers;
}
public <T> T parseType(String value, Class<T> type) {
if (value == null) {
throw new NullPointerException(Util.nullArgumentErrorMsg("value"));
}
if (type == null) {
throw new NullPointerException(Util.nullArgumentErrorMsg("type"));
}
// convert "null" string to null type.
if (value.trim().equalsIgnoreCase("null")) {
if (type.isPrimitive()) {
String message = "'%s' primitive can not be set to null.";
throw new IllegalArgumentException(String.format(message, type.getName()));
}
return null;
}
Object result = null;
if (typeParsers.containsKey(type)) {
result = callTypeParser(value, type);
} else if ((result = callFactoryMethodIfExisting("valueOf", value, type)) != null) {
//
} else if ((result = callFactoryMethodIfExisting("of", value, type)) != null) {
//
} else {
String message = "There is no registered 'TypeParser' for that type, or that "
+ "type does not contain one of the following static factory methods: "
+ "'%s.valueOf(String)', or '%s.of(String)'.";
message = String.format(message, type.getSimpleName(), type.getSimpleName());
message = canNotParseErrorMsg(value, type, message);
throw new IllegalArgumentException(message);
}
/*
* This cast is correct, since all above checks ensures we're casting to
* the right type.
*/
@SuppressWarnings("unchecked")
T temp = (T) result;
return temp;
}
private Object callTypeParser(String value, Class<?> type) {
try {
return typeParsers.get(type).parse(value);
} catch (NumberFormatException e) {
String message = canNotParseErrorMsg(value, type, numberFormatErrorMsg(e));
throw new IllegalArgumentException(message, e);
} catch (RuntimeException e) {
throw new IllegalArgumentException(canNotParseErrorMsg(value, type, e.getMessage()), e);
}
}
private static String numberFormatErrorMsg(NumberFormatException e) {
return String.format("Number format exception %s.", e.getMessage());
}
private static String canNotParseErrorMsg(String value, Class<?> type, String message) {
return String.format("Can not parse \"%s\" to type '%s' due to: %s", value, type.getName(), message);
}
private static Object callFactoryMethodIfExisting(String methodName, String value, Class<?> type) {
Method m;
try {
m = type.getDeclaredMethod(methodName, String.class);
if (!Modifier.isStatic(m.getModifiers())) {
// Static factory method does not exists, return null
return null;
}
} catch (Exception e) {
// Static factory method does not exists, return null
return null;
}
try {
if(type.isEnum()){
return m.invoke(null, value.trim());
} else {
return m.invoke(null, value);
}
} catch (InvocationTargetException e) {
throw new IllegalArgumentException(makeErrorMsg(methodName, value, type), e.getCause());
} catch (Throwable t) {
throw new IllegalArgumentException(makeErrorMsg(methodName, value, type), t);
}
}
private static String makeErrorMsg(String methodName, String value, Class<?> type) {
String methodSignature = String.format("%s.%s('%s')", type.getName(), methodName, value);
String message = " Exception thrown in static factory method '%s'. See underlying "
+ "exception for additional information.";
return canNotParseErrorMsg(value, type, String.format(message, methodSignature));
}
}
</code></pre>
<hr>
<pre><code>package com.github.drapostolos.typeparser;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
class Util {
private Util() { /* Not meant for instantiation */}
static String nullArgumentErrorMsg(String argName) {
return String.format("Argument named '%s' is illegally set to null!", argName);
}
static Class<?> extractTypeParameter(TypeParser<?> typeParser) {
return extractTypeParameter(typeParser.getClass(), typeParser);
}
/*
* Pass the original TypeParser as well, to be able to print
* it in error message.
*/
private static Class<?> extractTypeParameter(Class<?> c, TypeParser<?> typeParser) {
if(c == null){
String message = "Can not find parametirized type in %s !?!?!? Must be a bug somewhere...";
throw new IllegalArgumentException(String.format(message, typeParser));
}
for (Type t : c.getGenericInterfaces()){
if(t instanceof ParameterizedType){
ParameterizedType type = (ParameterizedType) t;
if(TypeParser.class.equals(type.getRawType())){
return (Class<?>) type.getActualTypeArguments()[0];
}
}
}
return extractTypeParameter(c.getSuperclass(), typeParser);
}
}
</code></pre>
<p>I should also give some usage examples. Use the below static method for simple usage (only supports the default java types):</p>
<pre><code>Integer i1 = StringToTypeParser.parse(" 1", Integer.class);
int i2 = StringToTypeParser.parse("2", int.class);
float f = StringToTypeParser.parse("2.2", float.class);
Number n = StringToTypeParser.parse("2.2", float.class);
MyEnum a = StringToTypeParser.parse("BBB", MyEnum.class);
File file = StringToTypeParser.parse("/path/to", File.class);
Boolean b1 = StringToTypeParser.parse("true", Boolean.class);
boolean b2 = StringToTypeParser.parse("0", Boolean.class);
</code></pre>
<p>where</p>
<pre><code>public enum MyEnum{AAA, BBB};
</code></pre>
<p>Or if you want to register your own TypeParsers, build your own StringToTypeParser instance (which by default supports the java types) as follow:</p>
<pre><code>StringToTypeParser parser = StringToTypeParser.newBuilder()
.registerTypeParser(new CarTypeParser())
.registerTypeParser(int.class, new MySpecialIntTypeParser())
.build();
Car volvo = parser.parseType("volvo", Car.class);
</code></pre>
<hr>
<p>Edit: after comments from review:</p>
<p>Thanks for the great comments in the answer! Below are the final outcome of the changes made. The Util.java class is now removed, so is also all the reflection code, which makes a much nicer/cleaner code.</p>
<hr>
<p>The TypeParser interface remains the same</p>
<pre><code>package com.github.drapostolos.typeparser;
public interface TypeParser<T> {
T parse(String value);
}
</code></pre>
<hr>
<p>Replaced the static inner classes with anonymous classes instead.</p>
<pre><code>package com.github.drapostolos.typeparser;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
class DefaultTypeParsers {
private DefaultTypeParsers() { new AssertionError("Not meant for instantiation"); }
private static final String BOOLEAN_ERROR_MESSAGE = "\"%s\" is not parsable to a Boolean.";
private static final String CHARACTER_ERROR_MESSAGE = "\"%s\" must only contain a single character.";
private static final Map<Class<?>, TypeParser<?>> DEFAULT_TYPE_PARSERS = new HashMap<Class<?>, TypeParser<?>>();
private static final Map<Class<?>, Class<?>> WRAPPER_TO_PRIMITIVE = new HashMap<Class<?>, Class<?>>();
static Map<Class<?>, TypeParser<?>> copy() {
return new HashMap<Class<?>, TypeParser<?>>(DEFAULT_TYPE_PARSERS);
}
static{
WRAPPER_TO_PRIMITIVE.put(Boolean.class, boolean.class);
WRAPPER_TO_PRIMITIVE.put(Byte.class, byte.class);
WRAPPER_TO_PRIMITIVE.put(Short.class, short.class);
WRAPPER_TO_PRIMITIVE.put(Character.class, char.class);
WRAPPER_TO_PRIMITIVE.put(Integer.class, int.class);
WRAPPER_TO_PRIMITIVE.put(Long.class, long.class);
WRAPPER_TO_PRIMITIVE.put(Float.class, float.class);
WRAPPER_TO_PRIMITIVE.put(Double.class, double.class);
}
private static <T> void put(Class<T> type, TypeParser<? extends T> typeParser){
DEFAULT_TYPE_PARSERS.put(type, typeParser);
if(WRAPPER_TO_PRIMITIVE.containsKey(type)){
// add primitive targetType if existing, example int.class, boolean.class etc.
Class<?> primitiveType = WRAPPER_TO_PRIMITIVE.get(type);
DEFAULT_TYPE_PARSERS.put(primitiveType, typeParser);
}
}
static{
put(Boolean.class, new TypeParser<Boolean>() {
@Override
public Boolean parse(final String value0) {
String value = value0.trim().toLowerCase();
if(value.equals("true")){
return Boolean.TRUE;
} else if(value.equals("false")){
return Boolean.FALSE;
}
throw new IllegalArgumentException(String.format(BOOLEAN_ERROR_MESSAGE, value0));
}
});
put(Character.class, new TypeParser<Character>() {
@Override
public Character parse(String value) {
if(value.length() == 1){
return Character.valueOf(value.charAt(0));
}
throw new IllegalArgumentException(String.format(CHARACTER_ERROR_MESSAGE, value));
}
});
put(Byte.class, new TypeParser<Byte>() {
@Override
public Byte parse(String value) {
return Byte.valueOf(value.trim());
}
});
put(Integer.class, new TypeParser<Integer>() {
@Override
public Integer parse(String value) {
return Integer.valueOf(value.trim());
}
});
put(Long.class, new TypeParser<Long>() {
@Override
public Long parse(String value) {
return Long.valueOf(value.trim());
}
});
put(Short.class, new TypeParser<Short>() {
@Override
public Short parse(String value) {
return Short.valueOf(value.trim());
}
});
put(Float.class, new TypeParser<Float>() {
@Override
public Float parse(String value) {
return Float.valueOf(value);
}
});
put(Double.class, new TypeParser<Double>() {
@Override
public Double parse(String value) {
return Double.valueOf(value);
}
});
put(File.class, new TypeParser<File>() {
@Override
public File parse(String value) {
return new File(value.trim());
}
});
put(String.class, new TypeParser<String>() {
@Override
public String parse(String value) {
return value;
}
});
}
}
</code></pre>
<hr>
<p>Removed the static StringToTypeParser.parse(...) method for simplicity.</p>
<pre><code>package com.github.drapostolos.typeparser;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
public final class StringToTypeParser {
private static final Object STATIC_METHOD = null;
private final Map<Class<?>, TypeParser<?>> typeParsers;
public static StringToTypeParserBuilder newBuilder() {
return new StringToTypeParserBuilder();
}
StringToTypeParser(Map<Class<?>, TypeParser<?>> typeParsers) {
this.typeParsers = Collections.unmodifiableMap(new HashMap<Class<?>, TypeParser<?>>(typeParsers));
}
public <T> T parse(String value, Class<T> type) {
if (value == null) {
throw new NullPointerException(nullArgumentErrorMsg("value"));
}
if (type == null) {
throw new NullPointerException(nullArgumentErrorMsg("type"));
}
// convert "null" string to null type.
if (value.trim().equalsIgnoreCase("null")) {
if (type.isPrimitive()) {
String message = "'%s' primitive can not be set to null.";
throw new IllegalArgumentException(String.format(message, type.getName()));
}
return null;
}
Object result = null;
if (typeParsers.containsKey(type)) {
result = callTypeParser(value, type);
} else if ((result = callFactoryMethodIfExisting("valueOf", value, type)) != null) {
//
} else if ((result = callFactoryMethodIfExisting("of", value, type)) != null) {
//
} else {
String message = "There is no registered 'TypeParser' for that type, or that "
+ "type does not contain one of the following static factory methods: "
+ "'%s.valueOf(String)', or '%s.of(String)'.";
message = String.format(message, type.getSimpleName(), type.getSimpleName());
message = canNotParseErrorMsg(value, type, message);
throw new IllegalArgumentException(message);
}
/*
* This cast is correct, since all above checks ensures we're casting to
* the right type.
*/
@SuppressWarnings("unchecked")
T temp = (T) result;
return temp;
}
/**
* This method is static because it is also called from {@link StringToTypeParserBuilder}.
*/
static String nullArgumentErrorMsg(String argName) {
return String.format("Argument named '%s' is illegally set to null!", argName);
}
private Object callTypeParser(String value, Class<?> type) {
try {
return typeParsers.get(type).parse(value);
} catch (NumberFormatException e) {
String message = canNotParseErrorMsg(value, type, numberFormatErrorMsg(e));
throw new IllegalArgumentException(message, e);
} catch (RuntimeException e) {
throw new IllegalArgumentException(canNotParseErrorMsg(value, type, e.getMessage()), e);
}
}
private String numberFormatErrorMsg(NumberFormatException e) {
return String.format("Number format exception %s.", e.getMessage());
}
private String canNotParseErrorMsg(String value, Class<?> type, String message) {
return String.format("Can not parse \"%s\" to type '%s' due to: %s", value, type.getName(), message);
}
private Object callFactoryMethodIfExisting(String methodName, String value, Class<?> type) {
Method m;
try {
m = type.getDeclaredMethod(methodName, String.class);
m.setAccessible(true);
if (!Modifier.isStatic(m.getModifiers())) {
// Static factory method does not exists, return null
return null;
}
} catch (Exception e) {
// Static factory method does not exists, return null
return null;
}
try {
if(type.isEnum()){
value = value.trim();
}
return m.invoke(STATIC_METHOD, value);
} catch (InvocationTargetException e) {
// filter out the InvocationTargetException stacktrace/message.
throw new IllegalArgumentException(makeErrorMsg(methodName, value, type), e.getCause());
} catch (Throwable t) {
throw new IllegalArgumentException(makeErrorMsg(methodName, value, type), t);
}
}
private String makeErrorMsg(String methodName, String value, Class<?> type) {
String methodSignature = String.format("%s.%s('%s')", type.getName(), methodName, value);
String message = " Exception thrown in static factory method '%s'. See underlying "
+ "exception for additional information.";
return canNotParseErrorMsg(value, type, String.format(message, methodSignature));
}
}
</code></pre>
<hr>
<p>Removed registerTypeParser(TypeParser) method, which allowed for removing reflection code.</p>
<pre><code>package com.github.drapostolos.typeparser;
import java.util.Map;
public final class StringToTypeParserBuilder {
private Map<Class<?>, TypeParser<?>> typeParsers;
StringToTypeParserBuilder() {
// Initialize with the default typeParsers
typeParsers = DefaultTypeParsers.copy();
}
public StringToTypeParserBuilder unregisterTypeParser(Class<?> type){
if(type == null) {
throw new NullPointerException(StringToTypeParser.nullArgumentErrorMsg("type"));
}
typeParsers.remove(type);
return this;
}
public <T> StringToTypeParserBuilder registerTypeParser(Class<T> type, TypeParser<? extends T> typeParser){
if(typeParser == null) {
throw new NullPointerException(StringToTypeParser.nullArgumentErrorMsg("typeParser"));
}
if(type == null) {
throw new NullPointerException(StringToTypeParser.nullArgumentErrorMsg("type"));
}
typeParsers.put(type, typeParser);
return this;
}
public StringToTypeParser build(){
return new StringToTypeParser(typeParsers);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T00:32:42.547",
"Id": "64497",
"Score": "1",
"body": "fyi. Have a look at this http://jodd.org/doc/typeconverter.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T22:53:10.163",
"Id": "64796",
"Score": "0",
"body": "Thanks! Just had a quick look a the jodd type-converter and it seems to not parse a string to a type, but just convert from one type to another (example: List<Object> to int[])"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T23:04:32.690",
"Id": "64798",
"Score": "0",
"body": "[too long time passed for me to edit above comment]\nThanks, I did not know about the jodd library! Just had a quick look at jodd type-converter and it seems to be able to do the same as the code above :)\n\nHowever, I'm currently updating the type-parser library to be able to parse a string to Parameterized types (example: parse string \"1,2,3,4\" to a List<Integer> [1,2,3,4]). Jodd type-converter does not seem to be able to do that. But I guess this update will be a separate review :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-16T21:27:16.420",
"Id": "77290",
"Score": "0",
"body": "Jodd type coverter knows to parse a string to a type. And you are right, it can parse `\"1,2,3,4\"` to e.g. `int[]` but not `List<Integer>` because of type erasure in java."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T22:28:31.177",
"Id": "77469",
"Score": "0",
"body": "Modified the type-parser library to handle generic types and made a new review. See http://codereview.stackexchange.com/questions/43823/library-for-parsing-strings-to-java-types-generic-types-and-collections-arrays"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T13:38:29.127",
"Id": "85440",
"Score": "1",
"body": "First version of the type-parser library is now available in maven central and github here: https://github.com/drapostolos/type-parser"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-05-31T11:14:51.073",
"Id": "312973",
"Score": "0",
"body": "com.github.drapostolos:type-parser:0.6.0 :)"
}
] |
[
{
"body": "<p>Overall, your code is very clean and looks good to me. However, I have some feedback, especially concering your use of reflection:</p>\n\n<ol>\n<li><p>In your <code>DefaultTypeParsers</code> class, you are enlisting all <code>TypeParser</code> implementations that are inner classes of your <code>DefaultTypeParsers</code> class via reflection. I would avoid that. You are both increasing the run time burden of your application (what is not too bad) and moving application (type) safety away from compile time to run time with this aproach. Also, you might introduce very subtle bugs when refactoring this code at some time in the future. I would rather list all <code>TypeParser</code> classes explicitly, even though your reflective solution is very elegant from an academic point of view.</p></li>\n<li><p>It is a good Java practice to use constants instead of local variables or magic values. Therefore, rather use something like</p>\n\n<pre><code>private static final String ERROR_MESSAGE = \"\\\"%s\\\" is not parsable to a Boolean.\";\n</code></pre>\n\n<p>instead of the local variable. This also allows the Java compiler to directly inline the statement and further improves the readability of your code. This advice applies to several segments of your code. Also, note that <code>static</code> variables are spelled in upper caps by Java convention.</p></li>\n<li><p>I feel like the trimming of input values should be up to the user and not some library magic. For example, you are trimming <code>Integer</code> values but not <code>Double</code> values. Why is that? Finally, the user should decide that. Maybe, you want to offer an interface for this purpose? You could for example offer some sort of</p>\n\n<pre><code>interface InputPreprocessor {\n String prepare(String input, Class<?> targetType);\n}\n</code></pre>\n\n<p>where a user could then easily implement a </p>\n\n<pre><code>class TrimmingInputPreprocessor implements InputPreprocessor {\n @Override\n public String prepare(String input, Class<?> targetType) {\n return input == null ? null : input.trim();\n }\n}\n</code></pre>\n\n<p>or anything that is required for a specific use case. Also, this would for example allow to replace <code>null</code> with some default value.</p></li>\n<li><p>I personally do not like libraries that use reflection for reading generic types. Especially if this is not known to the user. Your library will for example not be able to read the generic type of the following implementation:</p>\n\n<pre><code>abstract class MyAbstractTypeParser<T> implements TypeParser<T> {\n // some abstract implementation\n}\n\nclass MyTypeParser extends MyAbstractTypeParser<MyType> {\n // some actual implementation\n}\n</code></pre>\n\n<p>You will not read <code>MyType</code> since it is not stored with the implemented <code>TypeParser</code> interface but with the super class. Reading generic types is actually more tricky than it often seems and cannot always be done (when the used type is still generic). If you still feel the urge of going for this solution, use a library such as <a href=\"http://code.google.com/p/gentyref/\" rel=\"nofollow\">gentyref</a> that dedicates to such reflection access. You might also be interessted <a href=\"http://mydailyjava.blogspot.de/2013/06/advanced-java-generics-retreiving.html\" rel=\"nofollow\">in this summary I once wrote</a> on this aproach.\nAlternatively, I would rather add a method to <code>TypeParser</code> that returns the handled type:</p>\n\n<pre><code>public interface TypeParser<T> {\n T parse(String value);\n Class<T> getParsedType();\n}\n</code></pre>\n\n<p>This requires the interface implementor to name the type explicitly and will get rid of all trouble with the reflective soltion. (Also note that reflection is terrible to inline for your JVM if your code is executed a lot and the JVM wants to speed up its execution.)</p></li>\n<li><p>This is a minor issue but I do not think that the <code>BooleanTypeParser</code> should read <code>0</code> as <code>false</code> and <code>1</code> as <code>true</code> by default. This PHP-ish aproach can introduce subtle bugs.</p></li>\n<li><p>It might be a nice feature to allow for default values when a value cannot be parsed. Such as:</p>\n\n<pre><code>Integer i = StringToTypeParser.parse(\"foo\", Integer.class, 0);\n</code></pre>\n\n<p>This would encapsulate clean up logic and make user code more concise. I guess such a library would be mostly used for dealing with user input such that I feel this would be a common use case.</p></li>\n<li><p>I fear that <code>com.github.drapostolos</code> is not applying to the Java conventions for package naming since GitHub could (I guess the chance is close to zero) want to host a Java application bound to the domain<code>drapostolos.github.com</code> while you are only associated with <code>github.com/drapostolos</code> such that you do not (theoretically) <em>own</em> this package name.</p></li>\n<li><p>In my personal oppinion, I would recommend you to use immutability whereever possible. Therefore, wrap your <code>StringToTypeParser</code>'s map by <code>Collections#unmodifiableMap(Map)</code> what disallows reflective changes of this map.</p></li>\n<li><p><code>Util</code> is not a great name for a Java class. If I am searching for classes named <code>Utility</code> in one of our production projects, I find several classes by that name since in several of its many dependencies. I think the name is too generic and should be replaced by something more specific. Not for your own's sake but for those using your library such that they will get an impression what the class is a part of and can be used for only be knowing its name. You could name it <code>TypeParserUtility</code> or something.</p></li>\n<li><p>Why not move your <code>DefaultTypeParsers#list()</code> method to this utility? <code>DefaultTypeParsers</code> is dead weight and can be removed (also in order to make your class hierarchy leaner to the user). If you want to keep the class, make sure to declare a constructor that makes your intentions for this class explicit:</p>\n\n<pre><code>private DefaultTypeParsers() {\n throw new AssertionError(\"Do not instantiate\");\n}\n</code></pre>\n\n<p>This prohibits instanciation of this class (even by reflection).</p></li>\n</ol>\n\n<p>Other than that: good code.</p>\n\n<p>The builder pattern is applied by the book: with collections involved, I would keep the builder mutable and only make the <em>end product</em> immutable. Therefore, it's a good choice that you make a copy of the map when handing it over to the <code>TypeParser</code>. The registration mechanism is also fine. I would however add to the <code>TypeParser</code>'s javadoc (and thus to its implict contract) that <code>TypeParser</code>s should be immutable what would allow their concurrent use and reuse throghout several converters. (If you want that for your library.)</p>\n\n<p>Keep up the good work!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T15:20:25.020",
"Id": "63506",
"Score": "0",
"body": "THANK YOU for your constructive feedback! :) I'll make changes to the code. Should I re-edit the original post with the code changes, or post the code-changes in a new post? (Sorry, I'm new to codereview.stackexchange.com)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T15:48:17.453",
"Id": "63513",
"Score": "0",
"body": "Regarding 3) Java's [Double.valueOf(String)](http://docs.oracle.com/javase/6/docs/api/java/lang/Double.html#valueOf(java.lang.String)) and [Float.valueOf(String)](http://docs.oracle.com/javase/6/docs/api/java/lang/Float.html#valueOf(java.lang.String)) removes whitespaces by default see their javadocs. To make the StringToTypeParser API more consistent I added the trim() to the rest of the Number classes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T16:12:04.773",
"Id": "63521",
"Score": "0",
"body": "I have not been to active here either but I do not think that you are supposed to post your changes as it would make the postings hard to read for others. Glad that you found my answer helpful. Consider marking it as accepted if you feel like your question is answered."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T00:43:38.820",
"Id": "63591",
"Score": "0",
"body": "Edited the question and added final versison of the code."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T12:04:44.763",
"Id": "38167",
"ParentId": "38145",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "38167",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T01:35:50.443",
"Id": "38145",
"Score": "7",
"Tags": [
"java",
"parsing",
"serialization"
],
"Title": "Parse strings and convert the value to .java types"
}
|
38145
|
<p>The following code is my answer to a <a href="https://stackoverflow.com/questions/20745184/how-to-update-struct-item-in-binary-files/20794062#20794062">Stack Overflow question</a>:</p>
<pre><code>#include <string>
#include <vector>
#include <fstream>
#include <cstdio>
#include <cassert>
// #include <stdint.h> => DWORD
#ifndef int32_t
#define uint32_t DWORD
#define int32_t int
#endif
struct MapItem
{
std::string term;
std::vector<int32_t> pl;
// this function also emphasizes the way this objects are serialized to file; if something changes here,
// ReadNext & WriteNext must also be updated (unfortunate dependency)
size_t SizeWrittenToFile() const
{
return 2*sizeof(uint32_t)+term.length()+pl.size()*sizeof(int32_t);
}
};
bool ReadNext(std::istream& in, MapItem& item)
{
size_t size;
in.read(reinterpret_cast<char*>(&size), sizeof(uint32_t));
if (!in)
return false;
std::istreambuf_iterator<char> itIn(in);
std::string& out = item.term;
out.reserve(size);
out.clear(); // this is necessary if the string is not empty
// copy_n available in C++11
for (std::insert_iterator<std::string> itOut(out, out.begin()); in && (out.length() < size); itIn++, itOut++)
*itOut = *itIn;
assert(in);
if (!in)
return false;
in.read(reinterpret_cast<char*>(&size), sizeof(uint32_t));
if (!in)
return false;
std::vector<int32_t>& out2 = item.pl;
out2.resize(size); // reserve doesn't work here
in.read(reinterpret_cast<char*>(&out2[0]), size * sizeof(int32_t));
assert(in);
return true;
}
// a "header" should be added to mark complete data (to write "atomically")
bool WriteNext(std::ostream& out, const MapItem& item)
{
size_t size = item.term.length();
out.write(reinterpret_cast<const char*>(&size), sizeof(uint32_t));
if (!out)
return false;
out.write(item.term.c_str(), size);
if (!out)
return false;
size = item.pl.size();
out.write(reinterpret_cast<const char*>(&size), sizeof(uint32_t));
if (!out)
return false;
out.write(reinterpret_cast<const char*>(&item.pl[0]), size * sizeof(int32_t));
if (!out)
return false;
return true;
}
bool UpdateItem(std::ifstream& in, std::ofstream& out, const MapItem& item)
{
MapItem it;
bool result;
for (result = ReadNext(in, it); result && (it.term != item.term); result = ReadNext(in, it))
if (!WriteNext(out, it))
return false;
if (!result)
return false;
assert(it.term == item.term);
if (!WriteNext(out, item))
return false;
for (result = ReadNext(in, it); result; result = ReadNext(in, it))
if (!WriteNext(out, it))
return false;
return in.eof();
}
bool UpdateItem(const char* filename, const MapItem& item)
{
std::ifstream in(filename, std::ios_base::in | std::ios_base::binary);
assert(in);
std::string filename2(filename);
filename2 += ".tmp";
std::ofstream out(filename2.c_str(), std::ios_base::out | std::ios_base::binary);
assert(out);
bool result = UpdateItem(in, out, item);
in.close();
out.close();
int err = 0;
if (result)
{
err = remove(filename);
assert(!err && "remov_140");
result = !err;
}
if (!result)
{
err = remove(filename2.c_str());
assert(!err && "remov_147");
}
else
{
err = rename(filename2.c_str(), filename);
assert(!err && "renam_151");
result = !err;
}
return result;
}
</code></pre>
<p>Beside correctness, I'm concerned with two problems:</p>
<ol>
<li>performance when reading to string in <code>ReadNext</code>: "<code>in && (out.length() < size)</code>"
A better implementation would be capable of reading directly a block of data.</li>
<li>To update an item a second file is used. Is there a safe solution using only one file?</li>
</ol>
<p><strong>EDIT</strong> My interess goes beyond the initial Stack Overflow question as this is a (re)learning exercise of the C++ streams and I'll use it as a sample.
I also added the code <a href="https://github.com/landron/http---codereview.stackexchange.com-questions-38148-" rel="nofollow noreferrer">here</a>, with additional real tests, VS 2008, but it should be easily ported to other platforms.</p>
|
[] |
[
{
"body": "<p>I'm going to focus on readability rather than performance for this review.\nI will also (hopefully) avoid C++11 features since you're using VS2008.</p>\n\n<ol>\n<li><p>Change <code><assert.h></code> to <code><cassert></code>.<br>\nUse the C++ headers instead of the C headers.</p></li>\n<li><p>Rename <code>mapItem</code> to either <code>map_item</code> or <code>MapItem</code>.<br>\nThe former is favored in Unix/Linux circles while the latter is favored in\nWindows circles.</p></li>\n<li><p>Comment and explain the function <code>SizeWrittenToFile</code>.<br>\nSince you didn't explain the binary format, it's not clear why this returns \nwhat it does without looking at your <code>WriteNext</code> function.</p></li>\n<li><p>Depending on <code>sizeof (size_t)</code> can lead to incompatibilities for the binary\nfile format if this program is compiled on different machines or even\njust with different build settings. </p>\n\n<p>For example, let's say I have:</p>\n\n<p>Machine A -- Assume <code>sizeof (size_t)</code> returns 4 (Perhaps a 32-bit machine).<br>\nMachine B -- Assume <code>sizeof (size_t)</code> returns 8 (Perhaps a 64-bit machine). </p>\n\n<p>If I write a binary file on A and copy it over to B, B will not be able to\ncorrectly read or update the file.</p>\n\n<p>Having fixed width formats for the size fields would solve this problem.</p></li>\n<li><p>This is subjective, but I think exceptions would make your code a lot cleaner to read than returning error codes. </p></li>\n<li><p>See below.</p>\n\n<blockquote>\n <p>performance when reading to string in <code>ReadNext</code>: <code>in && (out.length() < size)</code><br>\n A better implementation would be capable of reading directly a block of data.</p>\n</blockquote>\n\n<p>I can't think of any standard way of getting around this.<br>\nA non-standard way would be to do:</p>\n\n<pre><code>out.resize (size) ; \nin.read (&out[0], size) ;\n</code></pre>\n\n<p>I don't recommend it, but it should work on many modern compilers.</p></li>\n<li><p>Because this is a binary file format, don't forget to use the \n<code>std::ios_base::binary</code> flag when opening files.</p>\n\n<p>I noticed you omitted that flag on your tests. </p></li>\n<li><p>See below.</p>\n\n<blockquote>\n <p>To update an item a second file is used. \n Is there a safe solution using only one file?</p>\n</blockquote>\n\n<p>I actually like your two-file approach.</p>\n\n<p>For a one-file approach, you would basically create a <code>std::vector <mapItem></code> \nand <code>ReadNext</code> the entire file into memory. \nYou would then modify whatever you want in memory and write everything back to the file\nafterwards. </p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T22:26:20.210",
"Id": "38375",
"ParentId": "38148",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T03:25:50.657",
"Id": "38148",
"Score": "6",
"Tags": [
"c++",
"file",
"stream"
],
"Title": "Updating a file through C++ streams"
}
|
38148
|
<p>I was playing around with Java Card and I try to do one of the examples.</p>
<p>P1 is what it has to do (e.g. decrypt, encrypt, etc) and P2 is to select which key to use in P1. Here is what the code looks like - well, half of it anyway, since I'm not really used to formatting in this site and it takes awhile to copy the code and make it pretty.</p>
<p>So my question here is, how can I simplify this nested switch? Or maybe I don't need to use nested switch at all?</p>
<pre><code>switch (buf[ISO7816.OFFSET_P1]){
case (byte) 0x01:
switch (buf[ISO7816.OFFSET_P2]){
case (byte) 0x01:
doSingleDES(apdu, DESKey1);
return;
case (byte) 0x02:
doSingleDES(apdu, DESKey2);
return;
case (byte) 0x03:
doSingleDES(apdu, DESKey3);
return;
case (byte) 0x04:
doSingleDES(apdu, DESKey3);
return;
default:
ISOException.throwIt(ISO7816.SW_WRONG_P1P2);
}return;
case (byte) 0x02:
switch (buf[ISO7816.OFFSET_P2]){
case (byte) 0x01:
doEncrypt(apdu, DESKey1);
return;
case (byte) 0x02:
doEncrypt(apdu, DESKey2);
return;
case (byte) 0x03:
doEncrypt(apdu, DESKey3);
return;
case (byte) 0x04:
doEncrypt(apdu, DESKey4);
return;
default:
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
}return;
default:
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T04:42:25.487",
"Id": "63464",
"Score": "0",
"body": "Since it looks like your code is working, I'm going to send you in the direction of the friendly folks at [codereview.se]."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T09:05:25.580",
"Id": "63476",
"Score": "1",
"body": "I don't know very much about Java Card, but what is the difference between `SW_WRONG_P1P2` (thrown in first inner `switch`) and `SW_INCORRECT_P1P2` (thrown in default and second inner `switch`)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T09:29:44.390",
"Id": "63477",
"Score": "0",
"body": "That's what I thought too when I saw them in the auto-completion list. I just try them both to see the difference. `SW_WRONG_P1P2` return \"Wrong parameter\" and `SW_INCORRECT_P1P2` return \"Incorrect parameter\" if you enter 05 for both case."
}
] |
[
{
"body": "<p>I would focus on eliminating the inner <code>switch</code> statements. You could try to eliminate the outer <code>switch</code> as well, but it's probably not worthwhile, especially for a resource-constrained environment.</p>\n\n<pre><code>byte[][] desKeys = new byte[][] {\n null, DESKey1, DESKey2, DESKey3, DESKey4\n};\n\ntry {\n switch (buf[ISO7816.OFFSET_P1]) {\n case 0x01:\n doSingleDES(apdu, desKeys[buf[ISO7816.OFFSET_P2]]);\n return;\n case 0x02:\n doEncrypt(apdu, desKeys[buf[ISO7816.OFFSET_P2]]);\n return;\n default:\n ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);\n }\n} catch (ArrayIndexOutOfBoundsException badP2) {\n ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T07:10:53.147",
"Id": "63470",
"Score": "0",
"body": "I try to use your code, but it gives me error because it says can't convert from byte [] to byte [][]..if I try eliminate one of the bracket, it gives me error because can't convert null to byte..if I were to add another bracket to the single bracket, the package is giving me error because of invalid type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T09:48:29.653",
"Id": "63479",
"Score": "0",
"body": "@Archie what is the type of `DESKey1`, `DESKey2`, etc? If its `long`, `try long[] desKeys = new long[] {0, DESKey1, DESKey2, DESKey3, DESKey4};`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T09:57:40.683",
"Id": "63480",
"Score": "0",
"body": "@abuzittingillifirca I use byte[]..maybe it's something to do with the version of the java card I'm using?\nI'm using 2.2 version btw."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T06:28:39.970",
"Id": "38151",
"ParentId": "38149",
"Score": "6"
}
},
{
"body": "<p>You could use the following construct to switch on both P1 and P2 simultaneously:</p>\n\n<pre><code>switch(Util.getShort(buf, ISO7816.OFFSET_P1)) {\n case (short)0x0101:\n doSingleDES(apdu, DESKey1);\n return;\n case (short)0x0102:\n doSingleDES(apdu, DESKey2);\n return;\n case (short)0x0103:\n ...\n case (short)0x0201:\n doEncrypt(apdu, DESKey1);\n return;\n ...\n default:\n ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);\n return; // not-reachable\n}\n</code></pre>\n\n<p>If you insist on different SW for P1=0x01 the default case might look like this:</p>\n\n<pre><code> default:\n if(buf[ISO7816.OFFSET_P1]==(byte)0x01) {\n ISOException.throwIt(ISO7816.SW_WRONG_P1P2);\n } else {\n ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);\n }\n return; // not-reachable\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-17T10:44:46.493",
"Id": "97220",
"ParentId": "38149",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "38151",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T04:29:05.117",
"Id": "38149",
"Score": "6",
"Tags": [
"java",
"cryptography",
"embedded"
],
"Title": "Selecting an algorithm and key for Java Card encryption"
}
|
38149
|
For code that targets an embedded device or some severely resource-constrained environment.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T06:30:36.227",
"Id": "38153",
"Score": "0",
"Tags": null,
"Title": null
}
|
38153
|
<p><strong>Goal:</strong> To create a function that returns the relative time difference between two given timestamps, using the <a href="http://php.net/datetime" rel="nofollow">DateTime</a> class.</p>
<p><strong>Current approach:</strong></p>
<pre><code>function time_elapsed($date1, $date2) {
$dt1 = new DateTime($date1);
$dt2 = new DateTime($date2);
$diff = $dt1->diff($dt2);
$ret = $diff->format('%y years, %m months, %a days, %h hours, %i minutes, %S seconds');
$ret = str_replace(
array('0 years,',' 0 months,',' 0 days,',' 0 hours,', ' 0 minutes,'),
'',
$ret
);
$ret = str_replace(
array('1 years, ',' 1 months, ',' 1 days, ',' 1 hours, ',' 1 minutes'),
array('1 year, ','1 month, ',' 1 day, ',' 1 hour, ',' 1 minute'),
$ret
);
return $ret;
}
</code></pre>
<p>As you can see, the function <em>works</em> fine. I'm currently using a couple of <a href="http://php.net/str_replace" rel="nofollow"><code>str_replace()</code></a> calls to remove the unnecessary parts from the formatted string, but I don't think that's a very good approach. I'm sure what I have written can be cleaned up and improved, using a different approach, perhaps. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T07:05:36.287",
"Id": "63469",
"Score": "0",
"body": "@MrLore: The `@` has nothing to do with error reporting (in this context). DateTime [can accept](http://www.php.net/manual/en/datetime.construct.php) a timestamp if you prepend it with a `@`. It is not the error suppression operator. And the curly braces -- they serve as a substitution for concatenation. `echo \"Hello, {$foo}\";` is the same as `echo \"Hello, $foo\";` or `echo \"Hello, \" . $foo;`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T12:35:59.457",
"Id": "63492",
"Score": "0",
"body": "Your goal is to use the `DateTime` class, but do you _really need_ to use `DateTime`, and if so, why? Because as I show in my answer, using `DateInterval` (which is what `DateTime::diff` returns anyway) will do just fine"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T15:20:55.193",
"Id": "63507",
"Score": "0",
"body": "@EliasVanOotegem: I can't see any answers. Perhaps you deleted it? Also, I don't mind being downvoted, but please also explain the reason. That way, I can improve my question. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T15:23:21.200",
"Id": "63509",
"Score": "1",
"body": "@AmalMurali: Down-vote wasn't mine, but I agree: -1 requires explanation. undeleted my answer, though. On the -1, I think people voted to close your question, simply because the first one of your problems suggest you're not getting the results you hoped for, which is more of a SO-type question"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T10:15:00.503",
"Id": "75875",
"Score": "1",
"body": "You might want to watch what I found on [youtube](http://www.youtube.com/watch?v=-5wpm-gesOY)"
}
] |
[
{
"body": "<p>Since my initial answer, in which I asked the question <em>\"Why bother constructing 2 instances of <code>DateTime</code>?\"</em>, markegli has given me a reason why one would do this.<br>\nIn case the diff between 2 dates is likely to be >= 1 month, using <code>DateTime</code> <em>is preferable</em>. <code>DateTime</code> can take things into account like: leap years, variable month length (28-31 days) and, though not applicable to time-stamps, time-zone differences and DST (daylight saving time).</p>\n\n<p>In that case, please ignore the section of my review that recommends dropping the use of <code>DateTime</code> in favour of constructing a <code>DateDiff</code> object from the off. Just skip right ahead to the bit about <code>str_replace</code>, just after this:<Br>\nA function/method's signature <em>ideally</em> enforces uniformity, and should be regarded as part of that function's documentation.</p>\n\n<p>When working with dates in any programming language, dates can be a pain to deal with. That's precisely why <code>DateTime</code> exists. It is therefore not too difficult to imagine that the code that ends up calling your function is already using the <code>DateTime</code> class. As it now stands, your function, then, needs to be called like so:</p>\n\n<pre><code>time_elapsed(\n $myDT1->format('Y-m-d H:i:s'),\n $myDT2->format('Y-m-d H:i:s')\n);\n</code></pre>\n\n<p>Basically, creating 2 strings from a <code>DateTime</code> instance, only to create a secondary, <em>temporary</em> instance for both these dates all over... that's just silly.<br>\nOne alternative, then, might be:</p>\n\n<pre><code>function time_elapsed(DateTime $date1, DateTime $date2)\n{\n $diff = $date1->diff($date2);\n //and so on\n}\n</code></pre>\n\n<p>Now whoever ends up using your function <em>knows</em> what to do: pass 2 <code>DateTime</code> instances to this function. If he already has these instances, then no harm done... and 2 constructor calls have been made redundant.<br>\nIf the code isn't yet using the <code>DateTime</code> class, then it's a pretty easy fix:</p>\n\n<pre><code>time_elapsed(\n DateTime::createFromFormat('Y-m-d H:i:s', $dtString1),\n DateTime::createFromFormat('Y-m-d H:i:s', $dtString2)\n);\n</code></pre>\n\n<p>Or simply</p>\n\n<pre><code>time_elapsed(\n new DateTime($date1),\n new DateTime($date2)\n);\n</code></pre>\n\n<p>But now we still have this rather annoying <code>$date1->diff($date2)</code> call in our function. What if I, as a user want to format a diff I've obtained in a different way? Why wouldn't we change our function to simply accept 1 argument: a <code>DateInterval</code> instance:</p>\n\n<pre><code>function time_elapsed(DateInterval $diff)\n{\n //format the diff\n}\n</code></pre>\n\n<p>Now our function serves a clear purpouse: its job is <em>not</em> to compute the diff between 2 dates, its job is simply to <em>format</em> a diff in a given way, and remove unwanted zeroes and plurals.<br>\nNow it's just a matter of working on the function some more to allow some more variety:</p>\n\n<pre><code>function time_elapsed(DateInterval $diff, $format = '%y years, %m months, %a days, %h hours, %i minutes, %S seconds')\n{\n}\n</code></pre>\n\n<p>If you ever implement this function as a method, you can easily use constants for the format, too. Just play around with this... in the end, you'll just end up calling this function like so:</p>\n\n<pre><code>time_elapsed(\n $date1->diff($date2)\n);\n//or, if you only want the diff in days for some reason:\n time_elapsed(\n $date1->diff($date2),\n '%a days'\n);\n</code></pre>\n\n<p>IMO, this leaves you with a shorter, cleaner and more self-explanatory function that, in some ways is even more flexible. I'm not confined to a single format, nor am I obliged to pass 2 dates to this function for every call.<br>\nAs an added bonus: people using your function who are as of yet unaware of the <code>DateTime</code> class will have to educate themselves, and perhaps finally get round to learning to use this class.</p>\n\n<p>At the bottom of my original answer, you'll find a full example of what the function you end up with could look like, including the suggested alternatives to your <code>str_replace</code> solution.</p>\n\n<hr>\n\n<p>Why do you bother constructing those two instances of <code>DateTime</code>? If you're sure you're dealing with 2 timestamps anyway, Why not subtract them, and pass them to the <code>DateInterval</code> constructor from the off?</p>\n\n<pre><code>function time_elapsed($ts1, $ts2)\n{\n $diffAbs = abs($ts1 - $ts2);//get absolute value\n $diff = new DateInterval(\n sprintf('P%dS', $diffAbs)\n );\n $ret = $diff->format(\n '%y years, %m months, %a days, %h hours, %i minutes, %S seconds'\n );\n</code></pre>\n\n<p>Then, instead of using the <code>str_replace</code> with an array as long as yours, I'd, for once, opt for a regex approach instead:</p>\n\n<pre><code>$ret = preg_replace('/\\b0+\\s+[a-z]+,?\\s*/i', '', $ret);\n</code></pre>\n\n<p>This changes a string like <em>\"1 years, 0 months, 3 days, 5 hours, 12 minutes, 0 seconds\"</em> into <em>\"1 years, 3 days, 5 hours, 12 minutes\"</em><br/>\nThe expression works like this:</p>\n\n<ul>\n<li><code>\\b0+</code>: a word boundary (beginning of string, space, dash, slash... whatever) followed by one or more zeroes</li>\n<li><code>\\s+</code>: matches one or more spaces</li>\n<li><code>[a-z]+</code>: one or more chars</li>\n<li><code>,?</code>: matches a comma, if there is one</li>\n<li><code>\\s*</code>: zero or more spaces</li>\n<li><code>i</code>: case-insensitive flag</li>\n</ul>\n\n<p>I wouldn't care about the <em>\"1 years\"</em> substring, but you can get rid of it using the following expression:</p>\n\n<pre><code>$ret = preg_replace('/(\\b1\\s+[a-z]+)s\\b/i', '$1', $ret);\n</code></pre>\n\n<p>Which, when applied to <em>\"1 years, 3 days, 5 hours, 12 minutes\"</em> results in <em>\"1 year, 3 days, 5 hours, 12 minutes\"</em><br/>\nThis expression works similarly to the previous one:</p>\n\n<ul>\n<li><code>(\\b1\\s+</code>: matches a word boundary, one <code>1</code> char and one or more spaces, this match is <em>grouped</em></li>\n<li><code>[a-z]+)</code>: chars are matches (one or more) and is added to the group, so we can use this match in our replacement string</li>\n<li><code>s\\b</code>: matches a literal <em>s</em> (for plural*<strong>s*</strong>), if it's the end of a word (hence <code>\\b</code>). This match is <em>not</em> grouped</li>\n<li><code>i</code>: case insensitive</li>\n<li><code>'$1'</code>: is our replacement, it refers back to the group we make in our pattern: <code>\\b1\\s+[a-z]</code>: in the case of <em>\"1 days\"</em>, the entire string will be matched and replaced with the group: <em>\"1 day\"</em>, effectively removing the s at the end</li>\n</ul>\n\n<p>With some work, you'll probably be able to work this into a single expression, using a callback function.</p>\n\n<p>This would leave us with a function that looks like this:</p>\n\n<pre><code>function time_elapsed($ts1, $ts2)\n{\n if (!is_int($ts1) || !is_int($ts2))\n {//add some validation, is_int should do it, since timestamps ARE ints\n throw new InvalidArgumentException(__FUNCTION__.' expects 2 ints');\n }\n $diff = new DateInterval(\n sprintf('P%dS', abs($ts1, $ts2))\n );\n $ret = $diff->format(\n '%y years, %m months, %a days, %h hours, %i minutes, %S seconds'\n );\n return preg_replace(\n '/(\\b1\\s+[a-z]+)s\\b/i', '$1',//remove trailing 's'\n preg_replace(\n '\\b0+\\s+[a-z]+,?\\s*','',//remove 0 diff-values\n $ret\n )\n );\n}\n</code></pre>\n\n<p>The main benefit of regex's here is that the replace calls don't rely on an array that has to match the amount of spaces (trailing or leading), comma's and what have you. Instead, you're free to change the order in which you print out the diff, and the regex will still be able to work out what needs to be removed, and what not.</p>\n\n<hr>\n\n<p>After my edit, a full example using just the <code>DateInterval</code> argument, then, would look like this:</p>\n\n<pre><code>function time_elapsed(DateInterval $diff, $format = '%y years, %m months, %a days, %h hours, %i minutes, %S seconds')\n{\n $ret = $diff->format($format);\n return preg_replace(\n '/(\\b1\\s+[a-z]+)s\\b/i', '$1',\n preg_replace(\n '\\b0+\\s+[a-z]+,?\\s*','',\n $ret\n )\n );\n}\n</code></pre>\n\n<p>In this case, it is <em>imperative</em> that you use the <code>preg_replace</code>, as you no longer fully control the format that is being used.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T16:27:01.120",
"Id": "76049",
"Score": "3",
"body": "One **very** good reason to construct the `DateTime` instances is because not all months are equal lengths and going straight to a `DateInterval` from the difference between the time stamps will prevent calculation of carry over points. If the difference is 32 days is that 1 month and 4 days or 1 month and 1 day? PHP won't even try with your method because it is impossible to know if you do not convert to `DateTime` first."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T07:50:41.590",
"Id": "76209",
"Score": "0",
"body": "@markegli: good point. I'll edit my answer accordingly."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T08:11:07.850",
"Id": "38157",
"ParentId": "38154",
"Score": "7"
}
},
{
"body": "<ol>\n<li><p>I guess you have a bug here:</p>\n\n<blockquote>\n<pre><code>$ret = $diff->format('%y years, %m months, %a days, %h hours, %i minutes, %S seconds');\n</code></pre>\n</blockquote>\n\n<p><code>%a</code> should be <code>%d</code>. With %a</p>\n\n<pre><code>time_elapsed(\"2012-07-08 11:14:15.889342\", \"2014-09-10 13:15:17.889342\");\n</code></pre>\n\n<p>prints total number of days:</p>\n\n<pre><code>2 years, 2 months, 794 days, 2 hours, 1 minute, 02 seconds\n</code></pre>\n\n<p>Using <code>%d</code> changes <code>794 days</code> to <code>2 days</code>.</p></li>\n<li><p>Another approach is iterating through of an array of units:</p>\n\n<pre><code>function time_elapsed2($start, $end) {\n $start = new DateTime($start);\n $end = new DateTime($end);\n\n $interval = $end->diff($start);\n\n $units = array(\n \"%y\" => sp(\"year\", \"years\"),\n \"%m\" => sp(\"month\", \"months\"),\n \"%d\" => sp(\"day\", \"days\"),\n \"%h\" => sp(\"hour\", \"hours\"),\n \"%i\" => sp(\"minute\", \"minutes\"),\n \"%s\" => sp(\"second\", \"seconds\")\n );\n\n $result = array();\n foreach ($units as $format_char => $names) {\n $formatted_value = $interval->format($format_char);\n if ($formatted_value == \"0\") {\n continue;\n }\n $result[] = get_formatted_string($formatted_value, $names);\n } \n\n return implode(\", \", $result);\n} \n\nfunction sp($singular, $plural) {\n return array(\"singular\" => $singular, \"plural\" => $plural);\n}\n\nfunction get_formatted_string($formatted_value, $names) {\n $result = $formatted_value . \" \";\n if ($formatted_value == \"1\") {\n $result .= $names[\"singular\"];\n } else {\n $result .= $names[\"plural\"];\n }\n return $result;\n}\n</code></pre>\n\n<p>(In production code I'd use constants instead of <code>singular</code> and <code>plural</code>.) The array also helps if you want to translate your page to other languages.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-09T11:30:09.387",
"Id": "43849",
"ParentId": "38154",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "43849",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T06:53:16.963",
"Id": "38154",
"Score": "10",
"Tags": [
"php",
"datetime"
],
"Title": "Display the relative time difference between two dates"
}
|
38154
|
<p>I have two numbers: a and b. I want to put the smaller of them in one variable, and the larger in another variable (if they are equal, then any of them can be in any of the variables). Currently my code (in Javascript / Java) takes 7 lines:</p>
<pre><code>if (a<=b) {
small = a;
large = b;
} else {
small = b;
large = a;
}
</code></pre>
<p>I could also use the Math.max and Math.min functions:</p>
<pre><code>small = Math.min(a,b);
large = Math.max(a,b);
</code></pre>
<p>This takes only 2 lines but it is wasteful because the test of which one is larger will be done twice - once in Math.min and once in Math.max.</p>
<p>Is there a shorter / more elegant way to do this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T08:02:59.133",
"Id": "63475",
"Score": "4",
"body": "Is this for Java or JavaScript? They're two different languages."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T09:38:09.170",
"Id": "63478",
"Score": "3",
"body": "Currently I need this for Javascript, but, the code for Java is the same."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T10:06:02.227",
"Id": "63482",
"Score": "5",
"body": "If you are seriously concerned about the performance penalty of doing two comparisons here, perhaps you should post a bigger chunk of code so we can inspect your whole algorithm for inefficiencies."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T10:08:47.463",
"Id": "63483",
"Score": "2",
"body": "Micro-optimizations like these have little effect. I suggest you go for the 2-liner if you really want it short."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T11:34:17.683",
"Id": "63490",
"Score": "0",
"body": "@200_success thanks, this is a good idea, I will do this one piece at a time.."
}
] |
[
{
"body": "<pre><code>int t = a + b;\na = a > b ? t - a : a;\nb = t - a;\n// a is the small one\n</code></pre>\n\n<p>Or </p>\n\n<pre><code>small = a;\nlarge = b;\nif (a>b) {\n small = b;\n large = a;\n} \n</code></pre>\n\n<p>But I think it will be shorter in Python:</p>\n\n<pre><code>if a > b:\n a, b = b, a\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T10:11:26.493",
"Id": "38161",
"ParentId": "38156",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "38161",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T07:57:40.337",
"Id": "38156",
"Score": "1",
"Tags": [
"java",
"javascript",
"mathematics"
],
"Title": "min and max simultaneously"
}
|
38156
|
<p>I observe the same pattern in a number of my classes but can't extract/abstract it due the tight coupling inside each particular implementation.</p>
<p>Having the class accepting an optional number of dependencies onto its constructor:</p>
<pre><code>public Repository(IBuilder, IFormatter, ILoader, ISelector)
</code></pre>
<p>With the single method passing its arguments to the first dependency. Passing result to the second. And so on. Returning result of the last dependency:</p>
<pre><code>public XElement Do(int i)
{
string q = _builder.Build(i);
string f = _formatter.Format(q);
XDocument d = _loader.Load(f);
XElement r = _selector.Select(d);
return r;
}
</code></pre>
<p>(names of the classes, methods and variables are random, just to illustrate the pattern)</p>
<p>Can it be refactored to decouple the flow from the types of dependencies, arguments and return values?</p>
<p>It also will simplify the (unit) testing because currently I make sure that a dependency N passes its result to a dependency N+1:</p>
<pre><code>[TestMethod]
public void Do_Should_Pass_Result_Of_Build_To_Format()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T10:57:25.990",
"Id": "63485",
"Score": "1",
"body": "Do you use many different implementations of these interfaces, or always the same?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T15:55:58.797",
"Id": "63517",
"Score": "0",
"body": "Post some real code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T19:28:06.407",
"Id": "63558",
"Score": "0",
"body": "@GertArnold: I have different interfaces (about 5 now) with different implementation and number of dependencies but the patter is same: `D(i)` calls `D(i+1)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T19:30:33.057",
"Id": "63560",
"Score": "0",
"body": "@abuzittingillifirca: the real code is very similar: 4 dependencies with almost same names call each other in same order. Or 3 of them, or 5."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T20:10:31.863",
"Id": "63567",
"Score": "0",
"body": "@abatishchev `Do_Should_Pass_Result_Of_Build_To_Format`: You clearly are testing the implementation details."
}
] |
[
{
"body": "<p>One option would be to create a generic method that accepts delegates to the methods:</p>\n\n<pre><code>var combined = Combine(_builder.Build, _formatter.Format, _loader.Load, _selector.Select);\nreturn combined(i);\n</code></pre>\n\n<p>The implementation would look like this:</p>\n\n<pre><code>public static Func<T1, T5> Combine<T1, T2, T3, T4, T5>(\n Func<T1, T2> f1, Func<T2, T3> f2, Func<T3, T4> f3, Func<T4, T5> f4)\n{\n return input =>\n {\n var r1 = f1(input);\n var r2 = f2(r1);\n var r3 = f3(r2);\n var r4 = f4(r3);\n return r4;\n };\n}\n</code></pre>\n\n<p>The implementation would need to have overloads for different number of delegates.</p>\n\n<p>Also, I'm not completely sure whether this actually improves the situation. Your original code is very straightforward, this code is harder to understand, because it's not immediatelly clear what does <code>Combine()</code> do.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T17:35:32.230",
"Id": "63534",
"Score": "0",
"body": "Maybe if you call it `Chain` it becomes clearer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T20:00:17.990",
"Id": "63564",
"Score": "0",
"body": "Thanks for your answer! I agree that the code is straightforward but its testing is unfortunately not, it's messy. I need to mock all dependencies turn by turn and make sure that the flow takes place (passing result from one to another). I feel like I'm testing a wrong thing. I'd like to have a set of strongly-typed flow steps and just make sure that SUT uses the flow manager."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T23:01:16.517",
"Id": "63583",
"Score": "0",
"body": "Confusion. This code sample could/should be what the TEST method signature might be, yes?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T07:22:30.587",
"Id": "63620",
"Score": "0",
"body": "No, that's current test name. I have such test for each member/dependency in the underlying flow. Everything is mocked up but still too messy."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T07:27:48.467",
"Id": "63622",
"Score": "0",
"body": "The main drawback of your solution for me is that the number of \"steps\" is not dynamic but mandatory and hard-coded. So I need to have separate Chain() for a case of 2,3,4,etc. Also having T1,T2,T3,etc. degrades readability significantly :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T07:30:12.320",
"Id": "63623",
"Score": "0",
"body": "Your solution is really answers my question! But more in \"how to refactor\" and less in \"how I'd like to see it be refactored\" or \"how it should be refactored\" :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T11:24:13.420",
"Id": "63625",
"Score": "0",
"body": "@abatishchev I was trying to make the usage syntax as simple as possible. I think that a more complicated syntax (like the one suggested by Dan) wouldn't actually improve the code."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T11:20:13.663",
"Id": "38164",
"ParentId": "38158",
"Score": "3"
}
},
{
"body": "<p>An alternative to @svick's answer is to use an extension method which only takes in two functions, and then chain them together, as follows:</p>\n\n<pre><code>public static class ExtensionHelper\n{\n public static Func<T1,T3> Chain<T1,T2,T3> (this Func<T1,T2> f1, Func<T2,T3> f2)\n {\n return item => f2(f1(item));\n }\n}\n</code></pre>\n\n<p>Then, you can chain any number of functions as follows:</p>\n\n<pre><code>static void Main(string[] args)\n{\n Func<int,int> f1 = AddOne;\n\n var chained3 = f1.Chain(Double).Chain(i => i - 1); // overall: i => ((i + 1) * 2) - 1\n var val = chained3(1); // returns 3\n}\n\npublic static int AddOne(int i)\n{\n return i + 1;\n}\n\npublic static int Double(int i)\n{\n return i * 2;\n}\n</code></pre>\n\n<p>The downside is that you have to declare the initial function as a Func type to start the chain. You cannot use the method group or a lambda directly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T09:15:56.340",
"Id": "63685",
"Score": "0",
"body": "Add this static method to your extension class: `Identitx<T>() = (x)=>x`. Then you can say `Identity<int>.Chain(class1.method1).Chain(class2.method2)`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T19:35:11.097",
"Id": "38190",
"ParentId": "38158",
"Score": "2"
}
},
{
"body": "<p>This is basically a <a href=\"http://www.eaipatterns.com/PipesAndFilters.html\" rel=\"nofollow\">pipe and filter pattern</a> - where you construct some number of filters into a chain and just pass the outputs to the next filter. If you control all instances, then the simple thing is to abstract out to an interface:</p>\n\n<pre><code> interface IFilter {\n object Filter(object o);\n }\n</code></pre>\n\n<p>Note the weak typing of using <code>object</code> - if these classes are used somewhere else, implementing <code>IFilter</code> as an explicit interface would probably be preferable. You could do generics, but that makes the chaining harder.</p>\n\n<pre><code> interface IBuilder : IFilter {\n string Build(int i);\n }\n\n class Builder : IBuilder {\n public string Build(int i) {\n // Do stuff\n }\n\n object IBuilder.Filter(object o) {\n return (object)this.Build((int)o);\n }\n }\n</code></pre>\n\n<p>Now, each filter simply takes an input and transforms to an output. We need a pipe to tie to it all together:</p>\n\n<pre><code> class Pipeline {\n private IFilter[] Filters { get; set; }\n\n public Pipeline(params IFilter[] filters) {\n this.Filters = filters;\n }\n\n public object Execute(object input) {\n foreach (var f in this.Filters) {\n input = f.Filter(input);\n }\n return input;\n }\n }\n</code></pre>\n\n<p>And, in use:</p>\n\n<pre><code> class Repository {\n private Pipeline { get; set; }\n\n public Repository(IBuilder b, IFormatter f, ILoader l, ISelector s) {\n this.Pipeline = new Pipeline(b, f, l, s);\n }\n\n public XElement Do(int i) {\n return (XElement)this.Pipeline.Execute(i);\n }\n }\n</code></pre>\n\n<p>Your unit tests for <code>Repository</code> now only need to be concerned with the results of <code>Do</code> - which verifies the <code>Pipeline</code> was constructed properly (an important bit to test, since it's weakly typed).</p>\n\n<p>You can dress it up with <a href=\"http://www.rantdriven.com/post/2009/09/16/Simple-Pipe-and-Filters-Implementation-in-C-with-Fluent-Interface-Behavior.aspx\" rel=\"nofollow\">generics, extension methods, builder patterns, etc.</a> - but that's the basic pattern.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T20:54:50.957",
"Id": "63568",
"Score": "0",
"body": "Looks like that's exactly I was looking for. Awesome, thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T20:55:29.010",
"Id": "63569",
"Score": "0",
"body": "But a question please: how to make it generic? I tried to roll out something similar by myself but stuck making it generic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T06:35:38.810",
"Id": "63616",
"Score": "0",
"body": "The post under last link is in top of Google for \"c# pipes filters generic\". It's good but (besides can be refactored nicely with `ops.Aggregate(input, (i, op) => op.Exec(i))`) its weak part is all input and output parameters have the same type `T` what makes Aggregate applicable to it and it not applicable to my case as 1:1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T14:54:58.093",
"Id": "63797",
"Score": "0",
"body": "If you make it strongly typed, you'll end up having to specify the exact steps as delegates (as others have mentioned). You could do a BasePipeline and then derive an XElementPipeline from it with the steps to prevent having to respecify it in your tests. You may also want to look at Task.ContinueWith which could be useful for chaining with or without async behavior."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T20:23:10.183",
"Id": "38194",
"ParentId": "38158",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "38194",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T08:20:15.320",
"Id": "38158",
"Score": "4",
"Tags": [
"c#",
".net",
"unit-testing",
"revealing-module-pattern"
],
"Title": "Extracting pattern and simplifying testing"
}
|
38158
|
<pre><code>Storage.prototype.setExpire = function (arrObj) {
var date,
now,
days,
deletes,
items,
fa, ta,
newItems = [],
storage = localStorage.getItem('limitStorage');
items = JSON.parse(storage || "[]");
date = new Date();
date = date.toString().split(' ');
date = Number(date[2]);
for (var key in arrObj) {
for (i = 0; i < items.length; i++) {
if (items[i].value == key) {
if (typeof (items[i].days) == "number") {
if (items[i].date !== date) {
days = (date - items[i].date);
} else {
days = items[i].days;
}
}
}
}
ta = {
value: key,
limit: arrObj[key],
date: date,
days: days !== undefined ? days : 0
};
if (ta.days >= ta.limit) {
localStorage.removeItem(ta.value);
}
if(localStorage.getItem(ta.value) !== null) newItems.push(ta);
}
localStorage.setItem('limitStorage', JSON.stringify(newItems));
};
</code></pre>
<p>This code runs by simply calling the Storage method and then adding method <code>.setExpire</code>.</p>
<p>Example:</p>
<pre><code>window.localStorage.setExpire({"item1":3,"item2":10,"item3":3});
</code></pre>
<p>I have to add more to the code to take into account day <code>31</code> to day <code>1</code>. But as of now, if the item is added on day <code>20</code> and you want it to expire in 7 days on day <code>27</code>, the <code>localStorage</code> item will be removed.</p>
<p>My question is: does anyone see anything they can review for me? Maybe a cross-browser compatibility issue? I already have a cross-browser <code>localStorage</code> that falls back to cookies if need be.</p>
<p>Also let me know if you may think of a way for the code to take into account the ending to the start of a months, since the code technically only takes the new date and then subtracts the stored date, which gets our days that have passed.</p>
<p>Any and all suggestions are welcomed.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T01:36:01.693",
"Id": "63594",
"Score": "0",
"body": "changed my code more. Now the code if you change `\"item1\":3` to less or more days `\"item1\":6` code will update the item."
}
] |
[
{
"body": "<p>I think this code could use a lot of polishing.</p>\n\n<p><strong>Getting the localStorage</strong></p>\n\n<pre><code> storage =localStorage.getItem('limitStorage');\n getItems = storage !== null && storage !== \"[]\" ? localStorage.getItem('limitStorage') : null;\n getItems = getItems !== null ? JSON.parse(getItems) : null;\n</code></pre>\n\n<p>can easily be replaced with:</p>\n\n<pre><code>items = JSON.parse( localStorage.getItem('limitStorage') || \"[]\" );\n</code></pre>\n\n<p>I renamed <code>getItems</code> to <code>items</code> ( <code>getItems</code> is a name better suited for a function ), the code also defaults <code>items</code> to an empty array if nothing was found.</p>\n\n<p><strong>Setting an expiry date</strong></p>\n\n<p>The easiest way to deal with that is to get <code>now</code> in milliseconds, add 1000 * 60 * 60 * 24 * <code>days</code> to it, and set that as the expiry date. Then you only have to compare <code>(new Date()).getTime()</code> with the expiry date.</p>\n\n<p>So you have something like</p>\n\n<pre><code>var now = (new Date()).getTime();\nvar day = 1000 * 60 * 60 * 24;\n\nfor (var key in arrObj) {\n newItems.push( { value : key , expires : now + day * arrObj[key] } );\n</code></pre>\n\n<p>Now, we are facing 2 problems:</p>\n\n<ul>\n<li>If you want to change the expiry date of an item, you cant..</li>\n<li>Much worse, once you set some items to expire, you can never add extra items to expire since you will always fall into the else branch.</li>\n</ul>\n\n<p>At this point, I think the whole code needs a re-write and re-think.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T20:00:25.657",
"Id": "63565",
"Score": "0",
"body": "well to add more items to expire, we could write another if condition or a more suitable if condition to push it to the array of objects. Like you said it does need to be polished, I only wrote it very quickly as I was tired of not having that option to set items to expire. Though I don't think it's a bad start. I will work on this some more to be able to change the expire day, and add more options to the expire, persay minutes hours days. Maybe, though I will take account what you've told me. Very helpful tomdemuyt! Thank you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T22:43:46.447",
"Id": "63579",
"Score": "0",
"body": "The concept is good, please do update your question once you have this more fleshed out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T01:35:16.910",
"Id": "63592",
"Score": "0",
"body": "ok so I've changed the code drastically, took in account some of what you said, still more needs to be edited. Though now if the setExpire days is changed it'll update it. Also it won't save any items that do not actually exist until they exist."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T14:29:44.067",
"Id": "38171",
"ParentId": "38159",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T08:41:35.047",
"Id": "38159",
"Score": "5",
"Tags": [
"javascript",
"datetime"
],
"Title": "localStorage setExpire code to add time expires"
}
|
38159
|
<p>The SDL code example on the <a href="http://wiki.libsdl.org/SDL_Init" rel="nofollow"><code>SDL_Init</code></a> page seems to be overly verbose, creating an exception class entirely for <code>SDL_Init</code>. I wanted to tone it down a bit by making everything <code>std::runtime_error</code>s.</p>
<ol>
<li>Does it make sense to have global variables and a cleanup function?</li>
<li>Is it necessary to check if <code>win</code> is a valid pointer before calling <code>SDL_DestroyWindow</code>?</li>
<li>Is <code>SDL_GLContext</code> a <code>typedef</code> for a pointer? If so, should I not pass it by reference?</li>
</ol>
<p></p>
<pre><code>#include <exception>
#include <stdexcept>
#include <string>
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#include <iostream>
void DestroyAndQuit(SDL_Window* win, SDL_Renderer* ren, SDL_GLContext& con)
{
if (ren)
SDL_DestroyRenderer(ren);
if (win)
SDL_DestroyWindow(win);
if (con)
SDL_GL_DeleteContext(con);
SDL_Quit();
}
SDL_Window* win = nullptr;
SDL_Renderer* ren = nullptr;
SDL_GLContext con;
int main(int argc, char **argv) try {
if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
throw std::runtime_error("SDL_Init failed.");
}
win = SDL_CreateWindow("Hello, world!", 0, 0, 640, 480, SDL_WINDOW_OPENGL);
if (!win) {
throw std::runtime_error("SDL_CreateWindow failed.");
}
ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED);
if (!ren) {
throw std::runtime_error("SDL_CreateRenderer failed.");
}
con = SDL_GL_CreateContext(win);
if (!con) {
throw std::runtime_error("SDL_GL_CreateContext failed.");
}
SDL_RenderClear(ren);
SDL_RenderPresent(ren);
glClearColor(0, 1, 1, 1);
glClear(GL_COLOR_BUFFER_BIT);
SDL_GL_SwapWindow(win);
SDL_Delay(2000);
DestroyAndQuit(win, ren, con);
return 0;
} catch(std::exception& ex) {
std::cerr << ex.what() << ": " << SDL_GetError() << "\n";
DestroyAndQuit(win, ren, con);
return 1;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T22:21:32.140",
"Id": "63724",
"Score": "2",
"body": "Putting the catch outside the body is extremely rare. You will confuse people by doing that. Also the catch happens after main has exited so the return is not doing what you think. To actually return one you must move the try/catch into the body of main and do the return from inside the body."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T10:42:22.790",
"Id": "38162",
"Score": "2",
"Tags": [
"c++",
"exception",
"sdl"
],
"Title": "SDL boilerplate"
}
|
38162
|
<p>As per a <a href="https://codereview.stackexchange.com/questions/35502/multi-producer-consumers-lockfree-stack">similar question</a>, following a lockfree list implementation. Note that this list has a pre-defined maximum set of elements which can be inserted (<code>N</code> argument in the template declaration). Please let me know if I've missed anything.</p>
<pre><code>// Lockfree FIFO list, with N pre-allocated slots
template<typename T, size_t N = 128>
class list {
typedef union {
struct {
T *ptr;
size_t cnt;
} s;
__int128 intv;
} ptrcnt;
volatile size_t _head,
_tail;
ptrcnt _ptrbuf[N];
public:
// Initialise elements' cnt with a non-equal seed
list() {
_head = _tail = 0;
for(size_t i = 0; i < N; ++i) {
_ptrbuf[i].s.ptr = 0;
_ptrbuf[i].s.cnt = i*100 + i*3 + i;
}
}
bool push(const T& in) {
std::auto_ptr<T> v(new T(in));
while(true) {
// first, prepare pointer to use next
ptrcnt cur_ptr = _ptrbuf[_tail%N],
next_ptr = cur_ptr;
cur_ptr.s.ptr = 0;
next_ptr.s.ptr = v.get();
++next_ptr.s.cnt;
if(_tail - _head >= N) {
break;
}
// add new element
if(!__sync_bool_compare_and_swap(&_ptrbuf[_tail%N].intv, cur_ptr.intv, next_ptr.intv)) {
continue;
}
// if we're after this point, no other thread should have
// accessd the slot, set the tail
__sync_fetch_and_add(&_tail, 1);
// all done, return true
v.release();
return true;
}
return false;
}
bool pop(T& out) {
while(true) {
// get current pointer, then swap
ptrcnt lcl_ptr = _ptrbuf[_head%N],
next_ptr = lcl_ptr;
next_ptr.s.ptr = 0;
++next_ptr.s.cnt;
if(!lcl_ptr.s.ptr || _head == _tail) {
return false;
}
// first, swap pointer to use next
if(!__sync_bool_compare_and_swap(&_ptrbuf[_head%N].intv, lcl_ptr.intv, next_ptr.intv)) {
continue;
}
// then increment the head; no other thread should access 'head'
// while performing this increment
__sync_fetch_and_add(&_head, 1);
// return the value
out = *lcl_ptr.s.ptr;
delete lcl_ptr.s.ptr;
return true;
}
return false;
}
};
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p><a href=\"http://en.cppreference.com/w/cpp/memory/auto_ptr\" rel=\"nofollow\">As of C++11, <code>std::auto_ptr</code> has been deprecated</a>. Consider switching to another type of supported smart pointer, such as <a href=\"http://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"nofollow\"><code>std::unique_ptr</code></a>.</p></li>\n<li><p>Your use of whitespace and indentation in some places is odd:</p>\n\n<blockquote>\n<pre><code>ptrcnt cur_ptr = _ptrbuf[_tail%N],\n next_ptr = cur_ptr;\n</code></pre>\n</blockquote>\n\n<p>It's also more readable to declare/initialize one variable per line.</p>\n\n<pre><code>ptrcnt cur_ptr = _ptrbuf[_tail%N];\nptrcnt next_ptr = cur_ptr;\n</code></pre></li>\n<li><p>I don't know what's required of this type of assignment:</p>\n\n<blockquote>\n<pre><code>cur_ptr.s.ptr = 0;\n</code></pre>\n</blockquote>\n\n<p>If it's supposed to be a pointer type and not specifically an integer, then use <a href=\"http://en.cppreference.com/w/cpp/language/nullptr\" rel=\"nofollow\"><code>nullptr</code></a>:</p>\n\n<pre><code>cur_ptr.s.ptr = nullptr;\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-12T22:04:38.517",
"Id": "113776",
"ParentId": "38166",
"Score": "3"
}
},
{
"body": "<h1>Problem with pop</h1>\n<p>Your <code>pop()</code> function could return <code>false</code> when there are still elements in the list. The problem is with this check:</p>\n<blockquote>\n<pre><code> if(!lcl_ptr.s.ptr || _head == _tail) {\n return false;\n }\n</code></pre>\n</blockquote>\n<p>Here, <code>lcl_ptr.s.ptr</code> could be <code>NULL</code> if some other thread just popped that element. If that happens, you should just move on to the next element instead of returning false. So for example:</p>\n<pre><code> if (_head == _tail) {\n return false;\n }\n if (!lcl_ptr.s.ptr) {\n continue;\n }\n</code></pre>\n<p>This solution spins until the other thread finishes incrementing the head pointer. There may be better ways of handling this case which involve searching forward for an element to pop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-25T12:24:46.273",
"Id": "213503",
"Score": "0",
"body": "You're right mate, good changes. Everything else looks ok, am i right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-25T18:21:46.423",
"Id": "213534",
"Score": "0",
"body": "@Emanuele Honestly I didn't realize this question was a year old. It showed up near the top one day and I looked at it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-25T18:23:12.717",
"Id": "213537",
"Score": "1",
"body": "Not an issue at all, in fact I saw your useful review today whilst accessing codereview for a _long_ time. Thanks again!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-13T06:01:10.483",
"Id": "113810",
"ParentId": "38166",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T11:53:07.110",
"Id": "38166",
"Score": "3",
"Tags": [
"c++",
"multithreading",
"linked-list",
"lock-free"
],
"Title": "Multi producer/consumers lockfree list"
}
|
38166
|
<p>Is this correct? Or am I overloading the responsibilities of the view?</p>
<pre><code><table class="table table-striped table-hover">
<thead>
<tr>
<th>Estado</th>
<th>Prioridad</th>
<th>Responsable</th>
<th>Categoría</th>
<th>Solicitud</th>
<th>Creado</th>
<th>Cerrado</th>
</tr>
</thead>
<tbody>
<?php
$class = '';
$label = '';
foreach ($solicitud as $key => $value) {
if( $value['priority'] > 0 && $value['priority'] < 4 ) $class = 'badge-important';
if( $value['priority'] > 4 && $value['priority'] < 7 ) $class = 'badge-info';
if( $value['priority'] > 7 ) $class = 'badge-warning';
if( $value['id'] == 1 ) $label = 'label-info';
if( $value['id'] == 2 ) $label = 'label-success';
if( $value['id'] == 3 ) $label = 'label-danger';
echo '<tr>';
echo ' <td><span class="label label-sm '.$label.'">'.ucfirst($value['status']).'</span></td>';
echo ' <td><span class="badge '.$class.' ">'.$value['priority'].'</span></td>';
echo ' <td>'.$value['sname'].' '.$value['last_name'].'</td>';
echo ' <td>'.$value['name'].'</td>';
echo ' <td>'.$value['message'].'</td>';
echo ' <td>'.$value['created'].'</td>';
echo '<td>'.(( $value['closed'] ) ? $value['closed'] : 'pendiente').'</td>';
echo '</tr>';
} ?>
</tbody>
</table>
</code></pre>
|
[] |
[
{
"body": "<p>In my opinion, there is way too much logic in your view.</p>\n\n<p>Personally I would manipulate the data in the controller so that <code>$value</code> has a <code>label</code> and a <code>class</code> attribute, and then just loop over the data in the view.</p>\n\n<p>This way view and controller are decoupled and, if you think in terms of testability, you can easily unit-test the controller so that the data always has the required fields.</p>\n\n<p>(Actually, I would do the data manipulation in a model.)</p>\n\n<p>Hope this helps.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T15:56:25.253",
"Id": "38176",
"ParentId": "38175",
"Score": "0"
}
},
{
"body": "<p>These <code>0</code>, <code>4</code> and <code>7</code> means nothing to any code reader, nor <code>1</code>, <code>2</code> and <code>3</code> for the label.</p>\n\n<p>Move this logic in the controller and consider using ENUMs in your controller class i.e.:</p>\n\n<pre><code>const BADGE_IMPORTANT = 0;\nconst BADGE_INFO = 4;\nconst BADGE_WARNING = 7;\n</code></pre>\n\n<p>This way it will be more readable for the one who will read and change it later, also it will became less hard changable and more reusable.</p>\n\n<p>Also, try to not echo HTML, I mean, use PHP blocks only when you have PHP in it. HTML should be outside:</p>\n\n<pre><code><?php foreach ($solicitud as $key => $value): ?>\n <tr>\n <td><span class=\"label label-sm<?=$label;?>\"><?=ucfirst($value['status']);?></span></td>\n <td><span class=\"badge <?=$class;?>\"><?=$value['priority'];?></span></td>\n <td><?=$value['sname'].$value['last_name'];?></td>\n <td><?=$value['name'];?></td>\n ....\n </tr>\n<?php endforeach; ?>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T22:15:21.597",
"Id": "38198",
"ParentId": "38175",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "38198",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T15:18:20.150",
"Id": "38175",
"Score": "0",
"Tags": [
"php",
"codeigniter",
"controller"
],
"Title": "Codeigniter - in the view or in the controller?"
}
|
38175
|
<p>I am working on an Android app that has an Abstract view controller class. I am using that Abstraction and implementing it for an <a href="http://developer.android.com/reference/android/widget/Spinner.html" rel="nofollow noreferrer">Android Spinner</a> view. It has a method that assigns the view to be controlled. I implemented it as:</p>
<pre><code>@Override
public void setView(@Nonnull View view) {
super.setView(view);
mView = (Spinner) Preconditions.checkNotNull(view);
}
</code></pre>
<p>I am getting feedback in a code review that would have me revise the method to:</p>
<pre><code>@Override
public void setView(@Nonnull View view) {
super.setView(view);
Preconditions.checkNotNull(view, "The view provided is null");
Preconditions.checkArgument(view instanceof Spinner,
"view provided was not a Spinner view");
mView = Spinner.class.cast(view);
}
</code></pre>
<p>I am unclear as to why the second is a better implementation. From what I understand, using <code>Class.cast()</code> is only really useful for generics (<a href="https://stackoverflow.com/questions/7900410/why-would-i-use-java-lang-class-cast/7908554">1</a>, <a href="https://stackoverflow.com/questions/243811/when-should-i-use-the-java-5-method-cast-of-class">2</a>).</p>
<p>Other than that, it looks like the second implementation does the same thing. It will crash the app if <code>view</code> is null, or crash the app if <code>view</code> is not an instance of <code>Spinner</code>.</p>
<p>Is there a benefit to using the Precondition <code>instanceOf</code> check to crash the app in testing rather than a standard <code>ClassCastException</code>?</p>
|
[] |
[
{
"body": "<p>This is a relatively new area in Java, and best practice is not as well established....</p>\n\n<p>... but, as I think about it, I think your reviewer has a point.</p>\n\n<p>In your code base, consistency counts for a lot. If you check all your preconditions in a consistent way, and are disciplined about it, it will make a number of things easier to manage and maintain:</p>\n\n<ol>\n<li>logs will be consistent</li>\n<li>Exceptions will have more meaningful messages</li>\n<li>Programmer's expectations are clearly shown</li>\n</ol>\n\n<p>So, if the suggestions from your reviewer are consistent with the common-practice at your location, then, absolutely, do them.</p>\n\n<p>Even if they are not common practice, still do them.</p>\n\n<p>But, I have some comments to come after a small diversion.....</p>\n\n<blockquote>\n <p>You are correct that <code>Spinner.class.cast(...)</code> was introduced with Generics. The main purpose of this method appears to be related to the return value of methods with a Generic return type or where generic erasure makes internal manipulation of the data impossible without some help from the class (i.e. it counteracts the effects of erasure).</p>\n \n <p>These methods (or the class they are in) are supplied with an instance of the generic class, and they then use that class instance to cast the value.... for example, in <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#checkedList%28java.util.List,%20java.lang.Class%29\" rel=\"nofollow\">Collections.checkedList(....)</a>. It is unusual to see this method (<code>cast()</code>) referenced from a static context <code>Spinner.class.cast(value)</code> when a simple <code>(Spinner)value</code> will suffice.</p>\n \n <p>On the other hand, it is interesting that, if you have multiple values being cast on a single line of code, the ClassCastException stack trace for <code>(Spinner)value</code> will be different to the trace for <code>Spinner.class.cast(value)</code>. I need to verify this, but it may make traces slightly more useful.</p>\n \n <p>So, <code>Spinner.class.cast(value)</code> is not exactly the same as <code>(Spinner)value</code>.</p>\n</blockquote>\n\n<p>Now, having said that, I can understand why <code>Spinner.class.cast(...)</code> may be recommended, but then I would have to question why <code>Preconditions.checkArgument(view instanceof Spinner, ...)</code> was recommended....</p>\n\n<p>The <code>view instanceof Spinner</code> is logical to me, but, given the context of using <code>Spinner.class.cast()</code> I would also suggest that you should use <code>Spinner.class.isInstance(view)</code> as well.</p>\n\n<p>If you are going to use these methods then I would suggest consistency.</p>\n\n<p>Finally, I think that, unless there is the intention to turn this class in to a more generic-based one, that using the <code>cast(...)</code> and <code>isInstance(...)</code> is redundant. I would prefer the traditional <code>(Spinner)view</code> and <code>view instanceof Spinner</code>.</p>\n\n<p>But, I fully agree that if you are going to check pre-conditions, that separating out the precondition check for <code>instanceof</code> is a good idea (although I would add the word 'The' to the beginning of the message).</p>\n\n<p>So, if it were me, I would (given the context), suggest a compromise:</p>\n\n<pre><code>@Override\npublic void setView(@Nonnull View view) {\n super.setView(view);\n\n Preconditions.checkNotNull(view, \"The view provided is null\");\n Preconditions.checkArgument(view instanceof Spinner,\n \"The view provided was not a Spinner view\");\n mView = (Spinner)view;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T22:28:29.483",
"Id": "38244",
"ParentId": "38177",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38244",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T16:05:13.237",
"Id": "38177",
"Score": "4",
"Tags": [
"java",
"android"
],
"Title": "Android View Controller: Precondition vs ClassCastException"
}
|
38177
|
<p>This questions is originally from <a href="http://contestcoding.wordpress.com/2013/06/28/fizz-buzz-bizz-fuzz/" rel="nofollow">http://contestcoding.wordpress.com/2013/06/28/fizz-buzz-bizz-fuzz/</a>.</p>
<blockquote>
<ul>
<li>Print the integers from 1 to 100, </li>
<li>but for the multiples of 3, print "Fizz" instead and </li>
<li>for multiples of 5, print "Buzz". </li>
<li>If the number contains a 3 (for example 23), print "Bizz" and</li>
<li>if the number contains a 5, print “Fuzz” </li>
<li>(if it contains multiple 3s or 5s, just print one "Bizz" or "Fuzz"). </li>
<li>If the number contains more than one of these attributes, print every word (for example 33 prints "FizzBizz", as 33 is both a multiple
of 3 and contains the digit 3).</li>
</ul>
</blockquote>
<p>My Java solution is:</p>
<pre><code>public class FizzBuzz {
public static void main(String[] args) {
for (int i = 1; i < 101; i++) {
// Set this to true when one of the special conditions is met.
boolean printed = false;
if (i % 3 == 0) {
// When i is divisible by 3, then print "Fizz"
printed = true;
System.out.print("Fizz");
} else if (i % 5 == 0) {
// When i is not divisible by 3 but is divisible by 5, then print "Buzz"
printed = true;
System.out.print("Buzz");
}
if (Integer.valueOf(i).toString().indexOf("3") != -1) {
// When i has the digit 3 in it, then print "Bizz"
printed = true;
System.out.print("Bizz");
} else if (Integer.valueOf(i).toString().indexOf("5") != -1) {
// When i has the digit 5 in it, then print "Fuzz"
printed = true;
System.out.print("Fuzz");
}
if (printed == false) {
// The number does not satisfy any of the special conditions above.
System.out.print(i);
}
System.out.println();
}
}
}
</code></pre>
<p>Please provide code review comments.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T18:45:16.517",
"Id": "63548",
"Score": "0",
"body": "Wouldn't it simply make the most sense to have an acceptance test in place before just jumping right to code? As with the original fizz buzz, you should be able to know exactly what all of the lines of the output should be in advance, and then craft your program to match that test."
}
] |
[
{
"body": "<p>Overall, this is a pretty straightforward program. See the bottom of my answer for an <strong><em><a href=\"http://en.wikipedia.org/wiki/Extreme_Makeover:_Home_Edition\" rel=\"nofollow noreferrer\">Extreme Makeover: Code Edition</a></em></strong> of the program.</p>\n\n<hr>\n\n<p><a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">You have a hard-coded \"magic number\" in your <code>for</code> loop</a>. It would be better to use a variable.</p>\n\n<pre><code>for (int i = 1; i < 101; i++) // not the best\n\nint num = 101;\nfor (int i = 1; i < num; i++); // better\n</code></pre>\n\n<hr>\n\n<p>Your <code>if</code> test conditions can be shortened a bit.</p>\n\n<pre><code>if (Integer.toString(i).indexOf(\"3\") != -1)\n</code></pre>\n\n<hr>\n\n<p>Your logic is a bit off. You should actually have fewer <code>else if</code> conditions (this is rarely the case, but here it is applicable). For example, when <code>i</code> reaches \"15\", is should print \"FizzBuzzFuzz\", but your program only prints \"FizzFuzz\".</p>\n\n<hr>\n\n<h2>Final code:</h2>\n\n<pre><code>public class Test\n{\n public static void main(String... args)\n {\n int num = 101;\n for (int i = 1; i < num; i++)\n {\n boolean printed = false;\n\n if (i % 3 == 0)\n {\n printed = true;\n System.out.print(\"Fizz\");\n }\n if (i % 5 == 0)\n {\n printed = true;\n System.out.print(\"Buzz\");\n }\n\n if (Integer.toString(i).indexOf(\"3\") != -1)\n {\n printed = true;\n System.out.print(\"Bizz\");\n }\n if (Integer.toString(i).indexOf(\"5\") != -1)\n {\n printed = true;\n System.out.print(\"Fuzz\");\n }\n\n if (printed == false) System.out.print(i);\n System.out.println();\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<h2><strong><em>Extreme Makeover: Code Edition</em></strong></h2>\n\n<p>Let's use a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html\" rel=\"nofollow noreferrer\"><code>StringBuilder</code></a> <strike>and some <a href=\"https://en.wikipedia.org/wiki/?:\" rel=\"nofollow noreferrer\">ternary operators</a></strike>. And let's get rid of that <code>boolean</code>.</p>\n\n<pre><code>public class Test\n{\n public static void main(String... args)\n {\n int num = 101;\n for (int i = 1; i < num; i++)\n {\n StringBuilder sb = new StringBuilder();\n if(i % 3 == 0) sb.append(\"Fizz\");\n if(i % 5 == 0) sb.append(\"Buzz\");\n\n if(Integer.toString(i).indexOf(\"3\") != -1) sb.append(\"Bizz\");\n if(Integer.toString(i).indexOf(\"5\") != -1) sb.append(\"Fuzz\");\n\n if (sb.length() == 0) System.out.print(i);\n else System.out.print(sb);\n System.out.println();\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T17:44:28.713",
"Id": "63538",
"Score": "0",
"body": "if you read the instructions OP gave again, the answer should be `FizzFuzz`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T17:47:46.340",
"Id": "63541",
"Score": "0",
"body": "@syb0rg, I think that I may have read it incorrectly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T19:50:16.330",
"Id": "63562",
"Score": "0",
"body": "Why use a ternary operator instead of just a single-line if statement: `if (Integer.toString(i).IndexOf(\"3\") != -1) sb.Append(\"Bizz\");` Unless Java's StringBuilder works different from what I'd expect, the return value is just for fluent chaining, but you don't have to assign it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T20:00:48.480",
"Id": "63566",
"Score": "0",
"body": "Just remember that fancy is usually not what you want with code. In this case it has to evaluate all those `sb.Append(\"\")` statements which effectively does nothing, but costs something."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T17:16:07.837",
"Id": "38183",
"ParentId": "38178",
"Score": "7"
}
},
{
"body": "<ol>\n<li><p>Your implementation is broken, for example 15 should print <code>FizzBuzzFuzz</code> but yours will print <code>FizzFuzz</code>. 35 should print <code>BuzzBizzFuzz</code> but yours will print <code>BuzzBizz</code>.</p></li>\n<li><p>Turning an integer into a string can be done with <code>Integer.toString(i)</code>.</p></li>\n<li><p>For reusability your code should be encapsulated in a class which you can instantiate and play as many games as you like.</p></li>\n<li><p>Once you have refactored the code into a class consider decoupling logic from output. For example you can pass in an <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Appendable.html\" rel=\"nofollow\"><code>Appendable</code></a> to which you can append your output without having to care where it ends up.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T17:36:38.717",
"Id": "63536",
"Score": "0",
"body": "Hi ChrisWue, Based on my understanding of the question: The first two conditions (divisibility rules) are mutually exclusive of each other. Similarly, the next two conditions (presence of 3 and 5 in the number) are mutually exclusive. I can see that the question can be read so too. However, when I contacted the original question owner, he felt that my answer was correct."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T17:37:05.907",
"Id": "63537",
"Score": "0",
"body": "In addition, thanks a lot for your other comments."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T18:48:45.347",
"Id": "63550",
"Score": "0",
"body": "@KarthickS: Well the requirements state `If the number contains more than one of these attributes, print every word` so the spec is ambiguous at least."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T10:04:02.617",
"Id": "63985",
"Score": "0",
"body": "Hi Chris, the original blog post owner has confirmed what you mentioned here. It is indeed a mistake. Thanks a lot for pointing it out."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T17:26:56.063",
"Id": "38185",
"ParentId": "38178",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "38183",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T16:19:49.267",
"Id": "38178",
"Score": "6",
"Tags": [
"java",
"programming-challenge",
"fizzbuzz"
],
"Title": "Fizz Buzz Bizz Fuzz in Java"
}
|
38178
|
<p>Is there a better way of doing this?</p>
<pre><code>// Definition: Count number of 1's and 0's from integer with bitwise operation
//
// 2^32 = 4,294,967,296
// unsigned int 32 bit
#include<stdio.h>
int CountOnesFromInteger(unsigned int);
int main()
{
unsigned int inputValue;
short unsigned int onesOfValue;
printf("Please Enter value (between 0 to 4,294,967,295) : ");
scanf("%u",&inputValue);
onesOfValue = CountOnesFromInteger(inputValue);
printf("\nThe Number has \"%d\" 1's and \"%d\" 0's",onesOfValue,32-onesOfValue);
}
int CountOnesFromInteger(unsigned int value)
{
unsigned short int i, count = 0;
for(i = 0; i < 32 ; i++)
{
if (value % 2 != 0)
{
count++;
}
value = value >> 1;
}
return count;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T21:50:20.367",
"Id": "63572",
"Score": "3",
"body": "Considering the title's reference to a bitwise operator, I was surprised to see `if (value % 2 != 0)` instead of `if (value & 1)`."
}
] |
[
{
"body": "<p>Yes, there is a better way:</p>\n\n<pre><code>int CountOnesFromInteger(unsigned int value) {\n int count;\n for (count = 0; value != 0; count++, value &= value-1);\n return count;\n}\n</code></pre>\n\n<p>The code relies on the fact that the expression <code>x &= x-1;</code> removes the rightmost bit from <code>x</code> that is set. We keep doing so until no more 1's are removed. This technique is described in K&R.</p>\n\n<p>This approach is superior because it doesn't depend on an integer's size - it's totally portable - and it tests every bit in a fairly efficient way (with the comparison <code>value != 0</code>).</p>\n\n<p>Also, you might want to replace <code>32</code> in <code>main()</code> with <code>sizeof(int)*CHAR_BIT</code> so that your code doesn't depend on an integer using 32 bits:</p>\n\n<pre><code>#include <stdio.h>\n#include <limits.h>\n\nint CountOnesFromInteger(unsigned int);\n\nint main()\n{\n unsigned int inputValue;\n short unsigned int onesOfValue;\n printf(\"Please Enter value (between 0 to 4,294,967,295) : \");\n scanf(\"%u\",&inputValue);\n onesOfValue = CountOnesFromInteger(inputValue);\n\n printf(\"\\nThe Number has \\\"%d\\\" 1's and \\\"%zu\\\" 0's\",onesOfValue,sizeof(int)*CHAR_BIT-onesOfValue);\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T22:40:27.790",
"Id": "63576",
"Score": "1",
"body": "I think `and it doesn't have to test every bit` isn't really the truth (it's impossible to solve this problem without testing all bits); the `value != 0` expression is just a fairly efficient way to test all bits (by doing so in parallel)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T22:45:43.597",
"Id": "63580",
"Score": "1",
"body": "Also `the loop will run in time proportional to the number of ones` sounds imprecise as well - the number of iterations of the loop doesn't depend on the number of ones, it merely depends on the position of the most significant one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T12:05:21.517",
"Id": "63627",
"Score": "0",
"body": "@FrerichRaabe Thanks for noting that. I edited my answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T17:25:54.650",
"Id": "38184",
"ParentId": "38182",
"Score": "28"
}
},
{
"body": "<p>@Filipe hit the main point I wanted to cover. But there are some minor improvements that can be made.</p>\n\n<hr>\n\n<p>Remove the <code>!= 0</code> for maximum C-ness.</p>\n\n<pre><code>if (value % 2)\n</code></pre>\n\n<hr>\n\n<p>If you are not taking any parameters into <code>main()</code>, you should declare them <code>void</code>.</p>\n\n<pre><code>int main(void)\n</code></pre>\n\n<hr>\n\n<p>You don't have any <code>return</code> statement, yet you declare that you are returning an <code>int</code>. Let's return <code>0</code> at the end of our program to indicate success.</p>\n\n<pre><code>return 0;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T22:41:46.390",
"Id": "63577",
"Score": "1",
"body": "I believe `main` should also `return` something (`return 0;` is only implicit for C++ IIRC)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T22:43:16.920",
"Id": "63578",
"Score": "0",
"body": "@FrerichRaabe Good catch, I've edited that it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-20T16:16:13.260",
"Id": "185571",
"Score": "1",
"body": "@FrerichRaabe: Starting with the C99 standard, the compiler is required to generate the equivalent of a `return 0` or `return EXIT_SUCCESS` if no return is supplied at the end of `main`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T17:34:31.403",
"Id": "38186",
"ParentId": "38182",
"Score": "5"
}
},
{
"body": "<p>I'd go for a non standard function, because C sucks with bit operations:</p>\n\n<pre><code>#include <stdio.h>\n\n#ifdef __GNUC__\nint popcount(int x) {\n return __builtin_popcount(x);\n}\n#else\n#error Unimplemented popcount\n#endif\n\n\nint main(void)\n{\n int x;\n scanf(\"%d\", &x);\n\n printf(\"%d\\n\", popcount(x));\n\n return 0;\n}\n</code></pre>\n\n<p>This will be translated to efficient processor instructions where available, or an efficient library implementation where it's not.</p>\n\n<p>References:\n<a href=\"http://en.wikipedia.org/wiki/Hamming_weight\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Hamming_weight</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/15736602/fastest-way-to-count-number-of-1s-in-a-register-arm-assembly\">https://stackoverflow.com/questions/15736602/fastest-way-to-count-number-of-1s-in-a-register-arm-assembly</a></p>\n\n<p><a href=\"http://wm.ite.pl/articles/sse-popcount.html\" rel=\"nofollow noreferrer\">http://wm.ite.pl/articles/sse-popcount.html</a></p>\n\n<p><a href=\"http://gcc.gnu.org/onlinedocs/gcc-4.8.2/gcc/Other-Builtins.html#Other-Builtins\" rel=\"nofollow noreferrer\">http://gcc.gnu.org/onlinedocs/gcc-4.8.2/gcc/Other-Builtins.html#Other-Builtins</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T17:59:21.753",
"Id": "63641",
"Score": "1",
"body": "Why do you say that C sucks with bit operations?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T18:01:31.747",
"Id": "63642",
"Score": "1",
"body": "For compatibility, I would define `int CountOnesfromInteger(unsigned int value)` { #ifdef \\_\\_GNUC\\_\\_ return __builtin_popcount(value); #else /* Your own implementation */ #endif }`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T23:28:06.720",
"Id": "38201",
"ParentId": "38182",
"Score": "6"
}
},
{
"body": "<p>From a <a href=\"https://stackoverflow.com/a/109025/1157100\">StackOverflow answer</a>:</p>\n\n<pre><code>int CountOnesFromInteger(uint32_t i)\n{\n i = i - ((i >> 1) & 0x55555555);\n i = (i & 0x33333333) + ((i >> 2) & 0x33333333);\n return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;\n}\n</code></pre>\n\n<p>This is the best known implementation for the general case. The <a href=\"http://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation\" rel=\"nofollow noreferrer\">explanation</a> (see <code>popcount_3</code>) is that it works with groups of 2, 4, and 8 bits.</p>\n\n<p>The solution posted by @FilipeGonçalves is best for sparse bitsets.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T07:34:56.520",
"Id": "64115",
"Score": "1",
"body": "Yes! To the interested reader there's a whole chapter on this in Hacker's Delight by Warren."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T17:52:32.570",
"Id": "38229",
"ParentId": "38182",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T17:15:37.363",
"Id": "38182",
"Score": "26",
"Tags": [
"c",
"bitwise",
"integer"
],
"Title": "Counting number of 1's and 0's from integer with bitwise operation"
}
|
38182
|
<p>I would like to improve code readability and reduce the complexity of my code to improve the maintainability of the source code.</p>
<p>If you have any tips, please say so. I was also wondering if it would be a good feature to add a 2-player option to this game. Currently, the game runs off of a word list in which it randomly selects a word.</p>
<pre><code>package com.game;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
class GameStructure {
private String[] wordList = { "computer", "java", "activity", "alaska",
"appearance", "javatar", "automobile", "falafel", "birthday",
"canada", "central", "character", "chicken", "chosen", "cutting",
"daily", "darkness", "shawarma", "disappear", "driving", "effort",
"establish", "exact", "establishment", "fifteen", "football",
"foreign", "frequently", "frighten", "function", "gradually",
"hurried", "identity", "importance", "impossible", "invented",
"italian", "journey", "lincoln", "london", "massage", "minerals",
"outer", "paint", "particles", "personal", "physical", "progress",
"quarter", "recognise", "replace", "rhythm", "situation",
"slightly", "steady", "stepped", "strike", "successful", "sudden",
"terrible", "traffic", "unusual", "volume", "yesterday" };
private JTextField tf;
private JLabel jlLetsUsed;
static String letter;
static int[] wordLength = new int[64];
static int level = (int) (Math.random() * 64);// random word
static JFrame frame = new JFrame();
static ImageIcon bg = new ImageIcon("hangman1.png");
static ImageIcon logo = new ImageIcon("logo.png");
static ImageIcon ic = new ImageIcon("hangmanIcon.png");
JLabel img = new JLabel(bg, JLabel.CENTER);
public void window() {
bg = new ImageIcon("hangman1.png");
img.setIcon(bg);
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
menu.setMnemonic(KeyEvent.VK_A);
menuBar.add(menu);
JMenuItem menuItem = new JMenuItem("Developer", KeyEvent.VK_T);
menu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {// right click key
JOptionPane.showMessageDialog(frame, "Developer: Joe Eid"
+ "\n" + "\n" + "The Javatar", "Developer",
JOptionPane.INFORMATION_MESSAGE, logo);
}// end actionPerformed method
});
JMenuItem menuItem2 = new JMenuItem("Instructions", KeyEvent.VK_T);
menu.add(menuItem2);
menuItem2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {// right click key
JOptionPane
.showMessageDialog(
frame,
" Hangman is a guessing game where the word"
+ "\n"
+ " to guess is represented by dashes. The player"
+ "\n"
+ " is given the option to enter a letter. If the letter"
+ "\n"
+ " guessed is contained in the word, the letter will"
+ "\n"
+ " replace the dash in its approprate placement."
+ "\n"
+ " You can not exceed 6 wrong guesses or else you"
+ "\n"
+ " lose. Words are selected randomly.",
"Instructions",
JOptionPane.INFORMATION_MESSAGE, logo);
}// end actionPerformed method
});
JMenuItem menuItem3 = new JMenuItem("Restart", KeyEvent.VK_T);
menu.add(menuItem3);
menuItem3.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {// right click key
GameStructure restart = new GameStructure();
level = (int) (Math.random() * 64);// random word
restart.window();
}// end actionPerformed method
});
JMenuItem menuItem4 = new JMenuItem("Exit", KeyEvent.VK_T);
menu.add(menuItem4);
menuItem4.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {// right click key
System.exit(0);
}// end actionPerformed method
});
JFrame gameFrame = new JFrame();
JPanel bottomRight = new JPanel();
JPanel bottomLeft = new JPanel();
JPanel top = new JPanel();
JPanel bottom = new JPanel();
JPanel imgPane = new JPanel();
JPanel panel1 = new JPanel();
bottom.setLayout(new BoxLayout(bottom, BoxLayout.X_AXIS));
imgPane.setLayout(new BorderLayout());
panel1.setLayout(new BorderLayout());
panel1.setOpaque(false);// !!
top.setBorder(BorderFactory.createTitledBorder(""));
bottom.setBorder(BorderFactory.createTitledBorder(""));
tf = new JTextField(1);
JLabel jl = new JLabel("Enter a letter", JLabel.CENTER);
jlLetsUsed = new JLabel("Letters used: ", JLabel.CENTER);
final JLabel jlLines = new JLabel("__ ", JLabel.CENTER);
jl.setFont(new Font("Rockwell", Font.PLAIN, 20));
tf.setFont(new Font("Rockwell", Font.PLAIN, 20));
jlLetsUsed.setFont(new Font("Rockwell", Font.PLAIN, 20));
jlLines.setFont(new Font("Rockewell", Font.PLAIN, 20));
imgPane.add(img);// center
top.add(jl);// top center
top.add(tf);// top center
bottomLeft.add(jlLetsUsed);// bottom left position
bottomRight.add(jlLines);// bottom right position
bottom.add(bottomLeft);// bottom
bottom.add(bottomRight);// bottom
panel1.add(imgPane, BorderLayout.CENTER);// background image (center)
panel1.add(top, BorderLayout.NORTH);// text field and jlabel (top)
panel1.add(bottom, BorderLayout.SOUTH);// blank spaces and letters used
gameFrame.setJMenuBar(menuBar);
gameFrame.setTitle("Hangman");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.setIconImage(new ImageIcon("logo.png").getImage());
gameFrame.setResizable(false);
gameFrame.add(panel1);
gameFrame.setSize(800, 500);
gameFrame.setLocationRelativeTo(null);
gameFrame.setVisible(true);
int j = 0;
String line = "";
for (j = 0; j < 64; j++) {
wordLength[j] = wordList[j].length();// gets length of words
}// end for
int m = 0;
// creates line first then put into .setText
while (m < wordLength[level]) {
line += "__ ";
m++;
}// end for
jlLines.setText(line);
tf.addActionListener(new ActionListener() {
int wrong = 0;
int right = 0;
@Override
public void actionPerformed(ActionEvent e) {// enter key
JTextField tf = (JTextField) e.getSource();
letter = tf.getText();
tf.setText("");
// tf.requestFocus();
jlLetsUsed.setText(jlLetsUsed.getText() + letter + " ");// sets
// jlabel
// text
// to
// users
// entered
// letter
char[] jlabelText = jlLines.getText().toCharArray();// converts
// string to
// character
// array
// (array is
// length of
// string)
char userEnteredChar = letter.charAt(0);
// System.out.println(wordList[level]);
if (!wordList[level].contains(letter)) {
wrong++;
if (wrong == 1) {
bg = new ImageIcon("hangman2.png");
img.setIcon(bg);
}
if (wrong == 2) {
bg = new ImageIcon("hangman3.png");
img.setIcon(bg);
}
if (wrong == 3) {
bg = new ImageIcon("hangman4.png");
img.setIcon(bg);
}
if (wrong == 4) {
bg = new ImageIcon("hangman5.png");
img.setIcon(bg);
}
if (wrong == 5) {
bg = new ImageIcon("hangman6.png");
img.setIcon(bg);
}
if (wrong == 6) {
bg = new ImageIcon("hangman7.png");
img.setIcon(bg);
}
if (wrong == 6) {
JOptionPane
.showMessageDialog(frame, "He's dead." + "\n"
+ "Press 'OK' to restart." + "\n"
+ "The word was " + wordList[level]
+ ".", "You Lost",
JOptionPane.INFORMATION_MESSAGE, ic);
GameStructure restart = new GameStructure();
level = (int) (Math.random() * 64);// generate new
// random word
restart.window();
}
return;
}
int i = 0;
for (i = 0; i < wordList[level].length(); i++) {
if (wordList[level].charAt(i) == userEnteredChar) {
jlabelText[3 * i] = ' ';
jlabelText[3 * i + 1] = userEnteredChar;
right++;
}// end if
}// end for
jlLines.setText(String.valueOf(jlabelText));
if (jlabelText.length / 3 == right) {
JOptionPane.showMessageDialog(frame, "You got the word!"
+ "\n" + "Press 'OK' for new word", "Good Job",
JOptionPane.INFORMATION_MESSAGE, logo);
GameStructure restart = new GameStructure();
level = (int) (Math.random() * 64);// generate new
// random word
restart.window();
}
}// end actionPerformed method
});
}// end window method
}
public class GameMain {
public static void main(String[] args) {
GameStructure game = new GameStructure();
game.window();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T17:47:20.597",
"Id": "63540",
"Score": "0",
"body": "Is there a reason that you keep posting questions asking us to review similar code that you have had reviewed before?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T17:51:03.667",
"Id": "63543",
"Score": "1",
"body": "the others weren't a complete game, this is the completed game"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T18:02:21.177",
"Id": "63544",
"Score": "0",
"body": "@Malachi Agreed, but I can see some points that I would fix which I have mentioned before to the OP."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T18:06:00.477",
"Id": "63546",
"Score": "1",
"body": "there were some things in my code that I didn't change, mostly because I wasn't sure the code needed the changes at that specific step, etc"
}
] |
[
{
"body": "<p>Review these <a href=\"https://codereview.stackexchange.com/a/26907/20611\">general concepts</a> for a Hangman game. Notice how LazySloth13's hangman game and your hangman game are not reusable. That is, there is no way to take your vision of hangman and get the vision from LazySloth13, or vice-versa. Yet they are both hangman, and a simple version at that.</p>\n\n<p>Object-Oriented Programming has <em>reusability</em> as a core goal. A concept that helps achieve that goal is the <a href=\"http://en.wikipedia.org/wiki/Open/closed_principle\" rel=\"nofollow noreferrer\">Open-Closed Principle</a>, along with other <a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\" rel=\"nofollow noreferrer\">SOLID</a> practices. Both versions of hangman violate most of these principles in similar ways.</p>\n\n<p>Most predominately, the biggest violation is that there is no separation between the game's logic and the game's presentation. What if you wanted to port your game to the Web? A mobile device? A custom piece of hardware? As it stands, a lot of code would have to be re-written.</p>\n\n<p>Let's take a closer look at how the code violates the SOLID principles.</p>\n\n<h1>Single Responsibility</h1>\n\n<p>Each class should be limited to a single reason for changing it. In the given code, if I wanted to change the number of guesses or the list of words, there is only a single class. This tight coupling means that it is possible to affect the code for guesses by changing the code for the list of words. Ideally, we'd want this to be impossible.</p>\n\n<p>This points to the first change: create a <code>HangmanDictionary</code> class that is responsible for all aspects of the game's dictionary:</p>\n\n<ul>\n<li>Set the dictionary source (could be an array, an input stream, a database, or HTTP connection).</li>\n<li>Load a dictionary (for a given language).</li>\n<li>Return a randomly selected word.</li>\n</ul>\n\n<p>That's it. A dictionary doesn't know about guessing words. The mechanism behind guessing words is part of the rules.</p>\n\n<h1>Open-Closed Principle</h1>\n\n<p>Once a class is finished (i.e., it performs the single responsibility required), it should be closed from further modifications. In the code, it is impossible to change the font without changing the class itself:</p>\n\n<pre><code> jl.setFont(new Font(\"Rockwell\", Font.PLAIN, 20));\n tf.setFont(new Font(\"Rockwell\", Font.PLAIN, 20));\n jlLetsUsed.setFont(new Font(\"Rockwell\", Font.PLAIN, 20));\n jlLines.setFont(new Font(\"Rockewell\", Font.PLAIN, 20));\n</code></pre>\n\n<p>This is due to the tight coupling between the logic and the view, which points to the second change: create a class that is responsible for displaying the results of the guesses, called <code>HangmanView</code>. In it you might see:</p>\n\n<pre><code>protected Font getTextFont() {\n return new Font( \"Rockwell\", Font.PLAIN, 20 );\n}\n</code></pre>\n\n<p>If I wanted to change the font, now I could create a subclass of <code>HangmanView</code> and override a single method <code>getTextFont()</code>. Your original code would remain untouched, thereby ensuring to a great extent that my code would not introduce bugs in your code. (My code could still be buggy, but that's a different issue.)</p>\n\n<h1>Liskov Substitution</h1>\n\n<p>From <a href=\"http://www.cs.utsa.edu/~cs3443/designPrinciples.html\" rel=\"nofollow noreferrer\">CS 3443</a>,</p>\n\n<blockquote>\n <p>objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.</p>\n</blockquote>\n\n<p>I cannot substitute my own subclass of <code>GameStructure</code>. This is because there is only one method to override: <code>window()</code>, which contains the entirety of the program.</p>\n\n<p>The third change, which should be reasonably apparent by this time, is to separate the functionality of the <code>window()</code> method into various classes, each with its own single responsibility. What if I wanted to change how the restart functionality worked? Currently:</p>\n\n<pre><code>GameStructure restart = new GameStructure();\n level = (int) (Math.random() * 64);\n restart.window();\n</code></pre>\n\n<p>Note that it should not be required to create a new instance of the entire game just to reset it. Resetting \"hangman\" means telling the view to reset, telling the rules to reset (e.g., the number of guesses), and then picking a new random word. The above code should be included in a method such as:</p>\n\n<pre><code>public void reset() {\n getView().reset();\n getRules().setGuessWord( getDictionary().getRandomWord() );\n\n // Setting the new word to guess could call reset as it makes\n // little sense, in Hangman, to pick a new word but keep the\n // current tally of incorrect guesses.\n getRules().reset();\n}\n</code></pre>\n\n<p>Now, if I wanted to change the way resetting the works, I can simply override the <code>reset()</code> method. (For example, what if I wanted to make a difficulty level that, in English, chooses words without the letters R S T L N E?)</p>\n\n<h1>Interface Segregation</h1>\n\n<p>There's not much to say here except that there is no code that a client class can reuse. My <a href=\"https://codereview.stackexchange.com/a/26907/20611\">answer</a> to a similar question has details on how to separate the interfaces.</p>\n\n<h1>Dependency Inversion</h1>\n\n<p>Martin Fowler identified three types of <a href=\"http://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow noreferrer\">dependency injection</a>:</p>\n\n<ul>\n<li>Interface - clients must implement a specific interface.</li>\n<li>Setter - expose setter methods for injecting dependencies.</li>\n<li>Constructor - clients inject dependencies upon instantiation.</li>\n</ul>\n\n<p>I, personally, feel that classes should \"just work\" upon instantiation and tend to opt for setter injection. This implies a fourth change: use class-scoped variables that can be changed while the program is running.</p>\n\n<p>Assuming the addition of a <code>HangmanDictionary</code> class, I should see:</p>\n\n<pre><code>public class HangmanDictionary {\n // Objects should \"just work\", so give some initially valid data.\n private String[] words = { \"computer\", ... };\n\n public void load( File file ) {\n load( new FileInputStream( file ) );\n }\n\n public void load( InputStream i ) { \n String wordList[];\n\n // ... reads the words from an input stream\n\n // Now replace the words used for the game.\n setWords( wordList );\n }\n\n protected void setWords( String[] words ) {\n assert words != null;\n\n if( words.length > 0 ) {\n this.words = words;\n }\n }\n}\n</code></pre>\n\n<p>Now, at any point, the user can opt to change the dictionary for the game. Note that this would allow for switching the language, for example.</p>\n\n<h1>Specific Comments</h1>\n\n<p>There are a few comments I'd like to make about the code.</p>\n\n<pre><code>if (wrong == 1) {\n bg = new ImageIcon(\"hangman2.png\");\n img.setIcon(bg);\n}\n</code></pre>\n\n<p>You can eliminate all the tests for <code>wrong == #</code> with:</p>\n\n<pre><code> bg = new ImageIcon(\"hangman\" + wrong + \".png\");\n img.setIcon(bg);\n</code></pre>\n\n<p>Reduce the numbering; rename <code>hangman2.png</code> to <code>hangman1.png</code>, for example.</p>\n\n<p>The following code is, again, a violation of some of the principles described.</p>\n\n<pre><code>if (wrong == 6) { // ...\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>if( getRules().exceedsGuesses( wrong ) ) { // ...\n</code></pre>\n\n<p>Or, at the very least:</p>\n\n<pre><code>if( wrong == getMaxGuesses() ) { // ...\n</code></pre>\n\n<p>But this is not as flexible as using a rules class.</p>\n\n<p>Lastly, add a separate method to set up the user interface.</p>\n\n<pre><code>JFrame gameFrame = new JFrame();\n// ... code ...\nJPanel panel1 = new JPanel();\n// ... code ...\ngameFrame.setVisible(true);\n</code></pre>\n\n<p>Separate all of that code into another method, or, even better, a <code>HangmanView</code> class.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T20:14:18.953",
"Id": "38193",
"ParentId": "38187",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "38193",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T17:39:05.263",
"Id": "38187",
"Score": "3",
"Tags": [
"java",
"optimization",
"game",
"hangman"
],
"Title": "Complete Hangman game"
}
|
38187
|
<p>I should preface this question by saying that I'm a Java programmer working on my first C++ application, so perhaps there are certain obvious things I don't know.</p>
<p>Some background on the problem:</p>
<p>Our application had data read from a socket stored in a character array, which was a fixed length message header, containing various fixed length fields i.e.:</p>
<pre><code>char[15] data;
</code></pre>
<p>The field positions were 0-5,6-7,8-10,11-13 (the last char is a delimiter). The class which wrapped this header offered convenience functions to retrieve the values for each field:</p>
<pre><code> int ApiHeader::msg_size(void)
{
return std::atoi(std::string(data, 6).c_str());
}
int ApiHeader::msg_type(void)
{
return std::atoi(std::string(data,6,2).c_str());
}
int ApiHeader::msg_subtype(void)
{
return std::atoi(std::string(data,8,3).c_str());
}
int ApiHeader::seqno(void)
{
return std::atoi(std::string(data,11,3).c_str());
}
</code></pre>
<p>I was trying to leverage the <code>std::atoi</code> which requires a c-string, but I needed to "slice" the character array into the sub-arrays which contained each separate field, which I did by constructing a string built from the positions in the <code>data</code> array for each field.</p>
<p>The code worked fine, but a user who was doing some code analysis pointed that the <code>msg_subtype()</code> function (and the 2 other similar ones), were actually unintentionally creating an extra string object.</p>
<p>They were invoking this constructor:</p>
<pre><code>basic_string(const basic_string& other,
size_type pos,
size_type count = std::basic_string::npos,
const Allocator& alloc = Allocator() );
</code></pre>
<p>So the code was first constructing a new string to turn the <code>char[]</code> to a <code>string&</code>, and then it was constructing another string invoking the <code>string(string&, int, int)</code> constructor.</p>
<p>I redesigned the code to be more efficient:</p>
<pre><code>int atoi(char* string, int start, int length)
{
double result = 0;
char* index = string + start*sizeof(char);
for(int i=length;i>0; i--)
{
result += (*index++ - '0') * pow((float) 10, (float) (i-1));
}
return (int) result;
}
</code></pre>
<p>There are no strings constructed, and it just iterates the part of the <code>data</code> array specified. The problem is that this code <em>requires</em> that there is no way to detect whether the user passed bad values for <code>start</code> and <code>length</code>. (I'm not exactly sure what happens if user passes a length outside of the array. In my unit test, I just saw it got an uninitialized value).</p>
<p>What can be done to make this code more exception proof?</p>
<p>Some ideas I have are:</p>
<ul>
<li>If <code>*index</code> is not within valid range ('0' to '9'), break out of the loop.</li>
<li>Same as above, except throw an <code>Exception</code> (which at least lets user know something went wrong).</li>
<li>Just document the method to tell user that if values are bad, behavior is "undefined" (I have seen some methods documented this way).</li>
</ul>
<p>What would be the best C++ way of handling this issue? Or is there a completely different approach which should be used for this function?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T22:34:28.497",
"Id": "63575",
"Score": "0",
"body": "Do you have to call these functions multiple times for a single header? Have you considered having a couple of `int` variables in your `ApiHeader` class (assuming it's a class and not a namespace). That way, you only have to do the work of extracting from the array once."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T23:16:11.423",
"Id": "63662",
"Score": "0",
"body": "These functions are only called once per message. The data array is the header for a message. The socket reads the bytes directly into that array."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T20:32:44.270",
"Id": "63817",
"Score": "0",
"body": "In your 2nd update the test `length > sizeof(unsigned int)` is invalid. You are comparing the length of the ascii representation with the size of the binary result. Also note that `sizeof(char)` is 1 by definition"
}
] |
[
{
"body": "<p>First a question: why do you care that an extra string is being created? Is this function used <strong>a lot</strong>. If not, then I see no need to change. </p>\n\n<p>But beyond that, although I don't know about C++ cleverness, is your replacement function so much more efficient? You are calling <code>pow</code> repeatedly and using floating point to do an integer job. Here is an alternative that would be cheaper. It returns 0 on success, 1 on failure (bad string) and the number desired is output in <code>result</code>. Notice that <code>string</code> is <code>const</code>. </p>\n\n<pre><code>int my_atoi(const char* string, int start, int length, long *result)\n{\n char copy[length+1];\n memcpy(copy, string + start, length);\n copy[length] = '\\0';\n char *end;\n *result = strtol(copy, &end, 0);\n return (*end != '\\0');\n}\n</code></pre>\n\n<p>You might also omit the <code>start</code> parameter and call with </p>\n\n<pre><code>my_atoi(string+start, length, &res);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T21:09:04.957",
"Id": "63656",
"Score": "2",
"body": "Rather than return true/false. I would make it return a pointer one past the last character read. The function can then be used to parse integers out of the middle of a string. If they also want to test that all characters have been used they just de-reference the pointer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-22T03:02:50.530",
"Id": "370049",
"Score": "0",
"body": "VLAs are not legal in C++."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T23:54:32.783",
"Id": "38204",
"ParentId": "38189",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "38204",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T18:26:49.110",
"Id": "38189",
"Score": "2",
"Tags": [
"c++",
"beginner",
"strings",
"error-handling"
],
"Title": "Making a function which takes char* exception-proof"
}
|
38189
|
<p>I'm kinda curious how I'd refactor this in the best way. I've only used Linq for simple queries.</p>
<p><strong>What it does:</strong> </p>
<p>Depending on the type that is submitted, we're grouping events or payments by duration (eg. every year, every month, every day (for the moment).</p>
<p>I'd like to extend this to Quarterly and Weekly, but the class is getting to bulky.</p>
<p>Any tips on refactoring this?</p>
<pre><code> public ActionResult Generate(MembershipManagement.ViewModels.ReportViewModel vm)
{
var chart = new ViewModels.ChartData();
Club club = Helpers.SiteHelper.GetCurrentClub();
List<DateTime> x_values = new List<DateTime>();
DateTime i = vm.StartDate.Date;
//go back to the first occurence of this duration
switch (vm.Duration)
{
case Enums.ReportDuration.Month:
i = i.AddDays(-(i.Day - 1));
break;
case Enums.ReportDuration.Quarterly:
//add check - 4 maand
i = i.AddDays(-(i.Day - 1));
break;
case Enums.ReportDuration.Year:
i = i.AddDays(-(i.Day - 1));
i = i.AddMonths(-(i.Month - 1));
break;
}
//case Enums.ReportDuration.Week:
// i = i.AddDays(7);
// if (i.Day <= 6)
// {
// i = i.AddDays(-(i.Day - 1));
// }
// break;
//add x-as values (not required currently, perhaps for refactoring this as it contains the limits of the x-as.
while (i <= vm.EndDate)
{
x_values.Add(i);
switch (vm.Duration)
{
case Enums.ReportDuration.Quarterly:
x_values.Add(i);
i = i.AddMonths(4);
break;
case Enums.ReportDuration.Month:
x_values.Add(i);
i = i.AddMonths(1);
break;
case Enums.ReportDuration.Year:
x_values.Add(i);
i = i.AddYears(1);
break;
default:
x_values.Add(i);
i = i.AddDays(1);
break;
}
}
switch (vm.Source)
{
case Enums.ReportSource.Attendance:
//1
List<ViewModels.ChartValue> attendance_data = null;
var attendance_raw_data = db.Attendances.Where(el => el.ClubId.Equals(club.Id) && ( el.On >= vm.StartDate && el.On <= vm.EndDate)).OrderBy(dl => dl.On);
var attendance_filtered_data = attendance_raw_data.Select(dl => new { On = dl.On, Count = dl.Count }).ToList();
switch (vm.Duration)
{
case Enums.ReportDuration.Day:
chart.Period = "day";
attendance_data = (from o in attendance_filtered_data
group o by o.On.ToString("yyyy-MM-dd") into g
select new ViewModels.ChartValue { x = g.Key, value = g.Sum(dl => dl.Count) }).ToList();
break;
case Enums.ReportDuration.Month:
chart.Period = "month";
attendance_data = (from o in attendance_filtered_data
group o by o.On.ToString("yyyy-MM") into g
select new ViewModels.ChartValue { x = g.Key, value = g.Sum(dl => dl.Count) }).ToList();
break;
case Enums.ReportDuration.Quarterly:
break;
case Enums.ReportDuration.Year:
chart.Period = "year";
attendance_data = (from o in attendance_filtered_data
group o by o.On.ToString("yyyy") into g
select new ViewModels.ChartValue { x = g.Key, value = g.Sum(dl => dl.Count) }).ToList();
break;
}
chart.Labels.Add("Aanwezigheden");//= attendance_data.Select(el => System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(int.Parse(el.x.Substring(5, 2)))).ToList();
chart.data = attendance_data;
chart.xkey = "x";
chart.yKeys.Add("value");
//chart.Period = "month";
//2
//var raw_data = db.Attendances.Where(el => el.ClubId.Equals(club.Id) && (el.On >= vm.StartDate && el.On <= vm.EndDate)).OrderBy(dl => dl.On)
// .Select(dl => new { On = dl.On, Count = dl.Count}).ToList();
//var att_data = from year in Enumerable.Range(vm.StartDate.Year,vm.EndDate.Year - vm.StartDate.Year)
// from month in Enum
break;
case Enums.ReportSource.Financial:
var financial_raw_data = db.Payments.Where(el => el.ClubId.Equals(club.Id) &&( el.On >= vm.StartDate && el.On <= vm.EndDate)).OrderBy(dl => dl.On);
var financial_filtered_data = financial_raw_data.Select(dl => new { On = dl.On, Value = dl.Amount * (int)dl.InOrOut }).ToList();
List<ViewModels.ChartValue> financial_data = null;
switch (vm.Duration)
{
case Enums.ReportDuration.Day:
chart.Period = "day";
financial_data = (from o in financial_filtered_data
group o by o.On.ToString("yyyy-MM-dd") into g
select new ViewModels.ChartValue { x = g.Key, value = (int)g.Sum(el => el.Value) }).ToList();
break;
case Enums.ReportDuration.Month:
chart.Period = "month";
financial_data = (from o in financial_filtered_data
group o by o.On.ToString("yyyy-MM") into g
select new ViewModels.ChartValue { x = g.Key, value = (int)g.Sum(el => el.Value) }).ToList();
break;
case Enums.ReportDuration.Quarterly:
break;
case Enums.ReportDuration.Year:
chart.Period = "year";
financial_data = (from o in financial_filtered_data
group o by o.On.ToString("yyyy") into g
select new ViewModels.ChartValue { x = g.Key, value = (int)g.Sum(el => el.Value) }).ToList();
break;
}
chart.Labels.Add("Financiëel");// financial_data.Select(el => System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(int.Parse(el.x.Substring(5, 2))) + " €").ToList();
chart.data = financial_data;
chart.xkey = "x";
chart.yKeys.Add("value");
break;
default:
break;
}
/*
* 1
*
* var query = repository.Flights .GroupBy(flight => flight.Date.Day) .OrderBy(group => group.Key) .ToList();
*
* var xValues = query.Select(group => group.Key).ToList();
* totalDelaySeries.Points.DataBindXY( xValues, query.Select( group => group.Sum( flight => flight.ArrivalDelay)).ToList());
* weatherDelaySeries.Points.DataBindXY( xValues, query.Select( group => group.Sum( flight => flight.WeatherDelay)).ToList());
*
* var overThresholdPoints = taxiOutSeries.Points .Where(p => p.YValues.First() > _taxiThreshold);
* foreach (var point in overThresholdPoints) { point.Color = Color.Red; }
*
* 2
*
* var sales = from o in context.Orders
* where o.DatePlaced.Value.Year == year
* group o by o.DatePlaced.Value.Month into g
* select new {Month = g, Orders = g.Count()};
*
* foreach (var sale in sales)
* SalesChart.Series["Series1"].Points
* .AddXY(Enum.Parse(typeof(Month),
* sale.Month.FirstOrDefault().DatePlaced.Value.Month.ToString()).ToString(),
* (double)sale.Orders);
*/
vm.chartData = chart;
return View(vm);
}
</code></pre>
<p>Post answer - Refactored outcome:</p>
<pre><code>public ActionResult Generate(MembershipManagement.ViewModels.ReportViewModel vm)
{
Club club = Helpers.SiteHelper.GetCurrentClub();
//calculate the first date
DateTime reportStartDate = ChartExtensions.StartDateSelector[vm.Duration](vm.StartDate.Date);
//generate chart
vm.chartData = GenerateChartByType[vm.Source](club.Id, vm.StartDate, vm.EndDate, vm.Duration);
return View(vm);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T04:29:24.550",
"Id": "63872",
"Score": "0",
"body": "You turned that monster into a 4-liner! Well done! Remember that comments say *why*, the **code** says *what*. Also I'm not sure about calling a dictionary `GenerateChartByType` - that's a name for a method, but it's a *dictionary of methods* you have in there; also, if it's more readable (probably is), you could separate the dictionary value extraction from the method call, like `var someDelegate = GenerateChartByType[vm.Source];`. Don't hesitate to post your refactored code as another CR question! *Feed the dragon!*"
}
] |
[
{
"body": "<p>The problem is that you have a method that does many, many, <em>many</em> things.</p>\n\n<p>The first thing I'd address is the <code>switch</code> blocks; a common way of refactoring those, is to use a <code>Dictionary<TKey,TValue></code>.</p>\n\n<blockquote>\n<pre><code> DateTime i = vm.StartDate.Date;\n\n //go back to the first occurence of this duration\n switch (vm.Duration)\n { \n case Enums.ReportDuration.Month:\n i = i.AddDays(-(i.Day - 1));\n break;\n case Enums.ReportDuration.Quarterly:\n //add check - 4 maand\n i = i.AddDays(-(i.Day - 1));\n break;\n case Enums.ReportDuration.Year:\n i = i.AddDays(-(i.Day - 1));\n i = i.AddMonths(-(i.Month - 1));\n break;\n }\n</code></pre>\n</blockquote>\n\n<p>Here you'd have a method for each case, whose role is to determine the value of <code>i</code> (which is a very, very naughty name for a <code>DateTime</code>). Something along these lines:</p>\n\n<pre><code>private DateTime GetMonthlyReportStartDate(DateTime date)\n{\n return date.AddDays(-(date.Day - 1));\n}\n\nprivate DateTime GetQuarterlyReportStartDate(DateTime date)\n{\n //add check - 4 maand // <~ whatever that means\n return date.AddDays(-(date.Day - 1));\n}\n\nprivate DateTime GetYearlyReportStartDate(DateTime date)\n{\n return date.AddDays(-(date.Day - 1))\n .AddMonths(-(date.Month - 1));\n}\n</code></pre>\n\n<p>Then you map each method to a <code>Dictionary</code> value:</p>\n\n<pre><code>var reportStartDateSelector = new Dictionary<Enums.ReportDuration, Func<DateTime, DateTime>>\n {\n { Enums.ReportDuration.Month, GetMonthlyReportStartDate },\n { Enums.ReportDuration.Quarterly, GetQuarterlyReportStartDate },\n { Enums.ReportDuration.Year, GetYearlyReportStartDate }\n };\n</code></pre>\n\n<p>Armed with such a dictionary, you can now replace the whole <code>switch</code> block like this:</p>\n\n<pre><code>var reportStartDate = reportStartDateSelector[vm.Duration](vm.StartDate.Date);\n</code></pre>\n\n<p>Rinse & repeat for all <code>switch</code> blocks; before you know it your <code>Generate</code> method will be much easier to follow (and debug!).</p>\n\n<hr>\n\n<p>As you're refactoring your <code>switch</code> blocks into methods, you'll notice the redundant query code can be passed as some <code>filteredData</code> parameter (thus eliminating the redundancy) - notice I didn't put an underscore in the variable's name.</p>\n\n<p>That said, this line:</p>\n\n<pre><code>Club club = Helpers.SiteHelper.GetCurrentClub();\n</code></pre>\n\n<p>Smells like <em>ambient context</em> to me. That would be the next thing I'd address; static helper classes are a nuisance if you want your code to be testable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T03:47:12.037",
"Id": "63597",
"Score": "0",
"body": "Yeah, i'm using a static SiteHelper (most of the time) to get an object i use a lot. \nAny docs on refactoring that? (currently it's helped me... But always open to suggestions..)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T03:50:16.393",
"Id": "63599",
"Score": "0",
"body": "PS. You've shown some great refactoring (and things i'll use in the future)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T17:38:46.267",
"Id": "63958",
"Score": "0",
"body": "So you're saying that for each switch, there should be a separate dictionary of delegates? I think that a single dictionary of objects that implement an interface (something like IPeriod) would be much cleaner."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T20:41:40.720",
"Id": "38196",
"ParentId": "38192",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "38196",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T20:08:55.950",
"Id": "38192",
"Score": "5",
"Tags": [
"c#",
"linq"
],
"Title": "Refactoring chart generator in Linq"
}
|
38192
|
<p>I'm playing around with switching some code to using <code>Parallel.ForEach</code> and I have a question about whether I need to be concerned about the effects of concurrency here. Here's a simplified version of what I'm doing:</p>
<pre><code>public IList<Item> RetrieveAllItems(int paramValue)
{
var itemFuncs = new List<Func<int, IEnumerable<Item>>>
{
RetrieveItems1,//one method to retrieve items, taking an int param
RetrieveItems2//another one that takes an int param
};
List<Item> allItems = new List<Item>();
Parallel.ForEach(itemFuncs, (f) =>
{
//is this a problem?
allItems.AddRange(f(paramValue));
});
return allItems;
}
</code></pre>
<p>For this application, I do not care about the order that my <code>Item</code> objects are added to <code>allItems</code> (in fact, I do explicit ordering later on). My question is whether I could get into trouble here with both functions attempting to add <code>Item</code> objects at the same time. </p>
<p>My motivation for playing around with this is simply to try to speed up this sequence of events, and when I tried using a <code>BlockingCollection</code> instead, my timings, obviously slowed down to the point that there was hardly any difference between doing these two operations in parallel versus the old, serial way. When I use a simple <code>List<Item></code> then I do see impressive speed-ups.</p>
<p>So, considering I am just adding objects to a collection in a parallel fashion, is using a non-thread safe collection asking for trouble here? My real-world experience with multi-threaded/parallel programming is very sparse, hence the uncertainty here.</p>
|
[] |
[
{
"body": "<p>If you only need to return an <code>IEnumerable<Item></code> you could simply enumerate to <code>List</code>s and then <code>Concat</code> the results.</p>\n\n<p>Otherwise you could consider using a linked list, enumerating in parallel and then again <code>Concat</code>enating for O(1).</p>\n\n<p>About the original question: yes, that code is dangerous and prone to race conditions</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T22:41:33.133",
"Id": "38199",
"ParentId": "38197",
"Score": "0"
}
},
{
"body": "<p>Yes, what you are doing is a problem. <code>List</code> is not thread-safe and adding items from multiple threads can lead to data corruption (for example individual elements overwriting each other).</p>\n\n<p>You said that you don't care about the order of items inserted quickest fix is to use <a href=\"http://msdn.microsoft.com/en-us/library/dd381779%28v=vs.110%29.aspx\" rel=\"noreferrer\"><code>ConcurrentBag</code></a></p>\n\n<p>Another option is to the PLINQ extensions and use the <a href=\"http://msdn.microsoft.com/en-us/library/dd383966%28v=vs.110%29.aspx\" rel=\"noreferrer\"><code>Select</code> extension of the <code>ParallelQuery</code></a>. The code would look like this:</p>\n\n<pre><code>return itemFuncs.AsParallel().SelectMany(f => f(paramValue)).ToList();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T22:48:34.600",
"Id": "63581",
"Score": "1",
"body": "Thanks for the tips and answer. Another way of asking about this would have been for me to ask if adding items to a `List` is an atomic operation. Apparently, it isn't so that is good to know."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T22:53:04.293",
"Id": "63582",
"Score": "0",
"body": "One correction, I'd need to use `itemFuncs.AsParallel().SelectMany(f => f(paramValue)).ToList();` otherwise I have a nested collection."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T01:35:40.463",
"Id": "63593",
"Score": "0",
"body": "@ledbutter: Ah yes, I missed that, corrected now."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T22:42:03.573",
"Id": "38200",
"ParentId": "38197",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T21:59:11.223",
"Id": "38197",
"Score": "6",
"Tags": [
"c#",
"task-parallel-library"
],
"Title": "Is Concurrent Collection Needed Here?"
}
|
38197
|
<p>I wrote my very first login/register PDO system today. I know there is still a lot of flaws, but I was wondering what tips and advice you have to help me improve this. I know that PDO is much more secure than MySQl, so would you say my code is secure? If so, to what extent, since I'm using PDO? Any tips and advice would be much appreciated! </p>
<p>login.php</p>
<pre><code><h1>Login</h1>
<form method="POST">
<input type="text" name="username"><br />
<input type="password" name="password"><br />
<input type="submit">
</form>
<?php
session_start();
if(isset($_POST['username'], $_POST['password'])){
require 'core/connect.php';
$query = dbConnect()->prepare("SELECT username, password FROM users WHERE username=:username AND password=:password");
$query->bindParam(':username', $_POST['username']);
$query->bindParam(':password', $_POST['password']);
$query->execute();
if($row = $query->fetch()){
$_SESSION['username'] = $row['username'];
header("Location: index.php");
}
}
?>
</code></pre>
<p>register.php</p>
<pre><code><h1>Register</h1>
<form method="POST">
<input type="text" name="username"><br />
<input type="password" name="password"><br />
<input type="submit">
</form>
<?php
session_start();
if(isset($_POST['username'], $_POST['password'])){
require 'core/connect.php';
$query = dbConnect()->prepare("INSERT INTO users (username, password) VALUES (:username, :password)");
$query->bindParam(':username', $_POST['username']);
$query->bindParam(':password', $_POST['password']);
if($query->execute()){
header("Location: index.php");
} else{
echo 'ERROR';
}
}
?>
</code></pre>
<p>index.php</p>
<pre><code><?php
session_start();
if(isset($_SESSION['username'])){
echo 'Welcome!', '<a href="logout.php">Logout</a>';
} else {
echo '<a href="login.php">Login</a><br />
<a href="register.php">Register</a>';
}
?>
</code></pre>
<p>core/connect.php</p>
<pre><code><?php
function dbConnect(){
try{
$username = 'root';
$password = '';
$conn = new pdo("mysql:host=localhost;dbname=test;", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
} catch(PDOException $e){
echo 'ERROR', $e->getMessage();
}
}
?>
</code></pre>
|
[] |
[
{
"body": "<p>Here are several tips:</p>\n\n<ul>\n<li>Use OOP - this way you could start the session only once</li>\n<li>Hash your passwords - this way no one can steal it from the db, or at least the chance is lower</li>\n<li>Use MVC - separate your HTML from the PHP code</li>\n<li>Move your db connect credentials to the .ini file - this way it could be easily changed and .ini files can be cached by the server</li>\n</ul>\n\n<p>Feel free to check <a href=\"https://bitbucket.org/t1gor/strategy/src/4568202177890480e4cc0268b4458889bc6bf0ae/application/model/player/Player.php?at=default#cl-180\" rel=\"nofollow\">my code</a> for user authorization here in my pet project.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T17:23:08.907",
"Id": "66162",
"Score": "0",
"body": "OOP - http://en.wikipedia.org/wiki/Object-oriented_programming"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T17:23:28.390",
"Id": "66163",
"Score": "0",
"body": "MVC - http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-09-06T07:53:18.227",
"Id": "331920",
"Score": "0",
"body": "@user3121014 I would appreciate if you could tick the answer if it helped."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-17T17:22:58.747",
"Id": "39490",
"ParentId": "38202",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T23:43:40.290",
"Id": "38202",
"Score": "5",
"Tags": [
"php",
"mysql",
"beginner",
"security",
"pdo"
],
"Title": "PDO Login/Register system review"
}
|
38202
|
<p>This week's <a href="https://codereview.meta.stackexchange.com/a/1324/23788">Code Review Weekend Challenge</a> is about implementing a simple console game.</p>
<p>Here's my game loop:</p>
<pre><code>class Program
{
static void Main(string[] args)
{
var player = new Player();
var intro = new IntroScreen(player);
var nextScreen = intro.Run();
while (nextScreen != null)
{
nextScreen = nextScreen.Run();
}
}
}
</code></pre>
<p>So I have a <code>Player</code> class:</p>
<pre><code>public class Player
{
public string Name { get; set; }
public ObservableCollection<InventoryItem> Inventory { get; private set; }
public Player()
{
Inventory = new ObservableCollection<InventoryItem>();
Inventory.CollectionChanged += Inventory_CollectionChanged;
}
private void Inventory_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action != NotifyCollectionChangedAction.Add) return;
foreach (InventoryItem item in e.NewItems)
{
Console.WriteLine("Received '{0}'!\n({1})", item.Name, item.Description);
}
Console.WriteLine();
Console.ReadLine();
}
public bool HasItem(string name)
{
return Inventory.Any(item => item.Name.ToLower() == name.ToLower());
}
}
</code></pre>
<p>The player has an <code>Inventory</code> that's made up of <code>InventoryItem</code> instances:</p>
<pre><code>public struct InventoryItem
{
public string Name { get; set; }
public string Description { get; set; }
}
</code></pre>
<p>So the role of the <code>Player</code> is really to carry an inventory, whatever that is; whenever an item is added to the player's inventory, there's an output to the console.</p>
<p>The game's mechanics are tucked inside a <code>GameScreen</code> abstract class:</p>
<pre><code>public abstract class GameScreen
{
protected IDictionary<string, Func<GameScreen>> MenuItems;
public abstract GameScreen Run();
protected void Write(string text)
{
Console.Write(text);
Console.WriteLine();
Console.WriteLine("[ENTER]");
Console.ReadLine();
}
protected string Prompt(string text)
{
Console.WriteLine(text);
var result = Console.ReadLine();
Console.WriteLine();
return result;
}
protected GameScreen Menu()
{
Console.WriteLine("What do you do?");
var i = 0;
foreach (var item in MenuItems)
{
i++;
Console.WriteLine("[{0}] {1}", i, item.Key);
}
Console.WriteLine();
Console.WriteLine("Selection?");
var input = Console.ReadLine();
int selection;
if (int.TryParse(input, out selection))
{
if (selection > 0 && selection <= MenuItems.Count)
{
return MenuItems.ElementAt(selection - 1).Value();
}
}
return null;
}
}
</code></pre>
<hr>
<p>This is a tiny little game, here's the <code>IntroScreen</code> and <code>KitchenScreen</code> implementations:</p>
<pre><code>public class IntroScreen : GameScreen
{
private readonly Player _player;
public IntroScreen(Player player)
{
MenuItems = new Dictionary<string,Func<GameScreen>>
{
{"Pick up empty bottles, chips and pretzels", () =>
{
MenuItems.Remove("Pick up empty bottles, chips and pretzels");
_player.Inventory.Add(new InventoryItem { Name = "Living Room badge", Description = "A badge that certifies the living room has been cleaned up." });
return this;
} },
{"Go to [KITCHEN]", () => new KitchenScreen(player) }
};
_player = player;
}
public override GameScreen Run()
{
Console.Clear();
if (!_player.HasItem("GREEN BAG")) return Intro();
return Menu();
}
private GameScreen Intro()
{
Write("You wake up with a headache, confused and\nsurrounded with empty bottles, chips and pretzels.");
Write("Ah! There you are! Time to clean up this mess!\nHere's a [GREEN BAG], meet you in the [KITCHEN] in 30 minutes!");
var bag = new InventoryItem { Name = "GREEN BAG", Description = "A general-purpose garbage bag." };
_player.Inventory.Add(bag);
var name = string.Empty;
int attempts = 0;
while (string.IsNullOrEmpty(name))
{
attempts++;
string prompt;
if (attempts == 1)
{
prompt = "You get up, pick up the bag and remember your name (enter it!):";
name = Prompt(prompt);
}
else if (attempts < 3)
{
prompt = "Uh, don't you remember your name?";
name = Prompt(prompt);
}
else
{
name = "Rudolph";
prompt = string.Format("Ok nevermind, we'll call you {0}.", name);
Write(prompt);
}
}
_player.Name = name;
return Menu();
}
}
public class KitchenScreen : GameScreen
{
private readonly Player _player;
public KitchenScreen(Player player)
{
MenuItems = new Dictionary<string, Func<GameScreen>>
{
{ "Go to [LIVING ROOM]", () => new IntroScreen(player) }
};
_player = player;
}
public override GameScreen Run()
{
Console.Clear();
if (_player.HasItem("Living Room badge"))
{
Write("You walk into the kitchen, your mom looks too happy.");
Write(_player.Name + ", finally! So you cleaned up everything! Great! So we're ready for NewYear's party!");
MenuItems = new Dictionary<string, Func<GameScreen>> { { "Collapse and wake up when the Holidays are over", () => null } };
}
else
{
Write("You walk into the kitchen, your mom is cleaning up dishes.");
Write(_player.Name + "! What are you doing here? I told you to clean up! Come back when you're done!");
}
return Menu();
}
}
</code></pre>
<hr>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>You wake up with a headache, confused and surrounded with empty bottles, chips and pretzels.
[ENTER]
Ah! There you are! Time to clean up this mess! Here's a [GREEN BAG], meet you in the [KITCHEN] in 30 minutes!
[ENTER]
Received 'GREEN BAG'!
(A general-purpose garbage bag.)
You get up, pick up the bag and remember your name (enter it!):
Uh, don't you remember your name?
Ok nevermind, we'll call you Rudolph.
[ENTER]
What do you do?
[1] Pick up empty bottles, chips and pretzels
[2] Go to [KITCHEN]
Selection?
2
You walk into the kitchen, your mom is cleaning up dishes.
[ENTER]
Rudolph! What are you doing here? I told you to clean up! Come back when you're
done!
[ENTER]
What do you do?
[1] Go to [LIVING ROOM]
Selection?
1
What do you do?
[1] Pick up empty bottles, chips and pretzels
[2] Go to [KITCHEN]
Selection?
1
Received 'Living Room badge'!
(A badge that certifies the living room has been cleaned up.)
What do you do?
[1] Go to [KITCHEN]
Selection?
1
You walk into the kitchen, your mom looks too happy.
[ENTER]
Rudolph, finally! So you cleaned up everything! Great! So we're ready for NewYear's party!
[ENTER]
What do you do?
[1] Collapse and wake up when the Holidays are over
Selection?
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T23:46:40.327",
"Id": "63584",
"Score": "0",
"body": "Well that was fast... you only accepted the CRWEC a few minutes ago :P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T23:48:47.633",
"Id": "63585",
"Score": "2",
"body": "@syb0rg I figured there wouldn't be a random new suggestion to beat the leading one, so I wrote this code earlier today - was either that or I couldn't post my entry this week :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T19:20:57.653",
"Id": "63922",
"Score": "3",
"body": "Typo: \"You walk into the kitchen, you mom is cleaning up dishes.\" -> *your* mom."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T14:35:18.020",
"Id": "65512",
"Score": "1",
"body": "I like it. Just a few questions though,\n \n- Why Expose Inventory as ObservableCollection rather than an Inventory class with some helper functions?\n- I'd throw the \"what do you do\" strings n such to consts.\n- and I am really curious about the foreach with the index, why not a for loop?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-12-08T20:52:56.853",
"Id": "280884",
"Score": "0",
"body": "I had to add the following in order for the program to run.\nusing System.Collections.ObjectModel;\nusing System.Collections.Specialized;"
}
] |
[
{
"body": "<p>Well, i am new to this weekend-challenge thing so I am not sure, from which stand point should i review such question. I'll give it a try.</p>\n\n<ol>\n<li><p>I like your game loop. Its simple and makes sense. It can be simlified further though:</p>\n\n<pre><code>var activeScreen = new IntroScreen(player);\nwhile (activeScreen != null) // do-while, if you are not a hater ;)\n{\n activeScreen = activeScreen.Run();\n}\n</code></pre></li>\n<li><p>I don't like your intro screen. It feels like it consists of two separate screens (1 - where you try to recall your name, 2 where you clean up). As it is - it is somewhat difficult to follow the execution path.</p></li>\n<li><p>I think instead of being a protected method <code>Menu</code> should be an actual screen class which accepts options as constructor parameter. That would simplify reading.</p></li>\n<li><p>I dont like the use of an observable collection, i think it is an overkill. And it exposes the methods it should not. A simple wrapper around List which only exposes <code>AddItem</code> and <code>HasItem</code> methods would be much batter. At very least - collection should not be public.</p></li>\n<li><p><code>Player</code> should probably be a protected property of your base screen.</p></li>\n<li><p><code>return Inventory.Any(item => item.Name.ToLower() == name.ToLower());</code> I think <code>ToLower()</code> is confusing. Imho you should not manipulate properties which you use as an ID. Its better to make sure that all the green bags are called \"GREEN BAG\" instead (by saving it to constant field, for example)</p></li>\n<li><p>In general, i do not like implementation which uses hardcoded strings. I think that proper implementation should use scripts or (if the implementation should be C#-only) XML parsing. But i guess its a bit too much work for a two-hour challenge, right? :)</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T06:39:49.157",
"Id": "39357",
"ParentId": "38203",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "39357",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-27T23:45:10.930",
"Id": "38203",
"Score": "13",
"Tags": [
"c#",
"game",
"console",
"community-challenge"
],
"Title": "Simple Text Adventure: Cleaning up after the party"
}
|
38203
|
<p>I am using the <a href="http://curl.haxx.se/" rel="nofollow">cURL</a> tool in MATLAB 2013b with Ubuntu to download a whole bunch of files. The files have one of three possible versions: 1.0.0, 2.0.0, or 2.1.0. Using the HTTP, I first check the headers with three queries to see which version exists. Then whichever exists I download it. If none exists (because of nonexistent dates) then I just move on.</p>
<p>Is there any other more efficient way of querying and then downloading the files? For example, check 1.0.0. If it exists, download it. If it doesn't exist then check 2.0.0 and so on. The only way I can think of doing that was some very ugly nested if-elseif statements. But this way, I query three times no matter what so a little wasteful I think.</p>
<p>Also any other comments on my coding style are welcome.</p>
<pre><code> clc
close all
clear all
for y = 2012:2013
for m = 1:12
for d = 1:31
% To limit the dates because of the available data
if y==2012 && m < 9
continue
elseif y==2013 && m > 9
break
end
% The date string is created with padded zeros
if (m < 10) && (d < 10)
thedate = [num2str(y) '0' num2str(m) '0' num2str(d)];
elseif m < 10
thedate = [num2str(y) '0' num2str(m) num2str(d)];
elseif d < 10
thedate = [num2str(y) num2str(m) '0' num2str(d)];
else
thedate = [num2str(y) num2str(m) num2str(d)];
end
newname = ['ephemA' thedate '.h5']
% The entire file name is created
thefile = ['http://www.rbsp-ect.lanl.gov/data_pub/rbspa/MagEphem/def/rbspa_def_MagEphem_TS04D_' thedate];
% Use curl with --head flag to check the header to see which version exists
[status, result1] = system(['curl --head ' thefile '_v1.0.0.h5']);
[status, result2] = system(['curl --head ' thefile '_v2.0.0.h5']);
[status, result3] = system(['curl --head ' thefile '_v2.1.0.h5']);
% 200 means the file exists and is downloaded
if ~isempty(strfind(result1,'HTTP/1.1 200'))
[status, result] = system(['curl -o ' newname ' ' thefile '_v1.0.0.h5']);
elseif ~isempty(strfind(result2,'HTTP/1.1 200'))
[status, result] = system(['curl -o ' newname ' ' thefile '_v2.0.0.h5']);
elseif ~isempty(strfind(result3,'HTTP/1.1 200'))
[status, result] = system(['curl -o ' newname ' ' thefile '_v2.1.0.h5']);
end
end
end
end
</code></pre>
|
[] |
[
{
"body": "<p>Why don't you read the index from <a href=\"http://www.rbsp-ect.lanl.gov/data_pub/rbspa/MagEphem/def/\" rel=\"nofollow\">http://www.rbsp-ect.lanl.gov/data_pub/rbspa/MagEphem/def/</a> and use that to decide which files you want to download?</p>\n\n<p>Also, try to give multiple files (eg. 20) to each <code>curl</code> call: this will enable curl to <a href=\"http://curl.haxx.se/docs/faq.html#What_about_Keep_Alive_or_persist\" rel=\"nofollow\">reuse the same connection for those files</a>.</p>\n\n<p>Please also note that Matlab is not the right tool for this job. For example, this would be easier in Python which has many libraries to perform HTTP requests.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T20:29:56.660",
"Id": "63655",
"Score": "0",
"body": "I am doing this in MATLAB because I do much more to the file when I download it. So instead of simply saving it, I download the file, process it, keep the data I want, and then delete it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T11:11:40.910",
"Id": "38218",
"ParentId": "38205",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "38218",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T01:09:08.583",
"Id": "38205",
"Score": "2",
"Tags": [
"performance",
"http",
"matlab",
"curl"
],
"Title": "Downloading the oldest available version of some data files"
}
|
38205
|
<p>I have a <code>myCon=getUnusedConnection()</code> method that gets a connection from <code>Connection</code> pool. I also have a <code>releaseConnection(myCon)</code> method to release <code>Connection</code> to the pool after finishing using it.</p>
<p>When coding, I need to select data from the database many times. I also want to reuse my code. I want to have many methods for a single action.</p>
<p>Example:</p>
<pre><code>public static List<String[]> getData(){
Connection myCon=null;
PreparedStatement preparedStmt=null;
try{
myCon=getUnusedConnection();
String sql="select ........";
preparedStmt=myCon.prepareStatement(sql);
ResultSet results=preparedStmt.executeQuery();
String str="";
if(results.next()){
str=results.getString(1);
}
if(!str.equals("")){
List<String[]> list=getData2(myCon, preparedStmt, str);
}
return list;
}
catch (SQLException ex) {
while (ex != null) {
System.out.println ("SQL Exception: " +
ex.getMessage ());
ex = ex.getNextException ();
}
}catch (java.lang.Exception e) {
System.out.println("***ERROR-->" + e.toString());
}
finally{
releaseConnection (myCon);
closeStatement (preparedStmt);
}
return null;
}
public static List<String[]> getData2(Connection myCon, PreparedStatement preparedStmt, String str){
try{
List<String[]> list=new ArrayList<String[]>();
String sql="c.......";
preparedStmt=myCon.prepareStatement(sql);
ResultSet results=preparedStmt.executeQuery();
while(results.next()){
list.add(results.getString(1));
}
return list;
}catch (SQLException ex) {
while (ex != null) {
System.out.println ("SQL Exception: " +
ex.getMessage ());
ex = ex.getNextException ();
}
}catch (java.lang.Exception e) {
System.out.println("***ERROR-->" + e.toString());
}
finally {
closeStatement(preparedStmt);
releaseConnection(myCon);
}
return null;
}
</code></pre>
<p>Do I need to include <code>try - catch - finally</code> in <code>getData2</code>, since I am passing <code>myCon</code> and <code>prepareStatement</code> around? I am not sure if this the right way to code.</p>
<p>Is the way I'm coding considered standard? If not, do you have something better in mind?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T03:58:23.027",
"Id": "63600",
"Score": "0",
"body": "http://www.javaworld.com/article/2077817/java-se/understanding-jpa--part-1--the-object-oriented-paradigm-of-data-persistence.html"
}
] |
[
{
"body": "<p>There are a number of problems with your code. Let's go through the more important ones:</p>\n\n<ul>\n<li><p>you should close the PreparedStatement <strong>before</strong> you return the connection to the pool.... should be:</p>\n\n<pre><code>finally{\n closeStatement (preparedStmt);\n releaseConnection (myCon);\n}\n</code></pre></li>\n<li><p>you should be closing the ResultSet in addition to the Statement!</p></li>\n<li>but, this is all somewhat pointless because you only use your prepared statement once.... A prepared statement is useful for two reasons only:\n<ol>\n<li>they separate issues in syntax from issues in data (you get syntax errors early) ... but, your SQL Query code will not have syntax errors... right?</li>\n<li>they improve performance <strong>IF THEY ARE REUSED</strong>, but you are not reusing them.</li>\n</ol></li>\n<li>If you are using Java 7 you should be using <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow\">try-with-resources logic</a> on your objects. This will remove the need for the finally block.</li>\n</ul>\n\n<p>JDBC Connection pools are relatively complicated 'animals'. I strongly recommend you leverage the functionality that others have built. For example, Tomcat, WebSphere and I am sure other applications servers have good connection-pooling processes. Additionally, stand-alone applications can (re)use things like <a href=\"http://commons.apache.org/proper/commons-dbcp/index.html\" rel=\"nofollow\">the Apache DBCP component</a> (which also <a href=\"http://commons.apache.org/proper/commons-dbcp/configuration.html\" rel=\"nofollow\">supports PreparedStatement connection pools</a>)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T04:55:26.350",
"Id": "38211",
"ParentId": "38209",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T03:35:41.570",
"Id": "38209",
"Score": "3",
"Tags": [
"java",
"exception-handling"
],
"Title": "Passing around Connection"
}
|
38209
|
<p>I am supposed to take this code (that I made):</p>
<pre><code>public void showUpdatedStatus()
{
if(((itsUsersNumber - itsSecretNumber) <= 2) && ((itsUsersNumber - itsSecretNumber) >= -2))
JOptionPane.showMessageDialog(null, "You're hot!");
if (((itsUsersNumber - itsSecretNumber) <= 6) && ((itsUsersNumber - itsSecretNumber) >= -6))
JOptionPane.showMessageDialog(null, "You're warm.");
if ((itsUsersNumber - itsSecretNumber) < -6)
JOptionPane.showMessageDialog(null, "Too low.");
if ((itsUsersNumber - itsSecretNumber) > 6)
JOptionPane.showMessageDialog(null, "Too high.");
}
</code></pre>
<p>And change it so it does this:</p>
<blockquote>
<p>Have the program lie one-third of the time that the guess is too high;
it says it is too low. But it never lies about the guess being too
low, nor does it lie twice in a row.</p>
</blockquote>
<p>I believe I have managed to do this with this method for checking whether the guess is "too high."</p>
<pre><code>public void TooHigh()
{
int numLies = 1;
if ((itsUsersNumber - itsSecretNumber) > 6)
{
itsLieNum = randy.nextInt(2);
if(itsLieNum == 1 && numLies == 1){
numLies = 2;
JOptionPane.showMessageDialog(null, "Too low.");}
else
numLies = 1;
JOptionPane.showMessageDialog(null, "Too high.");
}
}
</code></pre>
<p>I just want to know whether or not it seems like it would work fine. I would just test it, but it would probably take me quite a while to make sure that it not only works 1/3 of the time, but also that it doesn't do it twice in a row.</p>
<p>EDIT: I managed to get everything working fine with this code:</p>
<pre><code>public void showUpdatedStatus()
{
if(((itsUsersNumber - itsSecretNumber) <= 2) && ((itsUsersNumber -itsSecretNumber) >= -2))
JOptionPane.showMessageDialog(null, "You're hot!");
else if (((itsUsersNumber - itsSecretNumber) <= 6) && ((itsUsersNumber -itsSecretNumber) >= -6))
JOptionPane.showMessageDialog(null, "You're warm.");
if ((itsUsersNumber - itsSecretNumber) < -6)
JOptionPane.showMessageDialog(null, "Too low.");
else
TooHigh();
}
public void TooHigh()
{
if ((itsUsersNumber - itsSecretNumber) > 6)
{
itsLieNum = randy.nextInt(3);
if(canLie && itsLieNum == 1){
canLie = false;
JOptionPane.showMessageDialog(null, "Too low.");}
else{
canLie = true;
JOptionPane.showMessageDialog(null, "Too high.");}
}
}
</code></pre>
<p>Thanks to rolfl</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T06:25:52.363",
"Id": "63613",
"Score": "1",
"body": "this is a really good question.....I don't know how \"on-topic\" your question is though?"
}
] |
[
{
"body": "<p>The concept you have going is 'OK' (cumbersome, but for a beginner it's OK). There are two bugs, and one recommendation that will help a lot.</p>\n\n<p>First the recommendation....</p>\n\n<p>Change <code>numLies</code> to be a boolean value like: <code>boolean canlie = true;</code></p>\n\n<p>Then, your code becomes:</p>\n\n<pre><code>if(canlie && itsLieNum == 1){\n canlie = false;\n ....\n} else {\n canlie = true;\n</code></pre>\n\n<p>This makes the purpose of the code more apparent. Also, a bug is that you have to declare this <strong>ourside</strong> your method. It should be a class-variable, not a method variable, otherwise it will <strong>always</strong> be the wrong value.</p>\n\n<p>The bug you have is a technical one (but important that you learn) ... <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt%28int%29\" rel=\"nofollow\"><code>Random.nextInt(value)</code></a> will never return the input <code>value</code>. It will retrun <code>0</code>(inclusive) to <code>value</code>(exclusive). In your case, with <code>nextInt(2)</code> it will only ever return <code>0</code>, or <code>1</code>. Change that to be <code>nextInt(3)</code> and you will get the values <code>0</code>, <code>1</code>, or <code>2</code> and it will be <code>1</code> 1 third of the time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T06:38:32.463",
"Id": "63617",
"Score": "0",
"body": "Oh okay I should have noticed the `nextInt(2)` thing. For some reason I was thinking that `nextInt(2)` WAS 0, 1, 2 not sure why haha. I also noticed what was happening from `numLies` being declared inside of the method after I tested it myself a couple times. :P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T06:42:49.167",
"Id": "63618",
"Score": "0",
"body": "Also there is another bug that I can't seem to figure out the reason for. It's that for some reason after I enter a number that is \"Too High\" the dialog that is supposed to tell me whether it is \"Too Low\" or \"Too High\" is blank with no buttons or text other than the X button in the top right. Any help on that matter? Thanks! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T06:46:44.380",
"Id": "63619",
"Score": "0",
"body": "I figured out the problem it had to do with the statements checking if it was Hot or Warm I had everything set to an else if off of those I just left hot and warm dependant off of each other and made too low its own if statement and that seemed to fix the issue."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T06:26:32.917",
"Id": "38213",
"ParentId": "38212",
"Score": "3"
}
},
{
"body": "<p>I'll review your <a href=\"https://codereview.stackexchange.com/revisions/38212/4\">Rev 4</a>, though some of these remarks also apply to the original code. Note that all of these criticisms are on style rather than correctness. The correctness of your code is pretty good starting with Rev 4.</p>\n\n<ul>\n<li>You use <code>(itsUsersNumber - itsSecretNumber)</code> many times. For brevity, readability, and maybe performance, define <code>int diff = itsUsersNumber - itsSecretNumber</code>.</li>\n<li>I suggest chaining your conditions as <code>if … else if … else if … else</code>, to emphasize that the code branches are all mutually exclusive, and that one of them must always be true. </li>\n<li><p>I strongly recommend writing the braces, and placing them according to the official <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-142311.html#449\" rel=\"nofollow noreferrer\">Java style guide (§ 7.4)</a>:</p>\n\n<pre><code>int diff = itsUsersNumber - itsSecretNumber;\nif (-2 <= diff && diff <= 2) {\n …\n} else if (-6 <= diff && diff <= 6) {\n …\n} else if (diff < -6) {\n …\n} else {\n assert diff > 6;\n …\n}\n</code></pre>\n\n<p>Your placement of braces in <code>TooHigh()</code> is weird and confusing.</p></li>\n<li>I would change <code>public void TooHigh()</code> to <code>private void handleTooHigh()</code>. It's a helper function, not to be called by code in any other class, so access should be <code>private</code>. Method names should start follow the <code>lowerCase</code> capitalization convention.</li>\n<li>I would expect that <code>TooHigh()</code> would only ever be called when a number is too high. Therefore, <code>TooHigh()</code> shouldn't have to bother checking that the guess is too high.</li>\n<li>In <code>TooHigh()</code>, <code>itsLieNum</code> should be local, if you need to have a variable at all.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T20:23:29.790",
"Id": "63654",
"Score": "0",
"body": "Thanks for the feedback. You are right about how `itsLieNum` should be local now that I look back at it. haha"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T09:08:55.367",
"Id": "38215",
"ParentId": "38212",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "38213",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T06:07:54.537",
"Id": "38212",
"Score": "4",
"Tags": [
"java",
"beginner"
],
"Title": "How to make a program that lies one-third of the time?"
}
|
38212
|
<p>Code review for best practices, optimizations, bug detection etc. Also please verify my complexity as mentioned within the function comments.</p>
<pre><code>/**
* Util class with 2 functions,
* 1. find the next consecutive prime
* 2. find the nth prime.
*/
public class PrimeUtil {
private PrimeUtil() {}
private static List<Integer> findAllPrimes(int upperBound) {
assert upperBound > 0;
final List<Integer> primeList = new ArrayList<Integer>();
int squareRoot = (int) Math.sqrt(upperBound);
boolean[] nonPrime = new boolean[upperBound + 1];
for (int m = 2; m <= squareRoot; m++) {
if (!nonPrime[m]) {
primeList.add(m);
for (int k = m * m; k <= upperBound; k += m)
nonPrime[k] = true;
}
}
for (int m = squareRoot; m <= upperBound; m++) {
if (!nonPrime[m]) {
primeList.add(m);
}
}
return primeList;
}
/**
* Returns the next / consecutive prime number of input number.
*
* Complexity: O (m * n) where m is number of primes till the input number, n is the difference between (to be found prime - input number)
*
* @param number The number whose next prime should be returned
* @return The next / consecutive prime number of input prime.
*/
public static int nextPrime (int number) {
if (number <= 0) {
throw new IllegalArgumentException("The value of n is " + number + ". It should be greater than 0");
}
int nextNum = number + 1;
boolean notPrime = true;
final List<Integer> primes = findAllPrimes(number);
while (notPrime) {
notPrime = false;
for (int i : primes) {
if (nextNum % i == 0) {
notPrime = true;
}
}
if (notPrime) {
nextNum++;
}
}
return nextNum;
}
/**
* Returns the nth prime number.
*
* Complexity: O(n * m) where n is the prime number, and m is number of primes till the n.
*
* @param n the nth prime number to be found.
* @return the nth prime number
*/
public static int nthPrime(int n) {
if (n <= 0) {
throw new IllegalArgumentException("The value of n is " + n + ". It should be greater than 0");
}
final List<Integer> primes = new ArrayList<Integer>();
int number = 2;
while (primes.size() < n) {
boolean notPrime = false;
for (int i : primes) {
if (number % i == 0) {
notPrime = true;
}
}
// if you are a prime.
if (!notPrime) {
primes.add(number);
}
number++;
}
return primes.get(primes.size() - 1);
}
public static void main(String[] args) {
System.out.println("Expected 101, Actual: " + nextPrime(100));
System.out.println("Expected 17, Actual: " + nextPrime(15));
System.out.println("Expected 7, Actual: " + nthPrime(4));
System.out.println("Expected 29, Actual: " + nthPrime(10));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-13T21:58:45.810",
"Id": "87398",
"Score": "0",
"body": "How long does it take to calculate the 10 billionth prime?"
}
] |
[
{
"body": "<p>This question is very similar to the <a href=\"http://projecteuler.net/problem=7\" rel=\"nofollow noreferrer\">Project Euler #7</a> challenge. This was asked recently: <a href=\"https://codereview.stackexchange.com/questions/38084/suggestions-for-improvement-on-project-euler-7\">Suggestions for improvement on Project Euler #7</a>. I answered that question there, and a lot of my suggestions there will follow through here. I also suggested an object-oriented class that will significantly improve the performance of this problem....</p>\n\n<p>Your solution is very different, but similar issues can be found...</p>\n\n<p>Some basic 'hygiene':</p>\n\n<ul>\n<li>double-negative logic is hard to read. <code>if (!nonprime[m])</code> should be <code>if (prime[m])</code>. If you cannot get the booleab values to be right (<code>Arrays.fill(prime, true)</code>) then you should revert to constants (<code>private static final boolean PRIME = false;</code>) and <code>==</code> comparisons: <code>if (primeflag[m] == PRIME)</code></li>\n<li>you also do double-negative logic in the <code>nextPrime()</code> method: <code>boolean notPrime = true;</code> and <code>if (notPrime)</code>. This should be something like <code>if (!prime)</code> ....</li>\n</ul>\n\n<p>First though, you actually have two very different solutions for 'find nth prime' and 'find primes less than x'. Your find nth prime algorithm is very slow. It does not use the Sieve of Eratosthenes at all. It is a 'naive' and slow mechanism for checking every value against all primes. There is a way to estimate the value of the nth prime, and you should use that, combined with the mechanism for calculating primes less than the estimate. This is <a href=\"https://codereview.stackexchange.com/a/38095/31503\">illustrated in that other answer</a> (reference <a href=\"http://en.wikipedia.org/wiki/Prime_number_theorem#Approximations_for_the_nth_prime_number\" rel=\"nofollow noreferrer\">Wikipedia</a>)</p>\n\n<p>:</p>\n\n<ol>\n<li>you have blindly followed the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Implementation\" rel=\"nofollow noreferrer\">wikipedia recommended algorithm/suggestion</a> of doing an incremental progression on a sieve of numbers.</li>\n<li>if you make 2 a special case, then you only actually need to process every second value (<code>m += 2</code> instead of <code>m++</code>).</li>\n<li>you do not cache previously computed prime numbers, as a result, calling your methods multiple times will require many re-computations of prime values.</li>\n<li>Integer.MAX_VALUE happens to be a prime.... what happens if you run: <code>nextPrime(Integer.MAX_VALUE - 1);</code> ? </li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-23T15:46:24.037",
"Id": "78615",
"Score": "0",
"body": "Bug: If squareRoot happens to be a prime, it will be added twice."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T15:49:30.697",
"Id": "38224",
"ParentId": "38214",
"Score": "3"
}
},
{
"body": "<p>In addition to rolfl's suggestions:</p>\n\n<p>A <code>boolean</code> <a href=\"https://stackoverflow.com/questions/3038392/do-java-arrays-have-a-maximum-size\">occupies at least 1 byte on most VMs</a>. You can reduce that by using a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html\" rel=\"nofollow noreferrer\"><code>BitSet</code></a> for your sieve. At least that should give you the ability to generate a sieve for all primes up to <code>Integer.MAX_VALUE</code> (2^28 entries vs 2^31 - <a href=\"https://stackoverflow.com/questions/3038392/do-java-arrays-have-a-maximum-size\">the maximum number of elements in an array</a> seems to be slightly below Integer.MAX_VALUE)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T17:55:39.577",
"Id": "38231",
"ParentId": "38214",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T08:18:57.437",
"Id": "38214",
"Score": "2",
"Tags": [
"java",
"primes"
],
"Title": "Find next consecutive prime and find nth prime"
}
|
38214
|
<p>I've made lots of improvements on my text-editing app. Please review it again.</p>
<pre><code>(function() {
"use strict";
if (!window.File) document.body.innerHTML = "<h1>Sorry your <a href='http://whatbrowser.org/'>browser</a> isn't supported :(</h1>";
var textarea = document.getElementById("textarea"),
statusBar = document.getElementById("status-bar"),
inputFile = document.getElementById("input-file"),
appname = "Notepad",
statusBarOn,
isModified,
filename;
function skipSave() {
if (!isModified || !textarea.value || confirm("You have unsaved changes that will be lost.")) {
isModified = false;
return true;
}
}
function changeFilename(newFilename) {
filename = newFilename;
document.title = filename + " - " + appname;
}
function updateStatusBar() {
var text = textarea.value;
statusBar.value = "Words: " + (text.split(/\b\S+\b/g).length - 1) + " Characters: " + text.replace(/\s/g, "").length + " / " + text.replace(/\n/g, "").length;
}
function newDoc(text, newFilename) {
if (skipSave()) {
textarea.value = text || "";
changeFilename(newFilename || "untitled.txt");
updateStatusBar();
}
}
function openDoc() {
var file = inputFile.files[0],
reader = new FileReader();
reader.readAsText(file);
reader.addEventListener("load", function() {
newDoc(reader.result, file.name);
});
}
function renameDoc() {
var newFilename = prompt("Name this document:", filename);
if (newFilename !== null) {
if (newFilename === "")
changeFilename("untitled.txt");
else
changeFilename(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;
}
}
function showHideStatusBar(toState) {
statusBarOn = toState;
statusBar.hidden = !statusBarOn;
textarea.style.height = statusBarOn ? "calc(100% - 21px)" : "";
}
textarea.addEventListener("input", function() {
isModified = true;
updateStatusBar();
});
inputFile.addEventListener("change", openDoc);
document.addEventListener("keydown", function(e) { // kbd shortcuts
var keys = {
66: function() { // B ; toggle
showHideStatusBar(!statusBarOn);
},
79: function() { // O ; open
if (skipSave()) inputFile.click();
},
82: newDoc, // R
83: saveDoc, // S
"noctrl9": function() { // tab
var text = textarea.value,
sStart = textarea.selectionStart;
textarea.value = text.substring(0, sStart) + "\t" + text.substring(textarea.selectionEnd);
textarea.selectionEnd = sStart + 1;
}
},
f = e.ctrlKey ? keys[e.keyCode] : keys["noctrl" + e.keyCode];
if (f) {
e.preventDefault();
f();
}
});
window.addEventListener("load", function() {
var appdata = JSON.parse(localStorage.getItem(appname));
if (appdata && appdata.isModified) {
newDoc(appdata.text, appdata.filename);
isModified = true;
} else {
newDoc();
}
showHideStatusBar(!appdata || appdata.statusBarOn);
});
window.addEventListener("unload", function() { // store data
var appdata = {
"isModified": isModified,
"text": textarea.value,
"filename": filename,
"statusBarOn": statusBarOn
};
localStorage.setItem(appname, JSON.stringify(appdata));
});
}());
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T17:28:52.683",
"Id": "63639",
"Score": "0",
"body": "Can you create a jsfiddle or jsbin ? This looks so much better than the first attempt."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T17:38:41.870",
"Id": "63640",
"Score": "1",
"body": "You can see the full app here - https://dl.dropboxusercontent.com/u/92126558/Notepad/index.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T18:09:57.557",
"Id": "63644",
"Score": "0",
"body": "whole app in a zip - https://dl.dropboxusercontent.com/u/92126558/Notepad.zip"
}
] |
[
{
"body": "<p>I like your code</p>\n\n<ul>\n<li>\"Use Strict\" within a IFFE</li>\n<li>No warnings in JsHint, good indenting</li>\n<li>Correct casing and decent naming</li>\n<li>Nice size of methods</li>\n</ul>\n\n<p>I can only comment on the lack of comments in your source, though I admit the code is pretty self-explanatory.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T14:23:08.953",
"Id": "38324",
"ParentId": "38220",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "38324",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T13:16:40.000",
"Id": "38220",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Text-editing app"
}
|
38220
|
<p>I wrote <a href="https://github.com/RobertZenz/ClosedDoor">a simple text-templating/processing system which resembles PHP</a>, except that it works with Clojure. The main goal was to provide an easy way to use Clojure PHP-style for small files.</p>
<p>This is a usage example, the following file</p>
<pre><code><?clj
(def theName "Soonog")
(defn replaceAs
[input]
(clojure.string/replace input "a" "X")
)
?>
Hello <% theName %>, this is a simple template which should allow
you to <% (replaceAs "see the basics how this might work some day") %>.
</code></pre>
<p>should output (here are two newlines at the start missing)</p>
<pre><code>Hello Soonog, this is a simple template which should allow
you to see the bXsics how this might work some dXy.
</code></pre>
<p>A short info on how it works:</p>
<ul>
<li>Accepts files as arguments
<ul>
<li>If no arguments are provided or the argument is "-" it will read from stdin</li>
</ul></li>
<li>Outputs to stdout</li>
<li>Uses regular expressions to split/process the text</li>
<li>Everything in <code><?clj ... ?></code> is evaluated with <code>load-string</code></li>
<li>Everything in <code><% ... %></code> is wrapped in <code>(echo ... )</code> and then treated like above</li>
</ul>
<p>A few things I'm unsure about:</p>
<ul>
<li>The treatment of static variables (f.e. <code>tag-start</code>)</li>
<li>The style itself</li>
<li>Using regular expressions to parse files</li>
<li><code>load-strings</code> will load it into the current context, so all files passed in share the same context...this is by design (for now) so that you can "include" files. Though, having a function that uses a separate context might be interesting if this is used as library.</li>
</ul>
<p>And here's the code:</p>
<pre><code>(ns closeddoor.core
(:gen-class :main true))
(require 'clojure.string)
(def tag-start
"The long/normal start tag."
"<\\?clj")
(def tag-end
"The long/normal end tag."
"(\\?>|\\Z)")
(def echo-start
"The short/echo start tag."
"<%")
(def echo-end
"The short/echo end tag."
"%>")
(def tag-pattern
"The compiled pattern for the long/normal tags."
(re-pattern (str tag-start "((?s:.+?))" tag-end)))
(def echo-pattern
"The compiled pattern for the short/echo tags."
(re-pattern (str echo-start "((?s:.+?))" echo-end)))
(defn- process-match
"Processes the given match, and returns the output of
the given match."
[[match group]]
; Create a StringBuilder which we'll use for our content.
(def buffer (StringBuilder.))
(defn echo
"A small helper function to allow to echo things."
[string]
(.append buffer string))
; Now load what the regex delivered to use.
(load-string (str "(use 'closeddoor.core)" group))
; Return the buffer.
; We're replacing the $ with an escaped version because this output
; is directly passed into string/replace.
(clojure.string/replace (.toString buffer) "$" "\\$"))
(defn- process-match-echo-wrapped
"Process the given match, but wraps it first in the echo function."
[[match group]]
(process-match [match (str "(echo " group ")")]))
(defn parse
"Parses the given input, processes the matches and returns the result.
The long/normal tags are processed first, after that the short/echo tags.
Order of appearance does not matter, all normal tags are processed first."
[input]
(clojure.string/replace
(clojure.string/replace
input
tag-pattern
process-match)
echo-pattern
process-match-echo-wrapped))
(defn process
"Processes the given source, which means that it reads everything from
the source with slurp, runs it through parse and spits it out into out.
So (process input *out*) is basically shorthand for (spit *out* (parse input))."
[source out]
(spit out (parse (slurp source))))
(defn -main
"The main function which does everything."
[& args]
(if (empty? args)
(process *in* *out*)
(doseq [arg args]
(if (= arg "-")
(process *in* *out*)
(process arg *out*)))))
</code></pre>
|
[] |
[
{
"body": "<p>Cool idea! I could definitely see this coming in handy in a variety of domains.</p>\n\n<p>I noticed that you have some <code>def</code> and <code>defn</code> statements within the function definition of <code>process-match</code>. It's generally considered un-idiomatic to use <code>def</code>/<code>defn</code> anywhere except for at the top level of the namespace you're in. Usually you would use <code>let</code> instead if what you're trying to <code>def</code>ine isn't used outside of the function, but it doesn't look like that's the case here -- I think you are wanting <code>buffer</code> and <code>echo</code> \nto be used at the top level, so I would pull them out of the <code>process-match</code> function and do something like this:</p>\n\n<pre><code>(ns closeddoor.core\n (:require clojure.string)\n (:gen-class :main true))\n\n(def tag-start \"<\\\\?clj\") ; The long/normal start tag.\n(def tag-end \"(\\\\?>|\\\\Z)\") ; The long/normal end tag.\n\n(def echo-start \"<%\") ; The short/echo start tag.\n(def echo-end \"%>\") ; The short/echo end tag.\n\n; the compiled regex patterns for each of the above\n(def tag-pattern (re-pattern (str tag-start \"((?s:.+?))\" tag-end)))\n(def echo-pattern (re-pattern (str echo-start \"((?s:.+?))\" echo-end)))\n\n(def buffer (StringBuilder.))\n\n(defn- echo [string]\n \"A small helper function for echoing things.\"\n (.append buffer string))\n\n(defn- process-match [[match group]]\n \"Processes the given match, and returns the output of the given match.\"\n (load-string (str \"(use 'closeddoor.core)\" group))\n (clojure.string/replace (.toString buffer) \"$\" \"\\\\$\"))\n\n(defn- process-match-echo-wrapped [[match group]]\n \"Process the given match, but wraps it first in the echo function.\"\n (process-match [match (str \"(echo \" group \")\")]))\n\n(defn parse [input]\n \"Parses the given input, processes the matches and returns the result.\n The long/normal tags are processed first, after that the short/echo tags.\n Order of appearance does not matter, all normal tags are processed first.\"\n (clojure.string/replace\n (clojure.string/replace input tag-pattern process-match)\n echo-pattern\n process-match-echo-wrapped))\n\n(defn process [source out]\n \"Processes the given source, which means that it reads everything from\n the source with slurp, runs it through parse and spits it out into out.\n So (process input *out*) is basically shorthand for (spit *out* (parse input)).\"\n (spit out (parse (slurp source))))\n\n(defn -main [& args]\n \"The main function which does everything.\"\n (if (empty? args)\n (process *in* *out*)\n (doseq [arg args]\n (if (= arg \"-\")\n (process *in* *out*)\n (process arg *out*)))))\n</code></pre>\n\n<p>BTW, I also changed your spacing from 4 spaces to 2 which is the Clojure standard. I guess there's nothing wrong with using 4 spaces, but 2 is predominantly what you see. </p>\n\n<p>I've generally rearranged the spacing and line breaks to suit my own aesthetic preference, but it isn't necessarily \"the right way,\" just my opinion on what formatting I find more readable. Just my 2 cents!</p>\n\n<p>I also moved the <code>(require 'clojure.string)</code> into the namespace definition, which is idiomatic and more concise.</p>\n\n<p>I'm a bit confused about your <code>parse</code> function... did you mean for the last argument of each call to <code>clojure.string/replace</code> function to be a function (<code>process-match</code> and <code>process-match-echo-wrapped</code>, respectively)? I believe you need to have strings there, indicating what to replace each match with. Maybe you meant <code>(process-match match group)</code>, where <code>match</code> and <code>group</code> are replaced with the actual match and group? Maybe I'm missing something.</p>\n\n<p>By the way, if you wanted to simplify the nested calls to <code>clojure.string/replace</code> in that function, you could do something like this:</p>\n\n<pre><code>(defn parse [input]\n \"Parses the given input, processes the matches and returns the result.\n The long/normal tags are processed first, after that the short/echo tags.\n Order of appearance does not matter, all normal tags are processed first.\"\n (reduce (fn [s [pat rep]] \n (clojure.string/replace s pat rep))\n input\n [[tag-pattern process-match]\n [echo-pattern pattern-match-echo-wrapped]]))\n</code></pre>\n\n<p>If I can offer one last criticism: your methods that deal with modifying <code>buffer</code> (which is initially defined as <code>(StringBuilder.)</code> are destructive actions, so you might consider adding <code>!</code> onto the end of your function names (<code>echo!</code>, <code>process-match!</code>, etc.)</p>\n\n<p>Hope this helps!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T15:20:40.213",
"Id": "44761",
"ParentId": "38223",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T15:33:29.573",
"Id": "38223",
"Score": "5",
"Tags": [
"clojure"
],
"Title": "A text-templating system similar to PHP...but with Clojure"
}
|
38223
|
<p>I'm working on an app for my school (not homework, an app that's going to be used by students), that's supposed to display our week schedules. I get the data from a webapp, but it has no API that I can use. So I have to parse the HTML. This HTML is a serious mess (and on top of that, they use Finnish in their pages), and it seems my code has become such a mess too. I'd like to simplify this code, but I don't know jsoup well enough to use little tricks that make code simple. Most of the code is probably fine, but I'm concerned about the <code>parseRows()</code> method.</p>
<p>It's an android app, and I use jsoup to parse the HTML. It's an AsyncTask, the compiler required me to do that. I've translated all variable and function names, so they might be inaccurate descriptions. In dutch they seem fine to me though. I also hope the comments tell enough about the code to be decipherable.</p>
<p>Here is an <a href="https://kalender.phl.be/kalenterit2/index.php?kt=lk&yks=&cluokka=2TING&av=131118131124131124&guest=IT/phl&lang=fla&print=arkipaivat" rel="nofollow">example page</a> that I parse. And here is the <a href="http://pastebin.com/eUjhifjU" rel="nofollow">relevant part of the HTML</a>, with a cleaner structure, on pastebin since the HTML was too long.</p>
<p>And here is the relevant code:</p>
<pre><code>public class DownloadScheduleTask extends AsyncTask<String, Void, Void>
{
private LesroostersActivity activity;
private Schedule schedule;
private String debugTag = "Pxl App";
public DownloadLesroosterTask(LesroostersActivity activity)
{
//keep a reference to the activity
this.activity = activity;
}
@Override
protected Void doInBackground(String... URLs)
{
//doInBrackground required varargs parameter, but I only ever pass one URL, so I select the first.
String URL = URLs[0];
try
{
//Download the HTML document.
Document document = Jsoup.connect(URL).get();
schedule = new Schedule();
//Get the first day of this week out of the table
SimpleDateTime firstDay = SimpleDateTime.parseDate(document.select("table th span.hdr_date font").first().text());
schedule.setFirstDay(firstDay);
//Get all <tr> elements from the table
Elements rows = document.select("table.asio_basic > tbody > tr");
//Parse rows to elements
ArrayList<IndexedElement> elements = parseRows(rows);
//Parse elements to get their data
parseElements(elements);
}
catch (IOException e)
{
//Show an error message in the activity
activity.showError("Error", "Something went wrong while downloading the schedule. Please try again");
e.printStackTrace();
}
//Nothing to return here, but doInBackground requires a return statement.
return null;
}
protected void onPostExecute(Void result)
{
//Let activity know we are done.
activity.ontvangLesrooster(schedule);
}
private ArrayList<IndexedElement> parseRows(Elements rows)
{
//Offsets are used to get the right element when rowspans are used.
int[] offsets = new int[rows.size()];
//The array to return
ArrayList<IndexedElement> elements = new ArrayList<IndexedElement>();
//We need to parse the table per column, because there is no other way to know to which day a course belongs.
//For each column (1 column is 1 day)
for (int i = 0; i < rows.get(0).children().size(); i++)
{
int lesIndex = 0;
//For each row (1 row is 30 minutes)
for (int j = 0; j < rows.size(); j++)
{
//Get the correct cell. 'offsets' shifts our index to the left, so that we read from the correct column after reading a rowspan.
Element cell = rows.get(j).child(i + offsets[j]);
//If the cell has a rowspan
if (cell.hasAttr("rowspan"))
{
//First get the size of the rowspan (e.g. rowspan="4")
int rowspan = Integer.parseInt(cell.attr("rowspan"));
//Then for each row affected by the rowspan, change its offset
for (int k = 1; k < rowspan; k++)
{
offsets[j + k]--;
}
//Then add rowspan to our index to skip nonexistent cells
j += rowspan - 1;
//Finally add the cell to the array. i - 1 is a correction for the first column.
elements.add(new IndexedElement(cell, i - 1, lesIndex++));
}
}
}
return elements;
}
private void parseElements(ArrayList<IndexedElement> elements)
{
for (IndexedElement e : elements)
{
//This selects "[beginHour] - [endHour]<br />[courseName]"
String timeAndNameHTML = e.getElement().select("b").html();
//There are some cells without data (remember that we added all cells with a rowspan), so we have to filter those out first
if (!timeAndName.equals(""))
{
//Selects two strings. 1) "[beginHour] - [endHour]" 2) "[courseName]"
String[] parts = timeAndNameHTML.split("<br />");
//Selects two strings. 1) "[beginHour]" 2) [endHour]"
String[] times = parts[0].split(" - ");
//Parse the time string to a SimpleDateTime
SimpleDateTime beginHour = new SimpleDateTime(SimpleDateTime.parseTime(times[0]));
//Set the day of beginHour to the first day of the week + the dayIndex we are at now.
beginHour.setDay(schedule.getFirstDay().getDay() + e.getDay());
//Identical to previous 2 lines, but for endHour
SimpleDateTime endHour = new SimpleDateTime(SimpleDateTime.parseTime(times[1]));
endHour.setDay(schedule.getFirstDay().getDay() + e.getDay());
//Selects the string "[courseName]"
String courseName = parts[1];
//Selects the string "<b>[beginHour] - [endHour]<br />[courseName]</b><br />[classroom]<br/>"
String classRoomHMTL = e.getElement().select("font").html();
//Selects three strings. 1) "<b>[beginHour] - [endHour]" 2) "[courseName]</b>" 3) "[classroom]"
String[] classRoomParts = classRoomHMTL.split("<br />");
String classRoom = "";
//It's possible that a course doesn't have a classroom, in that case the classRoom string will stay empty.
if (classRoomParts.length >= 3)
{
classRoom = classRoomParts[2];
}
//selects the name of the teacher
String leerkrachtHTML = e.getElement().select("tr > td").first().ownText();
//Put all data in the schedule.
schedule.addCours(new Course(courseName, classRoom, teacher, beginHour, endHour));
}
}
}
//This class stores an Element along with two indexes. One for the day of the course. The second for the course index of that day.
private class IndexedElement
{
private Element element;
private int dayIndex;
private int courseIndex;
public IndexedElement(Element element, int day, int course)
{
this.setElement(element);
this.setDay(day);
this.setCourse(course);
}
public Element getElement() {
return element;
}
public void setElement(Element element) {
this.element = element;
}
public int getDay() {
return dayIndex;
}
public void setDay(int day) {
this.dayIndex = day;
}
public int getCourse() {
return courseIndex;
}
public void setCourse(int course) {
this.courseIndex = course;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>At some point everyone ends up trying to parse HTML. And, in some of those cases, it is even unavoidable......</p>\n\n<p>... but, some suggestions (in order or preference):</p>\n\n<ol>\n<li>communicate with the server-side developers and try to create a better API for accessing the data (perhaps direct read-only access to their database even?)</li>\n<li>Decide whether the mobile application is really worth it.... if the data is available on the web, can you not just browse to it using your device's web-browser, and not do <strong>anything</strong>:\n<ul>\n<li>save yourself a lot of headaches</li>\n<li>give you some time in your life to answer questions on CodeReview!</li>\n<li>bonus is that it is iPhone compatible too!</li>\n</ul></li>\n<li>Perhaps collaborate with the actual host-side of the system and extend the functionality of the web side of the equation is extended and covers the features you need. Special bonuses here are:\n<ul>\n<li>you don't need to maintain the application, it is 'theirs'.</li>\n<li>it is also multi-platform compatible (including iOS, PC, and anything in the future)</li>\n</ul></li>\n<li>Suck it up and do the hard-work of parsing the HTML....</li>\n</ol>\n\n<p>OK, so you decide to dive in to the HTML, I have some recommendations for that too:</p>\n\n<h2>Abstract things away</h2>\n\n<p>HTML and web pages in general are <strong>not an API</strong>... they are a display mechanism. Believing that the web interface will stay constant is a failing belief.... so, you need to create your own API.</p>\n\n<p>Your application needs to access this API to get the data. The API needs to be as simple as possible, but likely something like:</p>\n\n<pre><code>public abstract class ScheduleFactory {\n\n public static ScheduleFactory newInstance(String datasource) {\n // datasource may be something like a URL, whatever....\n }\n\n public abstract Course[] getCourses();\n public abstract Timetable getTimeTable(Course course);\n}\n</code></pre>\n\n<p>Then, create an implementation of the factory for <strong>the current version</strong> of the web site (because you will need a new version when it changes).</p>\n\n<p>OK, so now you have a simple factory implementation for the data interface. The benefits of this are:</p>\n\n<ol>\n<li>You can easily test your <strong>real</strong> application/system with a simple (non-web-based) test factory</li>\n<li>your code is in distinct chunks, application layer, and data layer, and you don't need to change the application unless there are functionality changes....</li>\n</ol>\n\n<h2>The HTML Parser</h2>\n\n<p>OK, so you have a Factory class to implement which will access your web-page for the data you need. What will this look like?</p>\n\n<p>For this, I strongly recommend a multi-level approach. You do <strong>not</strong> want to be changing the code every time the web-page changes... so, create a 'dictionary' for your web-page. It is a 'resource locator'. Using JSoup you have a query language (<code>select</code>) so I recommend creating a property file that identifies data points, and the select statement required to get them.</p>\n\n<p>In this way you can abstract the actual location data from the code, and have 'simple' methods that return simple abstractions like <code>String</code>, or <code>List<Element></code> for JSoup queries like <code>document.select(\"table th span.hdr_date font\").first().text()</code> and <code>table.asio_basic > tbody > tr</code></p>\n\n<p>As an aside (and this is <strong>not</strong> a recommendation, necessarily....):</p>\n\n<blockquote>\n <p>I maintain the JDOM XML library. As a result my natural inclination is to use XPath/XQuery for accessing data. It is more expressive, it seems, than the JSoup (CSS) select. There are ways to convert JSoup to a DOM document, and with DOM, you can use XPath (and, if you want, you can convert the DOM to JDOM, and from that, XPath is easy (but that is a lot of conversion to do)).</p>\n</blockquote>\n\n<p>So, I recommend you create a 'HTMLScheduleFactory', and that HTMLScheduleFactory has a special configuration file for each version of your source-page formats.</p>\n\n<p>That configuration file tells the HTMLScheduleFactory where in the HTML to locate all the things you may need.</p>\n\n<h2>Conclusion</h2>\n\n<p>I recommend that:</p>\n\n<ul>\n<li>you separate the data layer from the application layer</li>\n<li>you create a factory implementation for the data layer, so that you can get data from different/multiple sources</li>\n<li>you create a generic HTML-based factory.</li>\n<li>you create a 'mapping' configuration for the HTML-based factory that maps the required data to the HTML locations for that data.</li>\n</ul>\n\n<p>Each of these layers can be put together relatively independently, and can be tested in isolation.</p>\n\n<p>As the web-site changes, if you do it right, you can:</p>\n\n<ul>\n<li>easily create a new factory if the data becomes available in a better format (XML/JSON/Direct-to-DB/whatever)</li>\n<li>relatively easily create a new configuration file if the website layout changes</li>\n<li>the actual configuration for the website can even be remote (you do not need to change any code if the config changes) so you can host a configuration file on a different server, and only change it if the main source changes.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T23:53:00.613",
"Id": "63843",
"Score": "0",
"body": "Tsss... just use a regex `</sarcasm>` ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T12:39:50.780",
"Id": "63896",
"Score": "0",
"body": "This seems like a really nice answer, thank you! I really wish there was anything I could do about the way the data is accessed. But my school has bought the software of a company, so I doubt that company is going to listen to what a lowly student has to say :D I do have some questions though. You say that I should make those configuration files. Would they for example contain lines like: `courseName = \"table.asio_basic > tbody > tr > b\"`? So that in my program I can point to that line in the config file?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T13:43:34.880",
"Id": "63897",
"Score": "0",
"body": "@SimonVerbeke - yes, something like that, but I imagine you will need to include a detail about the data type, like whether it is going to be a list, or a single value."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T21:49:14.707",
"Id": "38334",
"ParentId": "38227",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "38334",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T16:31:12.220",
"Id": "38227",
"Score": "4",
"Tags": [
"java",
"html",
"android",
"parsing"
],
"Title": "Simplifying HTML parsing"
}
|
38227
|
<pre><code>int FindStr(char* str, int strsize, char* fstr, int from)
{
for(int i=from, j=0; i<strsize; i++)
{
if(str[i]==fstr[j])
j++;
else
{i-=j; j=0;}
if(fstr[j]=='\0')
return i-j+1;
}
return -1;
}
</code></pre>
<p>The function searches for a string <code>fstr</code> in <code>str</code> and returns its index in <code>str</code> if found, otherwise, it will return -1. It's also possible to specify where to start searching in the string.</p>
<p>My question is, can I optimize this function further? Also, do you see any potential problems in this function?</p>
|
[] |
[
{
"body": "<p>Why is <code>fstr</code> treated as a null-terminated string, while the size of <code>str</code> has to be explicitly passed in?</p>\n\n<p>What is the expected behaviour when searching for an empty string?</p>\n\n<p>This is a pretty good simple string search. There are <a href=\"http://en.wikipedia.org/wiki/String_searching_algorithm\" rel=\"nofollow\">more sophisticated algorithms</a> that try to avoid backtracking.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T18:49:59.383",
"Id": "63650",
"Score": "0",
"body": "Well, I thought that if I want to traverse the string, I'm going to either have to check on each iteration if the end of the string is reached or search for the null-termination and find the size from there. Having the size makes it easier. Having the size of fstr can also help by simplifying the second if statement, now that I think of it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T19:07:34.913",
"Id": "63652",
"Score": "2",
"body": "Checking for `str[i] != '\\0'` is just as easy as checking for `i < strsize`. Null-terminated strings produce a much more natural interface. Furthermore, requiring an explicit `strsize` might force the caller to call `strlen()` first, which is O(n). On the other hand, you have to traverse the string anyway in `FindStr()`, so you get that work for \"free\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T04:43:51.917",
"Id": "63672",
"Score": "0",
"body": "Yeah, checking for the null-termination does look better and eliminates the the size parameter. The part about strlen() too."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T18:43:51.597",
"Id": "38233",
"ParentId": "38230",
"Score": "3"
}
},
{
"body": "<p>Some comments to add to the first two of @200_success:</p>\n\n<ul>\n<li><p><code>strstr</code> does a good job. Why reinvent?</p></li>\n<li><p>sizes are often passed as <code>size_t</code> rather than <code>int</code></p></li>\n<li><p>modifying the loop variable within the loop is generally considered bad\npractice</p></li>\n<li><p><code>i -= j</code> executes on every loop unless there is a match. Mostly in this\ncase <code>j</code> is zero so the line has no effect, but it still executes</p></li>\n<li><p>if <code>fstr</code> is an empty string it returns the wrong result (1)</p></li>\n<li><p>add some spaces around operators and after <code>if</code>, <code>for</code></p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T04:53:33.110",
"Id": "63673",
"Score": "0",
"body": "Reinvention is just due to curiosity. Why is loop variable modification bad practice? What if you know what you're doing? As for `i-=j;` I think `if(j>0){i-=j; j=0;}` would cut down on the redundant assignments, but is that going to improve its performance?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T06:25:56.317",
"Id": "63678",
"Score": "1",
"body": "Its not the compiler or the machine you write your code for. It is the next poor slub who has to come along and maintain and fix it. You may know what you are doing. But the next person who looks at the code does not know that you know what you are doing. Writing code that modifies the loop variable is never easy to understand. Writing it a slightly longer way that is easy to read will be unlikely to affect straight line speed. But will make it a thousand times faster to understand and thus fix. If you really know what you are doing then you write 5 paragraphs explaining each optimization :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T06:32:30.220",
"Id": "63680",
"Score": "0",
"body": "What you have done here is optimized away an inner loop in the source code. But effectively left it in the machine instructions. The `i-=j` is basically an inner loop reset. So you have gained no significant speed advantage but made the code much harder to read."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T14:56:25.963",
"Id": "63798",
"Score": "0",
"body": "Yes, that's something I need to keep in mind. I always write code without thinking about how other people will perceive it. I need to pay more attention to that. Thanks!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T19:14:12.483",
"Id": "38235",
"ParentId": "38230",
"Score": "4"
}
},
{
"body": "<p>I'm assuming you don't want to use the <code>string</code> library.</p>\n\n<p>The header for <code>FindStr</code> should be as follows:</p>\n\n<pre><code>char *FindStr(const char *str, const int strsize, const char *fstr, const int from)\n</code></pre>\n\n<p>You should return a pointer to the <code>char</code> where the substring is, if it is found, or <code>NULL</code> otherwise. There's no reason for <code>FindStr</code> to modify the arguments, so declare them <code>const</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T14:58:30.830",
"Id": "63799",
"Score": "0",
"body": "Is there any advantage to using const other than making it clear to the person reading the code that these variables can't be modified?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T18:01:17.770",
"Id": "63807",
"Score": "0",
"body": "@Hex4869 You can pass a string literal into `str` and `fstr` if they are `const`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T18:05:33.507",
"Id": "63808",
"Score": "0",
"body": "@Hex4869 It'll prevent you or somebody else who modifies the code later from making a mistake and modifying a value that shouldn't be modified. You may forget or make a mistake."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T07:50:08.567",
"Id": "38262",
"ParentId": "38230",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "38235",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T17:54:36.473",
"Id": "38230",
"Score": "6",
"Tags": [
"c++",
"optimization",
"strings",
"search"
],
"Title": "Can this FindString function be optimized further, in terms of speed?"
}
|
38230
|
<p>So I've read numerous tutorials on handling game states in XNA, and to each tutorial I've been read, it was different from the others. Now I want to ask which way is more efficient? I've created my own ScreenManager and what not, but it wasn't satisfying to me because it was inefficient since I didn't unload any unused content.</p>
<p>My question is: What is an efficient way to manage your screens and its content? Is using an enum fine? Or...?</p>
<p>Here's my current code:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
namespace Menu
{
public class ScreenManager
{
// Variables
List<GameScreen> gameScreens = new List<GameScreen>();
// Constructors
public ScreenManager()
{
gameScreens.Add(new Splashscreen());
gameScreens.Add(new Mainscreen());
gameScreens.Add(new Playscreen());
gameScreens.Add(new Pausescreen());
}
// Public Properties
public List<GameScreen> Screens
{
get { return gameScreens; }
set { gameScreens = value; }
}
// Public Methods
public void Add(GameScreen screen)
{
gameScreens.Add(screen);
}
public void LoadContent(ContentManager Content)
{
foreach (GameScreen screen in gameScreens)
{
screen.LoadContent(Content);
}
}
public void Update(GameTime gameTime)
{
foreach (GameScreen screen in gameScreens)
{
screen.Update(gameTime);
}
}
public void Draw(SpriteBatch spriteBatch)
{
switch (ScreenState.Instance.CurrentState)
{
case State.Splashscreen:
gameScreens[0].Draw(spriteBatch);
break;
case State.Menu:
gameScreens[1].Draw(spriteBatch);
break;
case State.Play:
gameScreens[2].Draw(spriteBatch);
break;
case State.Pause:
gameScreens[3].Draw(spriteBatch);
break;
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I can't be sure of this (I need to foster my XNA knowledge), but I would probably derive that class from <code>DrawableGameComponent</code> so that the <code>Update</code> and <code>Draw</code> methods would be overrides (not just methods that happen to be named "Update" and "Draw"), but deriving from that class might have other consequences that I'm not aware of; again, my XNA is fairly basic - it just seems natural to me for a class that has <code>Update</code> and a <code>Draw</code> methods, to derive from <code>DrawableGameComponent</code>: these method names are not an accident.</p>\n<h3>Update</h3>\n<p>Your <code>Update()</code> method is looping through each <code>GameScreen</code> and calling <code>Update()</code> on them all:</p>\n<blockquote>\n<pre><code>foreach (GameScreen screen in gameScreens)\n{\n screen.Update(gameTime);\n}\n</code></pre>\n</blockquote>\n<p>I think doing this incurs non-necessary processing: why would you bother updating the <em>splash screen</em> and <em>pause screen</em> at every single iteration? You're wasting cycles here.</p>\n<h3>Draw</h3>\n<p>Your <code>Draw()</code> method is more selective:</p>\n<blockquote>\n<pre><code>public void Draw(SpriteBatch spriteBatch)\n{\n switch (ScreenState.Instance.CurrentState)\n {\n case State.Splashscreen:\n gameScreens[0].Draw(spriteBatch);\n break;\n case State.Menu:\n gameScreens[1].Draw(spriteBatch);\n break;\n case State.Play:\n gameScreens[2].Draw(spriteBatch);\n break;\n case State.Pause:\n gameScreens[3].Draw(spriteBatch);\n break;\n }\n}\n</code></pre>\n</blockquote>\n<p>I like that you're using an enum here, but I don't like that you've hard-coded the <code>gameScreens</code> indices. Let's see.. you're storing the screens in a <code>List</code>, here:</p>\n<blockquote>\n<pre><code>List<GameScreen> gameScreens = new List<GameScreen>();\n\npublic ScreenManager()\n{\n gameScreens.Add(new Splashscreen());\n gameScreens.Add(new Mainscreen());\n gameScreens.Add(new Playscreen());\n gameScreens.Add(new Pausescreen());\n}\n</code></pre>\n</blockquote>\n<p>Allow me to open a nitpicking parenthesis here:</p>\n<blockquote>\n<p><strong>Nitpick</strong></p>\n<p>Instead of <code>List<GameScreen> gameScreens = new List<GameScreen>();</code> and then adding the screens in the list at construction, I would have used an interface here, and initialized everything in a single statement:</p>\n<pre><code>private readonly IList<GameScreen> _gameScreens;\n\npublic ScreenManager()\n{\n _gameScreens = new List<GameScreen> \n {\n new SplashScreen(),\n new MainScreen(),\n new PlayScreen(),\n new PauseScreen()\n };\n}\n</code></pre>\n<p>This allows the <code>_gameScreens</code> private field to be <code>readonly</code>, which prevents the list's reference to be tampered with.</p>\n</blockquote>\n<p>The mechanics <em>work</em>, but could work <em>better</em> if you leveraged <code>IDictionary</code> and turned <code>List<GameScreen> gameScreens</code> into a <code>IDictionary<State, Action<SpriteBatch>></code>:</p>\n<pre><code>private readonly IDictionary<State, Action<SpriteBatch>> _gameScreenRenderer;\nprivate readonly GameScreen _splashScreen = new SplashScreen();\nprivate readonly GameScreen _mainScreen = new MainScreen();\nprivate readonly GameScreen _playScreen = new PlayScreen();\nprivate readonly GameScreen _pauseScreen = new PauseScreen();\n\npublic ScreenManager()\n{\n _gameScreenRenderer = new Dictionary<State, Action<SpriteBatch>>\n {\n { State.SplashScreen, sb => _splashScreen.Draw(sb) },\n { State.MainScreen, sb => _mainScreen.Draw(sb) },\n { State.PlayScreen, sb => _playScreen.Draw(sb) },\n { State.PauseScreen, sb => _pauseScreen.Draw(sb) }\n };\n}\n</code></pre>\n<p>An <code>Action<SpriteBatch></code> is a delegate that points to any method that returns <code>void</code> and takes a <code>SpriteBatch</code> parameter; here the method is anonymous.</p>\n<p>Each <code>GameScreen</code> becomes a field of the <code>ScreenManager</code> class, there's no need to have them in a list of any kind. Doing this turns your <code>Draw</code> implementation into something like this:</p>\n<pre><code>private void Draw(SpriteBatch spriteBatch)\n{\n _gameScreenRenderer[ScreenState.Instance.CurrentState](spriteBatch);\n}\n</code></pre>\n<p>Implement a similar mechanism for your <code>Update</code> method and you'll only be updating and rendering the screen for your <code>CurrentState</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T00:07:55.020",
"Id": "63667",
"Score": "1",
"body": "Thank you so much for pointing out the flaws of this code. Thank you, thank you, thank you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T03:11:33.500",
"Id": "63670",
"Score": "1",
"body": "You're welcome! Thank **you** for asking here on CodeReview! Come back anytime, there's always someone around here to review C# code :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T19:45:45.437",
"Id": "38238",
"ParentId": "38232",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38238",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T18:29:39.270",
"Id": "38232",
"Score": "3",
"Tags": [
"c#",
".net",
"xna"
],
"Title": "GameState Management efficiency"
}
|
38232
|
<p>I wrote this code for dynamic strings and would like to know what mistakes I've made.</p>
<p>It's just a struct that gets filled on the first call to <code>ds_allocate</code> and freed on the first call to <code>ds_free</code>. It uses <code>memcpy</code> for concatenation and supports a few basic operations.</p>
<p><strong>Here's the header</strong></p>
<pre><code>#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>
//Size and expansion
#define MULTIPLIER 1.00 //add 100% every time
#define FIXED_STEP 0 //overrides multiplier
#define STARTING_SIZE 24
//Can set other memory functions
#define allocate malloc
#define deallocate free
#define reallocate realloc
//Main structure
typedef struct {
char *content;
char *position;
char *end; //1 past the end
} Dynamic_String;
</code></pre>
<p><strong>And the code so far:</strong></p>
<pre><code>static inline size_t max(size_t x, size_t y)
{
return (x > y) ? x : y;
}
static inline size_t min(size_t x, size_t y)
{
return (x < y) ? x : y;
}
//Allocate initial space and set the structure members, return pointer to
//newly allocated memory. Available for use is custom_size - 1. It doesn't
//allocate space for the structure itself
char *ds_allocate(Dynamic_String *ds, size_t custom_size)
{
//What's the point in having only the '\0' character?
assert(custom_size != 1);
size_t size = (custom_size > 0) ? custom_size : STARTING_SIZE;
char *start = allocate(size);
if(start == NULL){
return NULL;
}
ds->content = ds->position = start;
ds->end = start + size;
*start = '\0';
return start;
}
void ds_free(Dynamic_String *ds)
{
deallocate(ds->content);
}
//Keep memory allocated, clear contents
void ds_clear(Dynamic_String *ds)
{
ds->position = ds->content;
*ds->position = '\0';
}
//If the content is manipulated without using these functions, but the memory
//allocated is the same and there's a '\0', it corrects the string position.
//Otherwise it writes a new '\0' at the end and returns NULL. The string
//should be usable after calling this function.
char *ds_fix(Dynamic_String *broken)
{
assert(broken->content != NULL);
broken->position = memchr(broken->content, '\0', ds_capacity(broken));
if(broken->position == NULL){
broken->position = broken->end - 1;
*broken->position = '\0';
return NULL;
}
return broken->position;
}
//Equivalent of strlen
size_t ds_length(const Dynamic_String *ds)
{
return ds->position - ds->content;
}
//Total memory allocated
size_t ds_capacity(const Dynamic_String *ds)
{
return ds->end - ds->content;
}
//Space available, accounts for '\0'
size_t ds_space(const Dynamic_String *ds)
{
return ds->end - ds->position - 1;
}
bool ds_is_empty(const Dynamic_String *ds)
{
return ds->position == ds->content;
}
bool ds_is_full(const Dynamic_String *ds)
{
return ds_space(ds) == 0;
}
//Resize memory and update the structure
char *ds_resize(Dynamic_String *ds, size_t new_size)
{
//Can't free the string through this function and what's the point of
//having only space for the '\0' terminator
assert(new_size > 0 && new_size != 1);
//Location might change
size_t position_offset = ds_length(ds);
char *temp = reallocate(ds->content, new_size);
if(temp == NULL){
return NULL;
}
ds->content = temp;
ds->end = temp + new_size;
//Position still in range?
if(position_offset < new_size){
ds->position = temp + position_offset;
}
else {
ds->position = temp + new_size - 1;
*ds->position = '\0';
}
return temp;
}
//Allocate more bytes
char *ds_reserve(Dynamic_String *ds, size_t amount)
{
assert(amount > 0);
return ds_resize(ds, ds_capacity(ds) + amount);
}
//Deallocate part of memory
char *ds_shrink(Dynamic_String *ds, size_t amount)
{
assert(amount < ds_capacity(ds));
return ds_resize(ds, ds_capacity(ds) - amount);
}
//Reduce allocated storage so it's just enough for the current content
char *ds_shrink_to_fit(Dynamic_String *ds)
{
//Shouldn't be used to free the string
assert(ds_length(ds) > 0);
return ds_shrink(ds, ds_space(ds));
}
//Expand according to multiplier or fixed step
static char *expand(Dynamic_String *ds)
{
assert(FIXED_STEP > 0 || MULTIPLIER > 0);
if(FIXED_STEP > 0){
return ds_reserve(ds, FIXED_STEP);
}
return ds_reserve(ds, ds_capacity(ds) * MULTIPLIER);
}
//Expand by at least a minimum value
static char *expand_by_at_least(Dynamic_String *ds, size_t minimum)
{
assert(minimum > 0);
assert(FIXED_STEP > 0 || MULTIPLIER > 0);
size_t regular_size;
if(FIXED_STEP > 0){
regular_size = FIXED_STEP;
}
else {
regular_size = ds_capacity(ds) * MULTIPLIER;
}
return ds_reserve(ds, max(regular_size, minimum));
}
//Push character to the end of string, return pointer to it
char *ds_push_back(Dynamic_String *ds, int c)
{
if(ds_is_full(ds) && expand(ds) == NULL){
return NULL;
}
*ds->position++ = c;
*ds->position = '\0';
return ds->position - 1;
}
//Append one dynamic string to another, return content position
char *ds_append(Dynamic_String *destination, const Dynamic_String *source)
{
size_t destination_space = ds_space(destination);
size_t source_length = ds_length(source);
if(source_length > destination_space
&& expand_by_at_least(destination, source_length - destination_space)
== NULL){
return NULL;
}
char *insertion_point = destination->position;
destination->position += source_length;
*destination->position = '\0';
return memcpy(insertion_point, source->content, source_length);
}
//Append at most n characters from source to destination
char *ds_append_n(Dynamic_String *destination, const Dynamic_String *source, size_t max)
{
//Append whole string?
if(max > ds_length(source)){
return ds_append(destination, source);
}
size_t space = ds_space(destination);
if(max > space && expand_by_at_least(destination, max - space) == NULL){
return NULL;
}
char *insertion_point = destination->position;
destination->position += max;
*destination->position = '\0';
return memcpy(insertion_point, source->content, max);
}
//Compare two dynamic strings and return 0 if equal, positive if first
//differing character is greater on str1 or negative if smaller
int ds_compare(const Dynamic_String *str1, const Dynamic_String *str2)
{
size_t length = min(ds_length(str1), ds_length(str2));
return memcmp(str1->content, str2->content, length + 1);
}
//Compare up to n characters
int ds_compare_n( const Dynamic_String *str1,
const Dynamic_String *str2,
size_t max )
{
assert(max > 0);
size_t length = min(ds_length(str1), ds_length(str2));
return memcmp(str1->content, str2->content, min(length + 1, max));
}
///////////////////////
////// Functions to work with dynamic and regular strings
//Takes an already allocated regular string and put it into a container. Making
//it a normal dynamic string. Container must not hold an allocated string or
//there will be memory leaks.
void ds_from_cstring(Dynamic_String *ds, char *c_string)
{
ds->content = c_string;
ds->position = strchr(c_string, '\0');
ds->end = ds->position + 1;
}
//Return an allocated copy of Dynamic_String content
char *ds_content_copy(const Dynamic_String *ds)
{
assert(ds_length(ds) > 0);
size_t length = ds_length(ds);
char *temp = malloc(length + 1);
if(temp == NULL){
return NULL;
}
return memcpy(temp, ds->content, length + 1);
}
//Append regular C string to Dynamic_String
char *ds_append_cstring(Dynamic_String *destination, const char *c_string)
{
//It could trigger expansion without any need
assert(*c_string != '\0');
char *insertion_point = destination->position;
for(;;){
//Avoid checking the available space all the time
//Benchmark
//16 cases: 28,700,681
//8 cases: 29,747,016
//4 cases: 37,400,868
switch(ds_space(destination)){
case 0:
if(expand(destination) == NULL){
goto handle_error;
}
break;
default:
case 8:
if(*c_string == '\0'){
goto done;
}
*destination->position++ = *c_string++;
case 7:
if(*c_string == '\0'){
goto done;
}
*destination->position++ = *c_string++;
case 6:
if(*c_string == '\0'){
goto done;
}
*destination->position++ = *c_string++;
case 5:
if(*c_string == '\0'){
goto done;
}
*destination->position++ = *c_string++;
case 4:
if(*c_string == '\0'){
goto done;
}
*destination->position++ = *c_string++;
case 3:
if(*c_string == '\0'){
goto done;
}
*destination->position++ = *c_string++;
case 2:
if(*c_string == '\0'){
goto done;
}
*destination->position++ = *c_string++;
case 1:
if(*c_string == '\0'){
goto done;
}
*destination->position++ = *c_string++;
}
}
done:
*destination->position = '\0';
return insertion_point;
//Cancel changes if there's an error
handle_error:
destination->position = insertion_point;
*destination->position = '\0';
return NULL;
}
//Appending a C string of known size is a lot faster
char *ds_append_cstring_by_length( Dynamic_String *destination,
char *c_string,
size_t length )
{
assert(length > 0);
assert(c_string[length - 1] != '\0');
size_t destination_space = ds_space(destination);
if(destination_space < length
&& expand_by_at_least(destination, length - destination_space)
== NULL){
return NULL;
}
char *insertion_point = destination->position;
destination->position += length;
*destination->position = '\0';
return memcpy(insertion_point, c_string, length);
}
</code></pre>
|
[] |
[
{
"body": "<p>The code is generally nice, so my comments are really just picking up crumbs.</p>\n\n<p>I'm not comfortable with your use of asserts to catch errors that could\nlegitimately occur at runtime. I consider asserts to be for asserting logical\nimpossibilities, not for catching runtime errors.</p>\n\n<p>Function <code>expand</code> is equivalent to <code>expand_by_at_least(ds, 1)</code></p>\n\n<p>Long parameter names <code>destination</code> and <code>source</code> could be abbreviated <code>dst</code> and\n<code>src</code> with no loss.</p>\n\n<p>Is giving the user a read-write (ie. non-const) pointer to the private string\na good idea (functions returning char*)? And is the position returned\nconsistent (think not - sometimes the new end of string sometimes the old).</p>\n\n<p>In <code>ds_compare</code> (<code>ds_compare_n</code>), why not just return the <code>strcmp</code> (<code>strncmp</code>)\nof the two strings?</p>\n\n<p>I don't like the loop in <code>ds_append_cstring</code>. A simple loop copying and\nchecking for destination full, expanding as necessary would be simpler.</p>\n\n<p><strong>Edit:</strong> <em>Do you mind giving me an example of what assert errors could legitimately\noccur at runtime?</em></p>\n\n<p>In the context of your code, I have no problem with asserting non-null\npointers, but asserting for non-zero string length seems unsafe. There are\nmany times when a string could have a zero length but the assert says that\nusers of your code must guarantee that it is always a design fault in their\ncode for a nul string to pass into your functions. Not only is this\nunreasonable, it is is unnecessary as you can easily handle such cases. BTW\ndon't assume that mallocing 0 is equivalent to <code>free</code> (it isn't) - handle a\nzero request by allocating at least 1 byte.</p>\n\n<p>As an example of testing a logical impossibilty consider some code that does:</p>\n\n<pre><code>expected length = calculate expected length of string\nallocate memory\nreal length = create string in memory\nassert(real length = expected length)\n</code></pre>\n\n<p>The assert tells you whether your algorithms are consistent/correct</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T23:02:55.650",
"Id": "63661",
"Score": "0",
"body": "Thanks for replying. Do you mind giving me an example of what assert errors could legitimately occur at runtime? I tried using just a loop but that's consistently slower than the switch according to Valgrind. About the compare, I was looking at the code from glibc 2.18 and noticed memcmp compares `sizeof long` bytes at a time as soon as one of the string addresses is aligned while strcmp compares only one byte at time (just a regular while). So it should be a lot faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T00:59:20.603",
"Id": "63668",
"Score": "0",
"body": "I added some stuff on asserts. On the loop, I would expect it to do `ds_space` then `strncpy`, then `expand` in a loop. Note also that `strcmp` is a lexographic compare - `memcmp` is not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T00:33:28.150",
"Id": "63852",
"Score": "0",
"body": "Thank you for explaining. I looked about `memcmp` and I believe it should produce only return values with the same sign that would be produced by `strcmp` because the sign comes from the difference of the first pair of differing bytes interpreted as unsigned character. Source http://pubs.opengroup.org/onlinepubs/009696699/functions/memcmp.html That's exactly the same way `strncmp` returns http://pubs.opengroup.org/onlinepubs/9699919799/functions/strncmp.html Please let me know if I'm getting it wrong."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T22:34:59.363",
"Id": "38245",
"ParentId": "38236",
"Score": "4"
}
},
{
"body": "<p><strong>Overall</strong></p>\n\n<p>Your header doesn't include any function declarations so I'm not sure what your \"public interface\" will be but only few of your functions are <code>static</code> so I have to assume you intend to make all others available in which case I have to say I don't like the interface into your structure.</p>\n\n<p>From the looks of it your <code>Dynamic_String</code> should only be manipulated through the appropriate <code>ds_</code> functions yet your return the pointer to the internal storage from various functions which has the potential for the programmer screwing it up easily.</p>\n\n<p>So consider carefully defining the interface into your structure and how you intend it to be used. Most of you functions should either return <code>Dynamic_String *</code> or an <code>int</code> result indicating whether or not the operation was successfully executed. When dealing with memory allocation you should always check the result.</p>\n\n<p>I'd probably even go as far as making <code>Dynamic_String</code> opaque. Suggested interface in your header file:</p>\n\n<pre><code>typedef struct Dynamic_String Dynamic_String;\n\nDynamic_String* ds_allocate(size_t initial_size);\nint ds_resize(Dynamic_String* ds, size_t new_size);\nint ds_reserve(Dynamic_String* ds, size_t amount);\nint ds_shrink(Dynamic_String* ds, size_t amount);\nvoid ds_free(Dynamic_String* ds);\n\nint ds_compare(const Dynamic_String* first, const Dynamic_String* second);\nint ds_compare_cstr(const Dynamic_String* first, const char* second);\n\nint ds_copy(Dynamic_String* destination, const Dynamic_String* source);\nint ds_copy_cstr(Dynamic_String* destination, const char *src);\n\nDynamic_String* ds_duplicate(const Dynamic_String* ds);\nDynamic_String* ds_from_cstr(const char *str);\n\nint ds_append(Dynamic_String* destination, const Dynamic_String* source);\nint ds_append_cstr(Dynamic_String* destination, const char* source);\n\n... // etc. other useful manipulation functions \n\nconst char* ds_getcontent(Dynamic_String* ds);\nchar* ds_getcontent_unsafe(Dynamic_String* ds); // all bets are of\n\n... // query function like capacity, current size, is_empty/full etc.\n</code></pre>\n\n<p><strong>Technical Details</strong></p>\n\n<ol>\n<li><p><code>ds_allocate</code> does not check if there is already memory allocated and will simply leak if you pass in a structure which already has storage allocated. It think <code>ds_allocate</code> should simply allocate the structure and return it. Otherwise the programmer has to allocate the <code>Dynamic_String</code> structure and then call this init function which seems redundant. As user I'd prefer something along these lines:</p>\n\n<pre><code>Dynamic_String* ds_allocate(size_t initial_size)\n{\n Dynamic_String *result = malloc(sizeof(Dynamic_string));\n if (result == NULL)\n {\n return NULL;\n }\n ...\n}\n</code></pre>\n\n<p>Basically return <code>NULL</code> if any of the memory allocations fail or <code>initial_size < 1</code>. Provide a <code>ds_allocate_default()</code> if you want to give the programmer an option to just allocate an object with default size (I personally don't like these implicit \"pass 0 or negative to obtain a default size allocation\" implementations but YMMV).</p></li>\n<li><p>Technically the result of a pointer subtraction is <code>ptrdiff_t</code> and not <code>size_t</code>. The former is signed while the latter is unsigned. You should probably store the result of the subtraction in a local variable of type <code>ptrdiff_t</code> and check that it's not negative before returning it as <code>size_t</code>. If it's negative you apparently have hit a bug in the implementation.</p></li>\n<li><p><code>ds_append_cstring</code> can be greatly simplified by using <code>memcpy</code> rather than copying each byte individually. It will also be much faster.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T23:16:23.350",
"Id": "63831",
"Score": "0",
"body": "Thank you, your answer is really precise. I tested your suggestion 3: calculate length of string, allocate if needed and call memcpy and it's a lot faster indeed. Do you know why exactly?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T23:22:20.980",
"Id": "63832",
"Score": "0",
"body": "Considering both point to the same block of memory and end is always at least 1 past position, why isn't it acceptable to keep the operations like that?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T23:34:09.637",
"Id": "38254",
"ParentId": "38236",
"Score": "4"
}
},
{
"body": "<p>Others added many things, just some small <code>0</code> stuff follows.</p>\n\n<ol>\n<li><p><code>assert(max > 0);</code> in <code>ds_compare_n()</code> not needed.<br>\n<code>memcmp(,,0)</code> is well defined: returns zero. C11dr §7.24.1 2.</p></li>\n<li><p>In <code>ds_append_cstring()</code>, rather than <code>assert(*c_string != '\\0')</code>, simply <code>return destination;</code> when <code>*c_string == '\\0'</code>.</p></li>\n<li><p>In <code>ds_content_copy()</code>, the same. The need to insure <code>ds_length(ds) > 0)</code> is not needed and it takes away from your fine code's range.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T09:22:41.337",
"Id": "38266",
"ParentId": "38236",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "38245",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T19:26:33.400",
"Id": "38236",
"Score": "7",
"Tags": [
"c",
"strings"
],
"Title": "Dynamic Strings in C"
}
|
38236
|
<p>I have used <a href="http://www.php.net/manual/en/pdo.prepared-statements.php" rel="nofollow">this guide</a> to implement prepared statements in order to avoid SQL Injection.</p>
<p>I made some tests and no error was shown. However, I would like to ask you if you see any flaw in the code, so that I can improve it.</p>
<p>This is the code for a simple login:</p>
<pre><code><form action="conexion_PDO.php" method="post">
<label>User:</label>
<input type="text" name="user">
<label>Pass:</label>
<input type="password" name="pass">
<input type="submit" value="Ingresar">
</form>
</code></pre>
<p>This is Conexion_PDO.php:</p>
<pre><code><?php
try {
$gbd = new PDO('mysql:host=localhost;dbname=database', 'root', '');
$statement = $gbd->prepare("SELECT * FROM user where email = ? AND
password = ?");
if ($statement->execute(array($_GET['user'],md5($_POST['pass'])))) {
while ($rs = $statement->fetch()) {
print_r($rs);
}
$gbd = null;
} catch (PDOException $e) {
print "¡Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T20:08:48.420",
"Id": "64369",
"Score": "0",
"body": "Hope you don't mind, but I've gone ahead and _thoroughly_ reviewed your code. I know, criticism may come over as harsh and arrogant, but trust me, I'm only trying to help. And, IMHO, [that entails being bluntly honest](http://meta.codereview.stackexchange.com/questions/810/guidelines-for-new-users-proposal-tag)"
}
] |
[
{
"body": "<p>Your code does not have an SQL injection vulnerability because you are using placeholders instead of interpolating the variables. The way you interface with the database is laudable.</p>\n\n<p>Other aspects of your code can be improved:</p>\n\n<ul>\n<li><p>The variables <code>$gdb</code>, <code>$statement</code>, <code>$rs</code>, and <code>$e</code> are globals, which is not acceptable within a larger system. Enclose your code with a function to make them locals.</p>\n\n<p>Otherwise, you could accidentally overwrite variables from other parts in your code (e.g. when you <code>include</code> this snippet). Consider what happens if <code>$gdb</code> is already assigned: You try to clean up your usage by assigning <code>null</code> when you are finished, but the other code now suddenly has its contents for <code>$gdb</code> deleted.</p></li>\n<li><p>You do not seem to be using any intendation. Indent your code properly so that it can be understood easily.</p></li>\n<li><p>You use the literal <code>¡</code> inside a string, and print it directly to the output. As this is a non-ASCII character, this can get problematic depending on the encoding of your source code and the character encoding in the HTTP header and the HTML document. </p></li>\n<li><p>HTML markup is a kind of code as well – it too wants to be indented :)</p></li>\n</ul>\n\n<p>But now something important:</p>\n\n<blockquote>\n <p><strong>Do not use <code>md5</code> to hash passwords!</strong></p>\n</blockquote>\n\n<ol>\n<li>MD5 is extremely weak, and an increasing number of attacks are being discovered. Do not use it for anything in new systems.</li>\n<li>It is meant for checksums (e.g. when comparing files), not for hashing passwords. Such a checksum is designed that a subtle change in the input changes the output of the hash function drastically. It is <em>not</em> designed to irreversibly scramble a secret.</li>\n<li>It is far to easy to calculate the original password from a given hash, e.g. using rainbow tables. You do not even use a salt to defend against this (but even with a salt, an MD5-hashed password can be cracked within reasonable time).</li>\n</ol>\n\n<p>You should be using a <em>key-stretching</em> algorithm like <em>bcrypt</em>. I already wrote a rant about secure password hashing in <a href=\"https://stackoverflow.com/a/20462412/1521179\">another answer</a> which I would ask you to consult for a better hashing solution.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T21:49:20.473",
"Id": "63658",
"Score": "0",
"body": "wow, such a nice review, gracias"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T22:42:50.500",
"Id": "64386",
"Score": "0",
"body": "Good critique of md5"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T20:20:37.680",
"Id": "38240",
"ParentId": "38237",
"Score": "3"
}
},
{
"body": "<p>Flaws in terms of vulnerability to injecction: no. Prepared statements are safe when it comes to injection attacks. Querying the <code>user</code> table however... don't know, <code>user</code> is an iffy name, as it is often a reserved keyword <em>or</em> a table that already exists. Sure, not on your database, but I'd avoid the DB name, if I were you, or at least add the escaping backticks around it, as I will be doing throughout my answer...</p>\n\n<p>Now, in adition to amon's answer (I side with almost completely), I'd like to focus a bit more, if I may, on the code itself. As usual, I'll go through the PHP code practically line-by-line</p>\n\n<pre><code>try {\n$gbd = new PDO('mysql:host=localhost;dbname=database', 'root', '');\n</code></pre>\n\n<ul>\n<li>Right, as amon said, and I will now <em>\"order\"</em> <strong><em>indent your code</em></strong>. And don't do so randomly. Try to stick <a href=\"http://www.php-fig.org/\" rel=\"nofollow noreferrer\">to the most commonly adopted standards</a>, the PHP-FIG standards are as of yet unofficial, but all major players and Framework devs do adopt this coding style. The sooner we all do, the better.</li>\n<li>Variable names can be short, that's fine but <code>$gdb</code> might not be as obvious a name to your co-workers as it is to you. <code>$pdo</code> is as short, and is pretty descriptive, just use <em>logical, and easy to understand</em> var names throughout your code.</li>\n<li>Next, you're wrapping your code in a <code>try-catch</code> block, and that's fine. But do you know <em>when</em> <code>PDO</code> will throw exceptions? My guess is you're expecting it to throw whenever it errors. Well, <strong><em>it doesn't</em></strong>. Only <code>PDO::__construct</code> throws an exception when it failed to establish a connection (<a href=\"http://www.php.net/manual/en/pdo.construct.php\" rel=\"nofollow noreferrer\">see man here</a>). The other methods throw exceptions if the <code>PDO::ATTR_ERRMODE</code> was set to <code>PDO::ERRMODE_EXCEPTION</code>. This is done by <em>either</em> passing an array to the constructor, or calling <code>PDO::setAttribute</code>.</li>\n<li>Finally, you're using <code>localhost</code> in your DSN string. Now this will work, but <em>can slow you down, in some cases significantly</em>. This is because <code>PDO</code> has to use the DNS to translate <code>localhost</code> into <code>127.0.0.1</code>, so using the IP directly skips that step, doesn't harm readability one bit, and ensures your code will perform well.</li>\n</ul>\n\n<p>So, change this code to:</p>\n\n<pre><code>try {\n $pdo = new PDO(\n 'mysql:host=127.0.0.1;dbname=database',\n 'root',\n '',\n array(\n PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION\n )\n );\n</code></pre>\n\n<p>Next bit of code we'll look at</p>\n\n<pre><code>$statement = $gbd->prepare(\"SELECT * FROM user where email = ? AND password = ?\");\nif ($statement->execute(array($_GET['user'],md5($_POST['pass'])))) {\nwhile ($rs = $statement->fetch()) {\nprint_r($rs);\n}\n$gdb = null;\n} catch (PDOException $e) {//we're not going into the catch here, but I need it\n</code></pre>\n\n<p>If we simply <em>indent</em> the code, you'll soon notice a problem:</p>\n\n<pre><code>if ($statement->execute(array($_GET['user'],md5($_POST['pass'])))) {\n while ($rs = $statement->fetch()) {\n print_r($rs);\n }\n//WE ARE MISSING A CLOSING } HERE!\n$gdb = null;\n} catch (PDOException $e) {}\n</code></pre>\n\n<p>Ah, what a little indentation can do/avoid. Sorry, couldn't help myself here... Anyway, let's continue:</p>\n\n<ul>\n<li>Now that we've set the <code>PDO::ATTR_ERRMODE</code> so that an exception is thrown whenever a problem occurs, we don't need to check if the <code>$statement->execute()</code> call was successful, so the <code>if</code> branch is now redundant. Which is a good thing, too, because it was hellish to read, calling a method, and creating an array <em>and</em> hashing the password in one statement...</li>\n<li>When preparing statements, if you're not going to use variables in the string, I prefer using single quotes, but that's personal. I would, however, advise you to indent the query string in such a way that it is easy to read, comment and alter.</li>\n<li>You're dealing with a form, but getting the username from <code>$_GET</code> and the password from <code>$_POST</code>? that's not right, I suppose you made a mistake and meant for both to be <code>$_POST</code>. Either way, on <code>$_GET</code>: avoid whenever possible, it's <em>way</em> to vulnerable. POST isn't much safer, but every bit helps</li>\n<li>From the query I deduce that <code>$_POST['user']</code> is supposed to be an email address. Why aren't you checking if it is a valid email <em>before</em> bothering the DB? a simple <code>filter_var($_POST['user'], FILTER_VALIDATE_EMAIL)</code> would avoid a pointless query.</li>\n<li>The while-loop is fine, but I'd specify what the fetch-mode of <code>PDO</code> should be. If you want an assoc array, use <code>PDO::FETCH_ASSOC</code>, for objects use <code>PDO::FETCH_OBJ</code>... check the man pages, there are plenty to choose from. You can also choose a default fetch mode. Apart from that, all I'd say is that, if you do only have 1 statement in the loop's body (and this may be my bad C-coding habits that show here), I'd just inline it, especially if the statements are <em>that</em> short.</li>\n<li>Setting the <code>$gdb</code> variable to null in a <code>try</code> block is something I'd avoid, if an exception was thrown, you can't really be sure that the <code>$gdb = null;</code> statement was reached and executed, so don't write it there, there are better places for it</li>\n</ul>\n\n<p>Again, this is the code we now end up with:</p>\n\n<pre><code>//either set default here, in this case, I'll fetch objects by default\n$pdo->setAttribute(\n PDO::ATTR_DEFAULT_FETCH_MODE,\n PDO::FETCH_OBJ\n);\nif (!filter_var($_POST['user'], FILTER_VALIDATE_EMAIL)) {\n echo 'Invalid user: ', $_POST['user'], '<br/>';\n exit();//for now...\n}\n$statement = $pdo->prepare(\n 'SELECT * FROM `user`\n WHERE email = ?\n AND password = ?'\n);\n$statement->execute(\n array(\n $_POST['user'],\n md5($_POST['pass'] //change this to bcrypt or something, 15 cost should do\n )\n);\n//or specify fetch mode in fetch call, here, I'm fetching assoc arrays\nwhile ($row = $statement->fetch(PDO::FETCH_ASSOC)) {\n print_r($row);\n}\n//bad practice\nwhile($row = $statement->fetch()) print_r($row);\n</code></pre>\n\n<p>Now, more on the fetch modes <a href=\"http://www.php.net/manual/en/pdostatement.fetch.php\" rel=\"nofollow noreferrer\">can be found on the man page here</a><br/>\nAnd now, on to the catch block:</p>\n\n<pre><code>} catch (PDOException $e) {\nprint \"¡Error!: \" . $e->getMessage() . \"<br/>\";\ndie();\n}\n</code></pre>\n\n<p>There's only 1 thing I have to say about this <code>try-catch</code> block in your example code: <em>GET RID OF IT</em>. If all you're going to do in case of an exception is call <code>die()</code>, why bother catching the exception? why not let the app crash, and see the <em>\"fatal error uncaught exception...\"</em> message <em>and</em> the stack-trace that goes with it? If it's a production environment, you'll have <code>display erros</code> set to 0 anyway, so when developing, <em>don't hide information</em>, and get the full exception, not just the message.</p>\n\n<p>Other niggles I have are:</p>\n\n<ul>\n<li>This is where you should ensure the DB connection is closed, so this is where <code>$gdb = null;</code> belongs</li>\n<li><code>print</code> can only handle 1 string, so you have to concatenate it. <code>echo</code> is another language construct, to which you can pass any number of strings, comma-separated, so they needn't be concatenated. I've <a href=\"https://stackoverflow.com/a/20596645/1230836\">been rather verbose on the matter here</a></li>\n</ul>\n\n<p>So, if you <em>are</em> going to keep the <code>catch</code> block, this is what it <em>could</em> end up like</p>\n\n<pre><code>} catch (PDOException $e) {\n echo 'Error: ', $e->getMessage(), '<br/>';//comma-separated\n $pdo = null;\n //if the program should stop in case of an exception, then one of these works:\n exit(1);\n throw $e;//silly re-throw\n die();\n //but NOT catching the exception works best\n}\n</code></pre>\n\n<p>Then finally, you're closing the script using the close tag (<code>?></code>). Don't, as it can result in unintended white-space in the output.</p>\n\n<p>So, what would this code look like if I were to write it? Probably something like this</p>\n\n<pre><code><?php\nif (!filter_var($_POST['user'], FILTER_VALIDATE_EMAIL)) {\n header('Location: error-url');\n exit();\n}\n$pdo = new PDO(\n 'mysql:host=127.0.0.1;dbname=database',\n 'root',\n '',\n array(\n PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,\n PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ\n )\n);\n//I usually use named placeholders, the result is the same, though\n$stmt = $pdo->prepare(\n 'SELECT * FROM `user`\n WHERE email = :email\n AND password = :pass'\n);\n$bind = array(\n ':email' => $_POST['user'],\n ':pass' => password_hash(\n $_POST['pass'].MY_SALT_CONSTANT,\n PASSWORD_BCRYPT,\n array('cost' => 15)\n )\n);\n$stmt->execute($bind);\nwhile($row = $stmt->fetch()) {\n print_r($row);\n}\n$pdo = null;\n</code></pre>\n\n<p>With the exception that I would use an external config file (yaml, xml, ini, whichever takes your facy) that'd hold the DB connection params, options I'm passing to <code>password_hash</code> and what have you...</p>\n\n<p>Anyway, the resulting code isn't that much longer, it certainly is easier to read/maintain (very important), and just looks cleaner, more airy. There is much room for improvement, still, and yes, I would create a function, or class (so I don't have to use either an ugly <code>global</code>, but can have the constructor connect to the DB, or lazy-load the connection...) to which I can pass the form data, and get a boolean in response from.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T20:14:44.353",
"Id": "64370",
"Score": "0",
"body": "That's one hell of a review, great job."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T20:17:24.610",
"Id": "64371",
"Score": "2",
"body": "@DanAbramov: Thanks, my girlfriend is a little ticked off, as it took me quite some time to type it up. I thought I'd be done in a jiffy, but I really found myself talking about _every_ line of code... Never let it be said I'm not thorough in my reviews =]"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T11:55:16.160",
"Id": "64545",
"Score": "0",
"body": "Thank you Elias, I really appreciate the time you invested."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T12:54:22.467",
"Id": "64562",
"Score": "0",
"body": "@user2095819: You're welcome, but do note: _thank-you_-comments are discouraged (check help center, it says so explicitly). Instead you are asked to up-vote the helpful answer(s), and accept the one you found most useful"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T19:54:34.913",
"Id": "38587",
"ParentId": "38237",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T19:39:53.233",
"Id": "38237",
"Score": "5",
"Tags": [
"php",
"security",
"pdo"
],
"Title": "Do you see any flaws in these prepared statements to avoid SQL injection?"
}
|
38237
|
<p>A website I have designed uses a nav menu that shows submenus on <code>:hover</code>. The initial site did not use any responsive design: it targeted only the desktop environment. I am now using responsive-design techniques to target mobile devices and tablets, many of which are touch based rather than mouse based. </p>
<p>The big issue I was facing (and that many other people seem to have also faced) was the hover-based nav menu: it works great in a mouse environment, but on touch devices, there is no reliable way to trigger the hover, making the page difficult to use. </p>
<p>The goal is this:</p>
<ol>
<li>When a menu is hovered by a mouse, show the sub-menu.</li>
<li>When a menu is clicked with a mouse, open the link of the anchor tag.</li>
<li>The first time a menu is clicked by touch, show the sub menu. </li>
<li>The second time a menu is clicked by touch, open the link of the anchor tag. </li>
<li>Switch functionality seamlessly for tablets that also have mouse devices attached. </li>
</ol>
<p>My team is not willing to sacrifice the hover effect on mouse-based machines. They like it and do not want to make the menus click based on all devices. I agree with this. </p>
<p>After looking around the net, I couldn't find any single solution for my problem. I put a few of them together and developed something that has tested well on Android, getting exactly the functionality I wanted. Is there anything that can be improved and/or do you see any problems with this approach? </p>
<pre><code>jQuery(document).ready(function() {
var touched=false;
jQuery(".nav").on('touchstart', 'li .has_children', function (e) { touched=true; });
jQuery("html").on('mousemove', function (e) { touched=false; });
jQuery("html").on('click', updatePreviousTouched );
jQuery(".nav").on('click', 'li .has_children', function (e) {
updatePreviousTouched(e);
if( touched ) {
if (jQuery(this).data('clicked_once')) {
jQuery(this).data('clicked_once', false);
return true;
} else {
e.preventDefault();
jQuery(this).trigger("mouseenter");
jQuery(this).data('clicked_once', true);
}
}
touched=false;
});
var previous_touched;
function updatePreviousTouched(e) {
if( typeof previous_touched != 'undefined' && previous_touched != null && !previous_touched.is( jQuery(e.target) ) ) {
previous_touched.data('clicked_once', false);
}
previous_touched=jQuery(e.target);
}
}
</code></pre>
<p>If this solution can be improved, please provide any suggestions. If you find that it doesn't work for you, please let me know that too. I'm posting it here to try to get any suggestions for improvement and to publish the idea so others can benefit from it. </p>
<p>Here are the results of my tests so far:</p>
<ol>
<li><strong>Windows 7 on major 5 browsers</strong>: works. </li>
<li><strong>Android tablet on default browser</strong>: works. </li>
<li><strong>Windows 7 laptop with touch-screen on IE and Chrome</strong>: Sort-of-works. The machine is running the desktop version of both browsers, so it is not triggering the "touchstart" event. Somewhere between the touchscreen and the browser, something is converting the touch into mouse events. However, since the mouse is a non-removable part of this device, I don't consider this a failure. I would like it if it worked like a tablet, but there doesn't seem to be the technology available yet. </li>
<li><strong>iOS iPad</strong>: This worked as desired <em>before</em> I wrote the above javascript. It appears that ios does some of this hover/click magic for us behind the scenes. I have a team member checking to see if my javascript broke the iOS functionality, I will edit this post once I get an answer. </li>
</ol>
<p>Other notes:</p>
<ol>
<li>This is only the menu for the desktop and tablet site. There is a different, click-based menu for the mobile site. I wouldn't recommend using this solution for a phone-sized device. </li>
</ol>
|
[] |
[
{
"body": "<p>First of all, lets clean up your code to really leverage the power of <code>.on()</code>:</p>\n\n<pre><code>$(function() {\n var touched = false,\n previous_touched;\n\n function updatePreviousTouched(e){\n if(typeof previous_touched !== 'undefined' && previous_touched !== null && !previous_touched.is($(e.target))){\n previous_touched.data('clicked_once', false);\n }\n\n previous_touched = $(e.target);\n }\n\n $(\".nav\").on({\n touchstart:function(e) {\n touched=true; \n },\n click:function(e);\n var $this = $(this);\n\n updatePreviousTouched(e);\n\n if(touched) { \n if ($this.data('clicked_once')) {\n $this.data('clicked_once', false);\n return true;\n } else {\n e.preventDefault();\n $this.trigger(\"mouseenter\").data('clicked_once', true); \n }\n }\n\n touched = false;\n }\n },'li .has_children');\n\n $(\"html\").on({\n mousemove:function(e){\n touched=false;\n },\n click:updatePreviousTouched\n });\n});\n</code></pre>\n\n<p>Notice the following:</p>\n\n<ul>\n<li>Object use of <code>.on()</code> rather than mere string use (only one binding instead of multiple)</li>\n<li>caching where appropriate</li>\n<li>variables and functions declared at top</li>\n</ul>\n\n<p>Now that we've got your original code all pretty and efficient, I'll offer a different alternative that should be much more lightweight. </p>\n\n<p>Based on your currently use CSS to do the <code>:hover</code> piece. Instead, you may consider making that CSS a class, and then dynamically add / remove the class in the code. This maintains the speedy leveraging of CSS while avoiding dealing with the CSS and JS events fighting each other over what wins out. I have done something like this on a number of projects and it seems to work pretty well. The key is the custom event; by separating this out, you can control when it is fired rather than rely on some crazy <code>if</code> logic to determine whether it should be fired or not.</p>\n\n<p>Here is a working example:</p>\n\n<p>This CSS that was this...</p>\n\n<pre><code>.header-nav-menu ul li:hover > ul { display: inline-block; }\n</code></pre>\n\n<p>Becomes this...</p>\n\n<pre><code>.header-nav-menu ul li > ul.MenuActive { display: inline-block; }\n</code></pre>\n\n<p>And here is your working jQuery...</p>\n\n<pre><code>$(function(){\n var menuActive = false,\n touched = false,\n $nav = $('.nav');\n\n function removeActive(callback){\n $nav.find('.MenuActive').removeClass('MenuActive');\n callback();\n }\n\n function newActive($this,menu){\n removeActive(function(){\n $this.next().addClass('MenuActive').queue(function(){\n if(menu){\n menuActive = true;\n touched = false;\n } else {\n touched = true;\n }\n }).dequeue();\n }); \n }\n\n $nav.on({\n touchstart:function(e){ \n e.stopPropagation();\n newActive($(this),touched);\n },\n mouseenter:function(){\n newActive($(this),true); \n },\n click:function(e){\n e.preventDefault();\n\n if(menuActive){\n $(this).trigger('trueClick',e.target);\n }\n },\n trueClick:function(e,$target){\n $(this).parents('.nav').trigger('mouseleave');\n window.location.href = $target;\n }\n },'li .has_children').on('mouseleave',function(){\n removeActive(function(){\n menuActive = false;\n touched = false;\n });\n });\n\n $('html').on('touchstart',function(e){\n if(menuActive){\n $nav.trigger('mouseleave');\n }\n });\n});\n</code></pre>\n\n<p>This should manage what you want in a much cleaner way:</p>\n\n<ul>\n<li><code>menuActive</code> variable defaults to <code>false</code>, and is only set to <code>true</code> when submenu is open (by either <code>touchstart</code> or <code>mouseenter</code>)</li>\n<li>actual click action is prevented, and verification is done to determine if menu is appropriately active</li>\n<li>if menu is active, custom event is triggered to go to the link's target</li>\n<li>touch event is not bubble up to <code>html</code> by use of <code>e.stopPropagation();</code></li>\n<li>if user touches somewhere on the screen that is not the submenu, it will close the submenu and set <code>menuActive</code> to false</li>\n</ul>\n\n<p>I separated out a couple of actions into reusable functions, and separated events to avoid <code>if</code> checking. This code executes much faster than the original, and more importantly it is bulletproof. There is true separation of touch vs hover events, the show / hide of the menu still leverages CSS, and it accounts for browser inconsistencies (example: the reason for the use of the callback is because Safari 5.1 has a 300ms delay between adding a class and it displaying onscreen).</p>\n\n<p>I know this code is longer than the original, but guaranteed it will run faster and be easier to maintain. Hope it helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T00:38:08.797",
"Id": "63734",
"Score": "0",
"body": "This is a really good answer. Thank you. What is the etiquette here for accepting answers? I would be interested in additional code review, since there's never any one \"right\" answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T01:25:00.653",
"Id": "63736",
"Score": "0",
"body": "From what I've seen based on other CSS related reviews, newer answers generally cover things older answers have missed. All answers will usually have something of value to add, so it is just a case of choosing whoever adds the most."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T20:20:16.803",
"Id": "38292",
"ParentId": "38239",
"Score": "14"
}
}
] |
{
"AcceptedAnswerId": "38292",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T20:13:58.270",
"Id": "38239",
"Score": "24",
"Tags": [
"javascript",
"jquery",
"touch"
],
"Title": "Handling Hover Events on a Touch Screen"
}
|
38239
|
<p>I have a deck of flashcards that I want to shuffle. Here's the method I'm using to shuffle them:</p>
<pre><code>func (deck *Deck) Shuffle() {
rand.Seed(time.Now().UnixNano())
randomIndexes := rand.Perm(len(deck.Cards))
shuffledCards := make([]Card, len(deck.Cards))
for i := 0; i < len(deck.Cards); i++ {
shuffledCards[i] = deck.Cards[randomIndexes[i]]
}
deck.Cards = shuffledCards
}
</code></pre>
<p>Is this an efficient way of doing it, or is there a better way?</p>
|
[] |
[
{
"body": "<p>I would recommend something closer to a Knuth shuffle, where you swap items in place in the array, rather then allocating a new one.</p>\n\n<p>This is untested and is based on the <a href=\"http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"noreferrer\">Fisher-Yates shuffle</a>:</p>\n\n<pre><code>func (deck *Deck) Shuffle() {\n rand.Seed(time.Now().UnixNano())\n\n for i := len(deck.Cards)-1; i > 0; i-- {\n j := rand.Intn(i+1) // i+1 rather than i; the upper bound is not inclusive\n deck.Cards[i], deck.Cards[j] = deck.Cards[j], deck.Cards[i]\n }\n}\n</code></pre>\n\n<p>Unrelated to shuffling, you should also check out bucketed flashcards. Consider the <a href=\"http://en.wikipedia.org/wiki/Leitner_system\" rel=\"noreferrer\">Leitner system</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T12:42:32.740",
"Id": "63947",
"Score": "0",
"body": "Simple and Efficient. Thanks for the link :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T22:26:41.783",
"Id": "38243",
"ParentId": "38241",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "38243",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T20:29:27.627",
"Id": "38241",
"Score": "2",
"Tags": [
"optimization",
"go",
"shuffle"
],
"Title": "Shuffling an array of cards"
}
|
38241
|
<p>I'm trying to learn Python and am working on a simple <a href="https://github.com/bjorn/tiled/wiki/TMX-Map-Format" rel="nofollow">Tiled Map Format</a> (.tmx) reader as practice. So as to not post too much code at once, I'm only publishing the <code><data></code> element which stores the tiles displayed in a tiled map.</p>
<p>I'm looking for any critique, no matter how harsh, on quality of code, the Pythonic way of coding, my unit tests, etc.</p>
<p>First, the <a href="https://github.com/bjorn/tiled/wiki/TMX-Map-Format#data" rel="nofollow">description of the <code><data></code> element</a> from the documentation:</p>
<pre><code><data>
encoding: The encoding used to encode the tile layer data.
When used, it can be "base64" and "csv" at the moment.
compression: The compression used to compress the tile layer data.
Supports "gzip" and "zlib".
First you need to base64-decode it, then you may need to decompress it.
Now you have an array of bytes, which should be interpreted as an array of
unsigned 32-bit integers using little-endian byte ordering.
Whatever format you choose for your layer data,
you will always end up with so called "global tile IDs" (gids).
</code></pre>
<p>The code:</p>
<pre><code>@value_equality
class Data:
"""
Contains the information on how the current map is put together.
Data is compressed first, then encoded. Then the data is an array of bytes which should be interpreted
as an array of unsigned 32-bit integers in little-endian format.
If neither encoding nor compression is used, then the data is stored as an xml list of tile elements.
All formats represent global tile ids and may refer to any tilesets used by the map. In order to correctly map the
global id to the tileset, find the tileset with the highest firstgid that is still lower or equal than the gid. The
tilesets are always stored with increasing firstgids
"""
@property
def encoding(self):
"""
The encoding used to encode the tile layer data.
Can be either "base64" or "csv".
(Optional)
"""
self._encoding
@property
def compression(self):
"""
The compression used to compress the tile layer data.
Can be either "gzip" or "zlib"
(Optional)
"""
self._compression
@property
def tiles(self):
self._tiles
@property
def global_tile_ids(self):
self._global_tile_ids
def __init__(self, encoding=None, compression=None, global_tile_ids=[], tiles=None):
self._encoding = encoding
self._compression = compression
self._global_tile_ids = global_tile_ids
self._tiles = tiles
def __eq__(self, other):
return self.__dict__ == other.__dict__ if isinstance(other, self.__class__) else False
def __ne__(self, other):
return not self.__eq__(other)
@classmethod
def from_tmx(cls, element):
"""Parse <data> element from .tmx file"""
attributes = {
'encoding': element.attrib['encoding'] if 'encoding' in element.attrib else None,
'compression': element.attrib['compression'] if 'compression' in element.attrib else None,
}
tile_ids = []
if attributes['encoding'] is None and attributes['compression'] is None:
map(tile_ids.append, element.iter('tile'))
else:
decoded = Data._decode(element.text, attributes['encoding'])
decompressed = Data._decompress(decoded, attributes['compression'])
tile_ids = list(decompressed)
attributes['global_tile_ids'] = list(map(DataTile.from_bytes, tile_ids))
return cls(**attributes)
@staticmethod
def _decode(data, encoding):
decoders = {
'base64': (lambda x: base64.b64decode(x)),
'csv': (lambda x: map(int, x.strip().split(','))),
None: (lambda x: x)
}
return decoders[encoding](data)
@staticmethod
def _decompress(data, compression):
decompressors = {
'gzip': (lambda x: gzip.decompress(data)),
'zlib': (lambda x: zlib.decompress(data)),
None: (lambda x: x)
}
return decompressors[compression](data)
@value_equality
class DataTile():
HORIZONTAL_FLIP_BIT = 0x80000000
VERTICAL_FLIP_BIT = 0x40000000
DIAGONAL_FLIP_BIT = 0x20000000
@property
def global_tile_id(self):
return self._global_tile_id
@property
def flipped_horizontally(self):
return self._flipped_horizontally
@property
def flipped_vertically(self):
return self._flipped_vertically
@property
def flipped_diagonally(self):
return self._flipped_diagonally
def __init__(self, global_tile_id, flipped_horizontally=False, flipped_vertically=False, flipped_diagonally=False):
self._global_tile_id = global_tile_id
self._flipped_horizontally = flipped_horizontally
self._flipped_vertically = flipped_vertically
self._flipped_diagonally = flipped_diagonally
def __eq__(self, other):
return self.__dict__ == other.__dict__ if isinstance(other, self.__class__) else False
def __ne__(self, other):
return not self.__eq__(other)
@classmethod
def from_bytes(cls, tile_id):
attributes = {
'global_tile_id': tile_id & ~(cls.HORIZONTAL_FLIP_BIT | cls.VERTICAL_FLIP_BIT | cls.DIAGONAL_FLIP_BIT),
'flipped_horizontally': (tile_id & cls.HORIZONTAL_FLIP_BIT != 0),
'flipped_vertically': (tile_id & cls.VERTICAL_FLIP_BIT != 0),
'flipped_diagonally': (tile_id & cls.DIAGONAL_FLIP_BIT != 0)
}
return cls(**attributes)
</code></pre>
<p>My first unit tests:</p>
<pre><code>class TiledMapReaderTest(unittest.TestCase):
def setUp(self):
self._unknowntmx = self._resource('Unknown.tmx')
self._completexml = self._resource('Complete.xml')
self._minimaltmx = self._resource('Minimal.tmx')
self._completetmx = self._resource('Complete.tmx')
self._tilesettmx = self._resource('Tileset.tmx')
self._imagetmx = self._resource('Image.tmx')
self._datatmx = self._resource('Data.tmx')
self._csvtmx = self._resource('CsvData.tmx')
def _resource(self, name):
return os.path.join(os.path.dirname(__file__), 'res', name)
def _root(self, file):
return ET.parse(file).getroot()
# Snip unrelated tests
def test_datatag_constructsdata(self):
root = self._root(self._datatmx)
actual = Data.from_tmx(root)
expected = Data(encoding='base64', compression='gzip')
self.assertEqual(expected._encoding, actual._encoding)
self.assertEqual(expected._compression, actual._compression)
def test_datatag_base64_decodesdata(self):
data = b'H4sIAAAAAAAAAO3NoREAMAgEsLedAfafE4+s6l0jolNJiif18tt/Fj8AAMC9ARtYg28AEAAA'
actual = Data._decode(data, 'base64')
expected = base64.b64decode(data)
self.assertEqual(expected, actual)
def test_datatag_gzip_decompressesdata(self):
data = b'H4sIAAAAAAAAAO3NoREAMAgEsLedAfafE4+s6l0jolNJiif18tt/Fj8AAMC9ARtYg28AEAAA'
actual = Data._decompress(Data._decode(data, 'base64'), 'gzip')
expected = gzip.decompress(base64.b64decode(data))
self.assertEqual(expected, actual)
def test_datatile_frombytes(self):
flipped_horizontally = 0x80000001
flipped_vertically = 0x40000002
flipped_diagonally = 0x20000003
flipped_everyway = 0xe0000004
expected = DataTile(global_tile_id=1, flipped_horizontally=True)
self._datatile_equal(flipped_horizontally, expected)
expected = DataTile(global_tile_id=2, flipped_vertically=True)
self._datatile_equal(flipped_vertically, expected)
expected = DataTile(global_tile_id=3, flipped_diagonally=True)
self._datatile_equal(flipped_diagonally, expected)
expected = DataTile(global_tile_id=4, flipped_horizontally=True, flipped_vertically=True, flipped_diagonally=True)
self._datatile_equal(flipped_everyway, expected)
def _datatile_equal(self, bytes, expected):
actual = DataTile.from_bytes(bytes)
self.assertEqual(expected, actual)
</code></pre>
<p>Custom <code>@value_equality</code> decorator</p>
<pre><code>def value_equality(cls):
"""Implement __eq__ and __ne__; caution, does not work with polymorphic yet."""
cls.__eq__ = lambda self, other: self.__dict__ == other.__dict__ if isinstance(other, self.__class__) else False
cls.__ne__ = lambda self, other: not self.__eq__(other)
return cls
</code></pre>
|
[] |
[
{
"body": "<h3>1. General comments</h3>\n\n<ol>\n<li><p>You have a tendency to over-complicate things. As a result, your code is full of mistakes that you failed to spot. Keep code as simple as possible and it will be easier to inspect and test!</p></li>\n<li><p>The code you posted is missing a bunch of <code>import</code> statments needed to run. To help other reviewers, I think that these imports need to be:</p>\n\n<pre><code>import base64\nimport gzip\nimport os\nimport unittest\nimport xml.etree.ElementTree as ET\nimport zlib\n</code></pre></li>\n<li><p>It is worth keeping to 79 columns as recommended by the Python style guide (<a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a>). Your code is hard to read here on Code Review because the long lines don't fit and we have to scroll horizontally to read them.</p></li>\n</ol>\n\n<h3>2. value_equality decorator</h3>\n\n<ol>\n<li><p>Your decorator <code>value_equality</code> does not work! It looks as though you have not tested it in the subclass case. Suppose we have:</p>\n\n<pre><code>@value_equality\nclass A: pass\nclass B(A): pass\n</code></pre>\n\n<p>then an object of the subclass <code>B</code> does not compare equal to an object of the superclass <code>A</code> if we use the <code>==</code> operator:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> a, b = A(), B()\n>>> a == b\nFalse\n</code></pre>\n\n<p>and yet the <code>__eq__</code> method works fine:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> a.__eq__(b)\nTrue\n</code></pre>\n\n<p>The Python feature that explains this behaviour is a bit obscure, but it <em>is</em> documented, in <a href=\"http://docs.python.org/3/reference/datamodel.html#index-84\" rel=\"nofollow\">this note about the implementation of special methods</a>:</p>\n\n<blockquote>\n <p>Note: If the right operand’s type is a subclass of the left operand’s type and that subclass provides the reflected method for the operation, this method will be called before the left operand’s non-reflected method. This behavior allows subclasses to override their ancestors’ operations.</p>\n</blockquote>\n\n<p>Combined with the fact that <code>__eq__</code> is its own reflected operation, this means that when Python evaluates <code>a == b</code>, it notes that the type of <code>b</code> is a subclass of the type of <code>a</code>, and so it calls <code>b.__eq__(a)</code>, which tests <code>isinstance(a, b.__class__)</code> which is <code>False</code>.</p>\n\n<p>This highlights a basic problem with the design of <code>value_equality</code>. Equality should be a symmetric operation: that is, if <code>a</code> equals <code>b</code> then <code>b</code> should equal <code>a</code>, and so it shouldn't matter which way round the comparison is done. But in your implementation you use an <code>isinstance</code> test which is not symmetrical.</p></li>\n<li><p>I like that you've written docstrings. But unfortunately you've written them from the wrong point of view. The purpose of a docstring is to provide help to the <em>user</em>: that is, to answer questions like \"what does this do?\" and \"how do I use it?\". For example:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> help(abs)\nHelp on built-in function abs in module builtins:\n\nabs(...)\n abs(number) -> number\n\n Return the absolute value of the argument.\n</code></pre>\n\n<p>But you've written your docstrings from the point of view of the <em>implementor</em>: basically they are notes to yourself that really should be <em>comments</em> instead. For example, the docstring for <code>value_equality</code> is</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Implement __eq__ and __ne__; caution, does not work with polymorphic yet.\n</code></pre>\n\n<p>where the first clause is a detail of the implementation, and the second is just obscure to me. (See below for how the docstring should look.)</p>\n\n<p>Similarly, the docstring for the <code>Data</code> class contains a description of how the list of tiles is encoded into a <code><data></code> element. This is handy for you as an implementor, but is useless for the <em>user</em> of the <code>Data</code> class. Put this information in a comment (or better still, provide a link to the TMX documentation, which is more comprehensive).</p></li>\n<li><p><code>value_equality</code> doesn't need to be a decorator because it does not look at the implementation of <code>cls</code>. So you should prefer to make it into a class instead. Classes are simpler to understand than decorators.</p>\n\n<pre><code>class EqualAttributes(object):\n \"\"\"Class of objects that can be compared for equality. Instances\n compare equal if their type and writable attributes are equal. For\n example:\n\n >>> class Foo(EqualAttributes): pass\n >>> a, b = Foo(), Foo()\n >>> a.x, b.x = 1, 1\n >>> a == b, a != b\n (True, False)\n >>> a.y, b.y = 1, 2\n >>> a == b, a != b\n (False, True)\n\n \"\"\"\n def __eq__(self, other):\n return type(self) == type(other) and self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n return not (self == other)\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li>The docstring is written from the user's point of view.</li>\n<li>There are some examples in the form of <a href=\"http://docs.python.org/3/reference/doctest.html\" rel=\"nofollow\">doctests</a>.</li>\n<li>I've used <code>type(self)</code> which is clearer than <code>self.__class__</code>.</li>\n<li>I've addressed the symmetry problem by restricting equality to objects of the same type.</li>\n</ul></li>\n<li><p>The <code>Data</code> and <code>DataTile</code> classes have <code>__eq__</code> and <code>__ne__</code> methods, so why do they also have <code>@value_equality</code>? Surely they should have one or the other, but not both?</p></li>\n<li><p>Are you sure you really need the <code>value_equality</code> decorator at all? You only ever use it in your unit tests, so I think things would be much simpler if you just got rid of this class and compared attributes directly in the test cases.</p></li>\n</ol>\n\n<h3>3. DataTile class</h3>\n\n<ol>\n<li><p>There's no docstring for the <code>DataTile</code> class. What does this class do and how should I use it?</p></li>\n<li><p>The name <code>DataTile</code> seems superfluous. Why not just <code>Tile</code>?</p></li>\n<li><p>Instead of:</p>\n\n<pre><code>HORIZONTAL_FLIP_BIT = 0x80000000\nVERTICAL_FLIP_BIT = 0x40000000\nDIAGONAL_FLIP_BIT = 0x20000000\n</code></pre>\n\n<p>I would write:</p>\n\n<pre><code>HORIZONTAL_FLIP = 1 << 31\nVERTICAL_FLIP = 1 << 30\nDIAGONAL_FLIP = 1 << 29\n</code></pre>\n\n<p>to make it clear where these numbers come from.</p></li>\n<li><p>The <code>from_bytes</code> method is mis-named: it doesn't actually take a sequence of bytes as an argument, but rather a tile id as a number.</p></li>\n<li><p>In the <code>from_bytes</code> method, it's pointless to build a dictionary and then immediately pass it as keyword arguments. Just pass the keyword arguments instead.</p></li>\n<li><p>The value <code>~(cls.HORIZONTAL_FLIP_BIT | cls.VERTICAL_FLIP_BIT | cls.DIAGONAL_FLIP_BIT)</code> is always the same, so why not compute it just once?</p></li>\n<li><p>There doesn't seem to be any need for separate <code>__init__</code> and <code>from_bytes</code> methods. You only use <code>__init__</code> in the test cases. So I would replace <code>__init__</code> with <code>from_bytes</code> and adjust the test cases accordingly.</p></li>\n</ol>\n\n<h3>4. Data class</h3>\n\n<ol>\n<li><p>It's not clear to me what the purpose of this class is. What kind of <em>thing</em> does a <code>Data</code> object represent? As far as I can see, the only purpose of this class is to produce a list of <code>DataTile</code> objects from a <code><data></code> element. So why not just write a function?</p></li>\n<li><p>The properties <code>Data.encoding</code> and <code>Data.compression</code> are buggy: you need to explicitly <code>return</code> the value.</p></li>\n<li><p>But why bother with properties at all? In Python, properties are normally used in three scenarios. First, to provide a simple interface to a complex data structure. Second, to give the implementer freedom to change the implementation in future. Third, in combination with setters when writing a public API whose internal data structures have an invariant that needs to be preserved. But it's not clear to me that any of those scenarios apply to your code, so why not keep it simple and just use attributes?</p></li>\n<li><p><code>@staticmethod</code> is usually an anti-pattern in Python. When code has nothing to do with a class, then there's no need to make it a static method, you can just make it a plain function instead. Python is not Java (not everything needs to be part of a class).</p></li>\n<li><p>It's not clear why <code>Data.__init__</code> takes <code>compression</code> or <code>encoding</code> values: these are never used.</p></li>\n<li><p>There seems to be some confusion in this class about <code>global_tile_ids</code> versus <code>tiles</code>.</p></li>\n<li><p><code>Data.__init__</code> takes a parameter with a default value of an empty list: <code>global_tile_ids=[]</code>. Default values for function parameters are evaluated only once, when the function is defined. So all instances of <code>Data</code> will share the same default value for <code>global_tile_ids</code>.</p>\n\n<p>If this isn't what you want, you should create a new empty list for each instance:</p>\n\n<pre><code>def __init__(..., global_tile_ids=None, ...):\n # ...\n self.global_tile_ids = global_tile_ids or []\n</code></pre></li>\n<li><p>Instead of:</p>\n\n<pre><code>element.attrib['encoding'] if 'encoding' in element.attrib else None\n</code></pre>\n\n<p>use the <a href=\"http://docs.python.org/3/library/stdtypes.html#dict.get\" rel=\"nofollow\"><code>dict.get</code></a> method and write:</p>\n\n<pre><code>element.attrib.get('encoding')\n</code></pre></li>\n<li><p>This code doesn't work:</p>\n\n<pre><code>map(tile_ids.append, element.iter('tile'))\n</code></pre>\n\n<p>There are two problems. First, <code>map</code> returns an iterator and does not actually apply the function until you iterate over it. Second, even if you do iterate, you'll get a list of <code><tile></code> elements, whereas what you want is a list of global ids.</p>\n\n<p>So write instead:</p>\n\n<pre><code>tile_ids = [tile.attrib['gid'] for tile in element.iter('tile')]\n</code></pre></li>\n<li><p>This:</p>\n\n<pre><code>lambda x: gzip.decompress(data)\n</code></pre>\n\n<p>looks like a mistake for:</p>\n\n<pre><code>lambda x: gzip.decompress(x)\n</code></pre>\n\n<p>but this is just the same as:</p>\n\n<pre><code>gzip.decompress\n</code></pre>\n\n<p>(which computer scientists call <a href=\"https://en.wikipedia.org/wiki/Lambda_calculus#.CE.B7-conversion\" rel=\"nofollow\">η-equivalence</a>).</p></li>\n<li><p>I think you've misunderstood the TMX specification. Or at least, let us say, the TMX specification is very unclear. You've written, \"Data is compressed first, then encoded\" but that can't be right when <code>encoding=csv</code> because the types don't match. Compression outputs a <em>byte stream</em>, but CSV encoding takes a <em>list of gids</em> as input. These don't match, so the combination can't make any sense.</p>\n\n<p>The only way that I can see to make sense of the specification is that there are only four possibilities:</p>\n\n<pre><code>compression encoding gids represented as\n----------- -------- -----------------------------------------------\nNone None gid= attributes in <tile> elements\nNone 'csv' comma-separated numbers, encoded in ASCII\n'gzip' 'base64' 32-bit numbers, gzip-compressed, base64-encoded\n'zlib' 'base64' 32-bit numbers, zlib-compressed, base64-encoded\n</code></pre>\n\n<p>It might be worth opening an issue on GitHub and see if Thorbjørn Lindeijer can clarify the documentation.</p></li>\n<li><p>You don't properly decode the tile data! After decompressing it you just call</p>\n\n<pre><code>tile_ids = list(decompressed)\n</code></pre>\n\n<p>but this results in <code>tile_ids</code> being a list with one element for each byte in the decompressed data. But <a href=\"https://github.com/bjorn/tiled/wiki/TMX-Map-Format#data\" rel=\"nofollow\">in the TMX documentation it says</a> that these bytes \"should be interpreted as an array of unsigned 32-bit integers using little-endian byte ordering.\" You have completely omitted this step.</p></li>\n</ol>\n\n<h3>5. Revised code</h3>\n\n<pre><code>import base64\nimport gzip\nimport struct\nimport zlib\n\nclass Tile(object):\n \"\"\"An instance of a tile in a map.\"\"\"\n\n HORIZONTAL_FLIP = 1 << 31\n VERTICAL_FLIP = 1 << 30\n DIAGONAL_FLIP = 1 << 29\n TILE_ID_MASK = ~(HORIZONTAL_FLIP + VERTICAL_FLIP + DIAGONAL_FLIP)\n\n def __init__(self, gid):\n self.global_tile_id = gid & self.TILE_ID_MASK\n self.flipped_horizontally = bool(gid & self.HORIZONTAL_FLIP)\n self.flipped_vertically = bool(gid & self.VERTICAL_FLIP)\n self.flipped_diagonally = bool(gid & self.DIAGONAL_FLIP)\n\ndef parse_data(element):\n \"\"\"Parse a <data> element from Tiled Map Format (TMX) and return a\n list of Tile objects.\n\n \"\"\"\n assert(element.tag == 'data')\n encoding = element.attrib.get('encoding')\n compression = element.attrib.get('compression')\n if encoding not in (None, 'base64', 'csv'):\n raise ValueError('unsupported encoding={}'.format(encoding))\n if compression not in (None, 'gzip', 'zlib'):\n raise ValueError('unsupported compression={}'.format(compression))\n if not encoding and not compression:\n return [Tile(int(tile.attrib['gid'])) for tile in element.iter('tile')]\n elif encoding == 'csv' and not compression:\n gids = [int(gid) for gid in data.split(',')]\n elif encoding == 'base64':\n data = base64.b64decode(element.text)\n if compression == 'gzip':\n data = gzip.decompress(data)\n elif compression == 'zlib':\n data = zlib.decompress(data)\n gids = struct.unpack('<{}L'.format(len(data) // 4), data)\n else:\n raise ValueError('unsupported combination: encoding={} compression={}'\n .format(encoding, compression))\n return [Tile(gid) for gid in gids]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T15:23:37.773",
"Id": "63908",
"Score": "0",
"body": "Wow, that is a lot to take in. Incredible work, Gareth! I've read through it once and agree with most of your points. I've only one question regarding the value_equality decorator. Wouldn't the readability of a class being decorated be the same as that of a class inherting ValueEquality? `@value_equality class Foo:` and `class Foo(ValueEquality):` seem equally readable. In any case, thank you so much for the review! I'll read through it again and refactor my implementation accordingly :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T15:26:41.563",
"Id": "63909",
"Score": "1",
"body": "Yes, when you come to *use* it there's no advantage in readability. But the *implementation* of a class tends to be more readable than the implementation of a decorator, so it's best to reserve decorators for when a class won't do."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T15:04:54.427",
"Id": "38367",
"ParentId": "38246",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "38367",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T22:38:50.973",
"Id": "38246",
"Score": "4",
"Tags": [
"python",
"unit-testing",
"python-3.x",
"io"
],
"Title": "Partial data reading implementation"
}
|
38246
|
<p>The problem to the question is:</p>
<blockquote>
<p>Write a program that takes 3 integers as an input from the user using input dialog messages and sorts the three numbers.</p>
</blockquote>
<p>I just want to know: is there any major differences between my code and the book's code in terms of efficiency or anything specific that I could have done better in my code? I am slowly learning Java and am trying to pick up the best techniques as I go along trying to learn this language. Also, I really don't understand the logic behind the book's answer. It seems as if they are only comparing two numbers, but how can they guess what the third number will be in the sort?</p>
<p><strong>Note:</strong> I am following my textbook and the newest thing we have learned are if and else statements along with switch statements. I have not learned any looping and I am still in the basics. I am following Introduction To Java Programming 9th edition Daniel Liang and this is from the Chapter 3 exercises.</p>
<p><strong>My solution:</strong></p>
<pre><code>package Chapter3Exercises;
import javax.swing.JOptionPane;
public class SortThreeIntegers
{
public static void main(String[] args)
{
//Prompt user to enter three integers
String stringNum1 = JOptionPane.showInputDialog(null, "Please enter 1st Integer: ");
String stringNum2 = JOptionPane.showInputDialog(null, "Please enter 2nd Integer: ");
String stringNum3 = JOptionPane.showInputDialog(null, "Please enter 3rd Integer: ");
int num1 = Integer.parseInt(stringNum1);
int num2 = Integer.parseInt(stringNum2);
int num3 = Integer.parseInt(stringNum3);
if ((num1 > num2 && num1 > num3))
{
if(num2 > num3)
{
System.out.print(num3 + " " + num2 + " " + num1);
}
else
System.out.print(num2 + " " + num3 + " " + num1);
}
else if ((num2 > num1 && num2 > num3))
{
if(num1 > num3)
{
System.out.print(num3 + " " + num1 + " " + num1);
}
else
{
System.out.print(num1 + " " + num3 + " " + num2);
}
}
else if ((num3 > num1 && num3 > num2))
{
if(num1 > num2)
{
System.out.print(num2 + " " + num1 + " " + num3);
}
else
System.out.print(num1 + " " + num2 + " " + num3);
}
else
{
System.out.println("ERROR!");
}
}
}
</code></pre>
<p><strong>Book's solution:</strong></p>
<pre><code>public class Exercise03_08 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
// Enter three numbers
System.out.print("Enter three integers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
int number3 = input.nextInt();
if (number1 > number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}
if (number2 > number3) {
int temp = number2;
number2 = number3;
number3 = temp;
}
if (number1 > number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}
System.out.println("The sorted numbers are "
+ number1 + " " + number2 + " " + number3);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-02T09:24:07.167",
"Id": "98084",
"Score": "0",
"body": "Be aware that this is not a real world solution. The simple way to solve this problem is to put the 3 numbers on a List<Integer> then call Collections.sort(myList)."
}
] |
[
{
"body": "<p>The books solution, is definitely cleaner, and the biggest difference I can see is the books solution is actually sorting the variables, rather than just changing the display order.</p>\n\n<p>In terms of efficiency, displaying stuff to the console is more efficient than popping up message boxes. There's less conditional logic in the books solution and a lot less code duplication. Other than that, there is very little difference in the sorting operation, the books maybe slightly more efficient due to less conditional checks.</p>\n\n<p>Overall though, in my opinion the book provides the better solution, because it has virtually no duplicated code, conditionals are a single level deep (much easier to read), actually sorts the numbers in memory (if this program were to do more, your variables would already be sorted for you next time you need them, as opposed to having to duplicate the conditional logic, and overall it's much easier to understand what it's doing and what's going on.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T23:16:22.663",
"Id": "38251",
"ParentId": "38247",
"Score": "4"
}
},
{
"body": "<p>Why should there be an error case for sorting three integers? There shouldn't be any good reason for failure. Your code reports an error, for example, if all three inputs are the same. The book's code handles it just fine.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T06:50:58.077",
"Id": "38260",
"ParentId": "38247",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T22:47:34.587",
"Id": "38247",
"Score": "5",
"Tags": [
"java",
"beginner",
"sorting"
],
"Title": "Inputting and sorting three integers"
}
|
38247
|
<p>I am building a one-page JS app similar to redditinvestigator.com, and my goal is for it to be 100% done in JavaScript. Coming from a PHP/Java background, I'm more used to working in class oriented languages, so I just want to get a sense if I am implementing them correctly in JavaScript.</p>
<p>My code works as expected, and I am just hoping to get some feedback on if there is anything I technically am doing wrong, or if there is a better way to do some of the things I am implementing.</p>
<p><a href="http://jsfiddle.net/4ZD4U/" rel="nofollow">jsFiddle</a> (the results are just in the console FYI)</p>
<pre><code>var Comment = function(obj) {
if (obj) {
this.data = obj.body;
this.created_utc = obj.created_utc;
this.downs = obj.downs;
this.gilded = obj.gilded;
this.id = obj.id;
this.link_id = obj.link_id;
this.link_title = obj.link_title;
this.name = obj.name;
this.subreddit = obj.subreddit;
this.ups = obj.ups;
}
};
Comment.prototype.getBody = function() {
return this.data;
};
Comment.prototype.getCreated = function() {
return this.created_utc;
};
Comment.prototype.getDownvotes = function() {
return this.downs;
};
Comment.prototype.getUpvotes = function() {
return this.ups;
};
Comment.prototype.getScore = function() {
return this.ups - this.downs;
};
Comment.prototype.isGilded = function() {
return this.gilded;
};
Comment.prototype.getID = function() {
return this.id;
};
Comment.prototype.getLinkID = function() {
return this.link_id;
};
Comment.prototype.getLinkTitle = function() {
return this.link_title;
};
Comment.prototype.getName = function() {
return this.name;
};
Comment.prototype.getSubreddit = function() {
return this.subreddit;
};
var RedditInterface = function(username) {
this.userName = username;
this.commentCount = 0;
this.submissionCount = 0;
this.lastCall = 0;
};
RedditInterface.prototype.getUsername = function() {
return this.userName;
};
RedditInterface.prototype.sendQuery = function(endpoint, after, func) {
var curDate = new Date().getTime();
var timeSince = curDate - this.lastCall;
if (timeSince < 5000)
return null;
this.lastCall = curDate;
var urlD = '';
if (after === '')
urlD = "http://www.reddit.com/user/" + this.userName + "/" + endpoint + ".json?limit=100&jsonp=?";
else
urlD = "http://www.reddit.com/user/" + this.userName + "/" + endpoint + ".json?limit=100&after=" + after + "&jsonp=?";
$.ajax({
url: urlD,
dataType: 'json',
success: func
});
};
RedditInterface.prototype.loadAllComments = function() {
var here = this;
var intervalHandle = window.setInterval(function() {
here.sendQuery('comments', commentAfter, function(data) {
if (data.data.children.length === 0) { //We've loaded all the comments reddit will give us
console.log("Comments loaded. Total: " + commentLog.length);
window.clearInterval(intervalHandle);
}
for (var point in data.data.children) {
var ret = new Comment(data.data.children[point].data);
var accept = true;
for (var i = 0; i < commentLog.length; i++) {
if (commentLog[i].name == ret.name) {
console.log(i + ' (' + commentLog[i].name + ') is equal to current (' + ret.name + '), ommitting.');
accept = false;
break;
}
}
if (accept && typeof ret.name !== 'undefined') {
commentLog.push(ret);
commentAfter = ret.name;
}
}
console.log(commentLog);
});
}, 5500);
return intervalHandle;
};
//Begin Logic
var commentLog = [];
var submissionLog = [];
var commentAfter = '';
var ri = new RedditInterface("hueypriest");
var handle = ri.loadAllComments();
</code></pre>
|
[] |
[
{
"body": "<p>Your code is very clean, easy to understand and well written. My only comment for improving it would be to take advantage of a framework that does some of this lifting for you, such as:</p>\n\n<ul>\n<li>KnockoutJS</li>\n<li>BackboneJS</li>\n<li>AngularJS</li>\n</ul>\n\n<p>As well, coming from an OO background, you might be interested at looking at CoffeeScript, which is a higher level language that provides class constructs and such that compiles down into regular JavaScript.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T23:02:01.620",
"Id": "38250",
"ParentId": "38248",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "38250",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T22:52:50.737",
"Id": "38248",
"Score": "1",
"Tags": [
"javascript",
"beginner",
"jquery",
"api",
"reddit"
],
"Title": "Reddit Investigator-like JS app"
}
|
38248
|
<p>I am trying to print all the strings given in a N x N Boggle board. Its basically a N x N scrabble-like board where words can be made from a position - horizontally, vertically and diagonally.</p>
<p>Here is my naive implementation. Is this correct? Any hints on optimizations? Any other useful links?</p>
<pre><code>public class BoggleSolver {
private void solve(String prefix, int i, int j, char[][] Board, boolean[][] marker, int N)
{
if ((i < 0) || (j < 0) || (i >= N) || (j >= N)) return;
if (marker[i][j] == true) return;
String s = prefix + Character.toString(Board[i][j]);
// TODO Fictional dictionary that can tell us if
// a string is a legal word
if (dict.HasWord(s)) System.out.println(s);
// Mark current index and traverse horizontal,vertical
// and diagonal
marker[i][j] = true;
solve(s, i, j + 1, Board, marker, N);
solve(s, i + 1, j, Board, marker, N);
solve(s, i + 1, j + 1, Board, marker, N);
}
public void solve(char[][] Board, int N)
{
boolean[][] marker = new boolean[N][N];
solve("", 0, 0, Board, marker, N);
}
public static void main(String[] args) {
// TODO make board and call solve(board, N)
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T23:36:25.840",
"Id": "63664",
"Score": "0",
"body": "You have to mark the current position as unused as you return from recursion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T23:38:33.723",
"Id": "63666",
"Score": "1",
"body": "You also only go \"right\" or \"down\" or \"down right\". There are actually 8 different directions you can choose from any single tile."
}
] |
[
{
"body": "<p>I wouldn't consider that a Boggle solver, as you only consider words that start at [0, 0] and progress east, south, or southeast. (With coordinates that are always nondecreasing, you need not have bothered using <code>marker</code> to prevent backtracking.)</p>\n\n<p>A complete search will probably take an extremely long time. You should use a dictionary that can check whether there are any words that begin with some prefix, so that you can prune fruitless search paths. Use a trie data structure, or possibly a <code>TreeSet<String></code>.</p>\n\n<p><code>Board</code>, <code>N</code>, and <code>HasWord(…)</code> all have improper capitalization. It doesn't make sense to require <code>N</code> to be passed in explicitly, since it should be detectable from the board's dimensions.</p>\n\n<p>Appending a character to a string can be simply written as <code>prefix + board[i][j]</code>.</p>\n\n<hr>\n\n<p>I would recommend redesigning the class with a more versatile interface, because printing the results to <code>System.out</code> limits reusability.</p>\n\n<pre><code>public interface BoggleSolutionHandler {\n public void foundWord(String word);\n}\n\npublic class BoggleSolver {\n public static void solve(char[][] board, BoggleSolutionHandler callback, NavigableSet<String> dictionary) {\n …\n }\n}\n</code></pre>\n\n<p>An iterator would be even nicer to use, but probably harder to implement since you can't take advantage of recursion:</p>\n\n<pre><code>public class BoggleSolver implements Iterator<String> {\n public class BoggleSolver(char[][] board, NavigableSet<String> dictionary) {\n …\n }\n\n @Override\n public boolean hasNext() {\n …\n }\n\n @Override\n public String next() {\n …\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T07:12:03.540",
"Id": "38261",
"ParentId": "38249",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38261",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T22:53:53.580",
"Id": "38249",
"Score": "4",
"Tags": [
"java",
"optimization",
"algorithm",
"strings",
"recursion"
],
"Title": "Printing all strings in a Boggle board"
}
|
38249
|
<p>This was my first attempt at writing a program in LISP. Can anyone give any guides as to how it could be improved? The multiple loops in best-pattern seem awkward (I'd normally do that in just one loop but there doesn't seem to be a way of doing that with LOOP, although I'm told there's an iterate extension that can do it), as does the way of calculating alternatives..</p>
<pre><code>(defparameter *rows* (list (list :c :ds :fs :a) (list :cs :e :g :as) (list :d :f :gs :b)))
(defun row-for-note (note)
(position-if (lambda (row) (find note row)) *rows*)
)
(defun rows-for-notelist (notelist)
(mapcar #'row-for-note notelist)
)
(defun possible-alternates (rowlist)
(let ((alternatives '(()))) ;; Lots of irritating silly parentheses
(when (> (length rowlist) 1)
(setq alternatives (possible-alternates (cdr rowlist)))
)
(case (car rowlist)
((0) (mapcar (lambda (x) (append '(0) x)) alternatives))
((1) (append (mapcar (lambda (x) (append '(1) x)) alternatives)
(mapcar (lambda (x) (append '(-2) x)) alternatives)))
((2) (append (mapcar (lambda (x) (append '(2) x)) alternatives)
(mapcar (lambda (x) (append '(-1) x)) alternatives)))
)
)
)
(defun count-jumps (rowlist)
(loop for (a b) on rowlist while b counting (> (abs (- a b)) 1))
)
(defun best-pattern (notelist)
(let ((minval (loop for x in (possible-alternates (rows-for-notelist notelist)) minimize (count-jumps x))))
(loop for x in (possible-alternates (rows-for-notelist notelist)) when (= (count-jumps x) minval) collect x))
)
</code></pre>
<p>(If you're wondering what the program does, it tries to calculate the "most efficient" series of rows to use to play a melody on 5-row Bayan Accordion.)</p>
|
[] |
[
{
"body": "<p><em>I'm a Schemer, so my comments are not as detailed as they would be if I were reviewing a Scheme program.</em></p>\n\n<ul>\n<li>First, fix your indentation! There is a <a href=\"http://mumble.net/~campbell/scheme/style.txt\" rel=\"nofollow\">Lisp style guide</a> that most Lispers and Schemers agree with. In particular, use an indentation of 2 for functions, and don't use dangling parentheses.</li>\n<li>Instead of <code>(append '(0) x)</code>, just use <code>(cons 0 x)</code>. Ditto for all your other <code>append</code> usages too, of course.</li>\n<li>To reduce your parentheses (your \"lots of irritating silly parentheses\" did not escape my notice), you can use <code>'(nil)</code> instead of <code>'(())</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T17:42:52.580",
"Id": "63706",
"Score": "0",
"body": "Thanks! I'm really confused by the indentation thing though. The reason I did it the way it's shown above is because I built most of the functions a statement at the time and wanted to easily be able to extend them. I did know about the rule of not having a ) alone on a line but when I did that, then whenever I wanted to add a new statement to a defun or a new case, I ended up having to count parens in order to know where to add the new forms. Splitting them onto single lines made it much easier to extend the code. Is there a better way I'm missing?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T02:58:50.927",
"Id": "38256",
"ParentId": "38255",
"Score": "1"
}
},
{
"body": "<p>Done:</p>\n\n<ul>\n<li>improved formatting and layout</li>\n<li>instead of <code>car</code> and <code>cdr</code>, use <code>first</code> and <code>rest</code>.</li>\n</ul>\n\n<p>Missing:</p>\n\n<ul>\n<li>documentation strings</li>\n<li>example</li>\n</ul>\n\n<p>Only slight improvements.</p>\n\n<p>No need to use <code>list</code>:</p>\n\n<pre><code>(defparameter *rows* '((:c :ds :fs :a )\n (:cs :e :g :as)\n (:d :f :gs :b )))\n</code></pre>\n\n<p>Okay:</p>\n\n<pre><code>(defun row-for-note (note)\n (position-if (lambda (row) (find note row))\n *rows*))\n\n(defun rows-for-notelist (notelist)\n (mapcar #'row-for-note notelist))\n</code></pre>\n\n<p>Compute <code>alternatives</code> directly, without <code>setq</code>. Local functions for repeated use. Use <code>cons</code>. Not so good: recursion limits use, because of limited stack depth.</p>\n\n<pre><code>(defun possible-alternates (rowlist)\n (let ((alternatives (if (rest rowlist)\n (possible-alternates (rest rowlist))\n '(()) )))\n (flet ((add (item)\n (mapcar (lambda (x) (cons item x))\n alternatives)))\n (case (first rowlist)\n (0 (add 0))\n (1 (append (add 1) (add -2)))\n (2 (append (add 2) (add -1)))))))\n\n(defun count-jumps (rowlist)\n (loop for (a b) on rowlist\n while b\n count (> (abs (- a b)) 1)))\n</code></pre>\n\n<p>Slight improvements:</p>\n\n<pre><code>(defun best-pattern (notelist)\n (let* ((alternates (possible-alternates (rows-for-notelist notelist)))\n (jumps (mapcar #'count-jumps alternates))\n (min-jump (loop for j in jumps minimize j)))\n (loop for a in alternates and j in jumps\n when (= min-jump j)\n collect a)))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T17:45:53.357",
"Id": "63708",
"Score": "0",
"body": "Thanks very much! Is there a better way of doing this without recursion? I did spot a few cases where the depth of recursion could be limited (in particular when a note is on row 0 it is always on row 0 so looking ahead beyond it is less important) but that got a bit complex. Is there any way to do best-pattern without looping through the list twice?\n\nOh, and of (mapcar #' some-function somelist) and (loop for x in somelist collecting (some-function x)), is one faster or better in some way?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T17:05:49.333",
"Id": "38279",
"ParentId": "38255",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "38279",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T01:13:37.900",
"Id": "38255",
"Score": "5",
"Tags": [
"beginner",
"lisp",
"common-lisp"
],
"Title": "Calculating series of rows to use to play a melody on 5-row Bayan Accordion"
}
|
38255
|
<p>I am not wondering about error checking (I will add that soon). I would instead like to know about correctness, efficiency and simplicity.</p>
<pre><code>#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#define NTHREADS 7
#define RUN_N_TIMES 37
pthread_cond_t new_task_available = PTHREAD_COND_INITIALIZER;
pthread_cond_t task_complete = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
volatile int producerCond = 0;
volatile int consumerCond[NTHREADS] = {};
volatile int no_more_tasks = 0;
volatile int mini_tasks_complete = - NTHREADS;
void do_work(unsigned int* current_level){
/* Some work done */
++*current_level;
}
void *threadfunc(void *parm){
volatile int* thread_cond;
unsigned int level = 0;
thread_cond = (volatile int*)parm;
while(!no_more_tasks){
pthread_mutex_lock(&mutex);
mini_tasks_complete++;
if(mini_tasks_complete > 0)
printf("Thread %u has completed %u units of work.\nIt was #%d to complete it's task this round..\n", \
(unsigned int)pthread_self(), level, mini_tasks_complete);
if(mini_tasks_complete == NTHREADS){
producerCond = 1;
pthread_cond_signal(&task_complete);
}
*thread_cond = 0;
while (!*thread_cond) {
pthread_cond_wait(&new_task_available, &mutex);
}
pthread_mutex_unlock(&mutex);
if(no_more_tasks){
return NULL;
} else {
do_work(&level);
}
}
return NULL;
}
void reset_cond(int val){
int i;
for (i=0; i<NTHREADS; ++i)
consumerCond[i] = val;
}
int main(int argc, char **argv)
{
int i;
pthread_t threadid[NTHREADS];
for(i=0; i < NTHREADS; ++i) {
pthread_create(&threadid[i], NULL, threadfunc, (void*)&(consumerCond[i]));
}
while(mini_tasks_complete < 0){
/* Do nothing */
}
printf("Waking up all waiting threads " "#RUN_N_TIMES" " times...\n");
for(i = 0; i < RUN_N_TIMES; i++){
pthread_mutex_lock(&mutex);
mini_tasks_complete = 0;
printf("New tasks available.\n");
reset_cond(1);
/* Wake them up */
pthread_cond_broadcast(&new_task_available);
producerCond = 0;
while (!producerCond) {
printf("Main waiting\n");
/* Go to sleep */
pthread_cond_wait(&task_complete, &mutex);
}
pthread_mutex_unlock(&mutex);
}
pthread_mutex_lock(&mutex);
reset_cond(1);
no_more_tasks = 1;
printf("Go home everybody!\n");
pthread_cond_broadcast(&new_task_available);
printf("Wait for threads and cleanup...\n");
pthread_mutex_unlock(&mutex);
for (i=0; i<NTHREADS; ++i) {
pthread_join(threadid[i], NULL);
}
pthread_cond_destroy(&new_task_available);
pthread_cond_destroy(&task_complete);
pthread_mutex_destroy(&mutex);
printf("Main done\n");
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T09:30:32.840",
"Id": "63686",
"Score": "2",
"body": "Always a bit concerned seeing types like `pthread_t` assumed to be `sizeof(int)`. Check [How to print pthread_t](http://stackoverflow.com/questions/1759794/how-to-print-pthread-t)"
}
] |
[
{
"body": "<p>Here are some comments on your program. Note that I am not a threads expert.</p>\n\n<p>Firstly, the code runs nicely. I'm running OSX and it compiles cleanly and\nexecutes correctly (as far as I can tell). I was a little surprised that\nthreads wake up in the same order each time - in other words if thread 123456\nis the first to complete the first job, then it seems to be the first to\ncomplete each subsequent job. This says more about the thread implementation\nthan your code I guess.</p>\n\n<p>The problem I have with the code is that although it seems to work, it is coded\nvery specifically for the problem in hand. The barriers ensuring that all\nthreads come together at intervals are not separately identifiable but are\nentwined in the control code. The variable <code>mini_tasks_complete</code>, used in\ncreating the barrier is initialized to <code>-NTHREADS</code>, allowed to run up to zero\nduring the initial barrier and then cycles from 0 to <code>NTHREADS</code>. This clearly\nworks but is inelegant (I think you will find that the initial barrier can be\nomitted and worked into the loop with a bit of thought). </p>\n\n<p>I would prefer to see the thread function have the simple form:</p>\n\n<pre><code>while (more_tasks) {\n barrier();\n work();\n}\n</code></pre>\n\n<p>and the main thread have the general form:</p>\n\n<pre><code>for (...) {\n prepare_work();\n barrier();\n}\n</code></pre>\n\n<p>Written like this one can clearly identify the synchronisation. The barrier function\nhere would also preferably take a parameter identifying the barrier and not\nuse globals.</p>\n\n<p>I assume your platform, like mine, lacks the pthread barrier. You might write\nyour own barrier function. From what I have read, barriers are normally based\nupon a pair of condition variables and a pair of mutexes. The <a href=\"http://www.greenteapress.com/semaphores/\" rel=\"nofollow\">Little Book of\nSemaphores</a> has a discussion of this and there is a useful <a href=\"http://docs.oracle.com/cd/E19455-01/806-5257/6je9h034h/index.html\" rel=\"nofollow\">Solaris\nimplementation</a> that could be used as a template.</p>\n\n<p>Some trivia:</p>\n\n<ul>\n<li><p>I would find <code>while (more_tasks)</code> more logical than <code>while (!no_more_tasks)</code></p></li>\n<li><p>inconsistent use of camelCase</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T13:36:20.187",
"Id": "38363",
"ParentId": "38264",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38363",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T08:35:43.410",
"Id": "38264",
"Score": "2",
"Tags": [
"c",
"multithreading",
"pthreads"
],
"Title": "1 Producer, N Consumers working in parallel, each doing ~1/nth of a task"
}
|
38264
|
<p>My entry for <a href="https://codereview.meta.stackexchange.com/a/1324/14625">Weekend Challenge #5</a>.</p>
<p>In scope :</p>
<ul>
<li>Old Skool green on black text adventure</li>
<li>Keyboard handling</li>
<li>A story with 2 mini-quests</li>
<li>2 endings</li>
<li>Virtues ( Hi Ultima ) save the day</li>
</ul>
<p>Out of scope : </p>
<ul>
<li>Mouse handling, save games, high scores</li>
</ul>
<p>Biggest concern : </p>
<ul>
<li>Because both controller and view have a reference to model, I cannot simply re-create model as a new Object for a new game. My JSON solution feels awkward.</li>
</ul>
<p>An online version can be found <a href="http://jsbin.com/efoqiPat/15" rel="nofollow noreferrer">here</a>.
<strong>Updated</strong> to prevent winning without all virtues collected.</p>
<pre><code>$(function ()
{
var model = (function createModel()
{
var title = "Belle's Christmas\n=================",
originalScenes = {
menu:
{
text: "",
options: ["1. Start Game", "2. View Highscores"].join("\n")
},
garden:
{
text: 'You are standing in a white frosted garden in front of an ancient manor, 2 snowmen are flanking the front door.',
options: ["1. Enter the manor", "2. Look at the snowmen"].join("\n")
},
snowmen:
{
text: 'Against all odds, one of the poor snowmen seems to be shivering, he reminds you of the town drunkard, but frostier.',
dressedText: 'Both snowmen are now guarding valiantly the manor, no longer bothered by the cold.',
offendedText: 'The snowman on the left looks at you crossly, the snowman on the right is guarding valiantly the manor',
options: ["1. Offer your jacket", "2. Enter the manor"].join("\n")
},
lobby:
{
text: 'Lumiere the magical candelabra is here, waiting impatiently for you to clean him, he thinks you are late.',
cleaned1: 'Lumiere exclaims that you missed some spots and wants you to clean him again.',
cleaned2: 'Lumiere exclaims that he isnt shiny enough and insists you should clean him further.',
cleaned3: 'Lumiere is so clean now that he cant stop babbling about it!',
options: ['1. Go to the ballroom', '2. Clean Lumiere', '3. Exit the manor'].join("\n")
},
room:
{
text: 'You are in your bed room, it is small and badly lit',
options: ['1. Go to bed', '2. Go back the the ballroom'].join("\n")
},
ballroom:
{
text: 'You see Gaston hunched over a book, wearing festive clothing.',
options: ['1. Go to your room', '2. Tell Gaston what you did so far',"3. Exit the ballroom"].join("\n")
},
win:
{
text: 'Gaston is so touched with your charity, kindness, patience and temperance that he stands up, starts music and dances the night away with you. Best Christmas ever.',
options: 'Game Over. Press any key'
},
loose:
{
text: 'You fall asleep, dreaming feverishly about Monsieur D\'Arque and his crazy plans, worst Christmas ever',
options: 'Game Over. Press any key'
}
},
scenes = JSON.parse(JSON.stringify(originalScenes));
function reset()
{
this.scenes = JSON.parse( JSON.stringify( originalScenes ) );
this.virtues = {};
}
return {
scenes: scenes,
title: title,
warning: '',
virtues: {},
reset: reset
};
}());
var view = (function createView()
{
var $body = $(document.body),
model;
function init(_model, options)
{
options = options || {};
model = _model;
$body.css('background-color', options.backgroundColor || 'black')
.css('color', options.textColor || 'limegreen')
.css('font-weight', 'Bold')
.css('font-family', 'Lucida Console')
.css('white-space', 'pre');
$body.html(model.title);
}
function draw()
{
//Update the text
$body.html( model.title + "\n" +
model.scene.text + "\n\n" +
model.scene.options + "\n\n" +
model.warning );
//Only show the warning once
model.warning = '';
//Do not show 'feature not implemented'
return true;
}
return {
init: init,
draw: draw,
element: $body
};
}());
var controller = (function createController()
{
var model, view, keyboardHandler;
function wireKeyboard($element)
{
$element.keypress(function (e)
{
if(!keyboardHandler(String.fromCharCode(e.which)))
warnNotImplemented();
});
}
function attachHandlersToModel()
{
model.scenes.menu.handler = function (c)
{
if(c == '1') //1. Start game
return changeScene('garden');
};
model.scenes.garden.handler = function (c)
{
if(c == '1') //1. Enter the manor
{
model.scenes.snowmen.text = model.scenes.snowmen.offendedText;
return changeScene('lobby');
}
if(c == '2') //2. Look at the snowmen
{
return changeScene('snowmen');
}
};
model.scenes.snowmen.handler = function (c)
{
if(c == '1') //1. Offer your jacket
{
if(!model.virtues.dress)
{
model.scene.text = model.scene.dressedText;
model.virtues.dress = true;
}
else
{
model.warning = 'You already offered your jacket.';
}
return view.draw();
}
if(c == '2') //2. Enter the manor
{
if(!model.virtues.dress)
model.scene.text = model.scene.offendedText;
return changeScene('lobby');
}
};
//'1. Go to the ballroom' , '2. Clean Lumiere' , '3. Exit the manor'
model.scenes.lobby.handler = function (c)
{
if(c == '1') //2. Enter the ballroom
return changeScene('ballroom');
if(c == '2')
{
if(!model.virtues.kindness)
{
model.scene.text = model.scene.cleaned1;
model.virtues.kindness = true;
}
else if(!model.virtues.patience)
{
model.scene.text = model.scene.cleaned2;
model.virtues.patience = true;
}
else if(!model.virtues.temperance)
{
model.scene.text = model.scene.cleaned3;
model.virtues.temperance = true;
}
else
{
model.warning = 'Lumiere confirms that he is shiny enough';
}
return view.draw();
}
if(c == '3') //2. Exit the manor
return changeScene('garden');
};
model.scenes.ballroom.handler = function (c)
{
if(c == '1') //1. Go to your room'
return changeScene('room');
if(c == '2') //2. Tell Gaston what you did so far'
{
if(Object.keys(model.virtues).length != 4)
{
model.warning = 'Gaston listens politely with half an ear.';
return view.draw();
}
else
{
return changeScene('win');
}
}
if( c == '3' )
return changeScene('lobby');
};
model.scenes.room.handler = function (c)
{
if(c == '1') // '1. Go to bed'
return changeScene('loose');
if(c == '2') // '2. Go back the the ballroom'
return changeScene('ballroom');
};
function gameOverHandler()
{
//Whatever the player presses, just go to the main menu
return changeScene('menu');
}
//Both cases require the same keyboard handling
model.scenes.win.handler = gameOverHandler;
model.scenes.loose.handler = gameOverHandler;
}
function warnNotImplemented()
{
model.warning = 'That feature is not yet implemented';
view.draw();
}
function changeScene(name)
{
//This resets the model ( for n+1 plays of the game )
if(name == 'menu')
{
model.reset();
attachHandlersToModel();
}
//Look up the scene, wire keyboard, draw the scene
model.scene = model.scenes[name];
keyboardHandler = model.scene.handler;
return view.draw();
}
function init(_model, _view)
{
model = _model;
view = _view;
wireKeyboard(view.element);
changeScene("menu");
view.draw();
}
return {
init: init
};
}());
view.init(model);
controller.init(model, view);
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T23:19:55.443",
"Id": "63727",
"Score": "0",
"body": "It's an uplifting story for all Gastons out there ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T07:00:26.770",
"Id": "66494",
"Score": "1",
"body": "Loose is the opposite of tight, but the opposite of win is *lose*."
}
] |
[
{
"body": "<p>I enjoyed playing and won on my first attempt. I suppose that means I'm quite virtuous! :) </p>\n\n<p><strong>Quick Tips</strong></p>\n\n<ul>\n<li><p>Since <code>changeScene</code> calls <code>view.draw()</code> at the end, you can drop the same call at the end of <code>init</code> of the controller.</p></li>\n<li><p>I would put the extra handling of changing to the <code>menu</code> scene in a separate method such as <code>returnToMenu</code> that calls <code>changeScene</code> itself. While the menu is implemented as just another scene, functionally it's special and thus deserves to be made clear.</p></li>\n<li><p>Use <a href=\"http://api.jquery.com/jquery.extend/\"><code>jQuery.extend</code></a> to apply default option values so they appear at the top instead of mixed in at every access.</p>\n\n<pre><code>options = $.extend({\n backgroundColor: 'black',\n textColor: 'limegreen'\n}, options);\n</code></pre></li>\n<li><p>If you pass <code>true</code> as the first parameter, you can even use this as a deep copy instead of converting to JSON and back.</p>\n\n<pre><code>scenes = $.extend(true, {}, originalScenes);\n</code></pre></li>\n</ul>\n\n<p><strong>Design Review</strong></p>\n\n<p>As the story grows you'll find yourself spending a lot of time tracking down copy-n-paste and errors in the handlers. A lot of the code is repeated with minimal changes: key numbers, scene names, and virtues mostly. Now that you have a representative example for each type of scene it's time to generalize the handler code and move the data behind the logic into the model.</p>\n\n<p>The simplest is the menu as there are only two choices (one implemented) with no warnings or virtues. I've removed the explicit keys since you're using numbers and it shortens the code.</p>\n\n<pre><code>menu: {\n text: \"Main Menu\",\n choices: [{\n text: \"Start Game\",\n scene: \"garden\"\n }, {\n text: \"High Scores\",\n stub: true\n }]\n}\n</code></pre>\n\n<p>The handler for this is straight-forward, but let's break it up in anticipation of adding more features. Note that you no longer swap out the handler for each scene. Instead, a single handler picks the course of action based on the current scene and the key pressed.</p>\n\n<pre><code>$element.keypress(function (e) {\n // convert key \"1\"..\"9\" into 0..8 for index into choices array\n // values outside the available range will be undefined\n handleChoice(model.scene.choices[e.which - 49]);\n});\n\nfunction handleChoice(choice) {\n if (!choice) {\n warnInvalidChoice();\n }\n else if (choice.stub) {\n warnNotImplemented();\n }\n else {\n if (choice.scene) {\n changeScene(choice.scene);\n }\n }\n}\n</code></pre>\n\n<blockquote>\n <p>If you were implementing a simple, stateless choose-your-own-adventure (no virtues or changing text), you'd be done. Adding to the story would require changing only the scenes in the model.</p>\n</blockquote>\n\n<p>The next example shows how to set virtues using the snowmen.</p>\n\n<pre><code>snowmen: {\n text: \"Against all odds, one of the poor snowmen seems to be shivering.\",\n choices: [{\n text: \"Offer your jacket\",\n virtue: {\n name: \"charity\",\n text: \"Both snowmen are now guarding valiantly the manor.\",\n warning: \"You already offered your jacket.\"\n }\n }, {\n text: \"Enter the manor\",\n scene: \"lobby\"\n }]\n}\n</code></pre>\n\n<p>The handler sets the virtue, issues a warning if the virtue is already set, and changes the scene text. It does not, however, handle changing the scene text if it was bypassed on the first attempt. I'll leave that to you.</p>\n\n<pre><code>function handleChoice(choice) {\n ...\n else {\n if (choice.virtue) {\n handleVirtue(choice.virtue);\n }\n if (choice.scene) {\n changeScene(choice.scene);\n }\n }\n}\n\nfunction handleVirtue(virtue) {\n if (!model.virtues[virtue.name]) {\n model.virtues[virtue.name] = true;\n if (virtue.text) {\n model.scene.text = virtue.text;\n }\n }\n else if (virtue.warning) {\n model.scene.warning = virtue.warning;\n }\n}\n</code></pre>\n\n<p>I hope this gives you enough to go on. The idea is to move the scene-specific logic into the model so that you can continue the story without writing more code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T08:53:47.990",
"Id": "39644",
"ParentId": "38271",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "39644",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T14:04:12.660",
"Id": "38271",
"Score": "12",
"Tags": [
"javascript",
"weekend-challenge"
],
"Title": "Weekend Challenge - Belle's Christmas"
}
|
38271
|
<p>I am trying to write some string algorithms which I want to work for any kinds of strings and/or locale. I managed to get some results that do work, but I am not sure that what I am doing is idiomatic or anything. Here is a function:</p>
<pre><code>template<typename String>
auto upper(String str,
const std::ctype<typename String::value_type>& f =
std::use_facet<std::ctype<typename String::value_type>>(std::locale{}))
-> String
{
f.toupper(&str[0], &str[0]+str.size());
return str;
}
</code></pre>
<p>I have problems getting around the way C++ works with locales and UTF-8. This algorithm is intended to take a string (well, a range of characters with a standard string interface) and returning a copy of it with all the characters converted to uppercase according to a given locale. If no locale (ctype facet) is given, the last used locale is used.</p>
<p>Is there anyway to improve this code (taking <code>locale</code> vs <code>facet</code>) for examples so that it would be the most useful?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T20:59:06.870",
"Id": "63967",
"Score": "0",
"body": "I am not sure std::locale{} will give you the C-Locale. It will give you the current locale (which will be C-Locale if not explicitly set (though on windows it may inherit from the system and Linux will get it from environment variables automatically (I think)). So (if I am correct (and there is an if there)) if no locale is supplied it will use the application current locale"
}
] |
[
{
"body": "<p>I <em>think</em> I'd prefer to have the user pass a locale instead of a facet. In most typical cases, a user will deal only with locales, not with the individual facets that make up a particular locale. It's also relatively easy for a user to create a locale on demand, so the code looks something like:</p>\n\n<pre><code>std::string input{\"Now is the time for every good man to come of the aid of his country.\"};\n\nstd::string result = upper(input, std::locale(\"en-us\"));\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>std::string result = upper(input, std::locale(\"\"));\n</code></pre>\n\n<p>...though I suppose we can probably expect that the default parameter will be used a lot more often than not, in which case all of this is moot.</p>\n\n<p>Anyway, using a locale as the parameter lets us move the <code>use_facet</code> call inside the function body and use <code>auto</code> for it instead of writing out its full type:</p>\n\n<pre><code>auto const& f = std::use_facet<std::ctype<typename String::value_type>>(locale);\n</code></pre>\n\n<p>Not a huge change, but somewhat simpler nonetheless. Given that you're depending on <code>String</code> being contiguous and supporting random access, it might be worth considering making use of that a little more explicitly, by replacing <code>&str[0]+str.size()</code> with <code>&str[str.size()]</code>.</p>\n\n<p>Although I'm somewhat on the fence about it, I'm also less than excited about the idea of using a trailing return type when it's not actually necessary. Maybe it's just a sign of my age, but I still tend to prefer the return type in its traditional location when possible.</p>\n\n<p>Putting all those together, we'd end up with something on this order:</p>\n\n<pre><code>template<typename String>\nString upper(String str, std::locale const &locale = std::locale())\n{\n auto const& f = std::use_facet<std::ctype<typename String::value_type>>(locale);\n f.toupper(&str[0], &str[str.size()]);\n return str;\n}\n</code></pre>\n\n<p>I'm not sure anybody could call that a <em>huge</em> improvement, but I do think it's at least a minor one, especially in convenience to the user.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T21:56:02.130",
"Id": "74627",
"Score": "0",
"body": "Considering the length of the function, any improvement could be called huge. Thanks for your answer :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T21:58:08.543",
"Id": "74629",
"Score": "0",
"body": "Considering the trailing return type, I consider it a mere matter of taste and I actually love it - even though I was reluctant to use it at first. By the way, Loki told me the exact same thing that you did about it a few weeks a ago."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-03-02T21:22:51.887",
"Id": "43254",
"ParentId": "38272",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "43254",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T15:01:01.180",
"Id": "38272",
"Score": "5",
"Tags": [
"c++",
"strings",
"c++11",
"localization"
],
"Title": "String algorithms and locale"
}
|
38272
|
<p>What are your thoughts on the following code? is it secure enough?</p>
<p><strong>Note:</strong> <code>$password</code> is used to represent the secret, which would essentially be a SHA512 hash of</p>
<pre><code>username . password . signupdate(unixtime)
</code></pre>
<p>Do you think I'm covered?</p>
<p><a href="http://server.openex.pw/test.php" rel="nofollow">Here's a demo for the testing purposes</a>.</p>
<pre><code>error_reporting(E_ALL & ~E_NOTICE | E_STRICT);
ini_set("display_errors", "1");
echo '<pre>';
$break = '<br/>';
$password = trim("password");
echo 'step1 the password is posted<br/>';
echo $password;
echo $break;
echo $break;
$time = date("F j, Y, g:i a");
echo 'step2 get the time in human readable format<br/>';
echo $time;
echo $break;
echo $break;
$salt1 = $time . hash('sha512', (sha1 .$time));
echo 'step3 create salt1<br/>';
echo $salt1;
echo $break;
echo $break;
$salt2 = substr(md5(uniqid(rand(), true)), 0, 25);
echo 'step4 create salt2<br/>';
echo $salt2;
echo $break;
echo $break;
$hash = str_split($password);
echo 'step5 split the password into an array<br/>';
print_r($hash, false);
echo $break;
echo $break;
echo 'step6 hash each charachter of the password in the array<br/>';
foreach($hash as $key => $value) {
$hashed[] = $salt2 . hash('sha512', ($salt . $value)) . $salt . hash('sha256', (salt2 . $key));
}
print_r($hashed, false);
echo $break;
echo $break;
$hashed_2 = implode($hashed);
echo 'step7 implode the array into a single hash<br/>';
echo $hashed_2;
echo $break;
echo $break;
$hashfinal = str_shuffle($hashed_2);
echo 'step8 shuffle the hash to decrease entropy<br/>';
print_r($hashfinal, false);
</code></pre>
|
[] |
[
{
"body": "<p>No, it isn't secure.</p>\n\n<p>Inventing your own hashing algorithms is a horrible idea. When doing password hashing, use something invented by cryptographers that was made for password hashing, e.g. <em>bcrypt</em>. Because I'm not a cryptographer either, I can't give you a full explanation why your code is insecure. In short, the mistake you made was hashing each character of the password on its own. A few things I spotted:</p>\n\n<ul>\n<li>The final output has a length proportional to the length of the password. This can be abused for denial-of-service attacks or to limit the search space when cracking via brute force.</li>\n<li>In your final hash, the letters of <code>$salt2</code> will occur more often. Therefore the resulting hash isn't evenly distributed over the output domain.</li>\n<li>Same letters in the password obviously have the same hash. But as that is directly reflected in the output, this can be used as an attack vector (even if I don't know <em>which</em> letter is repeated). </li>\n<li>It is not possible to extract the salt(s) from a given hash because you shuffle the string – therefore it is impossible to say whether a given password is the same as the hashed password (we can only check whether the lengths are the same). This makes your hash function unsuitable for authentication – but for what are you using it then? <strong>For an API key, an unique random number that does not depend on user input would be better.</strong></li>\n<li>…</li>\n</ul>\n\n<p>Your code also uses, but does not define the <code>$salt</code> variable – it assigns <code>$salt1</code> and <code>$salt2</code>. The <code>$salt1</code> variable isn't used anywhere.</p>\n\n<p>Secure password hashing is only difficult if you try to use a home-brewed solution. I outlined <a href=\"https://stackoverflow.com/a/20462412/1521179\">suggested authentication workflows in another answer</a> which includes a list of recommended password hashing solutions (neither your code, SHA-512, nor MD5 is on that list, don't use them for passwords).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T16:49:23.990",
"Id": "63703",
"Score": "0",
"body": "did you even read? it says it in the opening stanza \"used for api key generation\". i'm builing a cryptocurrency exchange, and one of the things it doesn't have that is fairly standard is an api(so that users can make trade bots to handle their trading.) this is the early stages of the api key generation. once it is generated, it would be stored in the database table as their api key. basically, the thing i'm trying to avoid is collision. nevertheless i appreciate your comment. you gave me a fair deal to think about and pointed out a mistake i made. thank you"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T16:19:25.040",
"Id": "38276",
"ParentId": "38274",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T15:45:00.600",
"Id": "38274",
"Score": "0",
"Tags": [
"php",
"security",
"api"
],
"Title": "Evaluating a hashing function used to create secure API key"
}
|
38274
|
<p>I am trying to implement two simple convertors: date/time to time-stamp and vice-versa, without any dependencies on time library routines (such as <code>localtime</code>, <code>mktime</code>, etc, mainly due to the fact that some of them are not thread-safe).</p>
<p>I have the following date/time structure:</p>
<pre><code>typedef struct
{
unsigned char second; // 0-59
unsigned char minute; // 0-59
unsigned char hour; // 0-23
unsigned char day; // 1-31
unsigned char month; // 1-12
unsigned char year; // 0-99 (representing 2000-2099)
}
date_time_t;
</code></pre>
<p>I would like to have a second opinion on the following conversion routines (given a legal input):</p>
<pre><code>static unsigned short days[4][12] =
{
{ 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335},
{ 366, 397, 425, 456, 486, 517, 547, 578, 609, 639, 670, 700},
{ 731, 762, 790, 821, 851, 882, 912, 943, 974,1004,1035,1065},
{1096,1127,1155,1186,1216,1247,1277,1308,1339,1369,1400,1430},
};
unsigned int date_time_to_epoch(date_time_t* date_time)
{
unsigned int second = date_time->second; // 0-59
unsigned int minute = date_time->minute; // 0-59
unsigned int hour = date_time->hour; // 0-23
unsigned int day = date_time->day-1; // 0-30
unsigned int month = date_time->month-1; // 0-11
unsigned int year = date_time->year; // 0-99
return (((year/4*(365*4+1)+days[year%4][month]+day)*24+hour)*60+minute)*60+second;
}
void epoch_to_date_time(date_time_t* date_time,unsigned int epoch)
{
date_time->second = epoch%60; epoch /= 60;
date_time->minute = epoch%60; epoch /= 60;
date_time->hour = epoch%24; epoch /= 24;
unsigned int years = epoch/(365*4+1)*4; epoch %= 365*4+1;
unsigned int year;
for (year=3; year>0; year--)
{
if (epoch >= days[year][0])
break;
}
unsigned int month;
for (month=11; month>0; month--)
{
if (epoch >= days[year][month])
break;
}
date_time->year = years+year;
date_time->month = month+1;
date_time->day = epoch-days[year][month]+1;
}
</code></pre>
<p>I have tested this on an extensive amount of legal input (between 01/01/2000 and 31/12/2099). Any constructive comments would be appreciated (performance improvement suggestions, readability, etc).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T16:03:53.393",
"Id": "63699",
"Score": "1",
"body": "Your code will break for dates after 2100 (which is not a leap year), and you do not account for any timezones or daylight-savings."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T16:34:42.207",
"Id": "63701",
"Score": "0",
"body": "Date-time math is *hard*. I suggest you rewrite an existing test suite for your library, e.g. from [the DateTime Perl module's](https://metacpan.org/pod/DateTime) [test suite](https://metacpan.org/source/DROLSKY/DateTime-1.05/t). This should help you iron out most bugs. Note that using an `unsigned char` for a year opens up Y2K-style bugs, and that some minutes don't have 60 seconds. I also second rolfl's remark about the absence of time-zone awareness."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T17:47:37.040",
"Id": "63709",
"Score": "0",
"body": "I explicitly stated in the question that legal input is in the range 2000 - 2099"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T18:04:44.550",
"Id": "63710",
"Score": "0",
"body": "Use `localtime_r()` etc. Also see http://stackoverflow.com/q/2278919/1157100"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T18:29:26.343",
"Id": "63712",
"Score": "0",
"body": "I explicitly mentioned \"with no dependency on std library routines\". localtime_r uses a mutex (I'm guessing). I am unable to link this function to my system, which runs over STM32 (ARM based cortex) and ThreadX OS. So I need an OS agnostic solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T21:30:10.523",
"Id": "63716",
"Score": "0",
"body": "Ironic/surprising that an OS named ThreadX wouldn't have a reentrant version of `localtime()`. Check the documentation? `localtime_r()` and friends are thread-safe not because of mutexes, but because they are designed not to use static variables, so there's no shared state between threads."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T22:02:26.723",
"Id": "63720",
"Score": "0",
"body": "To my understanding (from other comments on a similar post of mine in stack-overflow), localtime_r simply encapsulates localtime with a mutex. Hence it is OS dependent and I cannot link it. Besides, even if ThreadX has a version of localtime_r, I would still like to avoid any use of OS resources in this case, as I don't see why such computation would require that in the first place."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T13:36:53.993",
"Id": "63795",
"Score": "0",
"body": "Now, I've never done any real C programming, but you're passing in an instance of your date/time structure that is then mutated, right? Which means that your code is no longer thread-safe either (if it can be shared, somebody'll do it); you'd be better off returning a new instance. For that matter, I'm of the opinion that value types should generally be immutable when possible. As a side note, you might want to check out Joda Time/JSR 310 - it's Java, but should be understandable; the base classes do this sort of thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T13:54:06.377",
"Id": "63796",
"Score": "0",
"body": "@Clockwork-Muse thanks, but this code IS thread-safe. It consists of only two functions, and a read-only static object (called 'days'). No read/write static objects whatsoever (in opposed to 'localtime'). All computations are safely executed within the stack of the calling thread. I just wanted a second opinion on correctness, performance improvement, etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-21T14:00:46.543",
"Id": "192704",
"Score": "1",
"body": "For this epoch unix timestamp \"1442842561\" i'm getting incorrect value for the date. Its shows year=45,month=9,**date=20**, hour=13, minutes=36, seconds=1.\nBut the date should be 21. Can you please resolve the bug."
}
] |
[
{
"body": "<ol>\n<li><p>Good that OP is using 4 simplifications: year 2000-2099, no DST, no leap second, no timezone. So OP knows of code limitations concerning these. Various elements of this function break without those givens.</p></li>\n<li><p>Make <code>static unsigned short days</code> a <code>const</code>.</p></li>\n<li><p>Use a <code>long</code> for your epoch as in:</p>\n\n<pre><code>void epoch_to_date_time(date_time_t* date_time,unsigned long epoch)\n</code></pre>\n\n<p>as <code>unsigned</code> is only guaranteed to range form 0 to at least 65535 which is insufficient here.</p></li>\n<li><p>For various functions, consider adding <code>const</code>. There are pros and cons to this, but may be beneficial in your case:</p>\n\n<pre><code>// unsigned int date_time_to_epoch(date_time_t* date_time)\nunsigned int date_time_to_epoch(const date_time_t* date_time)\n</code></pre></li>\n<li><p>There exist equation based (non-loop) solutions to the year-day that do not need a table like your <code>unsigned short days[4][12]</code>. Code then looks more complicated, but is faster. Please advise if interested.</p></li>\n<li><p>Most of the magic numbers like 60, 24 are so well-known that constant or macro substitution seems superfluous. But <code>(365*4+1)</code> may benefit with something like \"DaysPer4Years\".</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T23:37:31.350",
"Id": "63729",
"Score": "1",
"body": "Minor: `unsigned char hour; // 0-59` should be `unsigned char hour; // 0-23`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T01:24:04.813",
"Id": "63735",
"Score": "0",
"body": "Thank you. 2. Applied just before reading your answer. 5. Started with that approach, but code seemed much more complicated and much less readable; performance is not much different. 6. Thought about it when I wrote the code, but decided against it; macros are good when you want to keep the option of changing them in the future, which is not the case here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T01:58:45.817",
"Id": "63739",
"Score": "0",
"body": "@barak mano Thanks for the clear feedback. 6. Macros and constants are useful for self-documentation too. 5. Equation is less space (embedded concern) ."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T02:12:23.727",
"Id": "63742",
"Score": "0",
"body": "thanks. Since I changed 'days' to constant, it now resides in the code-section (EPROM on my system) instead of in the data-section (RAM on my system). An equation will probably take the same amount of memory (96 bytes) in the code-section anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T02:43:08.300",
"Id": "63747",
"Score": "0",
"body": "@barak manos I think I can well beat 96 bytes of code. The ymd --> epoch has a code snippet of `if (m < March) { m += 12; y--; } d = ((m-March) * (7832/4) + (140/4)) >> (8-2);`. Maybe later I'll post the entire thing for review and CC you. A bit busy now."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T23:19:57.480",
"Id": "38302",
"ParentId": "38275",
"Score": "13"
}
},
{
"body": "<ul>\n<li><p>This is too crammed for a single line:</p>\n\n<blockquote>\n<pre><code>return (((year/4*(365*4+1)+days[year%4][month]+day)*24+hour)*60+minute)*60+second;\n</code></pre>\n</blockquote>\n\n<p>You should split this line somehow and put it in a helper function if it could be reused.</p></li>\n<li><p>Just keep these as two lines:</p>\n\n<blockquote>\n<pre><code>unsigned int years = epoch/(365*4+1)*4; epoch %= 365*4+1;\n</code></pre>\n</blockquote>\n\n<p>You could also add a bit more whitespace for readability and make it <code>const</code>:</p>\n\n<pre><code>const unsigned int years = epoch / (365 * 4 + 1) * 4;\nepoch %= 365 * 4 + 1;\n</code></pre>\n\n<p>The first suggestion also applies to the three lines above this one. It can be easy to mistake them as a single statement. Plus, if you ever need to add additional statements to them, then they'll continue to get longer and hurt readability.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-18T15:52:36.560",
"Id": "107951",
"ParentId": "38275",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38302",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T15:51:15.973",
"Id": "38275",
"Score": "14",
"Tags": [
"c",
"datetime",
"converting",
"embedded",
"threadx"
],
"Title": "Convert between date/time and time-stamp without using standard library routines"
}
|
38275
|
<p>I have some questions regarding a common implementation of the UoW, Repository Pattern and EF:</p>
<pre><code>public interface IAppUow
{
void Commit();
IRepository<Customer> Customer{ get; } // IRepository<T>
IOrderRepository Order{ get; } // implements IRepository<T>
}
</code></pre>
<p>My questions are:</p>
<ol>
<li><p>If I need to add a new repository of whatever type, I have to change the UoW. Is this a good practice? If not, is there a better way?</p></li>
<li><p>If I run <code>Commit() { context.SaveChanges(); }</code>, it will save the state of all the context's repositories. Is this a good way?</p></li>
</ol>
|
[] |
[
{
"body": "<p>This question is on the edge of being off-topic, there's really not much code to review here.</p>\n\n<p>However your <code>IAppUow</code> interface has a number of flaws:</p>\n\n<ul>\n<li><strong>Naming</strong>: I don't see a need for the <code>App</code> part. I think a better name would be more like <code>IUnitOfWork</code>.</li>\n<li><strong>Inconsistency</strong>: You have <code>IRepository<Customer></code>, and then <code>IOrderRepository</code> - why don't you have <code>IRepository<Order></code> or <code>IOrderRepository</code>? When/if you <em>do</em> add repositories to your UoW interface, do you add a <code>IRepository<Entity></code> or a <code>IEntityRepository</code>? This inconsistency makes it very hard to tell.</li>\n</ul>\n\n<blockquote>\n <p>If I need to add a new repository of whatever type, I have to change the UoW. Is this a good practice? If not, is there a better way?</p>\n</blockquote>\n\n<p>An interface shouldn't be designed to change, as every change to an interface is a <em>breaking change</em>. I think you're mixing up the <em>abstraction</em> with its <em>implementation</em>; UoW encapsulates a <em>transaction</em> - and these things can be <em>committed</em> or <em>rolled back</em>. Thus, if I were to wrap the EF UoW into another layer of abstraction (I'll get back to that), I'd have a <code>void SaveChanges()</code> and <code>void DiscardChanges()</code> methods on the UoW interface.</p>\n\n<blockquote>\n <p>If I run <code>Commit() { context.SaveChanges(); }</code>, it will save the state of all the context's repositories. Is this a good way?</p>\n</blockquote>\n\n<p>This is how Entity Framework works. <code>DbContext</code> <em>is</em> a unit of work; if you <code>Dispose()</code> the context before saving any changes, nothing gets to the database. If you <code>SaveChanges()</code>, the unit of work commits all changes made.</p>\n\n<p><code>DbContext</code> is an <em>implementation</em> of a unit of work - it exposes <em>repositories</em> (<code>IDbSet<TEntity></code>) and a method to commit changes (and stuff about entity state management and model generation).</p>\n\n<p>This might not be what you want to hear, but this answer sums up my thoughts pretty well: <a href=\"https://softwareengineering.stackexchange.com/a/214022/68834\">https://softwareengineering.stackexchange.com/a/214022/68834</a> - in short, you don't need the pattern if you're using an Object/Relational Mapper.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T19:46:35.147",
"Id": "38290",
"ParentId": "38277",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T16:33:16.133",
"Id": "38277",
"Score": "1",
"Tags": [
"c#",
"design-patterns",
"entity-framework"
],
"Title": "Unit of work and common implementation"
}
|
38277
|
<p>I have an integer list <code>l</code> and a predefined integer value row (which is never manipulated inside the code). If value of row is 5, then I want the loop to exit if <code>l</code> contains 1,2,3,4. If it is 3, then <code>l</code> should contain 1,2 and so on for any value. I have devised a way of doing this, but since I mean to use this in an app, can someone tell me a better way of doing this?</p>
<pre><code>do
{
}while(check(row,l))
boolean check(int row,list<int> l)
{
for(int i=1;i<row;i++)
{
if((l.contains(i))
continue();
else
return true;
}
return false;
}`
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T17:17:39.830",
"Id": "63704",
"Score": "0",
"body": "You will need to post the contents of your `do...while` for this to make any real sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T17:42:15.290",
"Id": "63705",
"Score": "5",
"body": "This question appears to be off topic, because the code doesn't compile."
}
] |
[
{
"body": "<ol>\n<li><p><code>check</code> is not a good name for the function as it does not say what it checks. It returns false if all numbers below <code>row</code> are present and <code>true</code> otherwise. So a better name might be <code>numbersAreMissing</code>. </p></li>\n<li><p>You can make your loop body a bit shorter by inverting the condition:</p>\n\n<pre><code>for (int i = 1; i < row; ++i)\n{\n if (!l.contains(i)) { return true; }\n}\nreturn false;\n</code></pre></li>\n<li><p>You should really think about whether or not this check is something you want to do on every loop iteration. Especially if <code>row</code> is a bit larger this gets wasteful. There are probably better ways to organize your data so this check can be avoided but that entirely depends on the actual problem you are trying to solve.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T17:40:06.033",
"Id": "38281",
"ParentId": "38278",
"Score": "4"
}
},
{
"body": "<p>(I answered this question on <a href=\"https://stackoverflow.com/questions/20827489/an-exit-condition-for-a-do-while-loop-using-lists-c-sharp/20827701#20827701\">StackOverflow</a>, just copying it here...)</p>\n\n<p>If you want to check if your list contains all numbers from 1 to (row-1), you could use a <code>HashSet</code> like this:</p>\n\n<pre><code>var hashSet = new HashSet(myList.Where(item => item >= 1 && item < row))\n</code></pre>\n\n<p>This adds all \"relevant\" items of the list to the Set.</p>\n\n<p>Since a <code>HashSet</code> contains every item at most once, you can check the <code>Count</code> of it to ensure, all numbers are present, like:</p>\n\n<pre><code>var check = hashSet.Count == (row - 1)\n</code></pre>\n\n<p>Regarding performance, this might be more efficient than your solution, since the list needs only to be iterated once (in your solution, you have <code>row-1</code> iterations, one for every <code>Contains</code> operation). And adding to a <code>HashSet</code> is considered a O(1) operation.</p>\n\n<p>Note: The major drawback of this solution is that its not immediately apparent what it does. So consider adding a comment to it.</p>\n\n<p>Another, more readable approach would be to explicitely check, if all numbers are contained in the Set, like</p>\n\n<pre><code>var hashSet = new HashSet(myList);\nvar check = Enumerable.Range(1, row).All(number => hashSet.Contains(number));\n</code></pre>\n\n<p>If you consider <code>row</code> to be a constant the asymptotical time will be the same: O(n) for constructing the <code>HashSet</code>, and O(1)*O(1)=O(1) for the check itself (first O(1) for the constant number of \"rows\" to be checked, second O(1) for the <code>Contains</code> function...)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T17:42:32.003",
"Id": "38282",
"ParentId": "38278",
"Score": "4"
}
},
{
"body": "<p>In addition to what has been said already, I'll add the following points:</p>\n\n<ul>\n<li><code>do { ... } while (condition)</code> isn't the most readable form of loop construct. If it doesn't affect the number of iterations, you should prefer putting the condition at the top of the code block, like <code>while (condition) { ... }</code>, so you know what you're getting yourself into when you're reading the code from the top to the bottom.</li>\n<li><a href=\"/questions/tagged/c%23\" class=\"post-tag\" title=\"show questions tagged 'c#'\" rel=\"tag\">c#</a> doesn't have a <code>boolean</code> type. There's <code>System.Boolean</code> and its language alias <code>bool</code>. Did you mean <a href=\"/questions/tagged/java\" class=\"post-tag\" title=\"show questions tagged 'java'\" rel=\"tag\">java</a>?</li>\n<li>Single-letter variable names are <strong>evil</strong>. Single-letter identifiers that use a lowercase \"L\" are just plain careless. Use descriptive names.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T20:00:43.563",
"Id": "38291",
"ParentId": "38278",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "38281",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T16:50:12.813",
"Id": "38278",
"Score": "-2",
"Tags": [
"c#"
],
"Title": "An exit condition for a do-while loop using lists"
}
|
38278
|
<p>I've been working on a website and Rails and am fairly proud of my HTML semantics. However, my CSS code has become enormous in size, which is largely unnecessary for such a small website.</p>
<p>How could I shorten my code, make it easier to understand, and remove redundancy? I would prefer to have an automated process for this. If it helps at all, I do my editing in Vim, so I am happy with solutions that use that.</p>
<p>Here is my SCSS:</p>
<pre><code>@font-face {
font-family: 'baskerville_old_faceregular';
src: url('baskvill-webfont.eot');
src: url('baskvill-webfont.eot?#iefix') format('embedded-opentype'),
url('baskvill-webfont.woff') format('woff'),
url('baskvill-webfont.ttf') format('truetype'),
url('baskvill-webfont.svg#baskerville_old_faceregular') format('svg');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'copperplate_gothic_boldRg';
src: url('coprgtb-webfont.eot');
src: url('coprgtb-webfont.eot?#iefix') format('embedded-opentype'),
url('coprgtb-webfont.woff') format('woff'),
url('coprgtb-webfont.ttf') format('truetype'),
url('coprgtb-webfont.svg#copperplate_gothic_boldRg') format('svg');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'copperplate_gothic_lightRg';
src: url('coprgtl-webfont.eot');
src: url('coprgtl-webfont.eot?#iefix') format('embedded-opentype'),
url('coprgtl-webfont.woff') format('woff'),
url('coprgtl-webfont.ttf') format('truetype'),
url('coprgtl-webfont.svg#copperplate_gothic_lightRg') format('svg');
font-weight: normal;
font-style: normal;
}
@media screen and (min-width: 1024px) {
@media screen and (min-width: 1366px) {
.sign {
position: absolute;
}
#post {
position: absolute;
top: 0px;
left: 3.55%;
width: 1.5%;
height: 960px;
}
#holder {
position: absolute;
top: 0px;
left: 2.2%;
width: 44.3%;
z-index: 1;
}
#board {
position: absolute;
left: 7%;
top: 17.7%;
width: 36.9%;
}
#logo {
position: absolute;
left: 9.25%;
top: 24%;
width: 30.55%;
}
}
@media screen and (min-width: 1200px) and (max-width: 1300px) {
.sign {
position: absolute;
}
#post {
position: absolute;
top: 0px;
left: 3.55%;
width: 1.5%;
height: 990px;
}
#holder {
position: absolute;
top: 0px;
left: 2.2%;
width: 44.3%;
z-index: 1;
}
#board {
position: absolute;
left: 7%;
top: 10.7%;
width: 36.9%;
}
#logo {
position: absolute;
left: 9.25%;
top: 15.5%;
width: 30.55%;
}
}
@media screen and (min-width: 1024px) and (max-width: 1199px) {
.sign {
position: absolute;
}
#post {
position: absolute;
top: 0px;
left: 3.55%;
width: 1.5%;
height: 865px;
}
#holder {
position: absolute;
top: 0px;
left: 2.2%;
width: 44.3%;
z-index: 1;
}
#board {
position: absolute;
left: 7%;
top: 9.2%;
width: 36.9%;
}
#logo {
position: absolute;
left: 9.25%;
top: 14%;
width: 30.55%;
}
}
.home {
background: url(/assets/PaperBackground.png) no-repeat center center fixed;
background-size: cover;
}
.find_me {
background: url(/assets/Mill.png) no-repeat center center fixed;
background-size: cover;
}
.wholesale {
background: url(/assets/KraftPaper.png) no-repeat center center fixed;
background-size: cover;
}
#topnav {
list-style: none;
float: right;
margin-right: 4.5%;
margin-top: 5.2%;
}
#topnav li {
display: inline-block;
padding: 0 0.5em;
font-family: "copperplate_gothic_boldRg";
font-size: 18px;
}
#topnav li a {
text-decoration: none;
color: black;
}
#topnav li a:hover {
text-decoration: underline;
}
#info {
padding-right: 8%;
padding-left: 650px;
padding-top: 60px;
float: right;
width: 500px;
font-family: "baskerville_old_faceregular";
font-size: 23px;
font-weight: 600;
text-align: center;
}
@media screen and (min-width: 1200px) and (max-width: 1365px) {
#sidenav {
position: absolute;
top: 55%;
list-style: none;
}
}
@media screen and (min-width: 1024px) and (max-width: 1199px) {
#sidenav {
position: absolute;
top: 42%;
list-style: none;
}
}
@media screen and (min-width: 1366px) {
#sidenav {
position: absolute;
top: 67.5%;
list-style: none;
}
}
#sidenav {
left: 7%;
}
#sidenav li {
padding-bottom: 9%;
font-family: "copperplate_gothic_boldRg";
font-size: 18px;
}
#sidenav li a {
color: black;
text-decoration: none;
}
#sidenav li a:hover {
text-decoration: underline;
}
@media screen and (min-width: 1200px) {
#examples {
float: right;
margin-right: 7.5%;
margin-top: 10.5%;
text-align: center;
}
#examples img {
width: 150px;
}
#examples td {
padding-left: 70px;
padding-right: 70px;
}
}
@media screen and (max-width: 1199px) {
#examples {
float: right;
margin-right: 7.5%;
margin-top: 10.5%;
text-align: center;
}
#examples img {
width: 150px;
}
#examples td {
padding-left: 25px;
padding-right: 25px;
}
}
#examples img {
box-shadow: 6px 6px 20px 0;
}
#examples p {
font-family: "baskerville_old_faceregular";
font-size: 20px;
font-weight: 700;
}
#footer {
text-align: center;
}
#footer #footer_links {
list-style: none;
margin-bottom: 0;
}
#footer #footer_links li {
display: inline-block;
font-family: "copperplate_gothic_boldRg";
font-size: 20px;
}
#footer #footer_links li a {
margin-left: 30px;
margin-right: 30px;
color: black;
text-decoration: none;
}
#footer #footer_links li p {
margin-left: 30px;
margin-right: 30px;
}
#footer #footer_links li a:hover {
text-decoration: underline;
}
#footer #footer_links li img {
width: 25px;
margin-right: 2px;
}
#footer #footer-contact {
font-family: "baskerville_old_faceregular";
font-size: 18px;
margin-top: 0;
font-weight: 700;
}
@media screen and (min-width: 1200px) {
.home #footer {
position: relative;
margin-top: -5px;
height: 18px;
clear: both;
right: 200px;
float: right;
}
}
@media screen and (max-width: 1199px) {
.home #footer {
position: relative;
margin-top: 20px;
height: 18px;
clear: both;
right: 100px;
float: right;
}
}
.find_me #footer {
position: absolute;
top: 860px;
right: 150px;
}
@media screen and (min-width: 1200px) {
.wholesale #footer {
position: absolute;
top: 860px;
right: 300px;
}
}
@media screen and (max-width: 1199px) {
.wholesale #footer {
position: absolute;
top: 860px;
right: 160px;
}
}
#contact {
position: absolute;
right: 15%;
top: 180px;
width: 300px;
font-family: "baskerville_old_faceregular";
}
#contact ol {
list-style: none;
text-align: center;
}
#contact ol li h3 {
font-size: 26px;
}
#contact ol li h4 {
font-size: 24px;
}
#contact ol li p {
font-size: 22px;
}
#map {
position: absolute;
left: 400px;
top: 500px;
}
#in_the_shop {
position: absolute;
left: 60%;
top: 100px;
}
#shop_images {
position: absolute;
right: 5%;
top: 450px;
}
@media screen and (min-width: 1200px) {
#shop_images img {
width: 170px;
}
}
@media screen and (max-width: 1199px) {
#shop_images img {
width: 130px;
}
}
#shop_images tr td {
padding-left: 17px;
padding-right: 17px;
}
#contact_header, #mobile_nav, #leaf_1, #leaf_2, #find_me, #mobile_find_me_footer, #mobile_map, #mobile_wholesale, #wholesale_mobile_catalog {
display: none;
}
}
@media screen and (min-width: 768px) and (max-width: 1023px) {
.sign {
position: absolute;
}
#post {
position: absolute;
top: 0px;
left: 3.55%;
width: 1.5%;
height: 1000px;
}
#holder {
position: absolute;
top: 0px;
left: 2.2%;
width: 44.3%;
z-index: 1;
}
#board {
position: absolute;
left: 7%;
top: 8%;
width: 36.9%;
}
#logo {
position: absolute;
left: 9.25%;
top: 11%;
width: 30.55%;
}
#topnav {
list-style: none;
float: right;
margin-right: 4.5%;
margin-top: 5.2%;
}
#topnav li {
display: inline-block;
padding: 0 0.5em;
}
#sidenav {
position: absolute;
left: 10.37%;
top: 30%;
list-style: none;
}
#sidenav li {
padding-bottom: 19%;
}
#examples {
float: right;
margin-right: 7.5%;
margin-top: 25%;
text-align: center;
}
#examples img {
width: 150px;
}
#examples td {
padding-left: 25px;
padding-right: 25px;
}
#contact_header, #mobile_nav, #leaf_1, #leaf_2, #find_me, #mobile_find_me_footer, #mobile_map, #mobile_wholesale, #wholesale_mobile_catalog {
display: none;
}
#info {
padding-right: 5%;
padding-left: 600px;
padding-top: 60px;
float: right;
width: 400px;
}
#footer #footer_links {
list-style: none;
}
#footer #footer_links li {
display: inline-block
}
.home #footer {
position: relative;
margin-top: 20px;
height: 18px;
clear: both;
right: 130px;
float: right;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T18:36:40.590",
"Id": "66953",
"Score": "2",
"body": "I don't see anything Sass specific here, is this just the compiled CSS?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T19:44:33.030",
"Id": "66962",
"Score": "0",
"body": "It's SCSS, so it is handled slightly differently than normal CSS."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-27T19:42:23.547",
"Id": "97286",
"Score": "0",
"body": "This is css? its not written in scss at all. scss would look like this for example: `#footer #footer_links { list-style: none; li { display: inline-block;}}`"
}
] |
[
{
"body": "<p>You may want to look at <a href=\"http://compass-style.org/reference/compass/css3/font_face/\" rel=\"nofollow\">Compass</a> for generating your font-face information.</p>\n\n<p>Your media queries are a bit excessive here. Other than your font-face block, there's not a spec of code that exists outside of a media query.</p>\n\n<blockquote>\n <p>The absence of support for media queries is in fact the first media query.</p>\n</blockquote>\n\n<p>Source: <a href=\"http://www.slideshare.net/bryanrieger/rethinking-the-mobile-web-by-yiibu\" rel=\"nofollow\">http://www.slideshare.net/bryanrieger/rethinking-the-mobile-web-by-yiibu</a></p>\n\n<p>On top of that, you're failing to make use of cascade. Compare:</p>\n\n<pre><code>@media screen and (min-width: 1200px) and (max-width: 1365px) {\n #sidenav {\n position: absolute;\n top: 55%;\n list-style: none;\n }\n}\n\n@media screen and (min-width: 1024px) and (max-width: 1199px) {\n #sidenav {\n position: absolute;\n top: 42%;\n list-style: none;\n }\n}\n\n@media screen and (min-width: 1366px) {\n #sidenav {\n position: absolute;\n top: 67.5%;\n list-style: none;\n }\n}\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>@media screen and (min-width: 1024px) {\n #sidenav {\n position: absolute;\n list-style: none;\n top: 42%;\n }\n}\n\n@media screen and (min-width: 1200px) {\n #sidenav {\n top: 55%;\n }\n}\n\n@media screen and (min-width: 1366px) {\n #sidenav {\n top: 67.5%;\n }\n}\n</code></pre>\n\n<p>Using values like 1024px and 1200px in your media queries indicates to me that you're designing for specific devices, rather than your content. Consider the following code:</p>\n\n<pre><code>$breakpoint-medium: 45em;\n$breakpoint-two-column: 60em;\n\nheader {\n // use the small logo\n}\n@media (min-width: $breakpoint-medium) {\n header {\n // use the bigger logo\n }\n}\n\n@media (min-width: $breakpoint-two-column) {\n // code to make a 2-column layout\n}\n</code></pre>\n\n<p>There's quite a bit of code smell regarding your constant adjustments to things like positioning/margins, especially since you're using percentages (42% -> 55% -> 67.5%). It smells like the fixed-width designs of yesteryear. I can't comment any further here without seeing the impact it has on the layout.</p>\n\n<p>You have quite a few overqualified selectors (eg. <code>#footer #footer_links li img</code> vs <code>#footer_links img</code>). Always choose the shortest possible selector to get the job done.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T19:43:56.057",
"Id": "66961",
"Score": "0",
"body": "Thanks for the answer. I'm relatively new to responsive design, so your suggestions are a great help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T19:57:39.630",
"Id": "66965",
"Score": "0",
"body": "This site has a great summary on various aspects of responsive design: http://bradfrostweb.com/blog/post/7-habits-of-highly-effective-media-queries/"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-23T18:54:27.947",
"Id": "39902",
"ParentId": "38283",
"Score": "1"
}
},
{
"body": "<p>You can DRY your use of <strong>@font-face</strong> using this mixin <a href=\"http://codepen.io/Dygerydoo/pen/yebgPd\" rel=\"nofollow\">see on codepen</a> but you'll get better results using <code>compass</code>or <code>bourbon</code>, etc...</p>\n\n<pre><code>// Use variables instead names (name that vars as you wish, because I don't know which of them are the most used)\n$primary-font: baskerville_old_faceregular;\n$secondary-font: copperplate_gothic_boldRg;\n$tertiary-font: copperplate_gothic_lightRg;\n\n// -------------------------------------\n// Mixins\n// -------------------------------------\n\n@mixin font-face($font-name, $font-family-name) {\n font-family: $font-family-name;\n src: url('#{$font-name}-webfont.eot');\n src: url('#{$font-name}-webfont.eot?#iefix') format('embedded-opentype'),\n url('#{$font-name}-webfont.woff') format('woff'),\n url('#{$font-name}-webfont.ttf') format('truetype'),\n url('#{$font-name}-webfont.svg##{$font-name}') format('svg');\n font-weight: normal;\n font-style: normal;\n}\n\n@include font-face(baskvill, $primary-font );\n@include font-face(coprgtb, $secondary-font );\n@include font-face(coprgtl, $tertiary-font );\n</code></pre>\n\n<p>Output result for first mixin:</p>\n\n<pre><code>@font-face {\n font-family: baskerville_old_faceregular;\n src: url(\"baskvill-webfont.eot\");\n src: url(\"baskvill-webfont.eot?#iefix\") format(\"embedded-opentype\"), url(\"baskvill-webfont.woff\") format(\"woff\"), url(\"baskvill-webfont.ttf\") format(\"truetype\"), url(\"baskvill-webfont.svg#sample-font\") format(\"svg\");\n font-weight: normal;\n font-style: normal;\n}\n</code></pre>\n\n<p>As @font-face you can mixin other things in your code like this:</p>\n\n<pre><code>.home {\n background: url(/assets/PaperBackground.png) no-repeat center center fixed;\n background-size: cover;\n}\n.find_me {\n background: url(/assets/Mill.png) no-repeat center center fixed;\n background-size: cover;\n}\n.wholesale {\n background: url(/assets/KraftPaper.png) no-repeat center center fixed;\n background-size: cover;\n}\n</code></pre>\n\n<p>Turning it into this: (With the same output)</p>\n\n<pre><code>@mixin background-image($image-name, $image-file-format) {\n background: url(/assets/#{$image-name}.#{$image-file-format}) no-repeat center center fixed;\n background-size: cover;\n}\n\n.home {\n @include background-image(PaperBackground, png)\n}\n\n.find_me {\n @include background-image(Mill, png)\n}\n\n.wholesale {\n @include background-image(KraftPaper, png)\n}\n</code></pre>\n\n<p>Other things you may want to change for best results.</p>\n\n<p><strong>Use rem or em instead px</strong></p>\n\n<p>Search info about this for some properties</p>\n\n<p><strong>Use variables for colors</strong></p>\n\n<p>Instead of repeating your primary color 9999999 times use something like this:</p>\n\n<pre><code>$black: black;\n$navy-blue: #000080;\n$mexican-red: #9b3d3d;\n\n$primary-color: $navy-blue;\n$secondary-color: $mexican-red;\n</code></pre>\n\n<p>Create some variables to identify primary, and secondary color (and if later you decide to change the primary color of whole website, it will be so easy as change navy-blue with the color you want)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-08T12:12:28.943",
"Id": "116215",
"ParentId": "38283",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "39902",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T18:07:13.087",
"Id": "38283",
"Score": "2",
"Tags": [
"optimization",
"ruby-on-rails",
"sass"
],
"Title": "Quickly fixing unmaintainable SCSS code in Rails"
}
|
38283
|
<p>I have started working on my first open source project making an LDAP library in Python. I have coded quite a bit and am starting to think about a couple of the details related to design.</p>
<p>I have been considering what to do is in regard to the protocol part of the library. </p>
<p>Here is a sample of what I have for an encode/outbound protocol operation:</p>
<pre><code>class BindRequest:
""" BindRequest ::= [APPLICATION 0] SEQUENCE {
version INTEGER (1 .. 127),
name LDAPDN,
authentication AuthenticationChoice }
"""
APPID = 0x00
version = 3
name = ""
authentication = ""
def __init__(self, version, name, authentication):
self.version = version
self.name = name
self.authentication = authentication
def encode(self):
return ber_encode(APPLICATION, CONSTRUCTED, self.APPID,
ber_encode(UNIVERSAL, PRIMITIVE, INTEGER, self.version)
+ LDAPDN().encode(self.name)
+ AuthenticationChoice().encode(self.authentication))
</code></pre>
<p>What I am stuck thinking about is if the encode/decode (if appropriate) should have the parameters.... if for example encode had them then the init probably does not need to exist and I would instead just use the passed in parameters. This would remove the need for the class/instance variables and I would only create them on a decode/inbound operation.</p>
<p>Currently it works like this:</p>
<pre><code>bind = BindRequest(version, myname, mypassword)
encoded = bind.encode()
</code></pre>
<p>If I was to remove the init:</p>
<pre><code>encoded = BindRequest().encode(version, myname, mypassword)
</code></pre>
<p>If I did remove the init and the state then I may be better to just do this:</p>
<pre><code>def BindRequest_encode(version, name, authentication):
return ber_encode..........etc
encoded = BindRequest_encode(version, myname, mypassword)
</code></pre>
<p>I started with classes since the decode would break an encoded message into the appropriate instance variables and I could just attach a class to the appropriate places... if I remove classes then I would have to pass back something else like dictionaries or named tuples.</p>
<p>Here is the full code if more context is needed to understand the question: <a href="https://code.google.com/p/ldaplib/source/browse/ldaplib.py" rel="nofollow">ldaplib</a></p>
<p>I would guess this is pretty much an opinion question but what seems like the best way to proceed and why? I appreciate any feedback.</p>
<h2>Update</h2>
<p>After spending several hours experimenting, I think my best bet would be to have classes that hold any constants that the class needs but not the "field" data of the protocol. I am finding that both encoding and decoding seem best to return python objects such as strings/numbers/lists/dicts. This would avoid using any internal state in the classes other than constants/etc that are required for the class to know. I arrived at this because of how some of the protocol is naturally a list or string like this:</p>
<pre><code># Is just a list of uri
class Referral:
""" Referral ::= SEQUENCE SIZE (1..MAX) OF uri URI """
# A uri is just a simple string
class URI(LDAPString):
""" URI ::= LDAPString -- limited to characters permitted in
-- URIs
""
# This has a string and a list as fields
class PartialAttribute:
""" PartialAttribute ::= SEQUENCE {
type AttributeDescription,
vals SET OF value AttributeValue }
</code></pre>
<p>In these examples if I want to reference the string I would need to make a field to hold it, same with the list. In the bottom example it holds both a string and a list. If I just return regular python objects then I can make it like this which I believe is going to make the rest of this project much easier:</p>
<pre><code>{'type': 'cn', 'vals': ['name', 'etc']}
</code></pre>
<p>Then when each "flows" up through the protocol layers for example if something had a PartialAttribute then it would have a field that would contain that dictionary value. This is basically in favor of the syntax like this....</p>
<pre><code>encoded = BindRequest().encode(version, myname, myauthentication)
</code></pre>
<p>This being the case, the init and instance variables are unnecessary and it seems reasonable to use the class to hold constants and for the benefit of inheriting from other types if the encode/decode are the same.</p>
<p>I think I may have just answered my own question. Anything jump out as "Are you crazy...don't do that!" to anyone?</p>
|
[] |
[
{
"body": "<p>A class represents a group of <em>things</em> with common behaviour and persistent instance data. But in the fragment of code you present here, there is no <em>thing</em>. Your example is:</p>\n\n<pre><code>bind = BindRequest(version, myname, mypassword)\nencoded = bind.encode()\n</code></pre>\n\n<p>but do you ever use the <code>bind</code> object again? It doesn't seem as if you do. So why does <code>BindRequest</code> need to be a class at all? It looks to me as though a function is the appropriate implementation choice.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T18:53:35.033",
"Id": "63960",
"Score": "0",
"body": "Thanks for the reply Gareth. That is the crux of my question and why I have been thinking about just making it functions vs keeping it as classes. The place where having classes really helps is where some types are the same as others... for example a URI is an LDAPString or a SearchResultDone is an LDAPResult but with only a different appid."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T19:34:34.880",
"Id": "63963",
"Score": "0",
"body": "So I guess the question really is: Is it considered bad form to use classes *only* for grouping functions/constants together and for subclassing given that they would not have instance variables in most cases?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T15:07:35.423",
"Id": "64011",
"Score": "0",
"body": "Yes, it is considered bad form to use classes only for grouping things. Python is not Java: not everything needs to be a class. If you just want to group some functions, use a *module*."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T16:28:11.860",
"Id": "64025",
"Score": "0",
"body": "Thanks for the feedback. If I ditch the instance data and don't plan on creation of the classes (kind of hard to say all the use cases yet) I will likely refactor into functions."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T17:41:04.967",
"Id": "38392",
"ParentId": "38284",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "38392",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T18:13:13.567",
"Id": "38284",
"Score": "3",
"Tags": [
"python",
"library",
"ldap"
],
"Title": "LDAP Library design, classes, functions, initialization?"
}
|
38284
|
<p>ThreadX is a realtime operating system for <a href="/questions/tagged/embedded" class="post-tag" title="show questions tagged 'embedded'" rel="tag">embedded</a> systems from Express Logic, Inc. of San Diego, California, USA.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T18:34:24.257",
"Id": "38285",
"Score": "0",
"Tags": null,
"Title": null
}
|
38285
|
ThreadX is a realtime operating system for embedded systems.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T18:34:24.257",
"Id": "38286",
"Score": "0",
"Tags": null,
"Title": null
}
|
38286
|
<p>I need to speed up the function below:</p>
<pre><code>import numpy as np
import itertools
def combcol(myarr):
ndims = myarr.shape[0]
solutions = []
for idx1, idx2, idx3, idx4, idx5, idx6 in itertools.combinations(np.arange(ndims), 6):
c1, c2, c3, c4, c5, c6 = myarr[idx1,1], myarr[idx2,2], myarr[idx3,1], myarr[idx4,2], myarr[idx5,1], myarr[idx6,2]
if c1-c2>0 and c2-c3<0 and c3-c4>0 and c4-c5<0 and c5-c6>0 :
solutions.append(((idx1, idx2, idx3, idx4, idx5, idx6),(c1, c2, c3, c4, c5, c6)))
return solutions
X = np.random.random((20, 10))
Y = np.random.random((40, 10))
if __name__=='__main__':
from timeit import Timer
t = Timer(lambda : combcol(X))
t1 = Timer(lambda : combcol(Y))
print('t : ',t.timeit(number=1),'t1 : ',t1.timeit(number=1))
</code></pre>
<p>Results:</p>
<pre><code>t : 0.6165180211451455 t1 : 64.49216925614847
</code></pre>
<p>The algorithm is too slow for my standard use (<code>myarr.shape[0] = 500</code>). Is there a NumPy way to decrease execution time of this function (without wasting too much memory)? Is it possible to implement the problem in Cython?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T20:08:37.993",
"Id": "63713",
"Score": "2",
"body": "What are you trying to achieve here?"
}
] |
[
{
"body": "<p>Your algorithm is of time complexity <code>O(n^6)</code> in <code>ndims</code>. If your current code needs <code>65 s</code> for <code>ndims = 40</code>, then one could estimate the time for <code>ndims = 500</code> to be roughly <code>8 years</code>. Even an improvement of the most inner block's execution time by a factor of <code>1000</code> would yield an execution time of about <code>3 days</code>. I guess this is not good enough.</p>\n\n<p>So you should better try to improve the algorithm itself. However I do not really understand the problem the function is trying to solve and I couldn't come up with a better solution on the spot.</p>\n\n<p>Also I haven't looked at numpy approaches, because you seem to have no vectorizable calculations in there.</p>\n\n<p>Nonetheless I tried to make improvements to the code as is. I came up with the following:</p>\n\n<ol>\n<li><p>You use only the a small fraction of <code>myarr</code>, so extract these parts first</p>\n\n<pre><code>myarr1 = myarr[:,1]\nmyarr2 = myarr[:,2]\n</code></pre></li>\n<li><p>Since you do many index lookups on these arrays turn them into lists. Numpy is not good at single index lookups.</p>\n\n<pre><code>myarr1 = myarr[:,1].tolist()\nmyarr2 = myarr[:,2].tolist()\n</code></pre></li>\n<li><p>Instead of substracting and comparing to <code>0</code>, compare the variables directly saving one operation:</p>\n\n<pre><code>if c1>c2 and c2<c3 and c3>c4 and c4<c5 and c5>c6:\n</code></pre></li>\n<li><p>Instead of using <code>and</code>, you can also connect the comparisons all together, potentially saving the double variable lookups:</p>\n\n<pre><code> if c1 > c2 < c3 > c4 < c5 > c6:\n</code></pre></li>\n<li><p>Instead of assigning the array elements to <code>c1</code>, <code>c2</code>, etc., use them directly. Since later comparisons are not executed if earlier one already return <code>False</code> this might save array lookups:</p>\n\n<pre><code>if myarr1[idx1] > myarr2[idx2] < myarr1[idx3] > myarr2[idx4] < myarr1[idx5] > myarr2[idx6]:\n</code></pre></li>\n</ol>\n\n<p>All in all I get the following code:</p>\n\n<pre><code>import numpy as np\nimport itertools\n\ndef combcol(myarr):\n ndims = myarr.shape[0]\n solutions = []\n for idx1, idx2, idx3, idx4, idx5, idx6 in itertools.combinations(np.arange(ndims), 6):\n c1, c2, c3, c4, c5, c6 = myarr[idx1,1], myarr[idx2,2], myarr[idx3,1], myarr[idx4,2], myarr[idx5,1], myarr[idx6,2]\n if c1-c2>0 and c2-c3<0 and c3-c4>0 and c4-c5<0 and c5-c6>0 :\n solutions.append(((idx1, idx2, idx3, idx4, idx5, idx6),(c1, c2, c3, c4, c5, c6)))\n return solutions\n\ndef combcol2(myarr):\n ndims = myarr.shape[0]\n myarr1 = myarr[:,1].tolist()\n myarr2 = myarr[:,2].tolist()\n solutions = []\n for idx1, idx2, idx3, idx4, idx5, idx6 in itertools.combinations(range(ndims), 6):\n if myarr1[idx1] > myarr2[idx2] < myarr1[idx3] > myarr2[idx4] < myarr1[idx5] > myarr2[idx6]:\n solutions.append(((idx1, idx2, idx3, idx4, idx5, idx6),(myarr1[idx1], myarr2[idx2], myarr1[idx3], myarr2[idx4], myarr1[idx5], myarr2[idx6])))\n return solutions\n\nX = np.random.random((40, 10))\nY = [np.random.random((10, 10)) for i in range(100)]\n\nif __name__=='__main__':\n from timeit import Timer\n for test_case in Y: assert combcol(test_case) == combcol2(test_case)\n t = Timer(lambda : combcol(X))\n t1 = Timer(lambda : combcol2(X))\n print('t : ',t.timeit(number=1),'t1 : ',t1.timeit(number=1))\n</code></pre>\n\n<p>With results like these:</p>\n\n<pre><code>t : 12.221544027328491 t1 : 0.8104081153869629\nt : 10.69440507888794 t1 : 0.6592199802398682\nt : 12.91178011894226 t1 : 0.8727250099182129\nt : 11.21804690361023 t1 : 0.6851639747619629\n</code></pre>\n\n<p>The improvement is not even close to what you need. Also I tried to run the algorithm with <code>ndims = 80</code> and got memory problems. The reason is the number of solutions: There were <code>18679356</code> solutions taking up <code>5 GB</code> of RAM. With other values for <code>ndims</code> I found that around <code>5% - 25%</code> of all possible solutions are valid! So it seems you need to change the way you output your solutions if you want to get beyond <code>ndims = 100</code> on any realistic machine.</p>\n\n<p>Edit: I just notice that 5 GB is a bit too much for the number of solutions. However this was the memory allocated by the python process. A run with <code>ndims = 100</code> was unsuccessful due to lack of available memory.</p>\n\n<p>Edit2: There is actually something far more efficient you can do, by interweaving your solution checks with the combination generation (abandoning <code>itertools.combinations</code>). This doesn't look so nice however:</p>\n\n<pre><code>import numpy as np\nimport itertools\n\n\ndef combcol(myarr):\n ndims = myarr.shape[0]\n solutions = []\n for idx1, idx2, idx3, idx4, idx5, idx6 in itertools.combinations(np.arange(ndims), 6):\n c1, c2, c3, c4, c5, c6 = myarr[idx1,1], myarr[idx2,2], myarr[idx3,1], myarr[idx4,2], myarr[idx5,1], myarr[idx6,2]\n if c1-c2>0 and c2-c3<0 and c3-c4>0 and c4-c5<0 and c5-c6>0 :\n solutions.append(((idx1, idx2, idx3, idx4, idx5, idx6),(c1, c2, c3, c4, c5, c6)))\n return solutions\n\n\ndef combcol2(myarr):\n ndims = myarr.shape[0]\n myarr1 = myarr[:,1].tolist()\n myarr2 = myarr[:,2].tolist()\n solutions = []\n\n for idx1 in range(ndims):\n c1 = myarr1[idx1]\n for idx2 in range(idx1+1, ndims):\n c2 = myarr2[idx2]\n if c1 > c2:\n for idx3 in range(idx2+1, ndims):\n c3 = myarr1[idx3]\n if c2 < c3:\n for idx4 in range(idx3+1, ndims):\n c4 = myarr2[idx4]\n if c3 > c4:\n for idx5 in range(idx4+1, ndims):\n c5 = myarr1[idx5]\n if c4 < c5:\n for idx6 in range(idx5+1, ndims):\n c6 = myarr2[idx6]\n if c5 > c6:\n solutions.append(((idx1, idx2, idx3, idx4, idx5, idx6),(c1, c2, c3, c4, c5, c6)))\n return solutions\n\n\nX = np.random.random((40, 10))\nY = [np.random.random((10, 10)) for i in range(100)]\n\nif __name__=='__main__':\n from timeit import Timer\n for test_case in Y: assert combcol(test_case) == combcol2(test_case)\n t = Timer(lambda : combcol(X))\n t1 = Timer(lambda : combcol2(X))\n print('t : ',t.timeit(number=1),'t1 : ',t1.timeit(number=1))\n</code></pre>\n\n<p>The result:</p>\n\n<pre><code>t : 11.706523180007935 t1 : 0.15908312797546387\nt : 12.531341075897217 t1 : 0.16385602951049805\nt : 11.581043004989624 t1 : 0.14388418197631836\n</code></pre>\n\n<p>So with that we already have nearly a factor of 100x speed-up.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T22:24:45.143",
"Id": "38299",
"ParentId": "38287",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "38299",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T18:59:02.007",
"Id": "38287",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x",
"numpy",
"combinatorics"
],
"Title": "Fastest way for working with itertools.combinations"
}
|
38287
|
<p>Python 2.7.x is the final version of the Python 2.x series. Development on Python 2.7.x still continues, but no new features are being added.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T19:03:54.563",
"Id": "38288",
"Score": "0",
"Tags": null,
"Title": null
}
|
38288
|
Use this tag if you are specifically using Python 2.7. Such questions should be tagged with [python] as well.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T19:03:54.563",
"Id": "38289",
"Score": "0",
"Tags": null,
"Title": null
}
|
38289
|
<p>I have a large JavaScript function to calculate the number of chips, and which denomination of chips to show as the players chip stack. It's done on the base of 10.</p>
<p>I have chip denominations worth 1, 10, 100, 1000, 10000, 100000, 1000000. For a total of 7 different chip values, and 7 for loops in my JavaScript code.</p>
<p>Here's an example of how the 100,000 chips look when there is 5 in that spot:</p>
<p><img src="https://i.stack.imgur.com/5RxKN.jpg" alt="100000 chips"></p>
<p>Any John Nash's in here want to help me get this down to like one or two <code>for</code> loops? Any other improvements you'd like to mention?</p>
<p>Also, I use <code>$('.chips').remove();</code> right before the next hand, so that all the chips are removed and then recalculated again by a call to <code>chipStack();</code>. So that way it doesn't just add to the existing chips and show an incorrect stack of chips. But also means that every hand the below JavaScript is getting ran.</p>
<p><strong>JavaScript:</strong></p>
<pre><code>function chipStack() {
var a = hand1.cChips.toString(); //this gets the current chip amount in a string
var c = parseInt(a.substr(-1)); //this is the first 0-9
var d = parseInt(a.substr(-2, 1)); //second 0-9, in the tenth's spot
var e = parseInt(a.substr(-3, 1)); // etc etc etc
var f = parseInt(a.substr(-4, 1));
var g = parseInt(a.substr(-5, 1));
var h = parseInt(a.substr(-6, 1));
var j = parseInt(a.substr(-7, 1)); // this is the millionth spot
if (c > 0) { // if the last number is 0, doesn't run, so doesn't show any chips
eett = 4; // this is for css style bottom: number, for stack like appearance
for (var x = 0; x < c; x++) {
$('.chip1c').prepend('<div class="chip1 chips" style="bottom: -' + eett + 'px;"></div>');
eett += 4;
}
}
if (d > 0) {
eett = 4;
for (var x = 0; x < d; x++) {
$('.chip10c').prepend('<div class="chip10 chips" style="bottom: -' + eett + 'px;"></div>');
eett += 4;
}
}
if (e > 0) {
eett = 4;
for (var x = 0; x < e; x++) {
$('.chip100c').prepend('<div class="chip100 chips" style="bottom: -' + eett + 'px;"></div>');
eett += 4;
}
}
if (f > 0) {
eett = 4;
for (var x = 0; x < f; x++) {
$('.chip1kc').prepend('<div class="chip1000 chips" style="bottom: -' + eett + 'px;"></div>');
eett += 4;
}
}
if (g > 0) {
eett = 4;
for (var x = 0; x < g; x++) {
$('.chip10kc').prepend('<div class="chip10000 chips" style="bottom: -' + eett + 'px;"></div>');
eett += 4;
}
}
if (h > 0) {
eett = 4;
for (var x = 0; x < h; x++) {
$('.chip100kc').prepend('<div class="chip100000 chips" style="bottom: -' + eett + 'px;"></div>');
eett += 4;
}
}
if (j > 0) {
eett = 4;
for (var x = 0; x < j; x++) {
$('.chip1mc').prepend('<div class="chip1000000 chips" style="bottom: -' + eett + 'px;"></div>');
eett += 4;
}
}
}
</code></pre>
<p><strong>CSS:</strong></p>
<pre><code>.chips { width: 40px; height: 40px; border-radius: 100px; position: absolute; }
.ccont { position: absolute; width: 40px; height: 40px; }
.chip1c { right: 0; bottom: -30px; }
.chip10c { right: 50px; bottom: -35px; }
.chip100c { right: 100px; bottom: -40px; }
.chip1kc { right: 150px; bottom: -40px; }
.chip10kc { right: 200px; bottom: -38px; }
.chip100kc { right: 250px; bottom: -35px; }
.chip1mc { right: 300px; bottom: -30px; }
</code></pre>
<p><strong>HTML:</strong></p>
<pre><code><div class="chip1mc ccont"></div>
<div class="chip100kc ccont"></div>
<div class="chip10kc ccont"></div>
<div class="chip1kc ccont"></div>
<div class="chip100c ccont"></div>
<div class="chip10c ccont"></div>
<div class="chip1c ccont"></div>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T22:05:52.623",
"Id": "63722",
"Score": "2",
"body": "**7 for loops, 9 variables, 7 if statements, and one function** - doesn't it sound like you need more functions?"
}
] |
[
{
"body": "<p>Perhaps you can use the mod operator (<code>%</code>)? Something along this line (I don't really know JavaScript; below is just the concept):</p>\n\n<pre><code>value = parsetInt( chips.toString() );\nbase = 0.1;\n\nwhile( value > 0 ){\n stack = value % 10;\n value = Math.floor( value / 10 );\n base *= 10\n\n eett = 4\n for( var x = 0; x < stack; x++){\n // add stack with class = \"chip\"+unit+\" chips\"\n eett += 4;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T21:40:40.047",
"Id": "38295",
"ParentId": "38293",
"Score": "0"
}
},
{
"body": "<p>All the cases should be handled generically; the variables should be in an array. The class names, such as <code>chip10kc</code>, should be renamed to <code>chip10000c</code>.</p>\n\n<p>I would also split the calculation from the presentation.</p>\n\n<pre><code>/**\n * Decomposes a value as a sum of differently denominated chips.\n * The value must be a nonnegative integer.\n * Returns a seven-element array with the number of one-chips, ten-chips, …\n * million-chips. (Some of those elements may have undefined values.)\n */\nfunction chipCounts(value) {\n var chips = ('' + value).split('').reverse().map(function (e) { return parseInt(e) });\n\n // Handle value < 1 million or value >= 10 million\n chips.length = 7;\n chips[6] = Math.floor(value / 1000000);\n\n return chips;\n}\n\nfunction chipStack(chipCounts) {\n for (var exp = 0, denom = 1; exp < chipCounts.length; exp++, denom *= 10) {\n var $div = $('.chip' + denom + 'c');\n for (var c = 0, eett = 4; c < chipCounts[exp]; c++, eett += 4) {\n $div.prepend('<div class=\"chip' + denom + ' chips\" style=\"bottom: -' + eett + 'px;\"></div>');\n }\n }\n}\n\n// Test case\nchipStack(chipCounts(31415));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T22:22:44.363",
"Id": "38298",
"ParentId": "38293",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "38298",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T20:23:29.177",
"Id": "38293",
"Score": "4",
"Tags": [
"javascript",
"optimization",
"performance",
"beginner"
],
"Title": "Calculating number of chips and determining chip denominations for players"
}
|
38293
|
<p>I'm trying to refactor the following code and could use some suggestions. Basically, three functions generating random numbers in different ways are called:</p>
<pre><code>import java.util.Random;
public final class JP_RandomNumbers {
/**
* @param aArgs
*/
public static void main(String[] aArgs) {
genRandomNumbers1();
genRandomNumbers2();
genRandomNumbers3();
}
private static void genRandomNumbers1() {
log("Generating 10 random integers in range 0..99.");
//note that a single Random object is reused here
Random randomGenerator = new Random();
for (int idx = 0; idx < RANGE ; ++idx) {
int randomInt = randomGenerator.nextInt(100);
log("Generated :" + randomInt);
}
log("Done.");
}
private static void genRandomNumbers2() {
//Generating random numbers in a specific range
int START = 1;
int END = 10;
Random random = new Random();
for (int idx = 1 ; idx <= 10 ; ++idx) {
showRandomInteger(START, END, random);
}
log ("Done");
}
private static void showRandomInteger(int aStart, int aEnd, Random aRandom) {
if(aStart > aEnd) throw new IllegalArgumentException("Start cannot exceed End.");
//get the range, casting to avoid overflow problems
long range = (long)aEnd - (long) aStart + 1;
//compute a fraction of the range , 0 <= frac <= range
long fraction = (long) (range * aRandom.nextDouble());
int randomNumber = (int)(fraction + aStart);
log("Generated : " + randomNumber);
}
private void genRandomNumbers3() {
double MEAN = 100.0f;
double VARIANCE = 5.0f;
for(int idx = 1; idx <= 10; ++idx){
log("Generated : " + String.valueOf(getGaussean(MEAN,VARIANCE)));
}
log ("Done");
}
private double getGaussean(double aMean, double aVariance){
return aMean + fRandom.nextGaussian() * aVariance;
}
//Private
private static final int RANGE = 10;
private Random fRandom = new Random();
private static void log( String aString) {
System.out.println(aString);
}
}
</code></pre>
<p>Output: </p>
<pre><code>Generating 10 random integers in range 0..99.
Generated :74
Generated :99
Generated :75
Generated :15
Generated :32
Generated :31
Generated :96
Generated :61
Generated :80
Generated :89
Done.
Generated : 2
Generated : 4
Generated : 1
Generated : 9
Generated : 9
Generated : 5
Generated : 9
Generated : 4
Generated : 3
Generated : 7
Done
Generated : 96.16324820042756
Generated : 97.4298343909747
Generated : 105.18654272922421
Generated : 90.56523225378042
Generated : 100.26474837892167
Generated : 99.13288502577953
Generated : 105.99193834986883
Generated : 101.21081536019025
Generated : 99.48291677422242
Generated : 100.55524156214658
Done
</code></pre>
|
[] |
[
{
"body": "<p>The number generation technique is generally sound. I just have the following minor suggestions:</p>\n\n<ul>\n<li><p>The idiomatic way to repeat something 10 times is</p>\n\n<pre><code>for (int idx = 0 ; idx < 10 ; ++idx) { … }\n</code></pre></li>\n<li><p>Use the <code>fRandom</code> instance variable; you shouldn't need to create <code>new Random()</code> in each function.</p></li>\n<li>You hard-coded values in each function; those constants should probably be pulled out to the class level.</li>\n<li><code>showRandomInteger()</code> should be changed to return a random value instead of logging it.</li>\n<li><p>The compiler will implicitly do <code>String.valueOf()</code> for you, so you can just write</p>\n\n<pre><code>log(\"Generated : \" + getGaussean(MEAN,VARIANCE));\n</code></pre></li>\n<li><code>getGaussean()</code> should be spelled <code>getGaussian()</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T23:10:27.440",
"Id": "63726",
"Score": "0",
"body": "thanks, didnt notice I was creating multiple random objects"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T22:57:47.403",
"Id": "38300",
"ParentId": "38297",
"Score": "5"
}
},
{
"body": "<pre><code>public final class JP_RandomNumbers {\n</code></pre>\n\n<p>Classes are normally UpperCamelCase without underscores.</p>\n\n<hr>\n\n<pre><code>/**\n * @param aArgs\n */\n\npublic static void main(String[] aArgs) {\n</code></pre>\n\n<p>Why is the JavaDoc part empty? Either remove it or fill in some info. Leaving an empty JavaDoc comment laying around feels like the coder is lazy.</p>\n\n<p>Also, why is it called <code>aArgs</code>? Normally it's only <code>args</code>.</p>\n\n<hr>\n\n<pre><code>genRandomNumbers1();\ngenRandomNumbers2();\ngenRandomNumbers3();\n</code></pre>\n\n<p>These are not good function names. Whenever you have the urge to suffix functions, classes or variable names with numbers (because they're colliding) you're doing something wrong.</p>\n\n<hr>\n\n<pre><code>for (int idx = 0; idx < RANGE ; ++idx) {\n</code></pre>\n\n<p>I like your use of <code>idx</code> instead of <code>i</code>, though, <code>count</code> would be a better name in this case.</p>\n\n<hr>\n\n<pre><code>int randomInt = randomGenerator.nextInt(100);\nlog(\"Generated :\" + randomInt);\n</code></pre>\n\n<p>This could be shortened, there's no need to store the value first if it is not going to be reused.</p>\n\n<hr>\n\n<pre><code>//Generating random numbers in a specific range\nint START = 1;\nint END = 10;\n</code></pre>\n\n<p>Local and/or instance variables are lowerCamelCase. UPPER_SNAKE_CASE is preserved for (static) constants and enum members. These are neither <code>static</code> nor <code>final</code>.</p>\n\n<hr>\n\n<pre><code>private static void showRandomInteger(int aStart, int aEnd, Random aRandom) {\n</code></pre>\n\n<p>First: This function would be better named <code>logRandomInteger</code>.</p>\n\n<p>Second: Why are you prefixing every argument with <code>a</code>? That's not necessary in any way and will only complicate things in the long run. Drop it.</p>\n\n<hr>\n\n<pre><code>if(aStart > aEnd) throw new IllegalArgumentException(\"Start cannot exceed End.\");\n</code></pre>\n\n<p>Very good. Though, is a negative start allowed? Are both be allowed to be negative? If yes, this should be documented.</p>\n\n<hr>\n\n<pre><code>double MEAN = 100.0f;\ndouble VARIANCE = 5.0f;\n</code></pre>\n\n<p>Same here with the names. And you're storing floats in doubles, drop that <code>f</code> after the number.</p>\n\n<hr>\n\n<pre><code>for(int idx = 1; idx <= 10; ++idx){\n</code></pre>\n\n<p>You're inconsistent with your use of constants...in the first function the limit was <code>RANGE</code>.</p>\n\n<hr>\n\n<pre><code>private Random fRandom = new Random();\n</code></pre>\n\n<p>As I said, you should drop such prefixes. If it is unclear from the context what variable is used, you're doing something wrong (and there's always <code>this</code>).</p>\n\n<hr>\n\n<p>From time to time you have an empty line before the closing bracket of a function...normally there is none. At least be consistent.</p>\n\n<hr>\n\n<p>At the moment, your class looks like this:</p>\n\n<pre><code>import java.util.Random;\npublic final class JP_RandomNumbers {\n\n public static void main(String[] aArgs) { }\n\n private static void genRandomNumbers1() { }\n\n private static void genRandomNumbers2() { }\n\n private static void showRandomInteger(int aStart, int aEnd, Random aRandom) { }\n\n private void genRandomNumbers3() { }\n\n private double getGaussean(double aMean, double aVariance){ }\n\n //Private \n private static final int RANGE = 10;\n private Random fRandom = new Random();\n private static void log( String aString) { }\n\n}\n</code></pre>\n\n<p>This is quite messy. Group functions and variables by their visibility and if they're instances or not.</p>\n\n<p>Also consider extracting everything away from your <code>Main</code> class into a separate class that's easier to use. Putting functionality into the <code>Main</code> class can be the start of an unholy mess. Advice I always try to keep in ming:</p>\n\n<blockquote>\n <p>Your main function should tell you what the program does, not how it does it.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T16:42:29.293",
"Id": "63802",
"Score": "0",
"body": "thx, that was pretty thorough. the a in aArgs, aStart etc is to indicate that this is an argument to the function."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T12:27:36.577",
"Id": "38319",
"ParentId": "38297",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38300",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T22:13:10.510",
"Id": "38297",
"Score": "5",
"Tags": [
"java",
"random"
],
"Title": "Generating random numbers"
}
|
38297
|
<p>I wrote the following code to parse some weak ciphers out of an nmap.xml report. I am wondering if there is a more elegant way to write this code in order to avoid the nested for loops with the double <code>if</code> loops. Also, I had to create the two queues. There has to be a better way using list comprehension or a generator or something.</p>
<pre><code>from xml.etree import ElementTree
md5Stack = []
shaStack = []
ip = []
with open('nmap.xml', 'rt') as f:
tree = ElementTree.parse(f)
for node in tree.getiterator('address'):
ip = node.attrib.get('addr')
for node in tree.getiterator('elem'):
key = node.attrib.get('key')
if key == "sha1" and ip not in shaStack:
print ' %s :: %s' % (ip, key)
shaStack += ip.split(",")
if key == "md5" and ip not in md5Stack:
print ' %s :: %s' % (ip, key)
md5Stack += ip.split(",")
</code></pre>
<p><strong>Example XML</strong></p>
<pre><code><host starttime="1" endtime="1"><status state="up" reason="user-set" reason_ttl="0"/>
<address addr="1.1.1.1" addrtype="ipv4"/>
<table key="pubkey">
<elem key="type">md5</elem>
<elem key="bits">56</elem>
</table>
<table key="validity">
<elem key="notBefore">00:00+00:00</elem>
<elem key="notAfter">:00:00+00:00</elem>
</table>
<elem key="md5">34lk5jl4k5jlk34j5lk34j5lk</elem>
<elem key="sha1">234lk6j23lk6j2l3kj32lk4j3l4</elem>
<elem key="pem">BEGIN CERTIFICATE;END CERTIFICATE;</elem>
</script></port>
</ports>
<times srtt="98" rttvar="4" to="2"/>
</host>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T23:24:50.453",
"Id": "63728",
"Score": "0",
"body": "Could you provide an example of the input XML so that we can see whether the way you extract information from the document is optimal?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T23:47:36.463",
"Id": "63731",
"Score": "2",
"body": "FYI the DTD is at https://svn.nmap.org/nmap/docs/nmap.dtd"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T23:58:24.843",
"Id": "63732",
"Score": "0",
"body": "And I've found an example at https://github.com/cr0hn/golismero/blob/master/tests/test_nmap.xml"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T00:09:36.667",
"Id": "63733",
"Score": "0",
"body": "I added the XML to the original post. I am trying to get the IP address and the <elem key= values that have md5 or sha1. Note that it is heavily cut and obfuscated for obvious reasons. I still feel wrong even posting what I did lol."
}
] |
[
{
"body": "<p>I don't believe that this does what you want, for a few reasons.</p>\n\n<p>First, I'm not 100% on interleaving <code>ElementTree</code> iterators, but this may pick up more elements than you want; for example, what happens when the document is something like</p>\n\n<pre><code><host>\n<address addr=\"1.1.1.1\"/>\n</host>\n<host>\n<address addr=\"2.2.2.2\"/>\n<elem key=\"md5\"/>\n</host>\n</code></pre>\n\n<p>It's at least plausible to me that both IP addresses would show up in the md5 list. Even if it doesn't, you should strive to use code that has clear semantics.</p>\n\n<p>Second, your filters check that <code>ip not in md5Stack</code> but what you add to <code>md5Stack</code> is <code>ip.split(',')</code>.</p>\n\n<hr>\n\n<p>Let's try this:</p>\n\n<pre><code>from xml.etree import ElementTree\n\ndef extract_weak_ips(nmap_root):\n md5_ips = set()\n sha1_ips = set()\n hosts = list(nmap_root.iter('host'))\n for host in hosts:\n addresses = [address.get('addr').split(',') \n for address in host.findall(\".//address[@addr]\")]\n if host.find(\".//elem[@key='md5']\") is not None:\n md5_ips.update(addresses)\n if host.find(\".//elem[@key='sha1']\") is not None:\n sha1_ips.update(addresses)\n\ndef print_ip_set(s, key):\n for ip in s:\n print ' %s :: %s' % (ip, key)\n\nif __name__ == '__main__':\n parser = ElementTree.XMLParser()\n parser.parser.UseForeignDTD(True)\n md5_ips, sha1_ips = extract_weak_ips(ElementTree.parse('nmap.xml', parser).getroot())\n print_ip_set(md5_ips, 'md5')\n print_ip_set(sha1_ips, 'sha1')\n</code></pre>\n\n<p>I've extracted code into clear functions, and I'm using XPath queries so that the XML engine is doing the work of querying XML, not your application-specific code.</p>\n\n<hr>\n\n<p>I think that in this case the list-comprehension approach is less readable than the code with for-loops, but if you really want list comprehensions, try this:</p>\n\n<pre><code>def extract_ips_with_key_type(nmap_root, key_type):\n query = \".//elem[@key='%s']\" % key_type\n return set(apply(\n itertools.chain,\n (address.get('addr').split(',')\n for host in nmap_root.iter('host')\n if host.find(query) is not None\n for address in host.findall('.//address[@addr]')))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T01:53:50.423",
"Id": "63738",
"Score": "0",
"body": "Wow thank you for your time! I'll work on the first example, right now I'm getting an error: Traceback (most recent call last): File \"testCase.py\", line 20, in <module> md5_ips, sha1_ips = extract_weak_ips(ElementTree('nmapParseTest.xml','rt').getroot()) TypeError: 'module' object is not callable"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T01:59:05.527",
"Id": "63740",
"Score": "0",
"body": "Also I'm still doing research but I don't understand the following parts of your code: 1. what the ...set() is doing at the top. 2. What the hosts = list(nmap_root.iter('host'))is doing. And 3. What is the \".//elem[@key='md5']\" doing exactly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T02:11:03.270",
"Id": "63741",
"Score": "0",
"body": "Oops, I had a typo -- I forgot the `parse` in `ElementTree.parse`. 1. The `set()` initializes the variables as `set`s, which are data structures that can't have multiple entries with the same value. 2. This is generating a list of `host` nodes: the structure of `nmap.xml` is a a bunch of `host` elements that have subelements including `address` and `elem`. 3. That is an XPath query that finds sub-elements of the current element with tag `elem` and attribute `key` with value `'md5'`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T12:46:13.147",
"Id": "63790",
"Score": "0",
"body": "Dude thank you so much for taking your time and explaining that. You are very much appreciated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T16:55:03.377",
"Id": "63804",
"Score": "0",
"body": "Now I am getting the following error that I think may be a bug in ElementTree: Traceback (most recent call last):\n File \"testCase.py\", line 20, in <module>\n md5_ips, sha1_ips = extract_weak_ips(ElementTree.parse('nmapParseTest.xml', 'rt').getroot())\n File \"/usr/lib/python2.7/xml/etree/ElementTree.py\", line 1183, in parse\n tree.parse(source, parser)\n File \"/usr/lib/python2.7/xml/etree/ElementTree.py\", line 656, in parse\n parser.feed(data)\nAttributeError: 'str' object has no attribute 'feed'"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T22:14:54.000",
"Id": "63822",
"Score": "0",
"body": "This is relevant: http://stackoverflow.com/questions/7237466/python-elementtree-support-for-parsing-unknown-xml-entities. You have to enable UseForeignDTD."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T23:32:46.280",
"Id": "63835",
"Score": "0",
"body": "So I need to build a parser object and set the UseForeignDTD attribute to true? This would require a redesign right? Thank you for the link."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T00:52:21.513",
"Id": "63853",
"Score": "0",
"body": "No, not a full redesign; in fact, I've edited my post to do that (it still won't work on the snippet you've given because there's a couple stray tags in there: `</script></port></ports>`"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T01:33:32.830",
"Id": "38304",
"ParentId": "38301",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "38304",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-29T23:13:23.427",
"Id": "38301",
"Score": "2",
"Tags": [
"python",
"parsing"
],
"Title": "Parse weak ciphers out of an nmap.xml report"
}
|
38301
|
<p>I'm trying to improve my JavaScript (I'm usually a copy/paste guy but can do basic DOM stuff with jQuery too), so I decided to try and make a function to validate an email address without using Regex.</p>
<p>The code seems to work, but I'm interested in hearing how it could be improved.</p>
<p>I'll include the code below, but you can run/fork it on <a href="http://cdpn.io/ixbJD" rel="nofollow">Codepen</a>.</p>
<p><strong>HTML</strong></p>
<pre><code><input id="email" type="text">
<input id="submit" type="submit" value="Validate">
</code></pre>
<p><strong>JS</strong></p>
<pre><code>// Function: valid email address without regex
function isvalidemail(email) {
// Get email parts
var emailParts = email.split('@');
// There must be exactly 2 parts
if(emailParts.length !== 2) {
alert("Wrong number of @ signs");
return false;
}
// Name the parts
var emailName = emailParts[0];
var emailDomain = emailParts[1];
// === Validate the parts === \\
// Must be at least one char before @ and 3 chars after
if(emailName.length < 1 || emailDomain.length < 3) {
alert("Wrong number of characters before or after @ sign");
return false;
}
// Define valid chars
var validChars = ['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','.','0','1','2','3','4','5','6','7','8','9','_','-'];
// emailName must only include valid chars
for(var i = 0; i < emailName.length; i += 1) {
if(validChars.indexOf(emailName.charAt(i)) < 0 ) {
alert("Invalid character in name section");
return false;
}
}
// emailDomain must only include valid chars
for(var j = 0; j < emailDomain.length; j += 1) {
if(validChars.indexOf(emailDomain.charAt(j)) < 0) {
alert("Invalid character in domain section");
return false;
}
}
// Domain must include but not start with .
if(emailDomain.indexOf('.') <= 0) {
alert("Domain must include but not start with .");
return false;
}
// Domain's last . should be 2 chars or more from the end
var emailDomainParts = emailDomain.split('.');
if(emailDomainParts[emailDomainParts.length - 1].length < 2) {
alert("Domain's last . should be 2 chars or more from the end");
return false;
}
alert("Email address seems valid");
return true;
}
document.getElementById('submit').onclick = function() {
var email = document.getElementById('email').value;
isvalidemail(email);
};
</code></pre>
<p>One thing I know could be improved is where I repeat basically the same code twice to validate the characters in each section. I am more interested in hearing if the way I've structured the function and sections could be done better, as the exercise for me was more about writing well-structured JavaScript and getting familiar with some of the built-in functions than about writing a perfect validator (which is also the reason I didn't use Regex).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T02:45:00.017",
"Id": "63748",
"Score": "2",
"body": "_\"I'm interested in hearing how it could be improved\"_ - With a regex. But if the point of the exercise is specifically to practice coding without regex, well, yes, you will end up with some for of loop to test individual characters."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T12:48:18.883",
"Id": "63791",
"Score": "2",
"body": "Your array of `validChars` hardly covers the spec: spaces, quotes, @, #, >, ... all are valid chars, too. Validation for an email address is something done best server-side, because JS is easily bypassed + Server-side languages are better suited for validation"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-23T13:54:49.460",
"Id": "96259",
"Score": "1",
"body": "HTML5 has some new input types that does not require you to use JavaScript. `<input type='email' name='email'>` (This is not supported in Safari (yet).) Check the [full list of input types](http://www.w3schools.com/html/html5_form_input_types.asp)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-23T15:29:36.227",
"Id": "96289",
"Score": "1",
"body": "@ThijmenDF Please do not link to w3schools. Last time I checked, they were primarily known to spread broken/wrong information. Please link to [the nicely formatted and readable standard](http://www.w3.org/html/wg/drafts/html/master/forms.html#e-mail-state-%28type=email%29) or for example [the Mozilla docs](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) instead."
}
] |
[
{
"body": "<p>Read the <a href=\"http://en.wikipedia.org/wiki/Email_address#Syntax\" rel=\"nofollow\">(email address: syntax) article on Wikipedia</a> for what is allowed. Your current validation will produce a lot of fails for valid email addresses.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T02:24:11.953",
"Id": "63743",
"Score": "0",
"body": "Wow, you really can get away with a lot in an email address..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T02:42:46.473",
"Id": "63746",
"Score": "6",
"body": "@GusRuss89 - it is generally accepted that there is no better way to validate an e-mail than to actually send an e-mail, and get a response..... At that point, it is valid. This comes up often: http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T02:17:47.100",
"Id": "38306",
"ParentId": "38305",
"Score": "5"
}
},
{
"body": "<p>Right off the bat, there's too much explicit nit-picking going on for email validation without using a Regex... but since you're practicing javascript, here's a few tips:</p>\n\n<ol>\n<li>Since this function requires a parameter passed, you always want to make sure one exists before operating on it (i.e. using the split method).</li>\n<li>camelCase your method names for improved readability</li>\n<li>Declaring your variables on the top improves readability</li>\n<li>Optional but suggested: optimize your code for performance (i.e. research best patterns for for-loops, etc.)</li>\n</ol>\n\n<p>You can look up great references from Douglas Crockford on some Do's and Don'ts of Javascript to also improve your skills. Those were helpful to review in the early days. YouTube will have many of his lectures for review.</p>\n\n<p>Also, I agree with Gaby -- emails do accept so many valid characters, including ones we've never thought would be acceptable.</p>\n\n<p>Lastly, here's code that I quickly modified for yours. I'm sure there's a few more things you can do to improve the quality. A regex could obviously replace this entire function with roughly 5 lines of code if you're not picky.</p>\n\n<pre><code>// Function: valid email address without regex\nfunction isValidEmail(email) {\n // If no email or wrong value gets passed in (or nothing is passed in), immediately return false.\n if(typeof email === 'undefined') return null;\n if(typeof email !== 'string' || email.indexOf('@') === -1) return false;\n\n // Get email parts\n var emailParts = email.split('@'),\n emailName = emailParts[0],\n emailDomain = emailParts[1],\n emailDomainParts = emailDomain.split('.'),\n validChars = 'abcdefghijklmnopqrstuvwxyz.0123456789_-';\n\n // There must be exactly 2 parts\n if(emailParts.length !== 2) {\n alert(\"Wrong number of @ signs\");\n return false;\n }\n\n // Must be at least one char before @ and 3 chars after\n if(emailName.length < 1 || emailDomain.length < 3) {\n alert(\"Wrong number of characters before or after @ sign\");\n return false;\n }\n\n // Domain must include but not start with .\n if(emailDomain.indexOf('.') <= 0) {\n alert(\"Domain must include but not start with .\");\n return false;\n }\n\n // emailName must only include valid chars\n for (var i = emailName.length - 1; i >= 0; i--) {\n if(validChars.indexOf(emailName[i]) < 0) {\n alert(\"Invalid character in name section\");\n return false;\n }\n };\n\n // emailDomain must only include valid chars\n for (var i = emailDomain.length - 1; i >= 0; i--) {\n if(validChars.indexOf(emailDomain[i]) < 0) {\n alert(\"Invalid character in domain section\");\n return false;\n }\n };\n\n // Domain's last . should be 2 chars or more from the end\n if(emailDomainParts[emailDomainParts.length - 1].length < 2) {\n alert(\"Domain's last . should be 2 chars or more from the end\");\n return false; \n }\n\n alert(\"Email address seems valid\");\n return true;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T04:29:12.933",
"Id": "63758",
"Score": "0",
"body": "Thanks! This is excellent feedback :) Could you quickly explain the difference between return null and return false?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T18:25:57.073",
"Id": "63810",
"Score": "0",
"body": "@GusRuss89 You're asking \"isValidEmail(email)\" when passing in a value -- which you're either getting a YES (true) or NO (false). However, if you're not passing anything \"isValidEmail()\" you could return NULL since the function isn't technically answering isValidEmail() question.\n\nThere's a number of advantages doing that, including improved debugging if you realize a specific parameter doesn't have a value passing through properly, or setting specific behavior if NULL is returned from isValidEmail. Always remember to watch out for type coercion ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T03:47:50.597",
"Id": "38310",
"ParentId": "38305",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T02:10:15.130",
"Id": "38305",
"Score": "4",
"Tags": [
"javascript",
"validation",
"email"
],
"Title": "Validating email without Regex"
}
|
38305
|
<p>Here is an API key gen script for a cryptocurrency trading platform I am building.</p>
<p>First it checks to see if a key exists in the db for the user ID. If it does exist, it displays the key. If it doesn't, it creates one.</p>
<p>Next it checks to make sure the key is unique, by polling the db for identical keys. If one is found to be identical, the page is refreshed via <code>meta refresh</code>. If no key collision is found, it inserts the key in the database and refreshes the page via <code>meta refresh</code>. When the page is reloaded, there is now a key in the database for the user ID, and the key is displayed.</p>
<p>Any tips or feedback is greatly appreciated. I am a fairly inexperienced programmer and this is my first serious project.</p>
<pre><code>require_once("models/config.php");
$id = $loggedInUser->user_id;
$api_select = mysql_query("SELECT * FROM userCake_Users WHERE `User_Id`='$id'");
while($row = mysql_fetch_assoc($api_select)) {
if($row["api_key"] !== null) {
echo '<h3>Your Api Key is:</h3><br/>';
echo $row["api_key"];
}else{
$user = $row["Username"];
$pass = $row["Password"];
$length = 128;
$time = date("F j, Y, g:i a");
$salt1 = $time . hash('sha512', (sha1 .$time));
$salt2 = substr(md5(uniqid(rand(), true)), 0, 25);
$salt3 = substr(md5(uniqid(rand(), true)), 0, 25);
$salt4 = hash('sha256', (md5 .$time));
$user_hash = hash('sha512', ($salt2 . $user . $salt1));
$pass_hash = hash('sha512', ($salt1 . $pass . $salt2));
$keyhash_a = hash('sha512', ($user_hash . $salt3));
$keyhash_b = hash('sha512', ($pass_hash . $salt4));
$hash_a = str_split($keyhash_a);
$hash_b = str_split($keyhash_b);
foreach($hash_a as $key => $value) {
$hashed_a[] = $salt2 . hash('sha512', ($salt3 . $value)) . $salt1 . hash('sha256', ($salt4 . $key));
}
foreach($hash_a as $key => $value) {
$hashed_b[] = $salt2 . hash('sha512', ($salt3 . $value)) . $salt1 . hash('sha256', ($salt4 . $key));
}
$hash_merge = array_merge($hashed_b, $hashed_a);
$from_merge = implode($hash_merge);
$exploded_2 = str_split($from_merge);
$key_hash_last = implode($exploded_2);
$key0 = str_shuffle($key_hash_last);
$key1 = str_split($key0);
$key2 = array_unique($key1);
$key3 = implode($key2);
$key4 = str_shuffle($key3);
$key5 = str_shuffle($key4);
$api_key0 = str_shuffle($key3.$key4.$key5.$key2);
$api_key_prepped = mysql_real_escape_string($api_key0);
$api_check_no_collision = mysql_query("SELECT * FROM userCake_Users WHERE `api_key` = '$api_key_prepped'"); //check to see if an identical key exists
if(mysql_num_rows($api_check_no_collision) > 0) {
echo '<meta http-equiv="refresh" content="0; URL=index.php?page=api">';//an identical key exists in the database, refresh the page and generate a new key.
}else{
$api_insert = mysql_query("UPDATE `testing`.`userCake_Users` SET `api_key` = '$api_key_prepped' WHERE `userCake_Users`.`User_ID` ='$id';"); //the key is unique, submit it to the database.
echo '<meta http-equiv="refresh" content="0; URL=index.php?page=api">';
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T04:18:15.150",
"Id": "63757",
"Score": "1",
"body": "Three quick comments besides answering the actual question on security... First, `mysql_query` is deprecated and you should use newer implementations suggested here http://us2.php.net/mysql_query, unless you are using a much older PHP version. Second, is $id 'clean' enough to prevent SQL injection attacks in \"...WHERE User_Id = '$id'\"? Third, why will you want to force a page-refresh if there is a key collision, instead of just looping within the logic? In the extremely unlikely scenario of 10 key collisions, are you expecting the users to face 10 page refreshes as well?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T04:47:28.213",
"Id": "63759",
"Score": "0",
"body": "about mysql: i know. its faster to write it though and go back and change it later. about `$id`. yes, it comes from `userCake1.4.2` standard function library. basically the system is built on top of userCake, with modified password hashing and extra functions. by default, all of userCake functions are run through stringent sanitization. Third, as i stated, i have < 6 months experience in php/mysql. i haven't figured out a way to loop back through yet without a page refresh. can you provide me an example would i just return or something, i'm not sure exactly how to accomplish it in php."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T10:16:54.443",
"Id": "63783",
"Score": "0",
"body": "I'd recommend something less ambitious than a cryptocurrency trading platform as a beginner project, unless you're doing it privately just for fun."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T19:27:32.233",
"Id": "63814",
"Score": "0",
"body": "there's a difference between a beginner project and \"my first real project\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-24T12:25:04.193",
"Id": "67074",
"Score": "0",
"body": "To generate securely random bytes use `mcrypt_create_iv(length, MCRYPT_DEV_URANDOM)` with length set to 16 or so. Don't try to create your own CSPRNG."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-24T12:30:34.683",
"Id": "67075",
"Score": "1",
"body": "@.r3wt I agree with @200_success that you're not ready for such a high risk project. Choose a project where a mistake doesn't mean that cryptocurrency worth thousands of USD get stolen."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-08T16:57:12.247",
"Id": "404512",
"Score": "0",
"body": "When I use your code I do the following: include_once('genApiKey.php');\n$apiKey = Guid::NewGuid();\necho \"apiKey = \" . $apiKey . \"<br />\"; echo json_encode(array(\"License Key\"=>$apiKey)); This is what prints out. apiKey = cf53878e-1dce-4e51-8f22-337be491044e\n<br />{\"License Key\":{}} Why does $apiKey not go into my json"
}
] |
[
{
"body": "<p>An API key only have to be unique enough to avoid collison nothing more and here you are doing to much to achieve this. For example the rehashing will incrase the chance for a collison.</p>\n\n<p>I have created a class for generating unique keys for example an API key usage or simply for primary key in a database table.</p>\n\n<pre><code><?php\n\nfinal class Guid {\n\n private static $_empty = array(\"00000000\", \"0000\", \"0000\", \"0000\", \"000000000000\");\n\n private static $_parseFormats = array(\n \"D\" => \"/^[a-f\\d]{8}(-[a-f\\d]{4}){4}[a-f\\d]{8}$/i\",\n \"N\" => \"/^[a-f\\d]{8}([a-f\\d]{4}){4}[a-f\\d]{8}$/i\",\n \"B\" => \"/^(\\{)?[a-f\\d]{8}(-[a-f\\d]{4}){4}[a-f\\d]{8}(?(1)\\})$/i\",\n \"P\" => \"/^(\\()?[a-f\\d]{8}(-[a-f\\d]{4}){4}[a-f\\d]{8}(?(1)\\))$/i\",\n \"X\" => \"/^(\\{0x)[a-f\\d]{8}((,0x)[a-f\\d]{4}){2}(,\\{0x)[a-f\\d]{2}((,0x)[a-f\\d]{2}){7}(\\}\\})$/i\"\n );\n\n public static function NewGuid() {\n $data = openssl_random_pseudo_bytes(16);\n\n $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0010\n $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10\n\n $parts = str_split(bin2hex($data), 4);\n $guid = new Guid();\n $guid->_parts = array(\n $parts[0] . $parts[1],\n $parts[2],\n $parts[3],\n $parts[4],\n $parts[5] . $parts[6] . $parts[7]\n );\n\n return $guid;\n }\n\n public static function TryParse($asString, &$out_guid) {\n $out_guid = NULL;\n\n foreach (self::$_parseFormats as $format) {\n if (1 == preg_match($format, $asString)) {\n $clean = strtolower(str_replace(array(\"-\", \"{\", \"}\", \"(\", \")\", \"0x\", \",\"), \"\", $asString));\n $out_guid = new Guid();\n $out_guid->_parts = array(\n substr($clean, 0, 8),\n substr($clean, 8, 4),\n substr($clean, 12, 4),\n substr($clean, 16, 4),\n substr($clean, 20, 12),\n );\n\n return true;\n }\n }\n\n return false;\n }\n\n public static function Parse($asString) {\n if (self::TryParse($asString, $out_guid)) {\n return $out_guid;\n }\n\n throw new Exception(\"Invalid Guid: \" . $asString);\n }\n\n private $_parts;\n\n public function __construct() {\n $this->_parts = self::$_empty;\n }\n\n private static function _comparer(Guid $guid1, Guid $guid2) {\n return $guid1->_parts == $guid2->_parts;\n }\n\n public function Equals(ObjectBase $obj) {\n return self::_comparer($this, $obj);\n }\n\n public function ToString($format = NULL) {\n switch ($format) {\n case \"\";\n case \"D\";\n return implode(\"-\", $this->_parts);\n case \"N\";\n return implode(\"\", $this->_parts);\n case \"B\";\n return \"{\" . implode(\"-\", $this->_parts) . \"}\";\n case \"P\";\n return \"(\" . implode(\"-\", $this->_parts) . \")\";\n case \"X\";\n $tmp = array(\n \"0x\" . $this->_parts[0],\n \"0x\" . $this->_parts[1],\n \"0x\" . $this->_parts[2],\n \"{0x\" . implode(\",0x\", str_split($this->_parts[3] . $this->_parts[4], 2)) . \"}\"\n );\n\n return \"{\" . implode(\",\", $tmp) . \"}\";\n default:\n throw new \\Exception(\"Invalid Guid format\" . $format);\n }\n }\n\n public function __toString() {\n return $this->ToString(\"D\");\n }\n\n}\n</code></pre>\n\n<p>The usage is easy:</p>\n\n<pre><code>$apiKey = Guid::NewGuid();\n</code></pre>\n\n<p>Yes you can have different formats if you like, the default __toString() call will result in something like:</p>\n\n<pre><code>f9168c5e-ceb2-4faa-b6bf-329bf39fa1e4\n</code></pre>\n\n<p>And you don't have to check for collisons becouse it has a really small chance to have two identical Guid generated with openssl_random_pseudo_bytes(). The only thing you have to have is a PHP installation with version 5.3.0 or higher but it's recommended anyway to have the most recent PHP version (now 5.5.7).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T19:25:59.290",
"Id": "63813",
"Score": "0",
"body": "i disagree. why would you not check for collision? that's just lazy"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T19:36:39.390",
"Id": "63815",
"Score": "0",
"body": "Generate with my code 1 billion identifier you will see."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T01:58:47.720",
"Id": "63856",
"Score": "0",
"body": "Ok thank's Peter Kiss. i will consider using your method for creating tradekeys. they fit the bill perfectly for that, and i can use a similar scheme of polling the db to ensure uniqueness, just to be safe. this is a trading site, `margin for error == NULL`. i went with 200_success's answer. your's was very good, but his provided something a little more to my liking."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T02:55:50.963",
"Id": "63860",
"Score": "0",
"body": "Read [UUID generation techniques](http://tools.ietf.org/html/rfc4122) and [probability of duplicates](http://en.wikipedia.org/wiki/Universally_unique_identifier#Random_UUID_probability_of_duplicates). A properly generated UUID is so unlikely to collide that if you want to worry about collisions, you'll also want to worry about memory/CPU defects and cosmic rays making your computer behave nondeterministically."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T09:42:01.903",
"Id": "65487",
"Score": "0",
"body": "i would have used it if the class worked."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T09:32:44.590",
"Id": "38315",
"ParentId": "38309",
"Score": "5"
}
},
{
"body": "<p>It feels like you are combining lots of hashing and string transformation in hopes that complexity will make your scheme more secure. That's not engineering or computer science, though — it's <a href=\"http://en.wikipedia.org/wiki/Cargo_cult_programming\">Cargo Cult Programming</a>.</p>\n\n<p>There are two ways that an API key scheme could work:</p>\n\n<ol>\n<li><p>To generate the API key, concatenate the username with a salt and site-wide secret, then hash it. When it is later presented, verify it by concatenating the username, salt, and secret, and see if the hashes match.</p>\n\n<p>Advantages:</p>\n\n<ul>\n<li>It may be possible to verify the API key without a database lookup.</li>\n<li>You can immediately revoke all API keys ever issued by simply changing the site-wide secret.</li>\n</ul>\n\n<p>Disadvantages:</p>\n\n<ul>\n<li>It's tricky to revoke the API key for a particular user without a database lookup.</li>\n</ul></li>\n<li><p>Generate any distinct, unguessable string. Store it in the database, associated with the user. When it is later presented, verify it by looking it up in the database.</p>\n\n<p>Advantages:</p>\n\n<ul>\n<li>It's easy to understand how it works.</li>\n</ul>\n\n<p>Disadvantages:</p>\n\n<ul>\n<li>Verification requires a database lookup.</li>\n</ul></li>\n</ol>\n\n<p>What you have done is a combination of the two strategies. You store the generated API key in the database, associated with the user. However, while you could have used just any random string, you used a convoluted process involving lots of randomizing, hashing, concatenating, and shuffling, all without much justification, and in a way that offers no additional security benefits.</p>\n\n<p>Consider, for example:</p>\n\n<pre><code>$hash_merge = array_merge($hashed_b, $hashed_a);\n$from_merge = implode($hash_merge);\n$exploded_2 = str_split($from_merge);\n$key_hash_last = implode($exploded_2);\n</code></pre>\n\n<p>That just converts an array to a string, back into an array, and reconstitutes the same string again.</p>\n\n<p>If you consider the properties of cryptographic hash functions, you will notice that much of the manipulations are unnecessary. In particular, cryptographic hash functions are designed such that <a href=\"http://en.wikipedia.org/wiki/Avalanche_effect\">if inputs <em>a</em> and <em>b</em> differ by as little as one bit, hash(<em>a</em>) and hash(<em>b</em>) will not resemble each other at all</a>.</p>\n\n<p>Therefore, if you choose option (2), you can generate an API key securely using something as simple as</p>\n\n<pre><code>$api_key = hash('sha256', (time() . $id . $some_sitewide_secret . rand()));\n</code></pre>\n\n<p>The result will be secure because:</p>\n\n<ol>\n<li>Cryptographic hashes are one-way (irreversible) functions, so knowing the hash reveals nothing about the input that was hashed. (Unguessable)</li>\n<li>The input varies by time and includes randomness, so it is not repeatable. (Distinct)</li>\n<li>The input includes the user ID, so no two users should be able to generate the same key. (Distinct)</li>\n<li>The input includes some site-wide secret string (which you can set in your configuration file), so even if an attacker tried to generate a lot of keys using the same technique in an attempt to brute-force a match, knowing the approximate time at which the key was generated and even cracking the pseudorandom number generator would not help. Pick a very long random string for the site-wide secret (a SHA-256 of any word processing document would do). (Unguessable)</li>\n<li>The output has 256 bits of entropy, which is impossible to crack by exhaustive enumeration. (Unguessable)</li>\n</ol>\n\n<p>Furthermore, the chance that the same API key would be generated twice is about 2<sup>-250</sup>. It's more likely that your server would be struck by an asteroid tomorrow than that it would generate the same key twice using this technique, so don't worry about accidental collisions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-24T21:59:52.013",
"Id": "67175",
"Score": "1",
"body": "That is a great explanation you put together, you made it very simple and easy to understand"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T13:21:35.677",
"Id": "67705",
"Score": "1",
"body": "+1, except for \"a SHA-256 of any word processing document would do\". If an attacker got access to your word processing documents, they could then find the key. It would be better to use a secure source of random numbers, such as `/dev/random`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T09:44:10.507",
"Id": "38316",
"ParentId": "38309",
"Score": "17"
}
}
] |
{
"AcceptedAnswerId": "38316",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T03:04:13.440",
"Id": "38309",
"Score": "7",
"Tags": [
"php",
"mysql",
"api",
"cryptocurrency"
],
"Title": "Security of API Keygen for a cryptocurrency trading platform"
}
|
38309
|
<p>I wrote a simple android app to export the browsers history as JSON, but I do not know if the resulting JSON is a format that the user will easily be able to parse and use. </p>
<p>Is there any way that i could improve the resulting format? Will it be easy for the user to use? </p>
<p>I have the title of the page first, should I have the URL first instead? </p>
<p>The URL contains escape characters, but this does not work in all browsers, For example Chrome can reformat the url but Safari can't. Is there a way to fix this so the URL will work in all browsers? </p>
<p>Here is the code for the app. </p>
<pre><code>public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getBrowserHist();
}
public void getBrowserHist() {
try {
JSONObject parent = new JSONObject();
String[] proj = new String[] { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL, Browser.BookmarkColumns.DATE,
Browser.BookmarkColumns.VISITS };
String sel = Browser.BookmarkColumns.BOOKMARK + " = 0";
Cursor mCur = getContentResolver().query(Browser.BOOKMARKS_URI,
proj, sel, null, null);
mCur.moveToFirst();
if (mCur.moveToFirst() && mCur.getCount() > 0) {
boolean cont = true;
while (mCur.isAfterLast() == false && cont) {
JSONObject jsonObject = new JSONObject();
String title = mCur.getString(mCur
.getColumnIndex(Browser.BookmarkColumns.TITLE));
String url = mCur.getString(mCur
.getColumnIndex(Browser.BookmarkColumns.URL));
String date = mCur.getString(mCur
.getColumnIndex(Browser.BookmarkColumns.DATE));
String visits = mCur.getString(mCur
.getColumnIndex(Browser.BookmarkColumns.VISITS));
jsonObject.put("TITLE", title);
jsonObject.put("URL", url);
jsonObject.put("DATE", date);
jsonObject.put("VISITS", visits);
parent.put(title, jsonObject);
mCur.moveToNext();
}
EditText output = (EditText) findViewById(R.id.outputArea);
output.setText(parent.toString(4));
}
} catch (JSONException e) {
e.printStackTrace();
}
Button copy = (Button) findViewById(R.id.copy);
copy.setOnClickListener(new OnClickListener() {
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void onClick(View v) {
EditText output = (EditText) findViewById(R.id.outputArea);
String data = output.getText().toString();
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", data);
clipboard.setPrimaryClip(clip);
}
});
Button share = (Button) findViewById(R.id.share);
share.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
EditText output = (EditText) findViewById(R.id.outputArea);
String data = output.getText().toString();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, data);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
});
}
}
</code></pre>
<p>Here is a sample of the resulting JSON. </p>
<pre><code>{
"Academia Stack Exchange": {
"DATE": "1388375986375",
"URL": "http:\/\/academia.stackexchange.com\/",
"VISITS": "1",
"TITLE": "Academia Stack Exchange"
},
"ProgrammableWeb: Subscribe": {
"DATE": "1388307236378",
"URL": "http:\/\/www.programmableweb.com\/pwtsubscribe",
"VISITS": "1",
"TITLE": "ProgrammableWeb: Subscribe"
},
"Bitcoin Block Explorer - Blockchain.info": {
"DATE": "1388306500160",
"URL": "http:\/\/blockchain.info\/",
"VISITS": "1",
"TITLE": "Bitcoin Block Explorer - Blockchain.info"
},
"All Sites - Stack Exchange": {
"DATE": "1388375962623",
"URL": "http:\/\/stackexchange.com\/sites",
"VISITS": "1",
"TITLE": "All Sites - Stack Exchange"
},
"Block Explorer API - blockchain.info": {
"DATE": "1388306537030",
"URL": "http:\/\/blockchain.info\/api\/blockchain_api",
"VISITS": "3",
"TITLE": "Block Explorer API - blockchain.info"
},
"ProgrammableWeb: Subscribe Success": {
"DATE": "1388307257562",
"URL": "http:\/\/www.programmableweb.com\/pwtsubscribesuccess",
"VISITS": "2",
"TITLE": "ProgrammableWeb: Subscribe Success"
},
"http:\/\/blockchain.info\/rawaddr\/1CuJxwjqf8z2uy3EHh2Kge12tcR5eNiB4t": {
"DATE": "1388306616394",
"URL": "http:\/\/blockchain.info\/rawaddr\/1CuJxwjqf8z2uy3EHh2Kge12tcR5eNiB4t",
"VISITS": "1",
"TITLE": "http:\/\/blockchain.info\/rawaddr\/1CuJxwjqf8z2uy3EHh2Kge12tcR5eNiB4t"
},
"Code Review Stack Exchange": {
"DATE": "1388376002575",
"URL": "http:\/\/codereview.stackexchange.com\/",
"VISITS": "1",
"TITLE": "Code Review Stack Exchange"
},
"Stack Overflow": {
"DATE": "1388375977992",
"URL": "http:\/\/stackoverflow.com\/?as=1",
"VISITS": "1",
"TITLE": "Stack Overflow"
}
}
</code></pre>
<p>Here is the <a href="https://github.com/kylelk/BrowserHistory" rel="nofollow">repository</a> for the app.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T12:33:00.113",
"Id": "63789",
"Score": "0",
"body": "I'm not sure this question is in-topic. We do *code* reviews, not suggestions on how to make an *output format* better."
}
] |
[
{
"body": "<p>If you want to use the JSON to be easily parsed, I would suggest using a JSONArray so your output is ordered the way it is in the browsers history (unlike the JSONObject, which are key/value pairs not in order). If you use JSONArray you should save the title inside the objects of course.</p>\n\n<hr>\n\n<p>If you want to have it human readable, how about exporting it as <code>.pdf</code> or <code>.html</code> file with clickable links.</p>\n\n<hr>\n\n<p>If you want to do some more work, you could use the jsondata, export it as your own data-format, and build an Activity for reading and displaying this data to make it human readable.</p>\n\n<p>You could easily un-escape the URLs, then they should work in every browser.</p>\n\n<hr>\n\n<p>Small code correction: your variable <code>cont</code> in line 37 should be obsolete.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T12:40:29.260",
"Id": "38321",
"ParentId": "38311",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T04:12:56.693",
"Id": "38311",
"Score": "0",
"Tags": [
"java",
"android",
"json"
],
"Title": "Android export browser history as JSON"
}
|
38311
|
<p>I have recently been looking into the concepts/patterns behind dependency injection, inversion of control, and registries/service locators. I have searched about the internet on the subjects and have come up with some decent understanding about them, but some things still seem a little cloudy. To start, I would like to know if my understanding on the subjects is correct:</p>
<ul>
<li>Dependency Injection - injecting a dependent class into another class that needs the dependency to operate correctly. e.g. <code>ClassA</code> depends on <code>ClassB</code>, so <code>ClassB</code> is injected into <code>ClassA</code> through either a method or constructor of <code>ClassA</code>.</li>
<li>Registries/Service Locators - Basically an array or object with keys/properties that hold other objects that can be called up when needed by other classes.</li>
<li>Inversion of Control - I actually don't really know what this is completely, yet. From what I can understand IoC is simply dependency inject exploited and enhanced to another level. IoC seems to utilize <code>Closures</code> to create "definitions" of what objects should look like (with dependencies) that can be called later in an application.</li>
</ul>
<p>I'm interested in some clarifications on what these three things are in relation to each other and if I have the meanings/concepts behind each understood correctly. Each seem to have their uses, but I see mixed responses on the subjects. So perhaps some simple examples or situations on where they each have their use could help clear the air for me.</p>
<p>I learn best with practice, trial by error, and good 'ol hands-on approach. The internet, along with many posts over on Stack Overflow, reveal a number of tried and true IoC/DIC plugins you can use for your PHP apps, however I feel the need to make my own for understanding, experience, and personal enrichment. So to better understand all of these concepts I have tried to created my own IoC/DIC to get a grip on how all of this works and if I can use this sort of thing in future developments. I would like some feedback on my code and need to know if I am missing some considerations from an implementation standpoint. I have made this as a <code>static</code> class, as it seems to make sense. I know I will likely shamed and stoned for making such a thing <code>static</code>, but to me the end result if I were to use it would be to throw it behind a namespace and not pollute the global space. Making the class static also means I don't have to inject the IoC into other classes as well. But perhaps there are some considerations there I am not seeing right away either, so again, feedback is much appreciated.</p>
<p>Here is my IoC/DIC code I have in <code>IoC.php</code>:</p>
<pre><code><?php
/**
* Dependancy Injector Container / Inversion of Control
*
* Learning project for DIC/IoC design pattern.
*
*/
class IoC {
private static $definitions = array();
private static $registry = array();
/**
* Register a Closure for use in creating an object later.
*
* @param string $identifier String to identify the registered definition.
* @param Closure $closure A Closure to be called that will create an object.
*/
public static function register($identifier, Closure $closure) {
if(array_key_exists($identifier, self::$definitions)) {
throw new Exception("Identifier '$identifier' already defined in registry.");
} else {
self::$definitions[$identifier] = $closure;
}
}
/**
* Check if a registered definition exists.
*
* @param string $identifier The definition's indentifier to search for.
* @return bool TRUE if a definition was found or FALSE if it was not.
*/
public static function exists($identifier) {
if(array_key_exists($identifier, self::$definitions)) {
return true;
}
return false;
}
/**
* Launches the Closure definition to create a specified object.
*
* @param string $identifier The Closure definition to locate and call.
* @return mixed An object created by a Closure definition.
*/
public static function create($identifier) {
if(static::exists($identifier)) {
$item = self::$definitions[$identifier];
return $item();
} else {
throw new Exception("No item registered with the identifier of '$identifier'.");
}
}
/**
* Launches a Closure definition and stores the created object in the registry.
*
* @param string $identifier String to identify the created object in the registry.
* @param string $object A Closure definition to look for and call.
*/
public static function store($identifier, $object) {
if(static::exists($object)) {
$item = self::create($object);
self::$registry[$identifier] = $item;
} else {
throw new Exception("Unable to store item. No item registered with the identifier of '$identifier'.");
}
}
/**
* Gets an object stored in the registry.
*
* @param string $identifier The object identifier to find in the registry.
* @return mixed Returns the requested object or FALSE if the object wasn't found.
*/
public static function get($identifier) {
if(array_key_exists($identifier, self::$registry)) {
return self::$registry[$identifier];
} else {
throw new Exception("No item registered with the identifier of '$identifier'.");
}
return false;
}
}
?>
</code></pre>
<p>I have created a file for this, which works as expected, but I haven't thrown anything behind a namespace to see how it works there. For my test I define a number of objects and then register a few with the IoC container and then print out some results. I start by creating a class called <code>FruitBasket</code> which uses some setter injection to obtain <code>Fruit</code> objects. I then create a <code>Fruit</code> parent class and some child classes <code>Apple</code>, <code>Orange</code>, <code>Banana</code>, and <code>Pomegranate</code>. One function in the IoC is called <code>register()</code> which I create a definition of a closure in and give it a string to identify that closure by. After a definition has been made I can have that closure called by making a call to <code>create()</code>, which only needs the identifier for the closure. The IoC container also contains a registry where objects can be instantiated and preserved using the <code>store()</code> function. <code>store()</code> needs an identifier to be used to identify the newly created object by in the registry and the identifier for a closure definition that has already been made using <code>register()</code>.</p>
<p>Here are the classes used to create the <code>FruitBasket</code> and <code>Fruits</code>:</p>
<pre><code><?php
class FruitBasket {
/**
* Array of fruits in the basket
*/
private $fruits = array();
/**
* Constructor - no arguements
*/
public function __construct() {}
/**
* Add a fruit to the basket.
*
* In order for the fruit basket to be useful it should
* have some fruit in it. The fruits are the dependancies.
*
* @param Fruit $fruit A type of Fruit to add to the basket.
*/
public function addFruit(Fruit $fruit) {
$this->fruits[] = $fruit;
}
/**
* Show the flavors of all the fruit in the basket
*/
public function show() {
if(!empty($this->fruits)) {
foreach($this->fruits as $fruit) {
$fruit->getFlavor();
}
} else {
throw new Exception("Nothing to show, no fruits!");
}
}
}
/**
* Parent class: Fruit
*/
class Fruit {
private $flavor = "";
public function __construct($str) {
$this->flavor = $str;
}
public function getFlavor() {
print("The fruit " . get_class($this) . " tastes " . $this->flavor . ".\n");
}
}
/**
* Child class: Apple
*/
class Apple extends Fruit {
public function __construct() {
parent::__construct("sweet and juicy");
}
}
/**
* Child class: Orange
*/
class Orange extends Fruit {
public function __construct() {
parent::__construct("tangy - but in a citris way");
}
}
/**
* Child class: Banana
*/
class Banana extends Fruit {
public function __construct() {
parent::__construct("a bit on the bland side of sweetness");
}
}
/**
* Child class: Pomegrante
*/
class Pomegranate extends Fruit {
public function __construct() {
parent::__construct("juicy, seedy, and delicious followed by a little bit of sour-like sweetness");
}
}
?>
</code></pre>
<p>Here is the test that I did to check some of the functionality:</p>
<pre><code><?php
// - SET REGISTRATIONS
//Register the definition for an empty basket
//This definition doesn't do any injections.
IoC::register('emptyBasket', function () {
$basket = new FruitBasket();
return $basket;
});
//Register the definition with a basket that
//has some fruit. This would hopefully be
//an example of how to utilize setter injection.
IoC::register('fruitBasket', function () {
$basket = new FruitBasket();
$basket->addFruit(new Apple());
$basket->addFruit(new Orange());
return $basket;
});
//Register another definition but will all the
//fruits injected into the basket.
IoC::register('fullBasket', function () {
$basket = new FruitBasket();
$basket->addFruit(new Apple());
$basket->addFruit(new Orange());
$basket->addFruit(new Banana());
$basket->addFruit(new Pomegranate());
return $basket;
});
//Store an empty basket in the registry for shared use.
//Equivalent to storing a database connection.
IoC::store('emptyBasket', 'emptyBasket');
//Now it is time to do stuff with the things that have
//been created.
//Create a 'fruitBasket' and show its contents.
print("\nShowing contents of 'fruitBasket'. \n");
$basket = IoC::create('fruitBasket');
$basket->show();
//Create a 'fullBasket' and show its contents.
print("\nShowing contents of 'fullBasket'. \n");
$basket = IoC::create('fullBasket');
$basket->show();
//Get the 'emptyBasket' stored in the registry and add some fruits.
print("\nShowing contents of 'emptyBasket' - after some additions. \n");
$basket = IoC::get('emptyBasket');
$basket->addFruit(new Orange());
$basket->addFruit(new Pomegranate());
$basket->addFruit(new Apple());
$basket->show();
?>
</code></pre>
<p>This produced the following (expected) output:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Showing contents of 'fruitBasket'.
The fruit Apple tastes sweet and juicy.
The fruit Orange tastes tangy - but in a citris way.
Showing contents of 'fullBasket'.
The fruit Apple tastes sweet and juicy.
The fruit Orange tastes tangy - but in a citris way.
The fruit Banana tastes a bit on the bland side of sweetness.
The fruit Pomegranate tastes juicy, seedy, and delicious followed by a little bit of sour-like sweetness.
Showing contents of 'emptyBasket' - after some additions.
The fruit Orange tastes tangy - but in a citris way.
The fruit Pomegranate tastes juicy, seedy, and delicious followed by a little bit of sour-like sweetness.
The fruit Apple tastes sweet and juicy.
</code></pre>
</blockquote>
<p>All in all I am happy with what the results are so far, but since the subjects are new to me I am reaching out the community here on Code Review for feedback. I am basically concerned with whether or not my understanding of DI/IoC/Registries/Service Locators are sound and whether or not I am overlooking various design considerations. I would also like to know if I am going in the right direction with my IoC code as it is now or if I am completely missing the point on how to create such a thing in PHP.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T07:26:23.617",
"Id": "63764",
"Score": "0",
"body": "\"I know I will likely shamed and stoned\" Let me be the first to cast a stone at you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T08:17:21.813",
"Id": "63765",
"Score": "0",
"body": "Humorous as it was, I'll also let you be the first to add some substance please. What is so horrible about it? I don't necessarily need an instance of the IoC object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T09:23:52.397",
"Id": "63780",
"Score": "0",
"body": "Here is [your code without the static](http://sandbox.onlinephpfunctions.com/code/b13b1d6e3a6f87004def15d92bb3a628215c56b0). Apart from making `IoC` members non-static, only difference is the addition of `$ctx = new IoC();`. And it is *a step forward*, as it demonstrates I can now have many contexts in an application."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T16:52:23.063",
"Id": "63803",
"Score": "0",
"body": "Thanks for the suggestion. If I am understanding you correctly, are you recommending that instead of have a single IoC object out in the global space, I instead instantiate it as I need it in the various parts of my software??"
}
] |
[
{
"body": "<p>First off: _steer clear of <code>static</code>'s as much as you can, especially in PHP.</p>\n\n<p>You seem unclear as to <em>what</em> IoC exactly is. It's perfectly simple, though: IoC has more to do with <em>how</em> your code works. How you generate the desired results. It doesn't define how you do it. At least, not as much as a definite pattern/implementation of this technique.<br/>\nDependency Injection (DI) is, actually, a technique with which IoC is achieved. Take a class that writes stuff to a log of sorts:</p>\n\n<pre><code>class Logger\n{\n const LOG_FILE = 'file';\n const LOG_DB = 'db';\n\n private $resource = null;\n private $mode = null;\n\n public function __construct($resource, $mode = self::LOG_FILE)\n {\n $this->resource = $resource;\n $this->mode = $mode;\n }\n\n public function writeLog(array $params)\n {\n switch ($this->mode)\n {\n case self::LOG_FILE:\n return $this->logToFile($params);\n case self::LOG_DB:\n return $this->logToDb($params);\n }\n }\n\n private function logToFile(array $params)\n {\n fwrite($this->resource, implode(' - ', $params).PHP_EOL);\n }\n}\n</code></pre>\n\n<p>Now, in this example, the logger class has a generic <code>writeLog</code> function that is public. It's this method that'll be called by the code throughout. Yet, depending on what <em>resource</em> was injected, the <code>writeLog</code> function will result in a call to a specific <code>logTo*</code> method.<br/>\nPut simply: What you inject effectively <em>controls</em> how the class does what it does. The class' job is the same, but the specifics of its actions are controlled by its dependencies.</p>\n\n<p>Of course, this example doesn't fully surrender control, so the inversion is only half-way there. In real life example (ie frameworks) you're quite likely to come across something that is often referred to as <em>adapters</em>, and your <code>Logger</code> class will look more like:</p>\n\n<pre><code>namespace Log;\nuse Log\\Adapters\\Adapter;\n\nclass Logger\n{\n private $adapters = array();\n private $mode = null;\n private $active = null;\n\n public function __construct(Adapter $adapter)\n {\n $this->addAdapter($adapter, true);\n }\n\n public function write(array $params)\n {\n return $this->active->writeLog($params);\n }\n\n /**\n * Inject log adapters through this method\n * @param Log\\Adapters\\Adapter $adapter\n * @param bool $setActive = false\n * @return Log\\Logger\n **/\n public function addAdapter(Adapter $adapter, $setActive = false)\n {\n $this->adapters[$adapter->getType()] = $adapter;\n if ($setActive)\n {\n $this->mode = $adapter->getMode();\n $this->active = $adapter;\n }\n return $this\n }\n\n public function __destruct()\n {\n foreach($this->adapters as $type => $adapter)\n {\n $adapter->close();\n unset($this->adapters[$type];\n }\n }\n}\n</code></pre>\n\n<p>Now this method excepts a dependency of the type <code>Log\\Adapters\\Adapter</code> which, in itself doesn't say much. That's simply because this class should be <em>an abstract</em> from which all <em>actual</em> loggers should extend, or it should be an interface which all logger classes should then implement. This ensures/enforces the dependency will have all the methods that you're using in your <code>Logger</code> class, so it can do its job. However, how the data is written, and where it is written <em>is beyond the control of the <code>Logger</code> itself</em>. Hence, we have established a clear Inversion of Control: Here, the dependency actually controls how the <code>Logger</code> will <em>actually</em> function.</p>\n\n<p>Let's assume <code>Adapter</code> is an Interface:</p>\n\n<pre><code>namespace Log\\Adapters;\nInterface Adapter\n{\n public function getType();\n public function getMode();\n public function writeLog(array $params);\n public function close();\n}\n</code></pre>\n\n<p>Then, a DB logger would end up looking like:</p>\n\n<pre><code>namespace Log\\Adapters;\nclass DBLog implements Adapter\n{\n private $db = null;\n private $logTbl = null;\n public function __construct(\\PDO $db, $logTbl = 'logs')\n {\n $this->db = $db;\n $this->logTbl = (string) $logTbl;\n }\n public function writeLog(array $params)\n {//crude and horrid code, but just as an example\n $stmt = $this->db->prepare(\n 'INSERT INTO '.$this->logTbl.\n ' ('.implode(',',array_keys($params)).') VALUES ('.\n substr(str_repeat('?,',count($params)),0,-1).')'\n );\n $stmt->execute($params);\n return $this;\n }\n public function getType()\n {\n return get_class($this).'->'.$this->logTbl;\n }\n public function getMode()\n {\n return 'db';\n }\n public function close()\n {\n //$this->db->commit(); perhaps?\n $this->db = null;//deref db connection\n }\n}\n</code></pre>\n\n<p>On the front of <em>registries</em> and <em>serivice locators</em>, I'll be brief. A registry is actually nothing more than a global in drag, dressed in the tinsel of OO code. A registry class is actually pretty much <em>exactly</em> the same as <code>$_GLOBAL</code>. Compare the following:</p>\n\n<pre><code>Zend_Registry::set('db', new PDO());//set PDO connection in registry\n//compared to\n$_GLOBALS['db'] = new PDO();\n</code></pre>\n\n<p>And then, anywhere in your code:</p>\n\n<pre><code>$db = Zend_Registry::get('db');\n$db = $_GLOBALS['db'];\n</code></pre>\n\n<p>The advantages are that a registry allows you to implement some checks in the <code>set</code> method, to avoid accidentally reassigning a given dependency. Be it through your own code or third party dependencies. The drawbacks are: They still are global instances (thus their ref-count will always be 1 or more, and so they'll stay in memory, weather you need them to or not) and they allow for messy code: DB stuff in viewscripts <em>is</em> possible owing to a registry.<br/>\nA service locator is pretty much the same thing, but it's a <em>bit</em> more refined, and easier to test, because you can simply use an ini, xml or yaml file to list all the services you need, and test weather or not they are available, without needing to create an instance.<Br/>\nSo in a way, a service locator works like a registry, but <em>it</em> loads the dependencies when you need them (≃ lazy loading). Some more elaborate SL's allow for dependency injection on the services that it churns out (like Symfony2's container). The downsides are similar, though:<br/>\nHarder to read/test (though still easier to test than Registry), easier to make messy code, At its heart, SL is likely to be just a factory.</p>\n\n<p>IMO, If you want to know what is considered good practice, I'd say: a well written API, with plenty of injection, clear interfaces, and manually inject what you need, where you need it. Forget about registries, as they often are proof of <em>\"programming by afterthought\"</em>. (as in: Oh, wait, I forgot to write that to the DB, I'll get a connection from the registry, or SL, and put together a quick query, possibly accompanied by a <code>//TODO: find a better place for this</code> comment)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T16:37:30.503",
"Id": "63801",
"Score": "1",
"body": "Thank you for the (very) thorough answer. You've managed to shed a lot of light on the design principals I need to focus on. From your explanation my IoC container isn't really that, but more of a factory with a registry component, yes? In a practical example, let's say I am using the MVC pattern and I have 20 different models with 15 of them needing DB access. My goal would be to have a universal way of injecting the DB into all of those models but at the same time have the ability to swap out a DB connection for a mock or alternate DB without changing them all. Any suggestions for that??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T16:58:06.890",
"Id": "63805",
"Score": "0",
"body": "@Crackertastic: In an MVC context, the `Model` bit should be treated _as a layer_, not an object. In my projects, models are pure data carriers, that are passed on via a _service_ (that is accessed by the Controller), who then passes them on to a data mapper, which maps the model onto a database. These mappers can also contain queries that simply return Models, too. If you swap those out for mock objects, or return mock Models, you're home free... Injecting DB connections into data carriers is, IMO, a violation of the SRP (Single Responsibility Principle)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T17:15:51.047",
"Id": "63806",
"Score": "0",
"body": "@Crackertastic: On your IoC container thing: yup, it's just a factory + registry wrapper. It still requires you to `IoC::set` all dependencies you might need, which will then simply add those instances to an aptly named `$registry` property... Because it's all statics, the methods and properties essentially work in much the same way as globals do, only with the added noise (and overhead!) of object orientation (check google: static methods actually take longer to call than regular globals do, because of PHP having to create the `self::` reference + specific scope"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T19:16:12.953",
"Id": "63812",
"Score": "0",
"body": "Okay, I think is see what you mean with DB models. With models I didn't necessarily consider strict SRP, but instead kept responsibilities as low as possible. For example (non-DB related) in one project I had a model that I used to build an email. The model would accept user input, sanitize it, error check, and then store status/error info and build/send the email message if there were no errors. The view would query the model for indications that an error occurred (or succeeded) so something would be created on screen for the user. Do you think this is a bad approach in MVC context?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T22:02:21.993",
"Id": "63819",
"Score": "0",
"body": "@Crackertastic: I think I'd need to see that code, but from the looks of things, I'd say you're actually mixing what _Form-builders_ should do with the view's job. A view should contain _no_ logic whatsoever. It consists of markup, some loops and the occasional if and else, but other than that, it _does_ nothing but render the result. Checking a form/input's validity is done by the controller + model layer. I'd suggest you look at some of my other aswers on this site (I'm mainly active on the PHP tag anyway) and perhaps post a separate question focussing on your models. Also check how existing"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T22:03:13.793",
"Id": "63820",
"Score": "0",
"body": "frameworks deal with this sort of stuff. Symfony2 has a very elaborate and powerful Form component, it might be worth a look. (tip: think of symfony's forms as services, linked to doctrine entities)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T22:19:49.700",
"Id": "63823",
"Score": "1",
"body": "Thanks for the tips, I will do that. As for the View/Model interaction and views doing logic: it seems rudimentary that the view can't ask the model if it failed/succeeded or get some status update. If my view needs to know something that the model is going to answer, what is the real point of using the controller for that? My views do not do logic related to data processing, but they aren't dumb templates either. Basically the view is asking the model if it succeeded so it knows to display an error message or success message. Perhaps we have different philosophies on how to utilize MVC."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T09:58:19.677",
"Id": "63888",
"Score": "0",
"body": "@Crackertastic: Well, IMO, if the model layer failed at some point, it's the controller's job to then render a different view, based on the success of the overall request. If the model failed to do X, then view X shouldn't be rendered, but instead, view errorX is what needs to be presented to the end-user. A view, IMO, should receive pre-packaged/structured data and just iterate over it, and turn it into a nicely designed page"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T23:11:54.037",
"Id": "64091",
"Score": "0",
"body": "Thanks again for the tips and the info. You've made me rethink what a model should be, among other things. I'm looking into the model layer with a fresh start and hopefully a new understanding. I've posted a new question pertaining to it (since I was bringing the subject off topic here)."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T12:40:11.300",
"Id": "38320",
"ParentId": "38312",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "38320",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T06:34:39.203",
"Id": "38312",
"Score": "1",
"Tags": [
"php",
"design-patterns",
"dependency-injection",
"static"
],
"Title": "Dependency injection and inversion of control"
}
|
38312
|
<p>I have written this working block, but is it optimized? I am getting currency in this format: 1.234,25.</p>
<pre><code>public static String convertCurrency(String value, String exchangeCurrencyId)
{
java.text.NumberFormat format = null;
value = value.replaceAll("\\.", ",");
char[] chars = value.toCharArray();
chars[value.lastIndexOf(',')] = '.';
value = new String(chars);
value = value.replaceAll(",", "");
Double price = Double.valueOf(value);
price = price * (50); //exchange rate
return price.toString();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T11:18:04.410",
"Id": "63784",
"Score": "0",
"body": "Why do you replace `\\\\.` by `,`, change last `,` and replace all `,` by empty string? Why you can't immediately replace `.` by empty string and after that replace `,` by `.` if it exists?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T13:21:21.020",
"Id": "63794",
"Score": "5",
"body": "You have a couple of larger problems; `Double` (and floating point in general) does _not_ store exact amounts like people expect - ie, `.1` can't be represented (only something really close). This can lead to surprising results, which tends to make people itchy when it involves money. You're also storing the amount in a string, which means you have to convert it each time. For money, you want to use something based off/backed by `BigDecimal`, so you get the values you're expecting."
}
] |
[
{
"body": "<p>This code has various issues. Here is what I understand your code does:</p>\n\n<blockquote>\n <p>The code takes a formatted number which consists of digits, separators (commas or periods). The last separator is used as the decimal separator, all other separators are deleted.</p>\n \n <p>Then it multiplies the number with some exchange rate, and returns that as a string.</p>\n</blockquote>\n\n<p>The issues with your code are:</p>\n\n<ul>\n<li><code>format</code> is not used.</li>\n<li><code>exchangeCurrencyID</code> is not used.</li>\n<li>The exchange rate is hard-coded</li>\n<li>You use regexes for simple transliterations</li>\n<li>Your code obfuscates the intent.</li>\n<li>Your method does multiple unrelated things:\n<ol>\n<li>Sanitizing and parsing the number string</li>\n<li>Applying exchange rate conversion\nThese separate responsibilities should be performed by two separate methods.</li>\n</ol></li>\n</ul>\n\n<p>If we wish to avoid using regexes for a task that does not need them, we could write something like this:</p>\n\n<pre><code>StringBuilder sanitized = new StringBuilder();\nboolean decimalSeparatorFound = false;\nchar[] chars = value.toCharArray();\nfor (int i = chars.length-1; i >= 0; i--) {\n if (chars[i] == ',' || chars[i] == '.') {\n if (decimalSeparatorFound) continue; // skip this char\n decimalSeparatorFound = true;\n sanitized.append('.');\n } else {\n sanitized.append(chars[i]);\n }\n}\ndouble price = Double.valueOf(sanitized.reverse().toString());\n\n...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T12:04:20.440",
"Id": "63785",
"Score": "0",
"body": "it is throwing `NumberFormatException` as it appends comma `,`. Here comma needs to be replaced with dot `.`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T12:22:30.927",
"Id": "63787",
"Score": "0",
"body": "I have added some code after edit. any suggestion over this"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T12:58:20.863",
"Id": "63792",
"Score": "1",
"body": "@eatSleepCode No, that doesn't count: You just copied out the part of your code with least criticism. And you didn't manage without a loop, you just hid it behind a call to `replaceAll`. If you want to optimize for performance, you shouldn't use regexes if they aren't needed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T18:45:24.850",
"Id": "63921",
"Score": "1",
"body": "You could remove the regexes and not use a `for` loop by simply changing the call to `String.replaceAll()` to `String.replace()` which takes a char argument instead of a regex String."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T11:56:00.317",
"Id": "38318",
"ParentId": "38317",
"Score": "6"
}
},
{
"body": "<p>It seems like you tried to use <code>NumberFormat</code> but gave up on the idea. You should take advantage of it — after all, that's what the standard library is there for.</p>\n\n<p>Furthermore, I would split the parsing and the currency conversion into two separate functions.</p>\n\n<p>You should avoid \"stringly typed\" variables. Once you parse the string into a number, hang on to the number, not the string. Convert back into string form as late as possible, just for presentation purposes.</p>\n\n<pre><code>import java.math.BigDecimal;\nimport java.text.DecimalFormat;\nimport java.text.NumberFormat;\nimport java.text.ParseException;\nimport java.util.Locale;\n\npublic class CR38317 {\n public static BigDecimal parseCurrency(String value) throws ParseException {\n // Pick a suitable locale. GERMANY, for example, uses the 1.234,56 format.\n // You could call .getCurrencyInstance() instead, but then it will\n // require the value to contain the correct currency symbol at a\n // specific position.\n NumberFormat fmt = NumberFormat.getNumberInstance(Locale.GERMANY);\n\n // By default, fmt.parse() returns a Number that is a Double.\n // However, some decimals, such as 0.10, cannot be represented\n // exactly in floating point, so it is considered best practice to\n // use BigDecimal for storing monetary values.\n ((DecimalFormat)fmt).setParseBigDecimal(true);\n\n return (BigDecimal)fmt.parse(value);\n }\n\n public static BigDecimal convertCurrency(BigDecimal inValue, String inCurrency, String outCurrency) {\n // TODO: Derive the conversion rate from the currencies\n return inValue.multiply(new BigDecimal(50));\n }\n\n public static void main(String[] args) throws ParseException {\n BigDecimal in = parseCurrency(\"1.234,56\");\n BigDecimal out = convertCurrency(in, \"EUR\", \"INR\");\n System.out.println(\"In = \" + in);\n System.out.println(\"Out = \" + out);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T05:47:31.340",
"Id": "63976",
"Score": "0",
"body": "Yes, It was in my mind to use NumberFormat. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T11:46:33.747",
"Id": "38382",
"ParentId": "38317",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "38382",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T10:19:02.370",
"Id": "38317",
"Score": "4",
"Tags": [
"java",
"parsing",
"floating-point",
"i18n",
"finance"
],
"Title": "Optimize parsing of number for currency conversion"
}
|
38317
|
<p>I would like to refactor code below and get rid of if statements for classes from view.</p>
<pre><code>.container
.tabbable.tabs-left
%ul.nav.nav-tabs
- @related_tasks.each do |task|
%li{class: ("active" if @task == task)}
= link_to task.name, "#tab#{task.id}", data: { toggle: 'tab' }, class: @current_user_tasks.include?(task.id) ? '' : 'inactive'
.tab-content
- @related_tasks.each do |task|
.tab-pane{id: "tab#{task.id}", class: ("active" if @task == task)}
= render 'task_tab', task: task
</code></pre>
|
[] |
[
{
"body": "<p>Helper methods are good for this. In your view's helper file:</p>\n\n<pre><code>def task_link_class(task)\n if @current_user_tasks.include?(task)\n ''\n else\n 'inactive'\n end\nend\n</code></pre>\n\n<p>Some would prefer the trinary operator instead:</p>\n\n<pre><code>def task_link_class(task)\n @current_user_tasks.include?(task) ? '' : 'inactive'\nend\n</code></pre>\n\n<p>And in your view:</p>\n\n<pre><code>= link_to task.name, \"#tab#{task.id}\", data: { toggle: 'tab' }, class: task_link_class(task)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T19:09:53.200",
"Id": "64771",
"Score": "0",
"body": "Its my understanding that using `@instance_variables` in helpers is not a good practice. Better pass values as arguments."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T19:16:43.343",
"Id": "64773",
"Score": "0",
"body": "@tokland, Thanks for pointing that out. Do you have a link where I can learn why?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T21:10:42.620",
"Id": "64789",
"Score": "1",
"body": "@tokland, How about this? http://rails-bestpractices.com/posts/27-replace-instance-variable-with-local-variable"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-08T09:38:01.713",
"Id": "64845",
"Score": "1",
"body": "Yes, that would be the idea, in partials, in helpers, etc, use arguments. The key is reusability, this way you can use and tests those functions in isolation."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T12:34:36.603",
"Id": "38625",
"ParentId": "38322",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "38625",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T13:55:39.550",
"Id": "38322",
"Score": "2",
"Tags": [
"ruby",
"ruby-on-rails",
"haml"
],
"Title": "Render dynamically vertical tabs and set classes depends on if statement"
}
|
38322
|
<p>I have a complicated select procedure that I solved with a 5 query select, so I am posting it here to get suggestions on how I can shorten it up a bit. I am hoping that someone can help me make it a single query select.
I'm using nhibernate query over here.</p>
<p>I have 7 tables which are</p>
<ul>
<li><code>t_user</code></li>
<li><code>t_category</code></li>
<li><code>t_event</code></li>
<li><code>t_announcement</code></li>
<li><code>t_event_follower</code></li>
<li><code>t_event_register</code></li>
<li><code>t_event_subcribe</code></li>
</ul>
<p>I will represent them in the classes below:</p>
<pre><code>class User {
int id;
string username;
IList<Registration> registrations;
IList<Category> subscribes;
IList<Event> follows;
}
class Category {
int id;
string description;
IList<User> subscribers;
}
class Event{
int id;
string title;
Category category;
IList<Registration> registrations;
IList<User> followers;
IList<Announcement> announcements;
}
class Announcement {
int id;
string title;
Event event;
bool isForFollower;
bool isForRegister;
bool isForSubscriber;
}
class Registration {
int id;
Event event;
User user;
string additionalInfo;
RegistrationStatus status;
}
enum UserRole {
PUBLIC,
FOLLOWER,
SUBSCRIBER,
REGISTERED
}
</code></pre>
<p>The goal is to show all announcements in 1 event based on user roles on that event. What I had done first is populate user role in list with the code below:</p>
<pre><code>User requester = _userRepo.SearchBy(username); // 1 query for user detail
// 3 lazy load objects make nhibernate to load the object from db, i assume it takes 3 query select if objects haven't load in session
bool isFollower = requester.Follows.Any(eventz => eventz.Id == eventId);
bool isSubscriber = requester.Subscribes.Any(category => category.Events.Any(eventz => eventz.Id == eventId));
bool isRegistered = requester.Registrations.Any(registration => registration.Event.Id == eventId);
var userRoleList= new List<UserRole>();
if (isFollower) userRoleList.Add(UserRole.FOLLOWER);
if (isSubscriber) userRoleList.Add(UserRole.SUBSCRIBER);
if (isRegistered) userRoleList.Add(UserRole.REGISTERED);
</code></pre>
<p>last with code in repository layer below i create dynamic disjunction for query over :</p>
<pre><code>Disjunction filterRestriction = Restrictions.Disjunction();
// this condition to select announcement which is for public not specific
filterRestriction.Add(Restrictions.Where<Announcement>(a => a.IsForFollower == false
&& a.IsForSubscriber == false
&& a.IsForRegistered == false));
foreach (UserRole role in userRoleList)
{
switch (role)
{
case UserRole.FOLLOWER:
filterRestriction.Add(Restrictions.Where<Announcement>(a => a.IsForFollower));
break;
case UserRole.SUBSCRIBER:
filterRestriction.Add(Restrictions.Where<Announcement>(a => a.IsForSubscriber));
break;
case UserRole.REGISTERED:
filterRestriction.Add(Restrictions.Where<Announcement>(a => a.IsForRegistered));
break;
}
}
//this is the last query transaction, so total 5 times select from db CMIIW,
return _session.QueryOver<Announcement>()
.Where(filterRestriction)
.And(a => a.Event.Id == id)
.List();
</code></pre>
<p>In the above code, the query result will show public announcement plus specific announcement based on role that user have in related event.</p>
<p>I admit this is the simplest solution I could think to solve the case. Could someone give a suggestion or rework this just by 1 simple operation with query over or just remake it with better query?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-25T04:15:44.080",
"Id": "67222",
"Score": "0",
"body": "Are you stuck with an NHibernate solution? Can you do a stored procedure/view/dynamic sql statement instead?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-25T05:05:04.417",
"Id": "67226",
"Score": "0",
"body": "nope, i knew there is a lot of alternatives like you said.. I just wanna get a better solution with nhibernate api. Because i lack of experience with nhibernate api, hoping someone else can provide something different or maybe a better point of view for this case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T22:45:16.377",
"Id": "72398",
"Score": "1",
"body": "Maybe I misunderstood what you mean by transaction, but if your only goal is to make all queries in one transaction, why not use NHibernate transaction support? [Use of implicit transactions is discouraged](http://www.hibernatingrhinos.com/products/nhprof/learn/alert/DoNotUseImplicitTransactions) according to NHibernate blog post. But I probably misunderstood you, you probably already have one transaction, and what you really want is to make fewer database queries in it, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-24T17:27:51.973",
"Id": "129234",
"Score": "0",
"body": "That's right, I want to make it to be a fewer query as for now it does 5 select to db. Is it possible?"
}
] |
[
{
"body": "<p>If this is a web application, you can use an HttpModule to do your session management. Begin every web request by opening a session and beginning a transaction. At the end of every web request, commit the transaction and close the session.</p>\n\n<p>As long as you're wrapping all the hits to the database in a single transaction, you don't need to worry about efficiency too much.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-24T17:30:26.180",
"Id": "129235",
"Score": "0",
"body": "Yes, I've been applying this module you talked about in every project. The problem is I want to know if there is a way to make my queries simpler than like mine above?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T20:05:29.863",
"Id": "42191",
"ParentId": "38330",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T16:28:33.223",
"Id": "38330",
"Score": "7",
"Tags": [
"c#",
"linq",
"hibernate"
],
"Title": "NHibernate select with Query Over optimization for user roles base case"
}
|
38330
|
<p>This program attempts to solve the following challenge:</p>
<blockquote>
<p>There is a 2D grid of cells containing <em>N</em> lamps. Each lamp illuminates its own cell as well as its eight neighbours. How many lamps can you possibly remove such that each cell that was originally illuminated remains illuminated?</p>
</blockquote>
<p>My code:</p>
<pre><code>import java.util.*;
class test
{
public static void main(String[] ar)
{
int use = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the dimensions: ");
int a = sc.nextInt();
int b = sc.nextInt();
int[][] f = new int[a][b];
System.out.print("Enter the no. of lamps: ");
int n = sc.nextInt();
int[][] l = new int[n][2];
//System.out.print("Enter the coordinates : ");
for(int i = 0; i < n; i++)
{
int t1,t2;
do
{
t1 = l[i][0] = (int)(Math.random()*a);
t2 = l[i][1] = (int)(Math.random()*b);
f[t1][t2] = 1;
}while(f[t1][t2] == 0);
}
print(f);
light(f);
for(int i = 0; i < l.length; i++)
{
int[][] f1 = new int[a][b];
for(int j = 0; j < l.length; j++)
{
if(i == j)
continue;
int x = l[j][0];
int y = l[j][1];
if(x < 0)
continue;
f1[x][y] = 1;
}
light(f1);
if(!same(f,f1))
use++;
else
{
l[i][0] = -1;
l[i][1] = -1;
}
}
System.out.println("Usefull : " + use);
}
public static boolean same(int[][] a, int[][] b)
{
for(int i = 0; i < a.length; i++)
{
for(int j = 0; j < a[i].length ; j++)
{
if(a[i][j] != b[i][j])
return false;
}
}
return true;
}
public static void print(int[][] a)
{
for(int i = 0; i < a.length ; i++)
{
for(int j = 0; j < a[i].length; j++)
System.out.print(a[i][j] + " ");
System.out.println();
}
System.out.println();
}
public static void light(int[][] a)
{
for(int i = 0;i < a.length; i++)
{
for(int j = 0; j < a[i].length; j++)
{
if(a[i][j] == 1)
light(a,i,j);
}
}
convert(a);
}
public static void light(int[][] a, int i, int j)
{
for(int p = i - 1; p <= i + 1; p++)
{
for(int q = j - 1; q <= j + 1; q++)
{
try
{
if(a[p][q] != 1)
a[p][q] = 2;
}catch(Exception e){}
}
}
}
public static void convert(int[][] a)
{
for(int i = 0; i < a.length; i++)
{
for(int j = 0; j < a[i].length; j++)
{
if(a[i][j] == 2)
a[i][j] = 1;
}
}
}
}
</code></pre>
<p>Please help to improve my code.</p>
|
[] |
[
{
"body": "<pre><code>import java.util.*;\n</code></pre>\n\n<p>Importing whole packages is not a very good idea, especially of there are multiple identical named classes in the imported packages. You should only import what is needed.</p>\n\n<hr>\n\n<pre><code>class test\n{\n</code></pre>\n\n<p>Classnames in Java are UpperCamelCase. Additionally Java normally uses a modified K&R style with the opening braces on the same line.</p>\n\n<pre><code>function style() {\n if (true) {\n // code\n } else {\n // code\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>public static void main(String[] ar)\n{\n int use = 0;\n Scanner sc = new Scanner(System.in);\n System.out.print(\"Enter the dimensions: \");\n int a = sc.nextInt();\n int b = sc.nextInt();\n int[][] f = new int[a][b];\n</code></pre>\n\n<p>Do you have an illness that makes typing hurt? There is <em>zero</em> reason to shorten variable names and there is <em>no</em> excuse to only use one-letter variables (only exception are dimensions, <code>x</code> <code>y</code> <code>z</code> and mathematical formulas). Your code is hard to read and reads more like it was obfuscated.</p>\n\n<p>Whenever you have the urge to give a variable a one-letter-name, stop, take a deep breath, and then you name the variable according to what it does.</p>\n\n<hr>\n\n<pre><code>for(int i = 0; i < n; i++)\n{\n // snip\n do\n {\n // snip\n}while(f[t1][t2] == 0);\n}\n</code></pre>\n\n<p>Your brace and indentation style is a mess, to be honest. This is very hard to read, f.e. while quick scanning the code I thought it would be such a construct:</p>\n\n<pre><code>for (loop-stuff)\n {\n\n } while (loop stuff)\n</code></pre>\n\n<p>A \"one-line-for-loop\" with an embedded while...and my next thought was \"wait, that's legal in Java?\". It would be easier to read like this:</p>\n\n<pre><code>for(int i = 0; i < n; i++) {\n // snip\n do {\n // snip\n }while(f[t1][t2] == 0);\n}\n</code></pre>\n\n<hr>\n\n<pre><code>public static boolean same(int[][] a, int[][] b)\n</code></pre>\n\n<p>Not bad, but a better name would be <code>areEqual</code> or <code>equal</code>.</p>\n\n<hr>\n\n<pre><code>public static void light(...)\n</code></pre>\n\n<p>This is a bad function name, it tells me nothing about what the function does.</p>\n\n<hr>\n\n<pre><code>if(a[p][q] != 1)\n a[p][q] = 2;\n</code></pre>\n\n<p>And see, this is why one-letter-names are bad. Quick! Tell me what it does?!</p>\n\n<p>Also, you should avoid magic numbers at all costs. Java has Enums, use them.</p>\n\n<hr>\n\n<p>To be honest, I can't really comment anything else on your code, with the one-letter-variables, odd brace-style and the not really well named functions, I can't tell what's going on.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T21:27:30.787",
"Id": "63818",
"Score": "0",
"body": "Re: `Additionally Java normally uses a modified K&R style with the opening braces on the same line.`- even so, who cares? Use whatever style you feel comfortable with as long as it's readable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T22:21:19.023",
"Id": "63824",
"Score": "0",
"body": "Actually, `do { …; f[t1][t2] = 1; } while (f[t1][t2] == 0);` is not a loop at all! It will always execute exactly once."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T22:42:57.030",
"Id": "63827",
"Score": "2",
"body": "@MrLore: I always mention it because that's what is defined in the Java Documentation as *default* style. It's a good move to try to unify that, and if you don't have a compelling reason not to follow these guidelines, you should stick to them. It's like premature optimization, if you don't have a compelling reason to strive from it, you shouldn't. \"I prefer that other style for clarity because ...\" is a compelling reason, \"I don't care\" or \"I did use that other style in that other language, I'm used to it\" is not."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T20:44:29.877",
"Id": "38333",
"ParentId": "38332",
"Score": "1"
}
},
{
"body": "<p>Your algorithm is faulty, because it only tries to eliminate redundant lamps in the order in which they were installed.</p>\n\n<p>Consider a 1 × 9 array with 7 initial lamps L0 … L6 at positions 2 … 8.</p>\n\n<p><img src=\"https://i.stack.imgur.com/viEnS.png\" alt=\"Faulty algorithm\"></p>\n\n<p>Your algorithm would first eliminate L0 at position 5, then L1 at position 4. It would consider L2 and L3 essential. Then it would eliminate L4 at position 7. L5 and L6 would be essential. Total lamps eliminated: three.</p>\n\n<p>An optimal solution would eliminate four lamps at positions 3, 4, 6, 7.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T02:51:42.563",
"Id": "63858",
"Score": "0",
"body": "@200_sucess A lamp also illuminates its own cell."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T02:53:38.460",
"Id": "63859",
"Score": "0",
"body": "Please advise how to solve this problem"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T02:56:41.763",
"Id": "63861",
"Score": "0",
"body": "I know, a lamp also illuminates its own cell."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T03:25:20.163",
"Id": "63863",
"Score": "0",
"body": "I believe this problem is equivalent to [finding a minimum vertex cover](http://en.wikipedia.org/wiki/Vertex_cover) of a graph whose vertices are lamps and their neighbouring cells, and whose edges link lamps to their illuminated neighbours. Guess what — it's an NP-hard problem!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T08:28:39.017",
"Id": "63882",
"Score": "0",
"body": "NP-hard means you might as well try a brute force algorithm (or resign yourself to an approximate solution). Enumerate all the _N_ ways to eliminate _N_-1 lamps. When trying to eliminate each lamp, if the removal turns a previously illuminated cell into an unlit one, disqualify that lamp configuration. Then try all _N_ * (_N_-1) ways to eliminate _N_-2 lamps. Proceed until you find a configuration that preserves the original lighting."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T08:29:46.050",
"Id": "63883",
"Score": "0",
"body": "Please post your code also."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T08:32:28.470",
"Id": "63884",
"Score": "2",
"body": "That's not how this site works. Asking for code to be written is off-topic (see [help/on-topic])."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T16:04:35.000",
"Id": "64017",
"Score": "0",
"body": "I'm sorry if I violated the rules.I'm just a beginner and don't know much. I would be extremely grateful even if you would give a pseudocode for the backtrack process."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T17:39:41.097",
"Id": "64041",
"Score": "0",
"body": "This is a non-trivial problem for a beginner to attempt. To generate all possible subsets of a given set, hope [this](http://codereview.stackexchange.com/a/16270/9357) helps. Once you arrive at a solution, feel free to ask for another review in a separate question (referring back to this one)."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T21:59:56.547",
"Id": "38337",
"ParentId": "38332",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T19:20:47.373",
"Id": "38332",
"Score": "6",
"Tags": [
"java",
"algorithm"
],
"Title": "Minimizing number of field lamps"
}
|
38332
|
<p>The following code will add to each code block a 'Select Code' button that will select the code belonging to that block. Please review for maintainability.</p>
<p>In order to use this, visit <a href="http://codereviewcommunity.github.io/CodeReviewBookmarklet/">http://codereviewcommunity.github.io/CodeReviewBookmarklet/</a></p>
<p></p>
<pre><code>javascript: if ($('button').length === 0) {
/* Stack Exchange does not do buttons, this does */
$(".prettyprint").each( function()
{
/* Thank you http://stackoverflow.com/a/2838358/7602 */
function selectCode(el, win)
{
win = win || window;
var doc = win.document, sel, range;
if (win.getSelection && doc.createRange)
{
sel = win.getSelection();
range = doc.createRange();
range.selectNodeContents(el);
sel.removeAllRanges();
sel.addRange(range);
}
else if (doc.body.createTextRange)
{
range = doc.body.createTextRange();
range.moveToElementText(el);
range.select();
}
}
var buttonText = 'Select Code',
length = buttonText.length,
codeBlock = this,
$link = $('<button type="button">' + buttonText + '</button><br>').click(function()
{
console.log( $(codeBlock).text().substring( length ) );
selectCode(codeBlock);
});
$(codeBlock).prepend( $link );
});
}
</code></pre>
<p>I have tested this on FF and Chrome and it works for me.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T23:13:57.847",
"Id": "63830",
"Score": "0",
"body": "Works on Safari 7."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T23:25:06.130",
"Id": "63833",
"Score": "0",
"body": "How do you test this with Chrome?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T23:50:57.490",
"Id": "63840",
"Score": "1",
"body": "Select the test, then mouse-down for half a second, and then drag the code into the bookmark-bar."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T23:53:38.583",
"Id": "63844",
"Score": "0",
"body": "Nice! You could consider putting the updated code below the original, while clearly marking it as such."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T00:21:00.293",
"Id": "63848",
"Score": "0",
"body": "@Jamal I don't like the button size with `before`, I will have to play with it a bit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T00:27:56.647",
"Id": "63850",
"Score": "0",
"body": "Okay. Do you also need to update what I've put on your post, assuming it only works that way with Chrome?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T00:30:12.080",
"Id": "63851",
"Score": "0",
"body": "I am thinking to actually make this a subproject of our github account, with a page where you can indeed drag/drop a link to the bookmark bar."
}
] |
[
{
"body": "<p>You inject the button using <a href=\"http://api.jquery.com/prepend/\"><code>jQuery.prepend()</code></a>, which inserts the button as the first child of the <code>.prettyprint</code> code block. Therefore, when the bookmarklet is invoked, and it selects the contents of the code block, the \"Select Code\" button is inadvertently included in the selection. I recommend using <a href=\"http://api.jquery.com/before/\"><code>jQuery.before()</code></a> instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T23:50:02.220",
"Id": "63839",
"Score": "0",
"body": "You are right, will fix. On FF, the text of the button does not actually make it into the clipboard."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T00:09:23.680",
"Id": "63847",
"Score": "1",
"body": "This works on Chrome."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T23:21:30.427",
"Id": "38343",
"ParentId": "38336",
"Score": "10"
}
},
{
"body": "<p>Since StackExchange can refresh page contents dynamically, the following sequence of events is possible:</p>\n\n<ol>\n<li>Page contains some code block(s).</li>\n<li>Bookmarklet is invoked, adding the button to existing code block(s).</li>\n<li>Page contents are updated, for example, with a new answer that contains a new code block.</li>\n<li>Bookmarklet is invoked again, but it refuses add a Select Code button to the new code block.</li>\n</ol>\n\n<p>Therefore, I suggest that the overall structure be changed such that it can be invoked again after a content update. Here is one approach (assuming that you also take my <a href=\"https://codereview.stackexchange.com/a/38343/9357\">previous advice</a> to use <code>jQuery.before()</code>):</p>\n\n<pre><code>javascript:$(\"pre.prettyprint\").not(\"button + *\").each(function() { \n …\n\n var buttonText = 'Select Code',\n length = buttonText.length,\n codeBlock = this,\n $link = $('<button type=\"button\">' + buttonText + '</button>').click(…);\n $(codeBlock).before( $link );\n });\n</code></pre>\n\n<p>I've changed the selector <code>$(\".prettyprint\")</code> to <code>$(\"pre.prettyprint\")</code> because class-only selectors are reputed to be slower.</p>\n\n<p>For the <code>.not(\"button + *\")</code> next-sibling filter to work, the button must not be inserted with a <code><br></code> afterwards. The <code><br></code> is unnecessary anyway, since <code><pre></code> is a block element.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T00:09:29.753",
"Id": "38345",
"ParentId": "38336",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "38343",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T21:58:06.630",
"Id": "38336",
"Score": "13",
"Tags": [
"javascript",
"bookmarklet",
"stackexchange"
],
"Title": "Bookmarklet for selecting code snippets on Code Review"
}
|
38336
|
<p>Due their nature they require a stricter coding style than simple JavaScript.</p>
<ul>
<li><p>All comments should be in the <code>/* */</code> form because the code can get concatenated in one line.</p></li>
<li><p>There is a size limit for bookmarklets which gives some freedom to use single-letter variables, etc.</p></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T22:00:27.233",
"Id": "38338",
"Score": "0",
"Tags": null,
"Title": null
}
|
38338
|
A bookmarklet is a bookmark stored in a web browser that contains JavaScript commands to extend the browser's functionality.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T22:00:27.233",
"Id": "38339",
"Score": "0",
"Tags": null,
"Title": null
}
|
38339
|
<p>I've just replaced <a href="http://linuxian.com/2013/12/30/bash-script-compressed-one-day-old-files/" rel="nofollow">my bash script</a> with a Python script, and this is my first script where I used <code>class</code>.</p>
<p>Please review and give me suggestions.</p>
<pre><code>#!/usr/bin/env python
# This Script will compress One day old file means yesterday files
from __future__ import print_function
import os
import sys
import time
import glob
import subprocess
from datetime import datetime
nday = 1 # set how many days old file
ftype = "*.log" # set file type which should be compressed
lookinto = "/var/log/" # path of files
class CheckFile(object):
'Operation on file like get size,file time etc..'
def __init__(self,fname):
self.fname = fname
def size(self):
'print size in bytes MB'
num = os.path.getsize(self.fname)
for s in [ 'bytes','KB','MB','GB','TB' ]:
if num < 1024.0:
return "%3.1f %s" % (num,s)
num /= 1024.0
def date(self):
'print file date'
self.unix_time = os.path.getmtime(self.fname)
self.file_date = datetime.fromtimestamp(self.unix_time)
return self.file_date.strftime('%d/%m/%y')
def days_of_days_old(self):
'print how much file is old from today'
self.date()
days = (datetime.today() - self.file_date).days
return days
def compresse_file(file):
print("Compressing...")
cmd = "gzip -v " + file
os.system(cmd)
if __name__ == '__main__':
os.chdir(lookinto)
print('{0:10}{1:10}{2:10}'.format("Size","Date","File Name"))
print('{0:10}{1:10}{2:10}'.format("-----","------","---------"))
for file in glob.glob(ftype):
f = CheckFile(file)
if f.days_of_days_old() == nday:
print('{0:10}{1:10}{2:10}'.format(f.size(),f.date(),f.fname))
compresse_file(file)
print("file status after compressesion")
f = CheckFile(file + ".gz")
print('{0:10}{1:10}{2:10}'.format(f.size(),f.date(),f.fname))
print()
</code></pre>
|
[] |
[
{
"body": "<p>First thing's first, instead of calling out to the <code>gzip</code> program with <code>os.system</code>, use the <code>gzip</code> module in Python. This will almost always be more portable: <a href=\"http://docs.python.org/2/library/gzip.html\" rel=\"nofollow\">http://docs.python.org/2/library/gzip.html</a></p>\n\n<p>Second of all, instead of using <code>os.path.getsize</code> and <code>os.path.getmtime</code> just use a single <code>os.stat</code> call: <a href=\"http://docs.python.org/2/library/os.html#os.stat\" rel=\"nofollow\">http://docs.python.org/2/library/os.html#os.stat</a> You can call this once and cache the results for a single file.</p>\n\n<p>Don't require calling <code>self.date()</code> in order to set the <code>unix_time</code> and <code>file_date</code> attributes. Instead make those into properties. For example you could write that like:</p>\n\n<pre><code>class CheckFile(object):\n 'Operation on file like get size,file time etc..'\n\n def __init__(self, fname):\n self.fname = fname\n self._stat = None\n\n @property\n def stat(self):\n if self._stat is None:\n # Note: This will not update automatically if your file's stats change\n self._stat = os.stat(self.fname)\n return self._stat\n\n @property\n def unix_time(self):\n return self.stat.st_mtime\n\n @property\n def datetime(self):\n return datetime.fromtimestamp(self.unix_time)\n\n @property\n def age_in_days(self):\n return (datetime.today() - self.datetime).days\n</code></pre>\n\n<p>All that said, although I wouldn't discourage anyone from wanting to learn object-oriented programming, for this particular application writing a class is overkill :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T22:41:44.700",
"Id": "63826",
"Score": "0",
"body": "I haven't understand the `@property`, I read it's something call decorator, but could you please explain the same."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T22:56:29.490",
"Id": "63829",
"Score": "0",
"body": "I've read there is performance issue with `gzip` module that's why I use gzip command, see this post http://stackoverflow.com/questions/8302911/python-equivalent-of-piping-file-output-to-gzip-in-perl-using-a-pipe"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T01:20:57.567",
"Id": "63854",
"Score": "0",
"body": "There are some performance issues with the `gzip` module, especially where things like random access are concerned. But those are mostly corner cases. On most systems it should be using your system's zlib to do the compression and is more or less as fast for most cases. As for `property` there are tons of guides to that online. See for example http://stackoverflow.com/questions/6618002/python-property-versus-getters-and-setters"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T07:13:27.237",
"Id": "63877",
"Score": "0",
"body": "thanks for your help.. :), I'm just concern that I've correctly define the `class` except `property` or not ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T12:01:44.003",
"Id": "63894",
"Score": "0",
"body": "can you please check http://stackoverflow.com/questions/20856987/python-gzip-compresse-file-with-preserve-modified-time-stamp"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T22:37:21.767",
"Id": "38341",
"ParentId": "38340",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "38341",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T22:24:16.503",
"Id": "38340",
"Score": "1",
"Tags": [
"python",
"datetime"
],
"Title": "Find and compress file in Python script"
}
|
38340
|
<p>I'm curious if this is the right way of going about the issue: </p>
<pre><code>function sortWordsByIncorrectAnswers(array) {
array = array.slice(0)
var sortedArray = array.sort(function (a, b) {
a = a.fields.false;
b = b.fields.false;
return a < b ? -1 : a > b ? 1 : 0;
});
return sortedArray
}
</code></pre>
<p>I want to return a new version of the array, and not change 'array' passed into the method (deep copy).</p>
<p>This works as I want it to, but is this the correct way of doing this? It seems off.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T23:45:41.220",
"Id": "63838",
"Score": "0",
"body": "You are making a shallow copy, not a deep copy. That means you get a new array, but if the elements in the array are objects or arrays themselves, then they are the same objects as in the first array (a shallow copy). A deep copy is usually done with a recursive algorithm that looks at the type of each element in the array to see if it is an object that needs to be copied."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T23:51:08.507",
"Id": "63841",
"Score": "0",
"body": "Doesn't array.slice(0) perform a deep copy?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T23:52:15.273",
"Id": "63842",
"Score": "0",
"body": "No. `array.slice(0)` makes a shallow copy. It gives you a new array with all the same elements in it. That's the definition of a shallow copy. A deep copy would have all new elements in it too and if any of the elements in the array were arrays, those arrays would be copies too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T23:58:15.403",
"Id": "63845",
"Score": "1",
"body": "You can see this answer for how to make a deep copy: http://stackoverflow.com/a/728694/816620"
}
] |
[
{
"body": "<p><code>.slice()</code> does not actually do a deep copy, the easiest way to do a deep copy with simple objects is </p>\n\n<pre><code>array = JSON.parse( JSON.stringify( array ) )\n</code></pre>\n\n<p>Also, you can sort on a boolean in a simpler way:</p>\n\n<pre><code>function sortWordsByIncorrectAnswers(array)\n{\n array = JSON.parse( JSON.stringify( array || [] ) );\n return array.sort( function(a, b)\n {\n return a.fields.false - b.fields.false;\n });\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T00:17:41.080",
"Id": "38346",
"ParentId": "38342",
"Score": "1"
}
},
{
"body": "<p>First off, that's what <a href=\"http://api.jquery.com/jquery.extend/\" rel=\"nofollow noreferrer\"><code>jQuery.extend</code></a> is for. <a href=\"https://stackoverflow.com/a/122704/575527\">Resig answered this one himself over at StackOverflow</a> and has <a href=\"http://api.jquery.com/jQuery.extend/\" rel=\"nofollow noreferrer\">documentation</a> for the deep copy.</p>\n\n<p>However, <a href=\"https://stackoverflow.com/a/728694/575527\">you can never completely clone an object</a>. There are corner cases where even <code>jQuery.extend</code> could not possibly handle. As the author of <a href=\"https://stackoverflow.com/a/728694/575527\">this answer</a> suggests:</p>\n\n<blockquote>\n <p>It will not be able to handle any JavaScript object, but it may be sufficient for many purposes as long as you don't assume that it will just work for anything you throw at it.</p>\n</blockquote>\n\n<p>Also, to comment at <a href=\"https://codereview.stackexchange.com/a/38346/11919\">@tomdemuyt's answer</a>, I have tried that method once in cloning object. However, it falls short when the object has non-serializable objects, like Functions. I once had an array with 6-10k entries, each 4-5 deep. When I did the stringify-parse routine, memory usage of the browser rocketed.</p>\n\n<p>I'd rather rethink the approach rather than resorting to deep copies or other complicated approaches. In your case, you needed to sort an array while not affecting the original array You only need a 1-level copy in that case, and <code>slice</code> should work just fine.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T04:11:07.327",
"Id": "63869",
"Score": "1",
"body": "I did mention simple objects ;)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T02:05:12.353",
"Id": "38350",
"ParentId": "38342",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "38346",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T23:01:17.830",
"Id": "38342",
"Score": "1",
"Tags": [
"javascript",
"reference"
],
"Title": "Deep reference and object passing"
}
|
38342
|
<p>I will admit that this code looks sloppy and repetitive. Which is why I'm asking how I can improve the efficiency and readability of this code.</p>
<pre><code>// Sidebar tab highlight when clicked
$("#sidebar-tabs-container table td").click(function() {
$("#sidebar-tabs-container table td").removeClass("sidebar-tab-selected");
$(this).addClass("sidebar-tab-selected");
});
// poll and faq
// when faq question bar is clicked, slide down answer
$(document).on("click", ".question-container", function() {
$(".answer-container").stop().slideUp("fast");
$(this).parent().find(".answer-container").stop().slideToggle("fast");
});
// news and social feed
// activity
// activity new media content
//media buttons click
$(document).on("click", "#activity-media-icons-container span", function() {
$("#activity-media-icons-container span").removeClass("activity-new-media-icon- clicked");
$(this).addClass("activity-new-media-icon-clicked");
});
// show new media category and hide others depending on button clicked
$(document).on("click", "#new-media-images-button", function() {
$("#activity-media-video-container, #activity-media-audio-container").slideUp( function() {
$("#activity-media-images-container").slideDown();
});
});
$(document).on("click", "#new-media-videos-button", function() {
$("#activity-media-audio-container, #activity-media-images-container").slideUp( function() {
$("#activity-media-video-container").slideDown();
});
});
$(document).on("click", "#new-media-audio-button", function() {
$("#activity-media-images-container, #activity-media-video-container").slideUp( function() {
$("#activity-media-audio-container").slideDown();
});
});
/* show image link icon when hovered over image */
$(document).ajaxComplete(function() {
$(".media-image-buttons-container").hide();
});
// fade in image buttons on hover
$(document).on("mouseenter", "#media-content-container .media-image-container", function() {
$(this).children(".media-image-buttons-container").stop().fadeIn(200);
});
$(document).on("mouseleave", "#media-content-container .media-image-container", function() {
$(this).children(".media-image-buttons-container").stop().fadeOut(200);
});
</code></pre>
|
[] |
[
{
"body": "<p>This code can use quite a bit of work.</p>\n\n<ul>\n<li>Run this code through a beautifier, ideally prior to posting it to codereview ;)</li>\n<li>You are repeating yourself a lot, example : </li>\n</ul>\n\n<blockquote>\n<pre><code>// Sidebar tab highlight when clicked\n$(\"#sidebar-tabs-container table td\").click(function() {\n $(\"#sidebar-tabs-container table td\").removeClass(\"sidebar-tab-selected\");\n $(this).addClass(\"sidebar-tab-selected\");\n});\n</code></pre>\n</blockquote>\n\n<p>Unless you have a dynamic number of sidebar tabs ( seems unlikely ), you can do the following.</p>\n\n<pre><code>var $sidebarTabs = $('#sidebar-tabs-container table td');\nvar selectedClass = 'sidebar-tab-selected';\n\n$sidebarTabs.click(function() {\n $sidebarTabs.removeClass( selectedClass );\n $(this).addClass( selectedClass );\n});\n</code></pre>\n\n<p>The interesting part is that you do this type of code twice, so you could also write a helper.</p>\n\n<pre><code>function wireClassToggler( elements, className )\n{\n elements.click(function()\n {\n elements.removeClass( className );\n $(this).addClass( className );\n });\n}\n\nwireClassToggler( $('#sidebar-tabs-container table td'), 'sidebar-tab-selected' );\nwireClassToggler( $('#activity-media-icons-container span'), 'activity-new-media-icon-clicked' );\n</code></pre>\n\n<p>You also seem to use copy pasted code for the slideUp and slideDown functions, you should generalize that as well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T01:14:57.657",
"Id": "38347",
"ParentId": "38344",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-30T23:24:51.273",
"Id": "38344",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Menu and SideBar Slides, Fades, and Hides"
}
|
38344
|
<p>I was trying to write some of the Haskell list functions into Java, and I realized that one of the key strengths for many of the functions was the ability to pass in a boolean expression. I decided to write a parser to facilitate this. It has worked perfectly as far as I have tested it, but <strong>I want to know just how [in]efficiently I've done this, and if there's anything key that I missed.</strong></p>
<p><strong>A few rules for using this parser:</strong></p>
<ul>
<li>You cannot use the <code>!</code> operator in an expression [yet].</li>
<li>For comparison of strings, use <code>==</code>, <code>!=</code>, etc...</li>
<li>For exponentiation, use <code>^</code>.</li>
<li>PEMDAS ("order of operations") is followed for mathematical expressions.</li>
</ul>
<p>Otherwise, expressions can be written almost exactly like a normal <code>if</code> statement. For example: </p>
<pre><code>Halo.takeWhile("[x]>=2", someArray);
</code></pre>
<p>As a direct call to the parser:</p>
<pre><code>ExpressionParser.evaluate("2+[x] == [y] && (1==1 && Joe==Joe && 3^2>10)", "x", 5, "y", 7);
</code></pre>
<hr>
<pre><code>class ExpressionParser
{
private static final String[] operators = { "!=", "==", ">=", "<=", ">", "<", "||", "&&", "*", "/", "+", "-", "^" };
private static boolean parseAndEvaluateExpression(String ex)
{
for (char c : ex.toCharArray())
{
if (!Character.isSpaceChar(c))
return parseWithStrings(ex);
}
System.err.println("ERROR: Expression cannot be empty!");
return false;
}
@SafeVarargs
static <T> boolean evaluate(String or, T... rep)
{
String[] temp = new String[rep.length];
for (int i = 0; i < rep.length; i++)
temp[i] = "" + rep[i];
return evaluate(or, temp);
}
static boolean evaluate(String or, String... vars)
{
if ((vars.length % 2 == 1 || vars.length < 2) && vars.length != 0)
{
System.err.println("ERROR: Invalid arguments!");
return false;
}
for (int i = 0; i < vars.length; i += 2)
or = or.replace("[" + vars[i] + "]", "" + vars[i + 1]);
return parseAndEvaluateExpression(or);
}
private static boolean parseWithStrings(String s)
{
int[] op = determineOperatorPrecedenceAndLocation(s);
int start = op[0];
String left = s.substring(0, start).trim();
String right = s.substring(op[1]).trim();
String oper = s.substring(start, op[1]).trim();
int logType = logicalOperatorType(oper);
System.out.println("PARSE: Left: \"" + left + "\" Right: \"" + right + "\" Operator: \"" + oper + "\"");
if (logType == 0) // encounters OR- recurse
return parseWithStrings(left) || parseWithStrings(right);
else if (logType == 1) // encounters AND- recurse
return parseWithStrings(left) && parseWithStrings(right);
if (containsMathematicalOperator(left)) // evaluate mathematical expression
left = "" + parseMathematicalExpression(left);
if (containsMathematicalOperator(right))// see above
right = "" + parseMathematicalExpression(right);
String leftSansParen = removeParens(left);
String rightSansParen = removeParens(right);
if (isInt(leftSansParen) && isInt(rightSansParen))
return evaluate(Double.parseDouble(leftSansParen), oper, Double.parseDouble(rightSansParen));
else
return evaluate(leftSansParen, oper, rightSansParen); // assume they are strings
}
private static int[] determineOperatorPrecedenceAndLocation(String s)
{
s = s.trim();
int minParens = Integer.MAX_VALUE;
int[] currentMin = null;
for (int sampSize = 1; sampSize <= 2; sampSize++)
{
for (int locInStr = 0; locInStr < (s.length() + 1) - sampSize; locInStr++)
{
int endIndex = locInStr + sampSize;
String sub;
if ((endIndex < s.length()) && s.charAt(endIndex) == '=')
sub = s.substring(locInStr, ++endIndex).trim();
else
sub = s.substring(locInStr, endIndex).trim();
if (isOperator(sub))
{
// Idea here is to weight logical operators so that they will still be selected over other operators
// when no parens are present
int parens = (logicalOperatorType(sub) > -1) ? parens(s, locInStr) - 1 : parens(s, locInStr);
if (containsMathematicalOperator(sub))
{
// Order of operations weighting
switch (sub)
{
case "^":
case "/":
case "*":
parens++;
break;
case "+":
case "-":
break;
}
}
if (parens <= minParens)
{
minParens = parens;
currentMin = new int[] { locInStr, endIndex, parens };
}
}
}
}
return currentMin;
}
private static int logicalOperatorType(String op)
{
switch (op.trim())
{
case "||":
return 0;
case "&&":
return 1;
default:
return -1;
}
}
private static boolean containsMathematicalOperator(String s)
{
s = s.trim();
for (char c : s.toCharArray())
if (c == '/' || c == '+' || c == '*' || c == '-' || c == '^')
return true;
return false;
}
private static int parens(String s, int loc)
{
int parens = 0;
for (int i = 0; i < s.length(); i++)
{
if (s.charAt(i) == '(' && i < loc)
parens++;
if (s.charAt(i) == ')' && i >= loc)
parens++;
}
return parens;
}
private static String removeParens(String s)
{
s = s.trim();
String keep = "";
for (char c : s.toCharArray())
{
if (!(c == '(') && !(c == ')'))
keep += c;
}
return keep.trim();
}
private static boolean isOperator(String op)
{
op = op.trim();
for (String s : operators)
{
if (s.equals(op))
return true;
}
return false;
}
private static boolean isInt(String s)
{
for (char c : s.toCharArray())
if (!Character.isDigit(c) && c != '.')
return false;
return true;
}
private static boolean evaluate(double left, String op, double right)
{
switch (op)
{
case "==":
return left == right;
case ">":
return left > right;
case "<":
return left < right;
case "<=":
return left <= right;
case ">=":
return left >= right;
case "!=":
return left != right;
default:
System.err.println("ERROR: Operator type not recognized.");
return false;
}
}
private static double parseMathematicalExpression(String s)
{
int[] op = determineOperatorPrecedenceAndLocation(s);
int start = op[0];
String left = s.substring(0, start).trim();
String right = s.substring(op[1]).trim();
String oper = s.substring(start, op[1]).trim();
System.out.println("MATH: Left: \"" + left + "\" Right: \"" + right + "\" Operator: \"" + oper + "\"");
if (containsMathematicalOperator(left))
left = "" + parseMathematicalExpression(left);
if (containsMathematicalOperator(right))
right = "" + parseMathematicalExpression(right);
return evaluateSingleMathematicalExpression(Double.parseDouble(removeParens(left)), oper,
Double.parseDouble(removeParens(right)));
}
private static double evaluateSingleMathematicalExpression(double result1, String oper, double result2)
{
switch (oper)
{
case "*":
return result1 * result2;
case "/":
return result1 / result2;
case "-":
return result1 - result2;
case "+":
return result1 + result2;
case "^":
return Math.pow(result1, result2);
default:
System.err.println("MATH ERROR: Mismatched Input.");
return 0;
}
}
private static boolean evaluate(String left, String op, String right)
{
switch (op)
{
case "==":
return left.equals(right);
case "!=":
return !left.equals(right);
default:
System.err.println("ERROR: Operator type not recognized.");
return false;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T01:29:37.727",
"Id": "63855",
"Score": "2",
"body": "Azar .... have you considered using the Rhino Javascript engine embedded in Java 7? [Consider these examples....](http://docs.oracle.com/javase/7/docs/technotes/guides/scripting/programmer_guide/#helloworld)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T02:13:49.277",
"Id": "63857",
"Score": "1",
"body": "@rolfl That is very neat, but I think it might be a little over-powered for my purposes, and possibly even slower as a consequence."
}
] |
[
{
"body": "<p>You've written something quite impressive there, but it is an unorthodox\napproach and some of the code is rather impenetrable. I've laid out a few\npoints of issue and in some cases possible solutions and comments below.</p>\n\n<h2>Method documentation</h2>\n\n<p>Your methods could stand to have a brief JavaDoc block at the top. Here's how\nyou might annotate what I believe to be your simplest method, <code>isInt</code>:</p>\n\n<pre><code>/**\n * Determines whether a given string consists only of digits.\n *\n * @param s The string to test.\n * @return True if the string consists only of digits; false otherwise.\n */\nprivate static boolean isInt(String s)\n{\n for (char c : s.toCharArray())\n if (!Character.isDigit(c) && c != '.')\n return false;\n return true;\n}\n</code></pre>\n\n<p>(By the way, <code>Character.isDigit('.') == false</code>, so you don't need that\n<code>&& c != '.'</code> bit in there.)</p>\n\n<h2>Proper typing of arguments</h2>\n\n<p>I notice you provide arguments with a sort of “key, value, key, value” style\nand explicitly check to make sure that format is followed. I suppose that\nworks, but you could be more semantic and get more out of the type system by\nusing a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Map.html\"><code>Map</code></a> from variable names to values.</p>\n\n<h2>Non-usage of exceptions</h2>\n\n<p>You've got a lot of error cases:</p>\n\n<pre><code>System.err.println(\"ERROR: Expression cannot be empty!\");\nSystem.err.println(\"ERROR: Invalid arguments!\");\nSystem.out.println(\"PARSE: Left: \\\"\" + left + \"\\\" Right: \\\"\" + right + \"\\\" Operator: \\\"\" + oper + \"\\\"\");\nSystem.err.println(\"ERROR: Operator type not recognized.\");\nSystem.out.println(\"MATH: Left: \\\"\" + left + \"\\\" Right: \\\"\" + right + \"\\\" Operator: \\\"\" + oper + \"\\\"\");\nSystem.err.println(\"MATH ERROR: Mismatched Input.\");\nSystem.err.println(\"ERROR: Operator type not recognized.\");\n</code></pre>\n\n<p>Printing them out to standard error (or standard output, without rhyme or\nreason) may be suitable for debugging, but it is not appropriate beyond that.\nJava has a method of dealing with errors: exceptions. Use them; they won't\nbite.</p>\n\n<h2>Inefficient concatenation</h2>\n\n<p>In <code>removeParens</code> (and possibly elsewhere), you're repeatedly concatenating\nstrings using <code>+</code>. This is fine for one-offs, or where the number of operands\nare constant, as Java can optimize it. However, doing it repeatedly in a loop\nis inefficient. You'd be better off using a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html\"><code>StringBuilder</code></a>:</p>\n\n<pre><code>private static String removeParens(String s)\n{\n s = s.trim();\n StringBuilder keep = new StringBuilder();\n for (char c : s.toCharArray())\n {\n if (!(c == '(') && !(c == ')'))\n keep.append(c);\n }\n return keep.toString().trim();\n}\n</code></pre>\n\n<p>Also realize you can change that <code>if</code> condition to <code>c != '(' && c != ')'</code>.\nYou may also want to consider initializing the <code>StringBuilder</code> to <code>s</code> and\n<a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html#deleteCharAt%28int%29\">deleting</a> the parentheses. Also keep in mind that\nthe first <code>s = s.trim()</code> is not necessary given the <code>trim</code> at the end.</p>\n\n<h2><code>parens</code></h2>\n\n<p>This could be clarified with more documentation as recommended at the top, but\nit seems to me like it's supposed to determine (twice?) the nesting level of\nparentheses at a particular location in the string. I'm worried there's a bug\nwith closing parentheses before the location or opening parentheses after.\nConsider the following situation, where <code>^</code> is the location in question.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>( ( ) ( ) ( ) )\n ^\n</code></pre>\n\n<p>At that <code>^</code> point, there are two levels of nesting of parentheses. <code>parens</code>\nwill return 6, counting these:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>( ( ) ( ) ( ) )\n^ ^ ^ ^ ^ ^\n</code></pre>\n\n<p>I think you probably want a result of 4 instead, ignoring the paired\nparentheses.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>( ( ) ( ) ( ) )\n ~~~ ~~~ <- irrelevant to middle pair, but counted anyway\n</code></pre>\n\n<h2><code>determineOperatorPrecedenceAndLocation</code></h2>\n\n<p>This method is quite impenetrable to me, and I really suspect there are latent\nbugs lurking within it, particularly given the behavior of <code>parens</code> above. I\nthink you'll want to comment more heavily what you're doing here or take a\ndifferent approach.</p>\n\n<h1>Overall approach</h1>\n\n<h2>Unorthodox method of parsing</h2>\n\n<p>Your overall approach to parsing expressions is unorthodox. Now, this isn't\n<em>necessarily</em> a bad thing, but it's more difficult for me to examine, and a\nmore traditional approach may end up being more extensible and easier to\nmaintain. Normally you'd split this up into a few stages: first, you lex the\nstring into a series of <em>tokens</em>, so the input <code>5 + 6 == 10 + [x]</code> might yield\nthe tokens</p>\n\n<pre><code>INT 5\nPLUS\nINT 6\nEQUALS\nINT 10\nPLUS\nVAR x\n</code></pre>\n\n<p>From there, you parse it out. If you're just planning on using the result, you\ncan evaluate it as you parse. You can also build an\n<a href=\"https://en.wikipedia.org/wiki/Abstract_syntax_tree\">abstract syntax tree</a> (AST) and evaluate from there, but evaluating\nimmediately should be fine.</p>\n\n<p>For the actual parsing, you've got a bunch of possible approaches. If you\nwanted to go down this route, I might read up on\n<a href=\"https://en.wikipedia.org/wiki/Recursive_descent_parser\">recursive-descent parsers</a> and then <a href=\"https://en.wikipedia.org/wiki/Pratt_parser\">Pratt parsers</a>. There\nare also a variety of parser-generators like <a href=\"http://www.antlr.org/\">ANTLR</a>, but I'd try to\nfirst write one manually.</p>\n\n<h2>Extensibility</h2>\n\n<p>You may want to consider making it easier to extend your expression parser to\nadd more operators and such. For example, say I wanted to use the modulo\noperator. A good API for this might be something like this:</p>\n\n<pre><code>ExpressionParser parser = new ExpressionParser();\nparser.addOperator(new InfixOperator() {\n @Override\n public String getSymbol() {\n return \"%\";\n }\n\n @Override\n public int getPrecedence() {\n return 20; /* or whatever's appropriate within your system */\n }\n\n @Override\n public Associativity getAssociativity() {\n return Associativity.LEFT;\n }\n\n @Override\n public double evaluate(double left, double right) {\n return left % right;\n }\n});\nSystem.out.println(parser.evaluate(\"7 % 3 == 2\")); // => false\n</code></pre>\n\n<p>I don't know how I'd fit this in with your approach, but it is trivial with a\nPratt parser.</p>\n\n<h2>Appropriateness</h2>\n\n<p>I admire your effort in this, and while I imagine this would be useful in many\ncases, I'm not so sure your list library needs this. There is a rather\nstraightforward translation of predicates into Java: that is, an interface and\nanonymous classes, as we did with the extensibility example. For example:</p>\n\n<pre><code>public interface Predicate<T> {\n public boolean matches(T item);\n}\n</code></pre>\n\n<p>Then you could filter a list of integers like so:</p>\n\n<pre><code>int[] integers = new int[] { 1, 2, 3, 4, 5 };\nintegers = Halo.filter(integers, new Predicate<Integer>() {\n @Override\n public boolean matches(Integer item) {\n return item % 2 == 0; // even items only\n }\n});\n</code></pre>\n\n<p>Now, I'm not suggesting you <em>completely</em> abandon your approach. I just think\nyou might want to support that use and then provide an <code>ExpressionPredicate</code> or\nsomething so I could do this:</p>\n\n<pre><code>integers = Halo.filter(integers, new ExpressionPredicate<int>(\"[item] % 2 == 0\"));\n</code></pre>\n\n<p>Then I can pick and choose whether I want to use Java or your mini-language to\nwrite my predicate. I can even use <code>ExpressionPredicate</code> from within my\n<code>Predicate</code> that's otherwise written in Java: I get the best of both worlds.</p>\n\n\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T16:28:58.460",
"Id": "63911",
"Score": "0",
"body": "To address some of what you've pointed out, the parens method will attribute all of the imaginary starred expressions `( (*) (*) (*) )` with equal levels of nesting. It simply counts the parens that are \"open\" to a given operator. That's what determineOperatorPrecedenceAndLocation() uses as it's main filter. It will return the operator with the least number of parens open to it, indicating it is at the topmost level. In this case, I have also manipulated those vales slightly, as to accomodate order of operations and the selection of logical operators first."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T16:34:06.540",
"Id": "63912",
"Score": "0",
"body": "Also, that concatenation weighed heavily on my mind, but I just wasn't sure if it was more expensive than the cost of creating a StringBuilder object. Come to think of it, `s.remove(\"regex that matches ()\",\"\");` might be the best solution there. As far as the rest, those are some very cool suggestions and I will certainly take a look. I should mention that this IS a recursive-descent parser, just perhaps a little strange in it's implementation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T21:02:50.130",
"Id": "63926",
"Score": "0",
"body": "Concatenating strings with `+` is definitely more expensive. The StringBuilder can extend the memory used, while `+` always creates new String objects when used. That means that you allocate more objects and that the garbage collector has more objects to collect."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T05:14:56.710",
"Id": "38352",
"ParentId": "38348",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "38352",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T01:17:12.747",
"Id": "38348",
"Score": "13",
"Tags": [
"java",
"strings",
"array",
"haskell",
"parsing"
],
"Title": "Boolean expression parser"
}
|
38348
|
<p>I've been working on a <a href="https://github.com/megawac/MutationObserver.js" rel="nofollow"><code>MutationObserver</code> es5 shim</a> and would appreciate some feedback on my technique for identifying changes between a <code>node</code> and its <code>clone</code> from earlier state. The reason I'm asking for this code review is that this function is likely not perfect (i.e. will have to be updated in the future for missed/incorrect cases) and was the most difficult snippet of code I've ever written. I would like to know if how I've written the code is intuitive/commented enough for fresh eyes and if you have any suggestions for a couple things.</p>
<p>Here's the pseudocode I wrote that my actual code is based on:</p>
<pre><code>findChildMutations ($node, $oldnode, deep):
mutations = []
conflicts = []
iterate each $node.childNodes as $node and $oldnode.childNodes as $old:
if(sameNode($node, $old)):
if(deep):
check children of $node and $old
resolveConflicts()
else:
if($node not checked):
if($node not in $oldnode.childNodes):
add addedNode MutationRecord to mutations
else if($node at different index in $oldnode.childNodes)
add conflict
#*similarly for $old*
resolveConflicts()
return mutations
</code></pre>
<p>The goals of the function is to accurately be able to identify <code>addedNodes</code> or <code>removedNodes</code> in the (optionally deep) <code>childNodes</code> of an element. The function should also notice when there is a change in order of nodes. Finally the function should of course be efficient as it will be running more than 20 times a second.</p>
<h2>Implementation 1</h2>
<p>This is the best I had gotten it with the <code>node.cloneNode</code> implementation (some room for optimization by checking if both $kids and $oldkids are empty and avoid entering resolver see imp #2)</p>
<p><a href="https://github.com/megawac/MutationObserver.js/blob/30ab064a19d0a4f9ad70f409b9a29186fd87a085/MutationObserver.js#L230-239" rel="nofollow">Usage</a><br>
<a href="https://rawgithub.com/megawac/MutationObserver.js/master/test/index.html" rel="nofollow">Actual Test cases</a><br>
<a href="http://jsbin.com/uhoVibU/7" rel="nofollow">JSBin</a> </p>
<pre><code>/*subtree and childlist helpers*/
var has = Object.hasOwnProperty;
//Assigns a unique id to each node to be watched in order to be able to compare cloned nodes
//TODO find a cleaner way eg some hash represnetnation
var counter = 0;
var getId = function($ele) {
var id = $ele.nodeType === 3 ? $ele.nodeValue ://text node id is the text content
$ele.id || $ele.getAttribute("mut-id") || ++counter;
if(id === counter) {
$ele.setAttribute("mut-id", id);
}
return id;
};
var sameNode = function(node1, node2) {
return node1 && node2 && getId(node1) === getId(node2);
};
var findIndex = function(set, node, from) {
from = ~~from;
for(var i = from,l=set.length; i<l; i++) {
if(sameNode(node, set[i])) return i;
}
return -1;
};
//set the ids for all of an elements children
var $id_kids = function(ele, deep) {
if(ele.nodeType !== 3) {
foreach.call(ele.children, function(node) {//only iterate elements not text nodes
getId(node);
if(deep) $id_kids(node, deep);
});
}
return ele;
};
//findChildMutations: array of mutations so far, element, element clone, bool => array of mutations
// dfs comparision search of two nodes
// perf and function tests: http://jsbin.com/uhoVibU/4
var findChildMutations = function(target, oldstate, deep) {
var mutations = [];
var add = function(node) {
mutations.push(new MutationRecord({
type: "childList",
target: node.parentElement,
addedNodes: [node]
}));
if(deep) $id_kids(node, deep);//ensure children of added ele have ids
};
var rem = function(node) {
mutations.push(new MutationRecord({
type: "childList",
target: deep ? node.parentElement : target,//so target will appear correct on childList - more complicated on subtree
removedNodes: [node]
}));
};
var findMut = function(node, oldnode) {
var $kids = node.childNodes;
var $oldkids = oldnode.childNodes;
var klen = $kids.length;
var olen = $oldkids.length;
//id to i and j search hash to prevent double checking an element
var id;
var map = {};
//array of potention conflict hashes
var conflicts = [];
//offsets
//var offset_add = 0;//nodes added since last resolve //we dont have to check added as these are handled before remove
var offset_rem = 0;//nodes removed since last resolve
/*
* There is no gaurentee that the same node will be returned for both added and removed nodes
* if the position has been shuffled
*/
var resolver = function() {
var counter = 0;//prevents same conflict being resolved twice
var conflict;
for (var i = 0, l = conflicts.length-1; i <= l; i++) {
conflict = conflicts[i];
//attempt to determine if there was node rearrangement... won't gaurentee all matches
//also handles case where added/removed nodes cause nodes to be identified as conflicts
if(counter < l && Math.abs(conflict.i - (conflict.j + offset_rem)) >= l) {
add($kids[conflict.i]);//rearrangment ie removed then readded
rem($kids[conflict.i]);
counter++;
} else if(deep) {//conflicts resolved - check deep
findMut($kids[conflict.i], $oldkids[conflict.j]);
}
}
offset_rem = conflicts.length = 0;
};
//iterate over both old and current child nodes at the same time
for(var i = 0, j = 0, p; i < klen || j < olen; ) {
if(sameNode($kids[i], $oldkids[j])) {//simple expected case
if(deep) {//recurse
findMut($kids[i], $oldkids[j]);
}
//resolve conflicts
resolver();
i++;
j++;
} else {//lookahead until they are the same again or the end of children
if(i < klen) {
id = getId($kids[i]);
//check id is in the location map otherwise do a indexOf search
if(!has.call(map, id)) {//not already found
if((p = findIndex($oldkids, $kids[i], j)) === -1) {
add($kids[i]);
} else {
conflicts.push(map[id] = {//bit dirty
i: i,
j: p
});
}
}
i++;
}
if(j < olen) {
id = getId($oldkids[j]);
if(!has.call(map, id)) {
if((p = findIndex($kids, $oldkids[j], i)) === -1) {
rem($oldkids[j]);
offset_rem++;
} else {
conflicts.push(map[id] = {
i: p,
j: j
});
}
}
j++;
}
}
}
resolver();
};
findMut(target, oldstate);
return mutations;
};
</code></pre>
<p><em>Usage</em></p>
<pre><code>//node is a html element
//deep is a boolean
findChildMutations(node, node.cloneNode(true), deep)
</code></pre>
<h2>Implementation 2</h2>
<p>Using a custom datastructure for cloned nodes and heavily optimized compared to imp #1. Appears about <em>3-6 times</em> faster in early tests with no mutations registered (expected case).</p>
<p><strong>Edits</strong> fixed the following bugs:</p>
<ol>
<li>Calling <code>Array.prototype.indexOf</code> on <code>$oldkids</code> would not work as we were comparing an element to a clone data structure. Added a comparitor function to handle the case</li>
<li>Started ids at 1 as 0 is falsy</li>
<li>Fixed a bug in resolve conflicts when there is more than 1 conflict (solved by making counter the ceil of dividing len of conflicts by 2 instead of subbing 1)</li>
<li>Added a special case for when <code>idx=0</code> so we can get out of the hacky resolve conflict case and return to the expected case</li>
</ol>
<p><a href="https://github.com/megawac/MutationObserver.js/blob/8de99a296017b07d71c2b9fce55dce41f9489d24/MutationObserver.js#L226-233" rel="nofollow">Usage</a><br>
<a href="https://rawgithub.com/megawac/MutationObserver.js/childList-implementation-2/test/index.html" rel="nofollow">Actual Test cases</a><br>
JSBin (todo) </p>
<pre><code>/*subtree and childlist helpers*/
//indexOf for collection using a comparitor
var has = Object.hasOwnProperty;
var map = Array.prototype.map;
var indexOf = Array.prototype.indexOf;
var findIndex = function(set, comparitor, from) {
for(var i = ~~from, l=set.length; i<l; i++) {
if(comparitor(set[i])) return i;
}
return -1;
};
//using a non id (eg outerHTML or nodeValue) is extremely naive and will run into issues with nodes that may appear the same like <li></li>
var counter = 1;//don't use 0 as id (falsy)
var getId = function($ele) {
return $ele.id || ($ele["mo_id"] = $ele["mo_id"] || ++counter);//normally mo_id is an expando variable
};
//clone an html node into a custom datastructure
// see https://gist.github.com/megawac/8201012
var clone = function (par, deep) {
var copy = function(par, top) {
return {
node: par,
kids: top || deep ? map.call(par.childNodes, function(node) {
return copy(node);
}) : null
};
};
return copy(par, true);
};
//findChildMutations: array of mutations so far, element, element clone, bool => array of mutations
// dfs comparision search of two nodes
// this has to be as quick as possible
var findChildMutations = function(target, oldstate, deep) {
var mutations = [];
var add = function(node) {
mutations.push(new MutationRecord({
type: "childList",
target: node.parentElement,
addedNodes: [node]
}));
};
var rem = function(node, tar) {//have to pass tar because node.parentElement will be null when removed
mutations.push(new MutationRecord({
type: "childList",
target: tar,
removedNodes: [node]
}));
};
var findMut = function(node, old) {
var $kids = node.childNodes;
var $oldkids = old.kids;
var klen = $kids.length;
var olen = $oldkids.length;
if(!olen && !klen) return;//both empty; clearly no changes
//id to i and j search hash to prevent double checking an element
var map = {};
var id;
var idx;//index of a moved or inserted element
//array of potention conflict hashes
var conflicts = [];
//offsets since last resolve. Can also solve the problem with a continue but we exect this method to be faster as i and j should eventually correlate
//var offset_add = 0;//nodes added since last resolve //we dont have to check added as these are handled before remove
var offset_rem = 0;//nodes removed since last resolve
/*
* There is no gaurentee that the same node will be returned for both added and removed nodes
* if the positions have been shuffled.
*/
var resolver = function() {
var size = conflicts.length - 1;
var counter = -~ (size / 2);//prevents same conflict being resolved twice consider when two nodes switch places. only one should be given a mutation event (note -~ is math.ceil shorthand)
conflicts.forEach(function(conflict) {
//attempt to determine if there was node rearrangement... won't gaurentee all matches
//also handles case where added/removed nodes cause nodes to be identified as conflicts
if(counter && Math.abs(conflict.i - (conflict.j + offset_rem)) >= size) {
add($kids[conflict.i]);//rearrangment ie removed then readded
rem($kids[conflict.i], old.node);
counter --;
} else if(deep) {//conflicts resolved - check deep
findMut($kids[conflict.i], $oldkids[conflict.j]);
}
});
offset_rem = conflicts.length = 0;//clear conflicts
};
//current and old nodes
var $cur;
var $old;
//iterate over both old and current child nodes at the same time
for(var i = 0, j = 0; i < klen || j < olen; ) {
//current and old nodes at the indexs
$cur = $kids[i];
$old = j < olen && $oldkids[j].node;
if($cur === $old) {//simple expected case - needs to be as fast as possible
//recurse on next level of children
if(deep) findMut($cur, $oldkids[j]);
//resolve conflicts
if(conflicts.length) resolver();
i++;
j++;
} else {//(uncommon case) lookahead until they are the same again or the end of children
if($cur) {
id = getId($cur);
//check id is in the location map otherwise do a indexOf search
if(!has(map, id)) {//not already found
/* jshint loopfunc:true */
if((idx = findIndex($oldkids, function($el) { return $el.node === $cur; }, j)) === -1) { //custom indexOf using comparitor
add($cur);//$cur is a new node
} else {
map[id] = true;//mark id as found
conflicts.push({//add conflict
i: i,
j: idx
});
}
}
i++;
}
if($old) {
id = getId($old);
if(!has(map, id)) {
if((idx = indexOf.call($kids, $old, i)) === -1) {//dont need to use a special indexof but need to i-1 due to o-b-1 from previous part
rem($old, old.node);
offset_rem++;
} else if(idx === 0) {//special case: if idx=0 i and j are congurent so we can continue without conflict
continue;
} else {
map[id] = true;
conflicts.push({
i: idx,
j: j
});
}
}
j++;
}
}
}
if(conflicts.length) resolver();
};
findMut(target, oldstate);
return mutations;
};
</code></pre>
<p><em>Usage</em></p>
<pre><code>//node is a html element
//deep is a boolean
findChildMutations(node, clone(node, deep), deep)
</code></pre>
<h2>Questions (answer or reasonable suggestions for any of these will earn the bounty):</h2>
<ol>
<li>Is there a better way to be able to accurately compare a node to its clone than to assign a unique id to each element being watched (see <code>getId</code> helper function)? My concern with using <code>.equalNode</code> or parsing the HTML is being able to match the node if there are changes and handling two similarly appearing nodes such as a <code>li</code>. I wrote a <a href="https://gist.github.com/megawac/8201012" rel="nofollow">gist describing the problem</a>. <em>Implementation #2 applies the soloution discussed in the gist.</em></li>
<li>Can you give me some feedback and suggestions on my implementation? Is there any way to reduce <a href="https://github.com/megawac/MutationObserver.js/blob/8de99a296017b07d71c2b9fce55dce41f9489d24/MutationObserver.js#L142-175" rel="nofollow">this redundant code?</a> (2.5) I feel like a node's position being moved in the child list does not have to be a special case and we may be able to just find it as an <code>addedNode</code> and <code>removedNode</code> in the algorithm (may be difficult). </li>
<li><strong>Update</strong> another issue with this code is it can be unacceptably slow when I tested it on some mobile devices (<a href="https://rawgithub.com/megawac/MutationObserver.js/master/test/index.html" rel="nofollow">runs some of these JSLitmus tests (doesnt work in webkit because MutationObserver is protected)</a> only 50 times a second). Can you give me some optimization tips for the snippet. Note, we can expect that there will usually not be any mutations.</li>
</ol>
<p><s>Also do you know of any research/papers discussing comparing two trees/graphs? I haven't found much on the topic.</s></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T14:48:46.617",
"Id": "63907",
"Score": "0",
"body": "Can you not simply compare 2 nodes with `===` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T17:58:25.193",
"Id": "63918",
"Score": "0",
"body": "No because the nodes are cloned using `node2 = node.cloneNode(true)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T19:28:54.813",
"Id": "63923",
"Score": "0",
"body": "I updated 1) with a gist https://gist.github.com/megawac/8201012"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T22:06:19.643",
"Id": "64082",
"Score": "1",
"body": "*Do you know of any research/papers discussing comparing two trees/graphs? I haven't found much on the topic.* Have you looked at [Facebook React](http://calendar.perfplanet.com/2013/diff/)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T00:55:23.597",
"Id": "64100",
"Score": "1",
"body": "Cool @DanAbramov [their implementation](http://facebook.github.io/react/docs/reconciliation.html#problematic-case) docs seem similar to mine and establishes some of my assumptions `o(n)` with `o(n^2)` worst case and they also use hashed ids."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T15:13:03.833",
"Id": "64588",
"Score": "1",
"body": "Your implementation of `has` is missing"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T18:50:58.903",
"Id": "64613",
"Score": "0",
"body": "@tomdemuyt whoops its just `has = Object.hasOwnProperty`"
}
] |
[
{
"body": "<p>I assume you already scoured most resources on optimizing js, since you use most tricks ( including <code>~~</code> for <code>Math.floor</code> ). The only 1 I did not see is </p>\n\n<ul>\n<li>Store a reference to <code>Math.abs</code>: <code>var abs = Math.abs;</code> </li>\n</ul>\n\n<p>I have to say I would not like to maintain this code, you have a serious arrow problem here:</p>\n\n<pre><code> });\n }\n }\n j++;\n }\n }\n }\n resolver();\n};\n</code></pre>\n\n<p>I am fairly certain that with some effort you could reduce this. Also the mixed naming does not help, you ought to stick to lowerCamelCasing at all times for variables and functions.</p>\n\n<p>As for comparing elements, see <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Node.isSameNode\" rel=\"nofollow\">this</a> :</p>\n\n<pre><code>// Instead of using\nnode1.isSameNode(node2)\n\n// use\nnode1 === node2 // or\nnode1 == node2\n</code></pre>\n\n<p><strong>Update</strong></p>\n\n<p>The new approach you provided actually compares the elements which you store in your own custom structure, which is what I was trying to advocate before.</p>\n\n<p>Some further observations:</p>\n\n<ul>\n<li>JSHint.com advises against creating functions in a loop, which you do on line 121, I agree with JSHint, you seem not to : /* jshint loopfunc:true */, do you need help unfunctioning that ?</li>\n<li><code>$ele[\"mo_id\"]</code> -> <code>$ele.mo_id</code></li>\n<li><code>comparitor</code> -> <code>comparator</code></li>\n<li><code>tar</code> -> <code>target</code> ?</li>\n<li>You have a number of times the following construct : </li>\n</ul>\n\n<blockquote>\n<pre><code>if ($old) {\n id = getId($old);\n if (!has(map, id)) {\n ...\n }\n j++\n}\n</code></pre>\n</blockquote>\n\n<p>To prevent arrow coding, you could consider the folllowing Golfic approach which is acceptable IMO in this narrow case :</p>\n\n<pre><code>if( $old && j++ && id = getId($old) && !has(map,id) )\n{\n ..\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T17:56:48.543",
"Id": "63916",
"Score": "0",
"body": "1) http://jsperf.com/abs-value no real dif afaik 2) I agree completely one of the reasons I requested this code to be reviewed. Would comments like `/*end lookahead search*/` make this more clear? 3) `sameNode` doesnt use `node.isSameNode` its a local helper"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T00:00:30.763",
"Id": "64391",
"Score": "0",
"body": "@megawac: you could use 2-space indentation, it's fairly standard for JS."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-09T17:45:59.177",
"Id": "65099",
"Score": "0",
"body": "If you want to edit your answer for imp #2 at all I'll award you the bounty"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-09T18:59:05.690",
"Id": "65112",
"Score": "0",
"body": "Will do, my problem is that imp#2 is pretty how I would have written this. I am hesitant to split it in to functions because of performance worries."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-09T20:39:54.660",
"Id": "65132",
"Score": "0",
"body": "Function call overhead isn't too much of a concern for the unexpected case (some mutations). If you think you can make that part clearer please help. I dont even remember all the cases I had to handle with imp #1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-09T23:42:03.677",
"Id": "65147",
"Score": "0",
"body": "Probably too late for the bounty, but yeah ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T02:09:02.473",
"Id": "65157",
"Score": "0",
"body": "I can still award it for another 3 hours... Pretty sure `$old && j++ && id = getId($old) && !has(map,id)` wont work when `j=0` and I'll need logic for adding the conflict"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T03:59:40.490",
"Id": "65171",
"Score": "0",
"body": "Right, because you use j inside, never mind then, I guess I cant find a way to remove the arrow point coding."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T14:57:30.650",
"Id": "38366",
"ParentId": "38351",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T05:03:02.437",
"Id": "38351",
"Score": "6",
"Tags": [
"javascript",
"tree",
"dom"
],
"Title": "MutationObserver (shim): Finding differences between 2 DOM trees"
}
|
38351
|
<p>Because the MLlib does not support the sparse input, I ran the following code, which supports the sparse input format, on spark clusters. The settings are:</p>
<ul>
<li>5 nodes, each node with 8 cores (all the CPU on each node are 100%, 98% for user model, when running the code). </li>
<li>the input: 10,000,000+ instance, and 600,000+ dimension on HDFS</li>
</ul>
<p>For the above settings, the code cost 20+ minutes for one iteration.</p>
<p>I have asked this question <a href="https://stackoverflow.com/questions/20768788/why-this-lr-code-run-on-spark-too-slowly">here</a>, where the first version of the code can be found. And the first version cost 3 hours for one iteration. @<a href="https://stackoverflow.com/users/2083327/rudiger-klaehn">Rüdiger Klaehn</a> gave me some suggestions, and I updated the code. The time for one iteration take from 3 hours to 20 minutes. For my application, this is also unacceptable, so can any one give me some suggestions?</p>
<pre><code>import java.util.Random
import scala.collection.mutable.HashMap
import scala.io.Source
import org.apache.spark.SparkContext
import org.apache.spark.rdd.RDD
import org.apache.spark.util.Vector
import java.lang.Math
import org.apache.spark.broadcast.Broadcast
import org.apache.spark.serializer.KryoSerializer
import org.apache.spark.serializer.KryoRegistrator
import com.esotericsoftware.kryo._
import scala.collection.mutable.ArrayBuffer
object SparseLRV3 {
val lableNum = 1
val dimNum = 632918
val iteration = 10
val alpha = 0.1
val lambda = 0.1
val rand = new Random(42)
var w = new Array[Double](dimNum)
class LRRegistrator extends KryoRegistrator {
override def registerClasses(kryo: Kryo) {
kryo.register(classOf[SparseVector])
kryo.register(classOf[DataPoint])
}
}
class SparseVector(val indices: Array[Int], val values: Array[Double]) {
require(indices.length == values.length)
def map(f: Double => Double): SparseVector = {
new SparseVector(indices, values.map(x => f(x)).toArray)
}
def +(that: SparseVector): SparseVector = {
var tups = new HashMap[Int, Double]
//load touples from this
for (i <- 0 until indices.length)
tups += indices(i) -> values(i)
//load touples from that
for (i <- 0 until that.indices.length) {
val idx = that.indices(i)
val v = that.values(i)
if (tups.contains(idx))
tups(idx) += v
else
tups += idx -> v
}
new SparseVector(tups.keys.toArray, tups.values.toArray) //return a new sparse vector
output
}
}
case class DataPoint(x: SparseVector, y: Int)
def parsePoint(line: String): DataPoint = {
val fields = line.split("\t")
val y = fields(0).toInt
var i = 0
val len = fields.length - 1 //get the length
var indices = new Array[Int](len)
var values = new Array[Double](len)
fields.filter(_.contains(":")).foreach(f => {
val feature = f.split(":")
indices(i) = feature(0).toInt
values(i) = feature(1).toDouble
i = i + 1
})
DataPoint(new SparseVector(indices, values), y)
}
def gradient(p: DataPoint, w: Broadcast[Array[Double]]): SparseVector = {
def h(w: Broadcast[Array[Double]], p: DataPoint): Double = {
val wb = w.value
var s = 0.0
for (i <- 0 until p.x.indices.length)
s += p.x.values(i) * wb(p.x.indices(i))
1 / (1 + Math.exp(-p.y * s))
}
val scale = -(1 - p.y * h(w, p))
p.x.map(v => v * scale)
}
def train(sc: SparkContext, dataPoints: RDD[DataPoint]) {
for (i <- 0 until iteration) {
val wb = sc.broadcast(w)
val g = dataPoints.map(p => gradient(p, wb)).reduce(_ + _)
for (i <- 0 until g.indices.length)
w(g.indices(i)) += alpha * g.values(i)
for (i <- 0 until w.length)
w(i) += lambda * wb.value(i)
}
}
def main(args: Array[String]): Unit = {
System.setProperty("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
System.setProperty("spark.kryo.registrator", "LRRegistrator")
System.setProperty("spark.executor.memory", "15g")
System.setProperty("spark.storage.blockManagerHeartBeatMs", "300000")
val sc = new SparkContext("spark://xxxx:12036", "LR", "xxxx", List("xxxx.jar"))
val lines = sc.textFile("hdfs://xxx", 40)
val trainset = lines.map(parsePoint).cache()
train(sc, trainset)
}
}
</code></pre>
<p>I update a new version of code, this version use the accumulator to avoid allocation new object when do the add operation. and the time cost from 20 min for one iteration to 2 s. But I am not sure if the logic is right:</p>
<pre><code>import java.util.Random
import scala.collection.mutable.HashMap
import scala.collection.immutable.TreeMap
import scala.io.Source
import org.apache.spark.SparkContext
import org.apache.spark.rdd.RDD
import java.lang.Math
import org.apache.spark.broadcast.Broadcast
import org.apache.spark.Accumulator
import org.apache.spark.AccumulableParam
import org.apache.spark.serializer.KryoSerializer
import org.apache.spark.serializer.KryoRegistrator
import com.esotericsoftware.kryo._
import scala.collection.mutable.ArrayBuffer
import org.apache.spark.AccumulatorParam
object SparseLR {
val lableNum = 1
val dimNum = 632918
val iteration = 10
val alpha = 0.1
val lambda = 0.1
val rand = new Random(42)
var w = Array.tabulate(dimNum)(_ => rand.nextDouble)
class LRRegistrator extends KryoRegistrator {
override def registerClasses(kryo: Kryo) {
kryo.register(classOf[SparseVector])
kryo.register(classOf[DataPoint])
kryo.register(classOf[SparseLR.Vector])
kryo.register(classOf[Array[Double]])
}
}
class SparseVector(val indices: Array[Int], val values: Array[Double]) {
require(indices.length == values.length)
def map(f: Double => Double): SparseVector = {
new SparseVector(indices, values.map(x => f(x)).toArray)
}
}
case class DataPoint(x: SparseVector, y: Int)
def parsePoint(line: String) : DataPoint = {
val fields = line.split("\t")
val y = fields(0).toInt
var i = 0
val len = fields.length - 1 //get the length
var indices = new Array[Int](len)
var values = new Array[Double](len)
fields.filter(_.contains(":")).foreach(f => {
val feature = f.split(":")
indices(i) = feature(0).toInt
values(i) = feature(1).toDouble
i = i + 1
})
DataPoint(new SparseVector(indices, values), y)
}
class Vector(val data: Array[Double]) extends Serializable {
}
implicit object VectorAP extends AccumulableParam[Vector, SparseVector] {
def zero(v: Vector) = new Vector(new Array(v.data.size))
def addInPlace(v1: Vector, v2: Vector) : Vector = {
var i = 0
while ( i < v1.data.size) {
v1.data(i) += v2.data(i)
i += 1
}
return v1
}
def addAccumulator(v1: Vector, v2: SparseVector) : Vector = {
var i = 0
while ( i < v2.indices.length ) {
v1.data(v2.indices(i)) += v2.values(i)
i += 1
}
v1
}
}
def train(sc: SparkContext, dataPoints: RDD[DataPoint]) {
var g_a = Array.tabulate(dimNum)(_ => 0.0)
for (j <- 0 until iteration) {
var wb = sc.broadcast(w)
var gx = sc.accumulable(new Vector(g_a))(VectorAP)
dataPoints.foreach { p =>
var s = 0.0
var i = 0
while (i < p.x.indices.length) {
s += p.x.values(i) * wb.value(p.x.indices(i))
i = i + 1
}
var res = 1 / (1 + Math.exp(-p.y * s))
val scale = -(1 - p.y * res)
gx += p.x.map(v => v * scale) // call the function: addAccumulator
}
val g = gx.value.asInstanceOf[Vector] // call the function: addInPlace
var i = 0
while ( i < g.data.length) {
w(i) = alpha * g.data(i) + lambda * wb.value(i)
i += 1
}
}
}
def main(args: Array[String]): Unit = {
System.setProperty("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
System.setProperty("spark.closure.serializer", "org.apache.spark.serializer.JavaSerializer")
System.setProperty("spark.kryo.registrator", "LRRegistrator")
System.setProperty("spark.executor.memory", "15g")
System.setProperty("spark.default.parallelism", "48")
System.setProperty("spark.storage.blockManagerHeartBeatMs", "300000")
val sc = new SparkContext("spark://xxx:12036", "LR", "xxxx", List("xxxx.jar"))
val lines = sc.textFile("hdfs://xxxx/", 40)
val trainset = lines.map(parsePoint).cache()
train(sc, trainset)
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-04T03:21:08.260",
"Id": "64295",
"Score": "0",
"body": "If you'd like your added code to be reviewed, I recommend posting it as a new question with a link back to this question."
}
] |
[
{
"body": "<p>It seems to me that if you have very sparse vectors, converting to a non-sparse vector will be very inefficient. E.g. you have a sparse vector with 4 non-zero elements and convert it into a flat vector with 1000000 elements, the array allocation will take the most time.</p>\n\n<p>You can of course delay the conversion for as long as possible and work with sparse vectors all the time, but if apache spark does not support sparse vectors you will have to convert at some point, so you might have to search for some other toolkit.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T13:56:50.213",
"Id": "38365",
"ParentId": "38354",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T08:15:30.590",
"Id": "38354",
"Score": "5",
"Tags": [
"performance",
"scala",
"machine-learning",
"apache-spark"
],
"Title": "Why does the LR on spark run so slowly?"
}
|
38354
|
<p><a href="http://spark.incubator.apache.org" rel="nofollow">http://spark.incubator.apache.org</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T10:00:45.763",
"Id": "38356",
"Score": "0",
"Tags": null,
"Title": null
}
|
38356
|
Apache Spark is an open source cluster computing system that aims to make data analytics fast — both fast to run and fast to write.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T10:00:45.763",
"Id": "38357",
"Score": "0",
"Tags": null,
"Title": null
}
|
38357
|
<p>I implemented an algorithm that gives me a list of points that should be drawn in order the get a line between two points. Please note: it works only in a coordinate system whose origin (0,0) is in the upper left corner.</p>
<p>I'd like to get some review on my Haskell code, could it be improved in terms of the language constructs used?
Could it be more readable, more straight forward?</p>
<pre><code>module DrawLine where
data Point = Point Float Float deriving (Show)
getRange :: Int -> Int -> [Int]
getRange a b
| a <= b = [a..b]
| otherwise = [b..a]
{-|
- Get the slope of a line described by the two points received as arguments
-}
getSlope :: Point -> Point -> Float
getSlope (Point x1 y1) (Point x2 y2) = (y2-y1)/(x2-x1)
{-|
- Get a list of points where pixels should be filled to draw a line
- (Inspired from Bresenham's line algorithm)
- Takes two Point arguments representing the end points of the line, the points
- will be located on a line between these two points
-}
getLinePoints :: Point -> Point -> [Point]
getLinePoints f@(Point fx fy) l@(Point lx ly)
-- vertical line
| fx == lx = [(Point fx (fromIntegral y)) | y <- getRange (round fy) (round ly)]
| otherwise =
-- generate points by mapping on the "longer side" of the line
if m > 1.0 || m < -1.0 then
-- the rise if higher than the run
map (\y ->
(Point
((1/m) * ((fromIntegral y) - fy) + fx)
(fromIntegral y)
)
)
(getRange (round fy) (round ly))
else
map (\x ->
(Point
(fromIntegral x)
(m * ((fromIntegral x) - fx) + fy)
)
)
(getRange (round fx) (round lx))
where
m = getSlope f l
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T10:22:11.733",
"Id": "63891",
"Score": "1",
"body": "`where m`… what?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T10:26:24.847",
"Id": "63892",
"Score": "0",
"body": "updated: `where m = getSlope f l`, sorry for that, copy&paste error"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T06:03:41.853",
"Id": "63937",
"Score": "1",
"body": "As a Haskell novice, I'd say that it looks fine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T11:14:13.737",
"Id": "63946",
"Score": "0",
"body": "Thank you. What if I'd like to advance a little bit? What other language features/concepts could be used in this context?"
}
] |
[
{
"body": "<p>Thoughts.</p>\n\n<p>Define a <code>Line</code> type and rename <code>getLinePoints</code> to <code>mkLine</code>. A list of points may represent anything but a <code>Line [Points]</code> implies the <code>Point</code>s within the line. Where possible let the type system work for you. Of course you could get cute and have <code>Line (m -> x -> b -> [Points])</code> or <code>List Point Point</code>.</p>\n\n<p>You could define Eq and Ord instances for the Point and maybe Line types.</p>\n\n<p>What if <code>getSlope</code> is passed a vertical line? Should it perhaps use <code>Maybe</code>?</p>\n\n<p>I'd move the non-vertical line support into its own function. Perhaps add a horizontal line function as well.</p>\n\n<p>Why use a list comprehension for the vertical one and <code>map</code> for the other type of line? It can all be done with a comprehension.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-26T06:02:45.220",
"Id": "79110",
"Score": "0",
"body": "Thank you! I'll definitely take a closer look on what you said and try to improve things."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-25T22:58:41.023",
"Id": "45356",
"ParentId": "38358",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T10:16:26.617",
"Id": "38358",
"Score": "3",
"Tags": [
"algorithm",
"beginner",
"haskell",
"graphics"
],
"Title": "Bresenham-like line algorithm"
}
|
38358
|
<p>A <strong>signal</strong> is an information-carrying wave, but in the digital sense, a 'signal' refers to either received or transmitted streams/blocks of data, commonly representing real-world quantities such as audio levels, luminosity, pressure etc over time or distance.
These real-world quantities usually comes as analogue signals that are being sample and quantized into a digital format.</p>
<p><strong>'Processing'</strong> is the act of altering, analyzing or characterizing the data to retrieve/modify information inherent in the signal in question.</p>
<p>Common topics include:</p>
<ul>
<li>digital filtering; </li>
<li>audio processing; </li>
<li>image processing; </li>
<li>sampling; </li>
<li>data compression; </li>
<li>spectral analysis; </li>
</ul>
<p>Analysis tools commonly in practice are the Discrete Fourier Transform (DFT), especially its fast implementations (FFT); and wavelet transforms. </p>
<p>Common softwares used in the field include <a href="/questions/tagged/matlab" class="post-tag" title="show questions tagged 'matlab'" rel="tag">matlab</a>; <a href="/questions/tagged/python" class="post-tag" title="show questions tagged 'python'" rel="tag">python</a>, especially with <a href="/questions/tagged/numpy" class="post-tag" title="show questions tagged 'numpy'" rel="tag">numpy</a>/SciPy; <a href="/questions/tagged/c" class="post-tag" title="show questions tagged 'c'" rel="tag">c</a>/<a href="/questions/tagged/c%2b%2b" class="post-tag" title="show questions tagged 'c++'" rel="tag">c++</a>/<a href="/questions/tagged/c%23" class="post-tag" title="show questions tagged 'c#'" rel="tag">c#</a>/<a href="/questions/tagged/objective-c" class="post-tag" title="show questions tagged 'objective-c'" rel="tag">objective-c</a>; <a href="/questions/tagged/java" class="post-tag" title="show questions tagged 'java'" rel="tag">java</a>; and various <a href="/questions/tagged/assembly" class="post-tag" title="show questions tagged 'assembly'" rel="tag">assembly</a> languages.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T12:56:03.553",
"Id": "38361",
"Score": "0",
"Tags": null,
"Title": null
}
|
38361
|
AKA digital signal processing (DSP). A signal is an information-carrying wave, but in the digital sense, a 'signal' refers to either received or transmitted streams/blocks of data, commonly representing real-world quantities such as audio levels, luminosity, pressure etc over time or distance. 'Processing' is the act of altering, analyzing or characterizing the data to retrieve/modify information inherent in the signal in question.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T12:56:03.553",
"Id": "38362",
"Score": "0",
"Tags": null,
"Title": null
}
|
38362
|
<p>I need a special dictionary that would do as follows:</p>
<ul>
<li><p>if key is set to more than once, the values are a list of all set values. Such a list is returned as value on get.</p></li>
<li><p>if key is set only once, it is set to that value, and returned as value as well.</p></li>
</ul>
<p>Sort of like MultiDict from Paste, but that does not seem to have the same interface as ordinary dict.</p>
<p>I wrote this:</p>
<pre><code>class ModalDict(dict):
def __init__(self, *args, **kwargs):
class Speclist(list):
pass
self.speclist = Speclist
dict.__init__(self, *args, **kwargs)
def __getitem__(self, k):
v = dict.__getitem__(self, k)
if isinstance(v, self.speclist) and len(v) == 1:
return v[0]
return v
def __setitem__(self, k, v):
self.setdefault(k, self.speclist()).append(v)
</code></pre>
<p>Obviously I defined Speclist to differentiate it from regular list that someone may set as value.</p>
<p>Problems? Any better way to do this?</p>
|
[] |
[
{
"body": "<p>I think the second requirement (return the value for a key with only a single assignment as itself) is a bad requirement. It goes against Guido's guidance that passing different values (of the same type) to a function should avoid returning different types, and you can see how it breaks simple code like this, making it differ significantly from iterating <code>d.items()</code>:</p>\n\n<pre><code>for k in d: # assume d is an instance of your ModalDict\n for v in d[k]: # can't iterate simple values, or accidentally iterates list values\n print(k, v)\n</code></pre>\n\n<p>Thus my recommendation would be to simply use <code>d = collections.defaultdict(list)</code> and always call <code>d[k].append(value)</code>. If you need to prevent, say, accidentally replacing a list of values, you could make <code>__setitem__</code> also do this or raise an exception. Since the implicit append seems like it would be surprising, I would rather raise an exception guiding towards the explicit append.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T20:45:52.330",
"Id": "38374",
"ParentId": "38364",
"Score": "5"
}
},
{
"body": "<p>It can be solved in <code>__setitem__</code>, so the special <code>__getitem__</code> will not affect the performance:</p>\n\n<pre><code>class ModalDict(dict):\n def __setitem__(self, k, v):\n if k in self:\n if isinstance(self[k], Speclist):\n v = self[k] + [v]\n else:\n v = Speclist([self[k], v])\n dict.__setitem__(self,k,v)\n\nclass Speclist(list):\n pass\n</code></pre>\n\n<p>If key is set only once, it is set to that value, and returned as value as well. So works like a normal dict:</p>\n\n<pre><code>>>> d = ModalDict()\n>>> d['a'] = 1\n>>> d['a']\n1\n>>> d # it prints the simple value too\n{'a': 1}\n</code></pre>\n\n<p>If key is set to more than once, the values are a list of all set values:</p>\n\n<pre><code>>>> d['a'] = 2\n>>> d['a']\n[1, 2]\n>>> d # it prints list too\n{'a': [1, 2]}\n\n>>> d['a'] = 3\n>>> d['a']\n[1, 2, 3]\n>>> d\n{'a': [1, 2, 3]}\n</code></pre>\n\n<p>Regular list is set as the value:</p>\n\n<pre><code>>>> d2 = ModalDict()\n>>> d2['b'] = [1]\n>>> d2['b']\n[1]\n>>> d2\n{'b': [1]}\n</code></pre>\n\n<p>More values:</p>\n\n<pre><code>>>> d2['b'] = 2\n>>> d2['b']\n[[1], 2]\n>>> d2\n{'b': [[1], 2]}\n\n>>> d2['b'] = [3]\n>>> d2['b']\n[[1], 2, [3]]\n>>> d2\n{'b': [[1], 2, [3]]}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T13:22:51.980",
"Id": "38748",
"ParentId": "38364",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T13:56:00.243",
"Id": "38364",
"Score": "2",
"Tags": [
"python",
"hash-map"
],
"Title": "Special dictionary"
}
|
38364
|
<p>I was solving Project Euler problem 16, which asks to find the sum of digits of the number 2 raised to the power 1000. Using Python, it can be solved in one line of code:</p>
<pre><code>sum(map(int, list(str(2**1000))))
</code></pre>
<p>It felt too easy so I decided to write a function in C to do the same job. Here's my program. In what ways can I improve it? Please suggest good practices also.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
int sumdigit(int a, int b);
int main(void) {
int a = 2;
int b = 10000;
printf("%d\n", sumdigit(a, b));
return 0;
}
int sumdigit(int a, int b) {
// numlen = number of digit in a^b
// pcount = power of 'a' after ith iteration
// dcount = number of digit in a^(pcount)
int numlen = (int) (b * log10(a)) + 1;
char *arr = calloc(numlen, sizeof *arr);
int pcount = 0;
int dcount = 1;
arr[numlen - 1] = 1;
int i, sum, carry;
while(pcount < b) {
pcount += 1;
sum = 0;
carry = 0;
for(i = numlen - 1; i >= numlen - dcount; --i) {
sum = arr[i] * a + carry;
carry = sum / 10;
arr[i] = sum % 10;
}
while(carry > 0) {
dcount += 1;
sum = arr[numlen - dcount] + carry;
carry = sum / 10;
arr[numlen - dcount] = sum % 10;
}
}
int result = 0;
for(i = numlen - dcount; i < numlen; ++i)
result += arr[i];
free(arr);
return result;
}
</code></pre>
|
[] |
[
{
"body": "<p>The problem calls for computing the sum of digits in 2<sup>1000</sup>. You did 2<sup>10000</sup>. Overachiever!</p>\n\n<p>There are a few things you could do to improve readability.</p>\n\n<p><code>char *arr</code> looks a lot like a string. One might initially think that you are storing the number as a string (i.e., ASCII <code>'0'</code>… <code>'9'</code>). You could dispel that impression by changing it to <code>unsigned char *arr</code>. To be even clearer, I would use a <code>typedef unsigned char digit;</code> so that you can declare <code>digit *arr</code>. Then it is clear that you are using binary-coded decimal.</p>\n\n<p>As long as you are doing binary-coded decimal, there is no advantage to putting the most-significant digit first. With the least-significant digit first, the code is simpler, and there is the nice property that the number is <code>sum(arr[i] * 10**i for i in range(len(arr)))</code>.</p>\n\n<p>For further readability, I would define a <code>struct</code> to represent the big decimal:</p>\n\n<pre><code>typedef unsigned char digit;\n\ntypedef struct {\n int capacity;\n int dcount;\n digit *digits; /* Unsigned binary-coded decimal. The number is\n sum(arr[i] * 10**i for i in range(dcount)) */\n} bigdecimal;\n</code></pre>\n\n<p>There are a lot of variables in your <code>sumdigit()</code> — not quite a mess, but enough to start being concerned. The function name <code>sumdigit</code> is also a bad code smell. I would also decompose the operations for readability. (Defining the <code>bigdecimal</code> type makes that practical.)</p>\n\n<pre><code>void mult(unsigned int a, bigdecimal *b) {\n int carry = 0;\n\n for (int i = 0; i < b->dcount; ++i) {\n int sum = a * b->digits[i] + carry;\n carry = sum / 10;\n b->digits[i] = sum % 10;\n }\n\n while (carry > 0) {\n int sum = b->digits[b->dcount] + carry;\n carry = sum / 10;\n b->digits[b->dcount] = sum % 10;\n b->dcount++;\n }\n}\n\nbigdecimal *exponentiate(unsigned int base, unsigned int power) {\n bigdecimal *result = malloc(sizeof(bigdecimal));\n result->capacity = 1 + (int) (power * log10(base));\n result->digits = calloc(result->capacity, sizeof(digit));\n\n /* base**0 == 1 */\n result->digits[0] = 1;\n result->dcount = 1;\n\n for (int p = 0; p < power; p++) {\n mult(base, result);\n }\n\n return result;\n}\n\nunsigned int sumdigit(bigdecimal *b) {\n unsigned int sum = 0;\n for (int i = b->dcount - 1; i >= 0; --i) {\n sum += b->digits[i];\n }\n return sum;\n}\n\nvoid free_bigdecimal(bigdecimal *b) {\n free(b->digits);\n free(b);\n}\n\nint main(void) {\n bigdecimal *n = exponentiate(2, 1000);\n printf(\"%u\\n\", sumdigit(n));\n free_bigdecimal(n);\n return 0;\n}\n</code></pre>\n\n<p>I've used C99 variable scoping in the for-loops because it's nicer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T20:31:59.933",
"Id": "63924",
"Score": "1",
"body": "Compiling with optimization enabled should cause the function calls to be inlined. (`clang` does it at `-O2`.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T22:08:01.253",
"Id": "63927",
"Score": "1",
"body": "In the function `sumdigit`, wouldn't iterating the `for` loop from `i = 0` to `i = b->dcount - 1` be simpler? Thanks a lot for many ideas on how to form abstractions and write clean, readable code :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T22:16:03.017",
"Id": "63928",
"Score": "1",
"body": "A for-loop counting up is more conventional. A for-loop counting down to 0 is a micro-optimization: CPUs have special instructions for comparing numbers with 0. The difference in performance would be negligible, so either way would be fine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T01:00:44.733",
"Id": "63934",
"Score": "2",
"body": "+1. I'd be inclined to save one allocation by passing the `bigdecimal` pointer into `exponentiate` so that the caller can define it on the stack. Either that or make the `digits` pointer a zero dimension array and allocate the struct in a single `calloc`. Also `sumdigit` should have a `const` parameter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T04:30:24.023",
"Id": "63935",
"Score": "0",
"body": "@WilliamMorris Learned [something new](http://stackoverflow.com/q/16553542/1157100). Thanks!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T20:24:55.230",
"Id": "38373",
"ParentId": "38370",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "38373",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T16:47:36.377",
"Id": "38370",
"Score": "4",
"Tags": [
"c",
"algorithm",
"project-euler"
],
"Title": "Function to find sum of digits in the number a^b where a, b are positive integers"
}
|
38370
|
<p>I'm responsible for maintaining a web service project in c#. I have one service class with a bunch of methods that look a lot like this:</p>
<pre><code> [OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "v1/Login", ResponseFormat = WebMessageFormat.Json)]
public string Login()
{
try
{
JObject incomingRequestJson = retrieveJson();
JObject returningJson = new JObject();
string accountId = incomingRequestJson.SelectToken("accountId", true).ToString();
string username = incomingRequestJson.SelectToken("userName", true).ToString();
string password = incomingRequestJson.SelectToken("password", true).ToString();
LoginResult result = readerBLL.Login(accountId, username, password);
returningJson.Add(new JProperty("userSessionId", result.userSessionId));
returningJson.Add(new JProperty("friendlyUserName", result.friendlyUserName));
return returningJson.ToString(Newtonsoft.Json.Formatting.None);
}
catch (Exception ex)
{
throw new WebFaultException<string>(ex.Message.ToString(), HttpStatusCode.OK);
}
}
</code></pre>
<p>Note that <code>retrieveJson()</code> grabs a JSON string from the <code>HttpContext</code> and runs <code>JObject.Parse()</code> on it.
Note also that the consumer of this service is a Flex app, so I do need the WebFaultException business with the "OK" response code (The networking component in Flex treats connection timeouts and all HTTP error codes exactly the same - no further data other than</p>
<p>I don't like the way I have the <code>try-catch</code> block repeated in every method, so I tried making the following method:</p>
<pre><code>private object invokeBusinessLogic(Func<JObject, object> f)
{
try
{
return f(retrieveJson());
}
catch (Exception ex)
{
WebFaultException<string> wfe = new WebFaultException<string>(ex.Message.ToString(), HttpStatusCode.OK);
throw wfe;
}
}
</code></pre>
<p>Then my service methods can look like this:</p>
<pre><code>public object Login()
{
LoginResult result = (LoginResult) invokeBusinessLogic(readerBLL.Login);
returningJson.Add(new JProperty("userSessionId", result.userSessionId));
returningJson.Add(new JProperty("friendlyUserName", result.friendlyUserName));
return returningJson.ToString(Newtonsoft.Json.Formatting.None);
}
</code></pre>
<p>However, this has the problem that the use of JSON to carry the request data gets exposed to the business layer. Is there a better way to avoid the duplicate <code>try-catch</code> blocks than this <code>invokeBusinessLogic</code> idea?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T15:41:36.630",
"Id": "63953",
"Score": "0",
"body": "Why are you parsing and creating the JSONs instead of using serialization? I think that would simplify your code quite a lot."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T07:22:17.377",
"Id": "63977",
"Score": "0",
"body": "Historical reasons. I'd love to change it, but then the clients of this service would need to be updated. That's something for version 2 of this service."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T11:44:02.697",
"Id": "63990",
"Score": "0",
"body": "Why would that affect the clients? You could still serialize to the same JSON."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T22:03:37.723",
"Id": "64081",
"Score": "0",
"body": "Oh, perhaps I misunderstood you. I thought doing serialization would mean function signatures like `public LoginResult Login()` in the service layer -- and that would break my clients. The current code actually sends an escaped string rather than a real JSON string :/"
}
] |
[
{
"body": "<p>I'm not sure why your change all of a sudden would expose data to the business layer when it didn't before.</p>\n\n<p>If you have a pattern of methods which look like this:</p>\n\n<pre><code>public string MyServiceCall()\n{\n try\n {\n JObject incomingRequestJson = retrieveJson();\n JObject returningJson = new JObject();\n\n // do stuff\n\n return returningJson.ToString(Newtonsoft.Json.Formatting.None);\n }\n catch (Exception ex)\n {\n throw new WebFaultException<string>(ex.Message.ToString(), HttpStatusCode.OK);\n }\n}\n</code></pre>\n\n<p>Then you can simply add a helper method to your service implementation:</p>\n\n<pre><code>private string ProcessServiceCall(Func<JObject, JObject> processor)\n{\n try\n {\n JObject incomingRequestJson = retrieveJson();\n JObject returningJson = processor(incomingRequestJson);\n\n return returningJson.ToString(Newtonsoft.Json.Formatting.None);\n }\n catch (Exception ex)\n {\n throw new WebFaultException<string>(ex.Message.ToString(), HttpStatusCode.OK);\n }\n}\n</code></pre>\n\n<p>and your service call then becomes:</p>\n\n<pre><code>public string MyServiceCall()\n{\n ProcessServiceCall(incomingRequestJson => {\n\n string accountId = incomingRequestJson.SelectToken(\"accountId\", true).ToString();\n string username = incomingRequestJson.SelectToken(\"userName\", true).ToString();\n string password = incomingRequestJson.SelectToken(\"password\", true).ToString();\n\n JObject result = new JObject();\n\n LoginResult result = readerBLL.Login(accountId, username, password);\n result.Add(new JProperty(\"userSessionId\", result.userSessionId));\n result.Add(new JProperty(\"friendlyUserName\", result.friendlyUserName));\n\n return result;\n }\n}\n</code></pre>\n\n<p>This should be a simple refactoring on your service class and not expose any more json to the business logic than before.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T21:24:07.457",
"Id": "64636",
"Score": "0",
"body": "Thanks, this is perfect. I hadn't thought of doing an anonymous function to pass to ProcessServiceCall."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-25T08:28:50.100",
"Id": "116692",
"Score": "0",
"body": "Maybe reuse source code (common logic, implementation) for WebAPI, WCF Service (JSON), WCF Service (SOAP-XML)? _IMHO, better samples for minimize learning curve are real \n\napplications with full source code and good patterns_"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T06:27:21.840",
"Id": "38379",
"ParentId": "38371",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "38379",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T16:54:15.347",
"Id": "38371",
"Score": "1",
"Tags": [
"c#",
".net",
"asp.net",
"wcf",
"web-services"
],
"Title": "Avoiding Duplicate Boilerplate Code in WCF Service"
}
|
38371
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.