body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<blockquote>
<p>Rewrite appropiate programs from earlier chapters and exercises with pointers instead of array indexing. Good posibilities include <code>getline</code>(Chapter 1 and 4), <code>atoi</code>, <code>itoa</code>, and their variants(Chapters 2, 3, and 4), <code>reverse</code>(Chapter 3), and <code>strindex</code> and <code>getop</code>(Chapter 4)</p>
</blockquote>
<p>Here is my solution: </p>
<pre><code>static char *hidden(int n, char *s) {
char *p;
if(n / 10) {
p = hidden(n / 10, s);
}
else {
p = s;
}
*p++ = n % 10 + '0';
*p = '\0';
return p;
}
char *itoa(int n, char *s) {
if(n < 0) {
*s = '-';
hidden(-n, s + 1);
}
else {
hidden(n, s);
}
return s; /* pointer to first char of s*/
}
</code></pre>
<p><code>itoa</code> is a wrapper for the function <code>hidden</code>. The function <code>hidden</code> returns a pointer to the next free slot in the array <code>s</code>. At the deepest level of recursion it returns a pointer to the first element (the else branch) of the array. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T14:48:58.150",
"Id": "70198",
"Score": "0",
"body": "I think that this is the most relevant function that needs pr, the other ones are quite simple. If you want to see them: https://drive.google.com/folderview?id=0BwF4dzZ2k9NRVnl0ZUEtTE0yQUE&usp=sharing"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T15:25:07.770",
"Id": "70213",
"Score": "0",
"body": "Please give a better name (and some explanatory comments) to your `hidden` function. It's hard to tell what the function does."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T14:04:19.380",
"Id": "70393",
"Score": "0",
"body": "There is absolutely no reason to use recursion for this. It is hard to read, inefficient and dangerous. I think the [classic K&R](http://en.wikibooks.org/wiki/C_Programming/C_Reference/stdlib.h/itoa) implementation of this algorithm is hard to beat in terms of efficiency. (But of course, K&R code is always an unreadable mess, filled with dangerous programming practice, so that snippet would need a code review of its own.)"
}
] |
[
{
"body": "<p>The standard version of itoa takes a parameter named base (which you have assumed is 10).</p>\n\n<p>You probably don't need a second hidden function; this would do instead:</p>\n\n<pre><code>if (n < 0)\n{\n *s++ = '-';\n n = -n;\n}\n// ... itoa implementation continues here ...\n</code></pre>\n\n<p>Recursing is clever; you could also probably do it with two loops instead (untested code ahead):</p>\n\n<pre><code>i = 1;\nwhile ((i * 10) <= n)\n i *= 10;\nfor (; i != 0; i /= 10)\n{\n int x = n / i;\n *p++ = (char)(x % 10 + '0');\n n -= (x * i);\n}\nassert(n == 0);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T13:34:35.967",
"Id": "70386",
"Score": "0",
"body": "There is no standard version of itoa. As in: how it should behave isn't specified anywhere."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T16:17:19.440",
"Id": "40975",
"ParentId": "40961",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "40975",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T14:38:27.517",
"Id": "40961",
"Score": "2",
"Tags": [
"c",
"beginner",
"pointers"
],
"Title": "Pointer version of itoa"
}
|
40961
|
<p>I'm trying to use an object and persist it into the data base.</p>
<p>I created a class in the library's folder.</p>
<pre><code><?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Solicitud {
private $categoria;
private $consecutivo;
private $id;
private $mensaje;
private $solicitante;
function __construct(){
$this->categoria = 1;
$this->consecutivo = 1;
$this->mensaje = "Mensaje por defecto";
}
public function escalarSolicitud( User $actual, User $nuevo){
$this->setSolicitante($nuevo);
}
# Getters and Setters
public function setCategoria( $categoria ){
$this->categoria = $categoria;
}
public function getCategoria(){
return $this->categoria;
}
</code></pre>
<p>Here is the <code>Controller</code>:</p>
<pre><code><?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Administrador extends Ci_Controller {
function __construct(){
parent::__construct();
}
public function crearSolicitud(){
$session_data = $this->session->userdata('session_user');
$usuario = $session_data['usuario'];
$categoria = $this->input->post('category');
$mensaje = $this->input->post('description');
$solicitud = new solicitud;
$solicitud->setSolicitante($user);
$solicitud->setCategoria($categoria);
$solicitud->setMensaje($mensaje);
$this->helpdesk_model->createSupport( $solicitud );
}
</code></pre>
<p>And in the <code>Model</code> how can I use the object properties:</p>
<pre><code>public function createSupport( $soporte ){
$this->db->trans_start();
$data = array(
'id' => null,
'id_user' => $soporte[usuario], ???
'id_category' => $soporte[categoria], ???
'message' => $soporte[mensaje] ???
);
$this->db->insert('supports', $data);
$this->db->trans_complete();
return $this->db->trans_status();
}
</code></pre>
<p>I need to know if I'm in the right direction or if the use of the 'Solicitud' class is not necessary. If I'm right, how should I call in the model the object attributes?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T14:51:44.353",
"Id": "70200",
"Score": "0",
"body": "I realized that int the model I can use the get functions like `'id_category' => $soporte->getCategoria();`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T12:04:49.517",
"Id": "81296",
"Score": "1",
"body": "yep in your case since you don't modify anything with the data i would pass them just as an array"
}
] |
[
{
"body": "<p>I would like to add something to @Dukeatcoding comment in the question. What is the point of passing the whole object? Thinking on it as a part of the main controller, you should only pass the data as an array to the model:</p>\n\n<pre><code>$data = array(\n 'id_user' => $usuario,\n 'id_category' => $soporte->getCategoria\n 'message' => $soporte->getMensaje\n)\n$this->helpdesk_model->createSupport( $solicitud );\n</code></pre>\n\n<p>Although, as you are getting all these properties so often, what about a general getter in your soporte class?</p>\n\n<pre><code>public function getValue( $var ){\n return $this->{$var};\n} \n</code></pre>\n\n<p>And you'd have something like:</p>\n\n<pre><code>$data = array(\n 'id_user' => $soporte->getVar( 'usuario'),\n 'id_category' => $soporte->getVar( 'categoria'),\n 'message' => $soporte->getVar( 'mensaje' )\n)\n</code></pre>\n\n<p>From your code, I would take care of the validation of your values, as it looks like you don't validate if they're numeric, if they exists on your DDBB, etc. Maybe you're doing it, because I suppose the code you posted is just a excerpt (due to some method are missed in Solicitud, as setSolicitante($nuevo) ), but I prefer to write it, just in case.</p>\n\n<p>Also, I won't assign to a var the values you take directly, just call them an take the value:</p>\n\n<pre><code>//Instead of:\n$session_data = $this->session->userdata('session_user'); \n$usuario = $session_data['usuario']; \n// Better \n$usuario = $this->session->userdata('session_user'); \n</code></pre>\n\n<p>Off topic, you could check Doctrine, <a href=\"http://www.doctrine-project.org/projects/orm.html\" rel=\"nofollow\">http://www.doctrine-project.org/projects/orm.html</a>, is an ORM that maybe could help you, and it has its own CI recipe:\n<a href=\"http://docs.doctrine-project.org/en/2.0.x/cookbook/integrating-with-codeigniter.html\" rel=\"nofollow\">http://docs.doctrine-project.org/en/2.0.x/cookbook/integrating-with-codeigniter.html</a></p>\n\n<p>Have fun!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-25T07:12:53.520",
"Id": "51673",
"ParentId": "40963",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T14:47:39.787",
"Id": "40963",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"mvc",
"codeigniter"
],
"Title": "Passing an object to the view in CodeIgniter"
}
|
40963
|
<p>Can anyone please help me to simplify this form validation script? It works great but I was just wondering if I can get some help to make it simpler. Your opinion on the approach I used below is also welcome (i.e it is good or bad practice/method). </p>
<pre><code><script type="text/javascript">
var FormValidation = function(form){
this.messages = {
required : 'This field should not be empty',
email : 'Please enter valid email',
number : 'Please enter valid number',
min : 'This field length should be minimum ',
max : 'This field length should not exceed ',
range : 'This field length between '
};
validator = this;
var currentmsg =this;
this.required = function(value){
var valid = (value.length > 0);
return {status: valid, message: valid ? '' : currentmsg.messages.required};
}
this.email = function(value){
var pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/ ;
var valid = pattern.test(value);
return { status:valid, message: valid ? '' : currentmsg.messages.email};
}
this.number = function(value){
var pattern = /^[0-9]+/ ;
var valid = pattern.test(value);
return { status:valid, message: valid ? '' : currentmsg.messages.number};
}
this.min = function(value,args){
if(value.length > 0){
var valid = (value.length >= args[0])
return { status:valid, message: valid ? '' : currentmsg.messages.min + args[0] };
}
}
this.max = function(value,args){
if(value.length > 0){
var valid = (value.length <= args[0])
return { status:valid, message: valid ? '' : currentmsg.messages.max + args[0] };
}
}
this.range = function(value,args){
var valid = (value.length >= args[0] && value.length <= args[1])
return {
status:valid,
message: valid ? '' : currentmsg.messages.range + args[0] + ' and ' + args[1]
};
}
this.validators = {
required : validator.required,
email : validator.email,
number : validator.number,
range : validator.range,
max : validator.max,
min : validator.min
};
this.validate = function(form){
var elements = form.elements;
var status = true;
for(var i = 0; i < elements.length ; i++){
var validate = elements[i].getAttribute('validate');
if(!validate){
continue;
}
var types = validate.split(' ');
for(var j = 0; j < types.length; j++){
var result = this.validateField(elements[i], types[j]);
if(!result) {
continue
}
this.displayErrors(elements[i], result);
if(!result.status) {
status = false;
break;
}
}
}
return status;
}
this.displayErrors = function(element, result){
element.className = result.status ? '' : 'error';
var elErr =element.errorMsg;
if(elErr!=null)
elErr.className = result.status ? '' :'valerr'
if(!element.errorMsg){
elErr = document.createElement("div");
elErr.id = 'valerr';
element.parentNode.appendChild(elErr);
element.errorMsg = elErr;
}
elErr.innerHTML = result.message;
}
this.validateField = function (element, type){
var validationType = type;
var args ;
if(type.indexOf("(")!= -1 && type.indexOf(")") != -1){
var result = this.getArguments(type);
validationType = result.type;
args = result.argsList;
}
validator = this.validators[validationType];
if(validator != null){
return validator(element.value ,args);
}
return null;
}
this.getArguments = function(type){
var validationtype = type.substring(0,type.indexOf("("));
var args = type.substring(type.indexOf("(")+1,type.indexOf(")")).split(',');
return { type : validationtype, argsList : args}
}
this.init = function() {
var curForm = this;
var forms = document.forms;
for(var i = 0; i < forms.length ; i++){
if(forms[i].getAttribute('validate')!=null){
forms[i].onsubmit = function(){
return curForm.validate(this);
};
}
}
}
}
window.onload = function() {
var formValidation = new FormValidation();
formValidation.init();
}
</script>
<form method="post" action="#" validate>
<table>
<tr>
<td>Name :</td>
<td><input type="text" name="" validate="required min(5)"></td>
</tr>
<tr>
<td>Mobile No :</td>
<td><input type="text" name="" validate="required number min(10) max(10)">
</tr>
<tr>
<td>Email :</td>
<td><input type="text" name="" validate="required email"></td>
</tr>
</table>
<input type="submit" value="submit"/>
</form>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T16:37:14.253",
"Id": "70224",
"Score": "1",
"body": "If that is meant to be jQuery plugin you are not wrapping it correctly into the jQuery namepsace. Could cause issues but its jsut precautin"
}
] |
[
{
"body": "<p>This is already quite tight, I like it.</p>\n\n<p>There is one big thing that jumps out:</p>\n\n<pre><code>validator = this;\nvar currentmsg =this;\n</code></pre>\n\n<p>You are using <code>this</code>, and <code>validator</code> and <code>currentmsg</code> all really pointing to <code>this</code>, that is making it harder than needed. Furthermore you escape scope by not using <code>var</code> for <code>validator</code>!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T17:10:31.577",
"Id": "70231",
"Score": "0",
"body": "Shall I delete `validator = this;\nvar currentmsg =this;` then mate?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T17:12:06.313",
"Id": "70232",
"Score": "0",
"body": "I think you should, and simply point to `this` in all cases."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T17:15:33.680",
"Id": "70233",
"Score": "0",
"body": "Please can you help me do it? I tried but can't figure out how to exactly do it. I am not really expert in JavaScript and had to get lot of help to get the above working"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T16:23:03.343",
"Id": "40976",
"ParentId": "40964",
"Score": "3"
}
},
{
"body": "<p>Spent a little hacking away at this to simplify the code. I wrote comments on changes inline the script, let me know if you have any questions</p>\n\n<p>Some thoughts on the changes. Notice that how I restructured your validators in the form</p>\n\n<pre><code>validatorName: {\n message: 'fail msg',\n classes: 'add classes to element on fail',\n test: function(){return true;}\n};\n</code></pre>\n\n<p>I've made some validators of my own and this is my personal preference for structuring validators and it allows us to due away with that weird <code>currentMessage</code> variable.</p>\n\n<p>I've also fixed a bunch of your linting errors - there were a lot of them so I didn't really comment on them. In the future run your code through <a href=\"http://jshint.com/\" rel=\"nofollow\">jshint</a> before posting it :)</p>\n\n<p>One last thought. There doesn't seem much of a reason for you to be writing this code as a class as its most likely a singleton and you're not writing the code on the prototype. I've resturctured your code to be a more conventional singleton rather than a class</p>\n\n<p>Here's the start of a counter proposal... Theres likely bugs but the code is a great deal simpler and uses less hackery than your original approach.</p>\n\n<pre><code>var FormValidation = function (form) {\n\n //Remove Gloabl variable and duplicate as mentioned by @konijn\n //replaces validator and currentMessage\n var self = {};\n\n //Counter proposal: I suggest you have an object of validators instead of\n // Dividing the parts of validators between messages/validators/this. Centeralize\n // all parts in a single object\n //Structure of a validator {test: fn(value, args) -> bool, message:str, classes:str}\n // Advantages: more explicit and you dont need that ugly current message variable\n self.validators = {\n required: {\n message: 'This field should not be empty',\n classes: 'reqerr',\n test : function (value) {\n return value.length > 0;\n }\n },\n email: {\n message: 'Please enter valid email',\n test : function (value) {\n //no need for a pattern var, this is explicit as it gets\n return /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$/.test(value); //comment what is a valid email or a link where you got the regexp\n }\n },\n number: {\n message: 'Please enter valid number',\n classes: 'valerr',\n test : function (value) {\n return /^\\d+$/.test(value); //simpler number regexp and ensures entire string is numbers not just start characters\n }\n },\n min: {\n message: 'This field length should be minimum ',\n test: function (value, args) {\n return value.length > 0 && value.length >= args[0];\n }\n },\n max: {\n message: 'This field length should not exceed ',\n test : function (value, args) {\n return value.length > 0 && value.length <= args[0];\n }\n },\n range: {\n message: 'This field length between ',\n test : function (value, args) {\n return value.length >= args[0] && value.length <= args[1];\n }\n }\n };\n\n var getArguments = function (type) {\n var validationtype = type.substring(0, type.indexOf(\"(\"));\n var args = type.substring(type.indexOf(\"(\") + 1, type.indexOf(\")\")).split(',');\n return {\n type : validationtype,\n argsList: args\n };\n };\n\n var displayErrors = function (element, validator) {\n element.className = validator.classes || 'error';\n var elErr = element.errorMsg;\n if (!element.errorMsg) {\n elErr = document.createElement(\"div\"); //dont set the id if you're not gonna use it\n element.parentNode.appendChild(elErr);\n element.errorMsg = elErr; //Warning this can make old ie very slow to unload\n }\n elErr.innerHTML = validator.message;\n };\n\n //This is your old validateField function modified to show the error if it fails in order to simplify the validate function\n var validateField = function (element, type) {\n //no need to make a var equal to a param\n var valid = true;\n var args, validator;\n //better to use a regexp here to get args\n if (/\\(.*\\)/.test(type)) {\n var result = getArguments(type);\n type = result.type;\n args = result.argsList;\n }\n validator = self.validators[type];\n if (validator) { //no need for the != null\n valid = validator.test(element.value, args);\n if (!valid) {\n //display errors\n displayErrors(element, validator);\n }\n }\n return valid;\n };\n\n self.validate = function (form) {\n var elements = form.elements;\n var status = true;\n var element, validate, types, result, //create variables outside the loop\n i, j;\n for (i = 0; i < elements.length; i++) {\n element = elements[i];\n validate = element.getAttribute('validate');\n if (!validate) {\n continue;\n }\n types = validate.split(' ');\n for (j = 0; j < types.length; j++) {\n if (types[i] && //not empty string and\n !validateField(element, types[j]) //if not valid\n ) {\n status = false;\n break;\n }\n }\n }\n return status;\n };\n\n self.init = function () {\n var forms = document.forms;\n for (var i = 0; i < forms.length; i++) {\n if (forms[i].getAttribute('validate') != null) {\n forms[i].onsubmit = function () {\n return self.validate(this); //this refers to the current form\n };\n }\n }\n };\n\n return self;\n};\n</code></pre>\n\n<p>Here's a demo of your code up and running: <a href=\"http://jsbin.com/ropi/1/edit\" rel=\"nofollow\">http://jsbin.com/ropi/1/edit</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T21:18:09.213",
"Id": "41001",
"ParentId": "40964",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41001",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T14:47:59.960",
"Id": "40964",
"Score": "6",
"Tags": [
"javascript",
"jquery",
"performance",
"html",
"validation"
],
"Title": "Simplifying this form validation script"
}
|
40964
|
<p>This code works, but since I'm just learning Haskell I'm wondering if it could have been done in a more idiomatic way.</p>
<p>The main function is called <code>tokenize</code>, and it uses helper functions called <code>tokenizeOne</code> and <code>tokenizeSeveral</code>.</p>
<p>Here is the code:</p>
<pre><code>tokenizeOne "" (' ':rest) = tokenizeOne "" rest
tokenizeOne str ('\\':ch:rest) = tokenizeOne (str ++ [ch]) rest
tokenizeOne x (' ':rest) = (x, rest)
tokenizeOne x "" = (x, "")
tokenizeOne x (ch:rest) = tokenizeOne (x ++ [ch]) rest
tokenizeSeveral x "" = x
tokenizeSeveral x str = let (token, rest) = tokenizeOne "" str in
tokenizeSeveral (x ++ [token]) rest
tokenize str = tokenizeSeveral [] str
</code></pre>
|
[] |
[
{
"body": "<p>Apart from general code layout I don't see much to improve - the only issue worth talking about is that you should never <em>ever</em> actually use something like <code>++ [ch]</code>. Your function is needlessly O(n²) for that reason alone. That might not sound like much here, but it is a good idea to shake this habit early.</p>\n\n<p>So let's talk about that a bit. Your options generally are:</p>\n\n<ol>\n<li><p>Find a library function that frees you from actually constructing the list yourself. But to be fair, for this examples I can't actually think of anything helpful myself.</p></li>\n<li><p>Use a data structure that copes better with it, such as <code>Seq</code> from <code>Data.Sequence</code>.</p></li>\n<li><p>First construct the list using just <code>(:)</code>, then <code>reverse</code> it at the end. That might seem inefficient, but given that <code>reverse</code> is only O(n), it will never actually increase algorithmic complexity.</p></li>\n<li><p>Rebuild your function so it constructs the list in the right order right away.</p></li>\n</ol>\n\n<p>Here is what things look like if we go for the last option:</p>\n\n<pre><code>import Control.Arrow ( first )\ntoken :: String -> (String, String)\ntoken \"\" = (\"\", \"\")\ntoken (' ' : cs) = (\"\", cs)\ntoken ('\\\\':c:cs) = first (c:) $ token cs\ntoken (c : cs) = first (c:) $ token cs\n</code></pre>\n\n<p>The key here is that we add the character <code>c</code> using <code>first (c:)</code> after the recursive call returns, and therefore to the <em>front</em> of the string.</p>\n\n<p>A notable advantage is that this version has better laziness properties:</p>\n\n<pre><code>*Main> head $ fst $ token ('t':undefined)\n't'\n</code></pre>\n\n<p>We know that the first character is <code>'t'</code> even without looking at the rest of the string, whereas your function always needs to finish a complete token before it can return. And as we are programming in Haskell, we often like our functions as lazy as possible.</p>\n\n<p>Finally, a matching <code>tokens</code> implementation:</p>\n\n<pre><code>tokens :: String -> [String]\ntokens str\n | null str' = []\n | otherwise = tok : tokens rest\n where str' = dropWhile (==' ') str\n (tok, rest) = token str'\n</code></pre>\n\n<p>This is again basically your version using direct list construction. Only difference is that we now deal with whitespace once per token, which I feel is slightly more elegant.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T17:51:27.040",
"Id": "41171",
"ParentId": "40968",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T15:17:35.457",
"Id": "40968",
"Score": "3",
"Tags": [
"haskell"
],
"Title": "Split a string on spaces, accounting for backslash as escape character, in Haskell"
}
|
40968
|
<p>I am using a combination of knockoutJS and jQuery. I have a number of jQuery plugins which perform particular re-usable functions, such as a numeric spinbox. </p>
<p>I have written a binding handler to allow me to bind an observable property to the spinbox, it looks like this:</p>
<pre><code>ko.bindingHandlers.spinbox = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var value = valueAccessor();
$(element).spinbox({
min: value.min === undefined ? -5 : ko.unwrap(value.min),
max: value.max === undefined ? 5 : ko.unwrap(value.max),
scale: value.scale === undefined ? 2 : ko.unwrap(value.scale),
step: value.step === undefined ? 0.1 : ko.unwrap(value.step),
bigStep: value.bigStep === undefined ? 0.5 : ko.unwrap(value.bigStep)
}).change(function() {
value.data(parseFloat($(this).val()));
});
},
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var value = valueAccessor();
var valueUnwrapped = ko.unwrap(value.data);
$(element).val(valueUnwrapped.toFixed(1));
}
};
</code></pre>
<p>and requires the binding to be set up something like:</p>
<pre><code>data-bind="spinbox: {data: myProperty, min: -100, max: 100}"
</code></pre>
<p>As you can see, I have used the object notation to sent multiple parameters to the binding (min, max etc) - this is similar to the syntax that the knockout <code>template</code> binding uses. However I am not sure this is a sensible way to do this. Should I have instead used <code>allBindings</code> and passed these along as separate values like:</p>
<pre><code>data-bind="spinbox: myProperty, min: -100, max: 100"
</code></pre>
<p>I am interested in opinions on complex knockout custom bindings.</p>
|
[] |
[
{
"body": "<p>I like your approach much better than using separate values.</p>\n\n<p>The code reads really well, I only have 1 minor suggestion.</p>\n\n<p>If you had a helper function like this:</p>\n\n<pre><code>function unwrapOrDefault( gift , defaultValue )\n{\n return gift === undefined ? defaultValue : ko.unwrap( gift ), \n}\n</code></pre>\n\n<p>then you could have </p>\n\n<pre><code> min: unwrapOrDefault(value.min, -5),\n max: unwrapOrDefault(value.max, 5 );\n scale: unwrapOrDefault(value.scale, 2);\n step: unwrapOrDefault(value.step, 0.1);\n bigStep: unwrapOrDefault(value.bigStep, 0.5);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T18:16:13.247",
"Id": "47166",
"ParentId": "40970",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "47166",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T15:34:06.207",
"Id": "40970",
"Score": "5",
"Tags": [
"javascript",
"jquery",
"knockout.js"
],
"Title": "knockout binding handler for custom components"
}
|
40970
|
<p>I have a class that listens to a file event constantly and reads that json file once it's created and makes of it a mail report and an excel file. </p>
<p>Now, I made the properties that are used for both these tasks static so I could determine their values once from the json and easily access them from all methods:</p>
<pre><code>public class Reporter
{
public static bool ShouldNotify = false;
public static string CSVFilePath;
private static string HTMLReport;
private string aSerializedObject;
...
public Reporter(string jsonFilePath)
{
//Determine static params values.
}
...
public string BuildHtmlReport() { ... }
public string WriteCsvFile() { ... }
}
</code></pre>
<p>There are a couple of things I feel that aren't best practices:</p>
<ol>
<li>Is it bad practice to combine static and non static params in the same non static class? Eventually it's a lot like using local and global variables but maybe I should encapsulate them.</li>
<li>Initializing all necessary params in the constructor - I always call the constructor with the jsonFilePath and don't use the default constructor.</li>
<li>I don't dispose the instance when finished since most properties are static and I don't really need to (functionality wise), should I?</li>
</ol>
|
[] |
[
{
"body": "<ol>\n<li><p>Not only is it bad practice, I'd say it's <em>horrible</em> practice. Save yourself, or others which will be dealing with your code, some future headache and use <strong>as few static variables as possible, preferably none!</strong> <em>(The reason why I say this is horrible could have something to do with the code I have to deal with at work, anyways, it is still not good practice...)</em></p>\n</li>\n<li><p>I'd say that not using the default constructor is perfectly fine, if all your <code>Reporter</code> objects needs a <code>jsonFilePath</code> then it's good to pass it in the constructor. Also, if this value shouldn't change then you can make it <code>readonly</code>.</p>\n</li>\n<li><p>If by disposing you mean "clearing it's state" or something, then no you don't need to. Garbage collector will take care of that. However, if you keep using the static variables then you might run into problems if you want to create another one.</p>\n</li>\n</ol>\n<h1>So, how to get rid of these static variables?</h1>\n<p>It's quite easy actually: <strong>Tell, don't ask</strong>.</p>\n<p>You haven't given much code here so I'll have to try to explain how it generally works:</p>\n<p>In your json class (which I will call <code>Foo</code> from now on since I don't know it's actual name), or whatever you have, instead of using <code>Reporter.ShouldNotify</code>, create an instance variable of the <code>Reporter</code> type. Then if you call/create your Foo class from your <code>Reporter</code> class, you <strong>tell</strong> the Foo object about it's <code>Reporter</code>. For example:</p>\n<pre><code>// In your reporter class\nFoo foo = new Foo();\nfoo.setReporter(this); // sorry for the Java naming conventions here, but I hope you get the idea\n</code></pre>\n<p>In Foo you can then use your <code>Reporter</code> object which you retreived from the <code>setReporter</code> method to use that particular object.</p>\n<p>Note that one can take the "Tell, don't ask" thing even further, but with the code in your question this is what I think you need for now.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T08:43:04.017",
"Id": "70349",
"Score": "0",
"body": "Thanks for the reply, I understand 2 and 3 now, but I still don't get **why** use as few static variables? how it affects whoever deals with the code later?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T08:56:09.237",
"Id": "70353",
"Score": "2",
"body": "@Moshisho Using static variables isn't object oriented, it makes your code less extensible. You won't be able to use multiple objects without them causing conflicts because of the static variables. All object instances share the same static variables."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T14:50:42.513",
"Id": "72297",
"Score": "1",
"body": "In C#, you can use events instead of something like `setReporter(this)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T02:59:37.620",
"Id": "434386",
"Score": "0",
"body": "for point no 3 GC wont take care of disposing static members."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T07:56:40.000",
"Id": "434418",
"Score": "0",
"body": "@JaydeepShil I'm not entirely familiar with the GC in C# but I doubt that is true. I don't see any reason why it wouldn't be able to deal with static members as well. Do you have a source for that claim?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T08:42:35.127",
"Id": "434424",
"Score": "0",
"body": "Static members are not store in Stack because those are not created using new() operator , they store in HEAP, GC only take care of disposing objects from managed resources."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-12T08:51:08.447",
"Id": "434425",
"Score": "0",
"body": "@JaydeepShil Read the end of this answer: https://stackoverflow.com/a/6600107/1310566 - *(Of course, if something changes the value of HasStatic.shared to reference a different instance, the first instance may become eligible for garbage collection.)* As long as the static variables are set, of course they will not be GC'ed as they are still reachable from the GC root, but as soon as you change the static variable to something for example `null`, the previous instance might be eligible for garbage collection (depending on if it is still accessible in other ways or not)."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T19:00:44.370",
"Id": "40989",
"ParentId": "40972",
"Score": "12"
}
},
{
"body": "<p>It's not so much a question of best practices, but rather a question of correctness. From my understanding of the problem you are trying to solve, using <code>static</code> variables for <code>CSVFilePath</code> and <code>HTMLReport</code> would be incorrect, since (I assume) their values depend on the <code>jsonFilePath</code> passed into the <code>Reporter</code>'s constructor. If you had multiple <code>Reporter</code>s, each monitoring a different JSON file, each <code>Reporter</code> would have a different <code>CSVFilePath</code> and <code>HTMLReport</code> — hence, they should be instance variables, not class variables.</p>\n\n<p>That said, instance methods rarely use class variables, unless the class variables are <code>const</code> or <code>readonly</code>. If your instance method does use a <code>static</code> variable, you should at least rethink what you are doing, and why.</p>\n\n<p>If you only expect to ever create one <code>Reporter</code> in your system, look into making <code>Reporter</code> a <a href=\"http://en.wikipedia.org/wiki/Singleton_pattern\" rel=\"nofollow\">singleton</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T22:54:06.243",
"Id": "41014",
"ParentId": "40972",
"Score": "4"
}
},
{
"body": "<p>Yes, that is a bad idea.</p>\n\n<p>Think of it this way.</p>\n\n<p>Say you want to process 10 items with your reporter. 5 should notify, 5 should not. So what do you do? </p>\n\n<pre><code>Reporter reporter = new Reporter();\nreporter.ShouldNotify = true;\n...\n...\nreporter.ShouldNotify = false;\n...\n...\n</code></pre>\n\n<p>Okay...so later on you have some more to do, swap em again? not only does this litter the code but it is something easy to forget to change it.</p>\n\n<p>Next, you have to make the task asyncronous...oops. no joy, people keep switching the flag on you! </p>\n\n<p>Any properties like this should be constructor based. In fact my personal favourite solution is to package such things either in an entirely different class or to at least pass in a parameterCollection</p>\n\n<p>so in short something like:</p>\n\n<pre><code>Reporter reporter = new Reporter(ReportTypeOneSettings);\n</code></pre>\n\n<p>and whats cool if you find yourself doing the same few configurations all the time you can instantiate multiple reporters super quickly.</p>\n\n<pre><code>Reporter reporterNotify = new Reporter(ReportTypeTwoSettings);\n</code></pre>\n\n<p>Now I can use the appropriate reporter with no fear of effecting anything else. \nalso, if I have to suddenly change something for ALL the reports all I have to do is swap out the settings.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T10:16:35.540",
"Id": "41053",
"ParentId": "40972",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "40989",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T15:55:02.813",
"Id": "40972",
"Score": "13",
"Tags": [
"c#",
"static"
],
"Title": "Non static class with static fields"
}
|
40972
|
<p>This is my first project I am doing in VB.NET, and also my first <strong>real</strong> programming project. There is sensitive data, so I am utilizing Microsoft's Encryption/Decryption class (<code>clsCrypt</code>).</p>
<p>For optimization, quality and best practice standards, which code the 'best' way to retrieve encrypted data from a MS SQL Server 2008 R2 db, and decrypt it, based on what the user enters in text boxes? (First Name, Last Name)</p>
<p>Note: I did not accommodate the text box values into the last code snippet.</p>
<pre><code>Public Class Form1
Dim eFirst As String
Dim eLast As String
Dim dFirst As String
Dim dLast As String
Public Sub Searchbtn_Click(sender As System.Object, e As System.EventArgs) Handles Searchbtn.Click
Me.DataGridView1.Show()
Dim SQLConnection As New SqlConnection("Data Source=SQLTEST_HR,4000\SQLEXPRESS;Integrated Security=True") 'Declare Connection String'
Dim SqlCommand As New SqlCommand 'Declare variable for SQL command'
Dim dt As New DataTable
Dim strKey As String = "Key1" 'encryption Key'
Dim clsEncrypt As clsCrypt 'Assigns a variable to clsCrypt class'
clsEncrypt = New clsCrypt(strKey) ' creates a new instance of the clsCrypt class'
eFirst = clsEncrypt.EncryptData(SearchFirsttxt.Text.Trim.ToUpper)
eLast = clsEncrypt.EncryptData(SearchLastTxt.Text.Trim.ToUpper)
SQLConnection.Open() 'Opens database Connection'
SqlCommand.Connection = SQLConnection 'Assigns connection to the command'
If SearchFirsttxt.Text = "" Then
SqlCommand.CommandText = "Select * FROM PARTICIPANT WHERE LAST_NM_TXT = '" & eLast & "';"
ElseIf SearchLastTxt.Text = "" Then
SqlCommand.CommandText = "Select * FROM PARTICIPANT WHERE FIRST_NM_TXT = '" & eFirst & "';"
ElseIf SearchFirsttxt.Text IsNot Nothing And SearchLastTxt.Text IsNot Nothing Then
SqlCommand.CommandText = "Select * FROM PARTICIPANT WHERE FIRST_NM_TXT = '" & eFirst & "' and LAST_NM_TXT = '" & eLast & "';"
Else
SqlCommand.CommandText = "Select * FROM PARTICIPANT;"
End If
'SQL Command returns rows where values in database and textboxes are equal'
Dim myAdapter As New SqlDataAdapter(SqlCommand) 'holds the data'
myAdapter.Fill(dt) 'datatable that is populated into the holder (DataAdapter)'
DataGridView1.DataSource = dt 'Assigns source of information to the gridview (DataTable)'
Try
For i As Integer = 0 To dt.Rows.Count - 1
dt.Rows(i)("FIRST_NM_TXT") = clsEncrypt.DecryptData(dt.Rows(i)("FIRST_NM_TXT"))
dt.Rows(i)("LAST_NM_TXT") = clsEncrypt.DecryptData(dt.Rows(i)("LAST_NM_TXT"))
Next
Catch ex As Exception
MessageBox.Show("Either the first name or last name did not match. Please check your spelling.")
End Try
</code></pre>
<p>OR this way</p>
<pre><code> Me.DataGridView1.Show()
Dim SQLConnection As New SqlConnection("Data Source=SQLTEST_HR,4000\SQLEXPRESS;Integrated Security=True") 'Declare Connection String
Dim cmd As New SqlCommand 'Declare variable for SQL command
Dim dt As New DataTable
Dim strKey As String = "Key1" 'encryption Key
Dim clsEncrypt As clsCrypt 'Assigns a variable to clsCrypt class
clsEncrypt = New clsCrypt(strKey) ' creates a new isntance of the clsCrypt class
Dim eFirst As String
Dim eLast As String
eFirst = clsEncrypt.EncryptData(SearchFirsttxt.Text.Trim.ToUpper)
eLast = clsEncrypt.EncryptData(SearchLasttxt.Text.Trim.ToUpper)
SQLConnection.Open() 'Opens database Connection
cmd.Connection = SQLConnection 'Assigns connection to the command
If SearchFirsttxt.Text = "" AndAlso SearchLasttxt.Text = "" Then
' Both emtpy so search everything'
cmd.CommandText = "SELECT * FROM PARTICIPANT;"
ElseIf SearchFirsttxt.Text = "" AndAlso SearchLasttxt.Text <> "" Then
' Search the last only if you have a last and not a first'
cmd.CommandText = "Select * FROM Participant Where LAST_NM_TXT = @searchLast"
cmd.Parameters.AddWithValue("@searchLast", eLast)
ElseIf SearchLasttxt.Text = "" AndAlso SearchFirsttxt.Text <> "" Then
' Search the first only if you have a first and not a last'
cmd.CommandText = "Select * FROM Participant WHERE FIRST_NM_TXT = @searchFirst"
cmd.Parameters.AddWithValue("@searchFirst", eFirst)
Else
' Both filled so search exactly (not sure if this is needed)'
cmd.CommandText = "Select * FROM Participant " & _
"WHERE FIRST_NM_TXT = @searchFirst " & _
"OR LAST_NM_TXT = @searchLast"
cmd.Parameters.AddWithValue("@searchFirst", eFirst)
cmd.Parameters.AddWithValue("@searchLast", eLast)
End If
Dim myAdapter As New SqlDataAdapter(cmd) 'holds the data
Dim ds As DataSet = New DataSet()
myAdapter.Fill(ds)
dt.Load(ds.CreateDataReader())
DataGridView1.DataSource = dt 'Assigns source of information to the gridview (DataTable)
'DECRYPTS ENCRYPTED DATA IN SPECIFICIED DT ROWS IN THE DGV1
Try
For i As Integer = 0 To dt.Rows.Count - 1
dt.Rows(i)("FIRST_NM_TXT") = clsEncrypt.DecryptData(dt.Rows(i)("FIRST_NM_TXT"))
dt.Rows(i)("LAST_NM_TXT") = clsEncrypt.DecryptData(dt.Rows(i)("LAST_NM_TXT"))
Next
Catch ex As Exception
MessageBox.Show("Either the first name or last name did not match. Please check your spelling.")
End Try
</code></pre>
<p>OR --</p>
<pre><code>Public Function GetDetails() As DataSet
Dim conn As New SqlConnection("Data Source=SQLTEST_HR,4000\SQLEXPRESS;Integrated Security=True")
Dim strKey As String = "MarkKey" 'encryption Key
Dim clsEncrypt As clsCrypt 'Assigns a variable to clsCrypt class
clsEncrypt = New clsCrypt(strKey) ' creates a new isntance of the clsCrypt class
Try
conn.Open()
Dim SqlCmd As New SqlCommand("Select * From Participant", conn)
Dim myAdapt As New SqlDataAdapter(SqlCmd)
Dim DSEmp As New DataSet()
myAdapt.Fill(DSEmp)
Dim DTEmp As New DataTable()
DTEmp.Load(DSEmp.CreateDataReader())
DataGridView1.DataSource = DTEmp
For i As Integer = 0 To DSEmp.Tables(0).Rows.Count - 1
DSEmp.Tables(0).Rows(i)("FIRST_NM_TXT") = clsEncrypt.DecryptData(DSEmp.Tables(0).Rows(i)("FIRST_NM_TXT"))
DSEmp.Tables(0).Rows(i)("LAST_NM_TXT") = clsEncrypt.DecryptData(DSEmp.Tables(0).Rows(i)("LAST_NM_TXT"))
Next
Return DSEmp
Catch ex As Exception
Throw (ex)
Finally
conn.Close()
End Try
End Function
Private Sub LoadReport()
Try
Dim ds As New DataSet
ds = GetDetails()
Dim rds As ReportDataSource = New ReportDataSource("DataSet1", ds.Tables(0))
rv1.LocalReport.DataSources.Clear()
rv1.LocalReport.DataSources.Add(rds)
rv1.RefreshReport()
Catch ex As Exception
End Try
End Sub
Private Sub Form2_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
LoadReport()
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T19:17:15.037",
"Id": "71324",
"Score": "0",
"body": "@Mark LaREZZA: In short, are you asking the best way to encrypt data from your app to SQL Server?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T19:19:22.763",
"Id": "71325",
"Score": "0",
"body": "@DominicZukiewicz No, sir, I am asking which way is the fastest, cleanest, most non-repetitive, best-practice. I have also heard of storing the connection string in the config file? Also, my code structure - does it make sense / am I coding efficiently?"
}
] |
[
{
"body": "<p>Okay, best practices... </p>\n\n<p><strong>Data Access</strong></p>\n\n<p>Never do data access directly in the UI. Have a separate class file to do this. Best practice would suggest creating an interface for each 'aggregate root' (collection of classes that act as an integral whole). that you want to retrieve, then a subclass that inherits from the interface. </p>\n\n<p>To be honest, and for simplicity, you can use something like the Gateway pattern. This is like a central place to do all database work. Its fine to start with, but may get cluttered depending on how complex your Data Access code will get:</p>\n\n<p>Here is a typical pattern to separate the DB from the UI:</p>\n\n<p>(Note - I don't work with VB.NET, so apologies for incorrect statements)</p>\n\n<pre><code>Public Interface IDbGateway \n Function SearchForParticipant(firstName As String, surname As String) As IQueryable Of(Participant)\n Function GetParticipant(id As Int32) As Participant \n Function AddOrUpdateParticipant(part As Participant) As Participant \n Sub Delete(part as Participant);\nEnd Interface\n\nPublic Class SqlDbGateway\n Implements IDbGateway\n\n Dim connectionString as String = null\n\n ' Your most commonly used way\n Public Sub New()\n Me.New \"MyConnectionStringKey\"\n\n ' In your App.config add this:\n ' <configuration>\n ' <connectionStrings>\n ' <add name=\"MyConnectionStringKey\" connectionString=\"Data Source.......\"/>\n ' </connectionStrings>\n ' </configuration>\n End New\n\n Public Sub New (connectionStringKey as String)\n Me.connectionString = ConfigurationManager.ConnectionStrings.Get(connectionStringKey).ConnectionString;\n End New\n\n ' Implement interface here\nEnd Class\n</code></pre>\n\n<p>Your UI could use a Dependency Injection framework, but you can simply go with (again, tactically)..</p>\n\n<pre><code>Public Class MyUIForm Inherits Form\n Dim dataAccess as IDbGateway = new SqlDbGateway();\nEnd Class\n</code></pre>\n\n<p>Okay, step back - What have we achieved?</p>\n\n<ol>\n<li>You can now develop and test the data access layer in isolation. </li>\n<li>If your DB environment is different in production, than on your development (which is almost always the case), then you just supply a new App.config file.</li>\n<li>The UI only sees what the <code>IDbGateway</code> interface is exposing, not what back end is hitting.</li>\n<li>You have also (partly) removed the knowledge of the data source (XML, CSV, Oracle etc)</li>\n</ol>\n\n<p>So next step is now removing the dependency of <code>DataTable</code>s. You can happily use <code>DataTables</code> in the SqlDataAccess class, but convert the rows to <code>Participant</code> classes before returning them. Therefore the UI only sees concrete classes, and DataGrid's will happily binding to <code>IEnumerable(Of T)</code> classes.</p>\n\n<p><strong>DB Performance</strong></p>\n\n<p>Never do <code>SELECT * FROM <Table></code> in a production application. Its fine for SSMS in a development environment to get a look over everything. In a production app, you should only pull out the columns you want, rather than everything. If a DBA decided to change this schema behind your application, you will start pulling in more columns, which could be dangerous, especially if there's something like 'IS_BLACK_LISTED', 'HAS_CRIMINAL_RECORD' .. etc.</p>\n\n<p>Using T-SQL like you are is fine, as its parameterised. But .. (as you'll see in encryption), if you are super paranoid, you should use Stored Procedures, rather than revealing the T-SQL you are querying with.\nThe barrier created by the <code>IDbGateway</code> ensures the UI doesn't have to care where it comes from, it just wants the data back. This pattern is called 'Inversion Of Control'.</p>\n\n<p><strong>Encryption</strong></p>\n\n<p>I need to know more details about what you are doing, but lets review what is going on:</p>\n\n<ol>\n<li>A user types text into a UI (unencrypted)</li>\n<li>The UI encrypts this text (encrypted)</li>\n<li>Send data to the database (unencrypted transport)</li>\n<li>Data returns from the DB (unencrypted transport)</li>\n<li>User sees results from DB (unencrypted)</li>\n</ol>\n\n<p>The UI encrypts it, but there is no other encryption going on as far as I can gather?</p>\n\n<p>So simplify encryption..</p>\n\n<ol>\n<li><p>Password fields can stop the UI revealing sensitive data.</p></li>\n<li><p>Use the <a href=\"http://msdn.microsoft.com/en-us/library/system.security.securestring%28v=vs.110%29.aspx\" rel=\"nofollow\">SecureString</a> class to encrypt at UI level. It isn't the most friendly of classes, as you have to retrieve items character by character. But if you want secure - you've got it and its relatively easy to use, rather than digging into the Crypto32 API. </p></li>\n<li><p>For database connections, you can install SSL certificates and used the \"Encrypt=true\". An <a href=\"http://support.microsoft.com/kb/316898\" rel=\"nofollow\">MSDN article is here</a>. This makes code even cleaner. Also use stored procedures to not reveal what the app is doing with the DB.</p></li>\n<li><p>See (3)</p></li>\n<li><p>User sees results.. 4 out of 5 isn't bad ;-)</p></li>\n</ol>\n\n<p>--</p>\n\n<p>Thats all I can say about it now. In summary:</p>\n\n<ol>\n<li>Separate data access from UI and business logic</li>\n<li>Only retrieve what you need, rather than everything </li>\n<li>Use a DTO (Data Transfer Object) to convert from the data sources (tables) to the UI layer. There are tools that can do this for you like Entity Framework and NHibernate.</li>\n<li>Look at all encryption options. How secure do you want this to be? To what extent should you go to (i.e. obfuscate the application code? SSL the DB connections? Encrypt the DB?)</li>\n</ol>\n\n<p>Raise another StackOverflow question for (4) and you should get a more helpful answer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T13:52:11.563",
"Id": "71429",
"Score": "0",
"body": "Thanks for the comments, Dominic. About the Encryption. I am using the MS encrypted class.[link](http://msdn.microsoft.com/en-us/library/ms172831.aspx). You are correct on the assumption that the Data is entered as plain text, encrypted, retrieved from the Db as encrypted and then I decrypt in the DataTable to display in DGV. As for the stored procedure aspect - this is a small system used to track people sending some of their income to stocks. Nothing dealing with SSNs or anything, and the data is encrypted to prevent DBAs from seeing it. Why is a stored procedure better than a function?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T13:56:05.763",
"Id": "71430",
"Score": "0",
"body": "@MarkLaREZZA: So you encrypt at the UI, and all data is stored pre-encrypted in the DB? How would you administer the database if all the data is encrypted? Generally, the DB is far behind a corporate firewall and shouldn't have open access. Only specific user accounts would be granted access."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T13:57:11.727",
"Id": "71431",
"Score": "0",
"body": "All data HAS to be encrypted in the DB. That's what the users have demanded. I am going to try and use indexes to help with navigation/querying data."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T14:04:21.450",
"Id": "71434",
"Score": "0",
"body": "Wait... Here's 3 scenarios. (1) No Encryption: I hack in and copied your database to my machine. Yey! (2) DB Encryption : I hack in and copy the DB to my machine. I can't view it as the DB server is the only server that can read it. D'OH! (3) Manual Encryption: Only your app can view the data. You cannot read the data in the DB to troubleshoot it. You must also share the password with other applications. And it must be stored securely (not a \"MyPassword\") as it can be decompiled. ARGH!! The only item I've ever had to encrypt pre-database, even on encrypted DBs is the password column."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T14:19:11.030",
"Id": "71440",
"Score": "0",
"body": "Well the trouble shooting is going to have to be the end user's problem. (I will give them ALL the tools to update/delete as necessary). Other than that, there is no work-around. We tossed around the idea of TDE (Transparent Data Encryption), however the DBAs must create the DataBase, however they are not allowed to see the data, at any point in time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T18:16:18.513",
"Id": "71474",
"Score": "0",
"body": "Odd.... I've worked in investment banks and retail banks before, and I've always had access to the data freeform. Your employment contract usually stipulates you cannot disclose or export the data, as it will lead to prosecution. Sometimes users don't know what they want; they want encryption. That's not a functional requirement, that's a technical specification and end-users should not have influence over these decisions. If your password is discovered, your entire database needs re-encrypting! I would raise it as a critical risk. Open ILDASM.exe and you'll see the password in your code!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T18:28:07.917",
"Id": "71476",
"Score": "0",
"body": "Well, what are your thoughts on this project: It's a private company, it's for VERY high executives, their names/address/ anything to identify them is to be encrypted. No one (not even me) should be able to see the encrypted data (only the 2 end users are entitled to). I'm not sure what other way this is possible. Keep in mind the DBA's create the Databases/instances/tables"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T19:53:51.430",
"Id": "71489",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/13025/discussion-between-dominic-zukiewicz-and-mark-larezza)"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T09:45:21.793",
"Id": "41542",
"ParentId": "40973",
"Score": "2"
}
},
{
"body": "<p>Just make sure you NEVER do something like the following line:</p>\n\n<pre><code>SqlCommand.CommandText = \"Select * FROM PARTICIPANT WHERE FIRST_NM_TXT = '\" & eFirst & \"';\"\n</code></pre>\n\n<p>This would be VERY easy to use SQL Injection to retrieve all the data you have in your DB. And once an attacker has that they will run decryption algorithms on your data until they crack it. </p>\n\n<p>Use parameterized queries like you have done in the second example you showed to protect yourself from SQL Injection.</p>\n\n<pre><code> cmd.CommandText = \"Select * FROM Participant WHERE FIRST_NM_TXT = @searchFirst\"\n cmd.Parameters.AddWithValue(\"@searchFirst\", eFirst)\n</code></pre>\n\n<p>This way your input from your users will be sanitized and SQL Injection will be prevented. Hurray!</p>\n\n<p>P.S. I would store your ConnectionString in you web or app config file so that you can change you DB connection <strong>without recompiling</strong> your application. This will come in handy if your application is deployed and you just want to change the which database the app is pointing at but don't want to have to change the code, recompile, and redeploy.</p>\n\n<p>Now you can just edit the config file on the server and WA-LA new DB connection! This will also make it easier to add multiple connections (Test and Production) and pull the correct DB connection depending on some environment variable or for example if you compiled your assemblies to Debug or Release.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T21:16:54.873",
"Id": "72838",
"Score": "0",
"body": "Thanks buddy! We need to get together and discuss Team City sometime!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T16:17:19.133",
"Id": "42317",
"ParentId": "40973",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "41542",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T16:07:28.703",
"Id": "40973",
"Score": "3",
"Tags": [
"sql",
"sql-server",
"vb.net",
"cryptography"
],
"Title": "Using SQL with encryption"
}
|
40973
|
<p>I think my current structure is way too repetitive. I feel like I must be missing something that would easily make this sign up wizard work far better.</p>
<pre><code> <ol class="registerMeter">
<li class="progress-point" ng-click="wiz('step1')" ng-class="{active: step1.active, done: step1.done, todo: step1.todo}">Step 1</li>
<li class="progress-point" ng-click="wiz('step2')" ng-class="{active: step2.active, done: step2.done, todo: step2.todo}">Step 2</li>
<li class="progress-point" ng-click="wiz('step3')" ng-class="{active: step3.active, done: step3.done, todo: step3.todo}">Step 3</li>
</ol>
<section class="row formMain" ng-switch="step">
<section class="row" ng-switch-default>
<form ng-submit="registerSubmit()">
</form>
</section>
<section ng-switch-when="step2">
<form>
</form>
</section>
<section ng-switch-when="step3">
<form>
</form>
</section>
</section>
app.controller('registerCtrl', function($scope, $http, $location, FlashService){
$scope.step1 = {active: true, done:false, todo: false};
$scope.step2 = {active: false, done:false, todo: true};
$scope.step3 = {active: false, done:false, todo: true};
$scope.wiz = function(step){
$scope.step = step;
switch (step) {
case 'step1':
$scope.step1 = {active: true, done:false, todo: false};
$scope.step2.active = false;
$scope.step3.active = false;
$scope.step2.todo = true;
$scope.step3.todo = true;
break;
case 'step2':
$scope.step1.active = false;
$scope.step1.todo = true;
$scope.step2 = {active: true, done:false, todo: false};
$scope.step3.active = false;
$scope.step3.active = false;
break;
case 'step3':
$scope.step1.active = false;
$scope.step2.active = false;
$scope.step1.todo = true;
$scope.step2.todo = true;
$scope.step3 = {active: true, done:false, todo: false};
break
default:
$scope.step1 = {active: true, done:false, todo: false};
$scope.step2 = {active: false, done:false, todo: true};
$scope.step3 = {active: false, done:false, todo: true};
}
}
$scope.registerSubmit = function(){
$http.post()
.success(function(data, status, headers, config){
$scope.step = 'step2';
$scope.step1 = {active: false, done:true , todo:false}
$scope.step2.active = true;
if (data.msg !='') {
$scope.msgs.push(data.msg);
} else {
$scope.errors.push(data.error);
}
}).error(function(data, status){
FlashService.show(response.flash);
$scope.errors.push(status);
})
};
});
</code></pre>
<p>I'm worried that the <code>switch</code> and <code>ngclass</code> statements are way more than I need. Is there a simpler way to accomplish this? This just doesn't feel DRY at all.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T01:29:01.870",
"Id": "70295",
"Score": "0",
"body": "You have a lot of booleans Are they all required? Could you instead check if values the user enters in the wizard exist (not null) instead of three boolean states?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T03:28:09.587",
"Id": "70308",
"Score": "0",
"body": "@Sukima That's interesting. I could check if the object from the form is user interacted yet. That would only work one way though and wouldn't allow a user to go back a step. It's a long sign up form."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T14:08:48.173",
"Id": "70396",
"Score": "0",
"body": "In that case I think it would be better to wrap your boolean logic into a finite state machine object which manages the state the user is in. A little abstraction can help with readability."
}
] |
[
{
"body": "<p>You can make this DRYer if you can assume that : </p>\n\n<ul>\n<li>You keep naming each step <code>stepx</code></li>\n<li>No other variables in <code>$scope</code> start with <code>step</code></li>\n</ul>\n\n<p>In that case you could use a function that sets in a first step the right scope active and then the other steps inactive:</p>\n\n<pre><code>function updateScopeSteps( $scope , step )\n{\n //Default to step1\n step = step || 'step1';\n //Set step\n $scope.step = step;\n //Activate step\n $scope[ step ] = {active: true, done:false, todo: false};\n //De-activate all other steps\n for( var name in $scope ){\n if( name.substring(0,4) == 'step' && name != step ){\n $scope[name].active = false;\n $scope[name].todo = true;\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T17:39:54.240",
"Id": "41088",
"ParentId": "40974",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T16:11:09.277",
"Id": "40974",
"Score": "3",
"Tags": [
"javascript",
"angular.js"
],
"Title": "Sign-up wizard structure seems too repetitive"
}
|
40974
|
<p>The code below finds the index of the lowest unique integer on each line of the file. The numbering starts at 1, and when there's no unique value, the <code>0</code> should be output.</p>
<p>The sample input looks like this:</p>
<pre><code>3 3 9 1 6 5 8 1 5 3
9 2 9 9 1 8 8 8 2 1 1
</code></pre>
<p>And the sample output is this:</p>
<pre><code>5
0
</code></pre>
<p>I wonder if this code can be simplified or made more elegant and idiomatic in any way. It's also interesting to me, could I get by w/o the <code>IntMap</code> and solve the problem with i.e. lists beautifully.</p>
<pre><code>module Main where
import Prelude hiding (filter)
import Control.Applicative ((<$>))
import Data.IntMap (IntMap, alter, empty, filter, findMin, fromList, size)
import System.Environment
counts :: [(Int, Int)] -> IntMap [Int]
counts = foldl f empty
where f m (i,v) = alter f' v m
where f' :: Maybe [Int] -> Maybe [Int]
f' (Just is) = Just (i:is)
f' (Nothing) = Just [i]
g :: IntMap [Int] -> Int
g a = i
where rs = filter ((== 1) . length) a
h m | size m == 0 = fromList [(0, [0])]
| otherwise = m
(_, [i]) = findMin $ h rs
minUnique :: [Int] -> Int
minUnique l = g r
where r = counts (zip [1..] l)
main =
head <$> getArgs >>= readFile >>=
putStrLn . unlines . map (show . minUnique . map read . words) . lines
</code></pre>
|
[] |
[
{
"body": "<p>First off, your usage of <code>alter</code> can easily be replaced by <code>insertWith</code>:</p>\n\n<pre><code>counts :: [(Int, Int)] -> IntMap [Int]\ncounts = foldr f empty\n where f (i,v) = insertWith (const (i:)) v [i]\n</code></pre>\n\n<p>You could also use <code>fromListWith</code>, which is neater but less efficient due to the need to concatenate lists:</p>\n\n<pre><code>counts :: [(Int, Int)] -> IntMap [Int]\ncounts = fromListWith (flip (++)) . map (\\(i,v) -> (v,[i]))\n</code></pre>\n\n<p>Second, you could shorten <code>g</code> quite a bit as well using a view:</p>\n\n<pre><code>g a = case minView $ filter ((== 1) . length) a of\n Nothing -> 0\n Just ([i],_) -> i\n</code></pre>\n\n<p>Which is also probably slightly less efficient, as it will construct at least a thunk for the rest of the <code>IntMap</code>.</p>\n\n<p>Concerning different approaches - you could make a recursive function that removes all duplicates:</p>\n\n<pre><code>import Data.List\nimport Data.Ord\n\ndedup :: [(Int,Int)] -> [(Int,Int)]\ndedup [] = []\ndedup ((i,v):ps)\n | null dups = (i,v):dedup ps\n | otherwise = dedup ndups\n where (dups, ndups) = partition ((==v) . snd) ps\n\nminUnique :: [Int] -> Int\nminUnique l\n | null ddups = 0\n | otherwise = fst $ minimumBy (comparing snd) $ ddups\n where ddups = dedup $ zip [1..] l\n</code></pre>\n\n<p>Once more this trades for a bit of efficiency, as the traversal in <code>partition</code> makes it O(n²). Not sure whether that can be helped though without involving more complex data structures.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T20:05:09.457",
"Id": "40998",
"ParentId": "40977",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "40998",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T16:33:04.057",
"Id": "40977",
"Score": "5",
"Tags": [
"haskell"
],
"Title": "Find index of lowest unique integer in each line of the file"
}
|
40977
|
<p>I just wrote this and don't like how bulky it is, also given the fact I will have to add at least another <code>if</code> statement.</p>
<p>I was going to switch it to a case statement but wanted to check if there were even better ways to reduce the clutter.</p>
<pre><code>string emailLetterPath = Server.MapPath("~/emails/rejected.htm");
if (jobApplicantAndJob.Jobs.Title == "Store Sales Manager" || jobApplicantAndJob.Jobs.Title == "Sales Representative")
{
emailLetterPath = Server.MapPath("~/emails/TC1RejectedP3.htm");
}
if (jobApplicantAndJob.Jobs.Title == "Outside Sales Professional")
{
emailLetterPath = Server.MapPath("~/emails/TC2RejectedP3.htm");
}
</code></pre>
<p>The default option should be the <code>rejected.htm</code>.</p>
|
[] |
[
{
"body": "<blockquote>\n <p>I was going to switch it to a case statement but wanted to check if there were even better ways to reduce the clutter.</p>\n</blockquote>\n\n<p>You could load the mappings from job titles to emails into a (static) dictionary, and then do a dictionary look-up (using the default value if it's not in the dictionary).</p>\n\n<p>The <code>Dictionary<string,string></code> can be <a href=\"http://msdn.microsoft.com/en-us/library/bb531208.aspx\">initialized with a collection initializer</a>.</p>\n\n<p>Using a (data-driven) dictionary instead of a (hard-coded) switch statement has the additional benefit that users can configure/maintain the behaviour by editing a configuration file (e.g. a tab-delimited 'CSV file' of title/email pairs) or database, instead of editing code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T04:26:43.027",
"Id": "70561",
"Score": "0",
"body": "I'm pleased to see I'm not the only person who feels that the generic term CSV should include tab-separated files."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T18:20:26.450",
"Id": "40988",
"ParentId": "40982",
"Score": "7"
}
},
{
"body": "<p>I'd at least shift it into its own function and then reorder the clauses:</p>\n\n<pre><code>string getEmailBaseFileForJobTitle(string title) { \n if (title == \"Outside Sales Professional\") \n return \"TC2RejectedP3\";\n if (title == \"Store Sales Manager\" || title == \"Sales Representative\")\n return \"TC1RejectedP3\";\n return \"rejected\";\n}\n</code></pre>\n\n<p>Then your function will look like:</p>\n\n<pre><code>string emailLetterPath = Server.MapPath(\"~/emails/\" +\n getEmailBaseFileForJobTitle(jobApplicantAndJob.Jobs.Title) +\n \".htm\");\n</code></pre>\n\n<p>You could move the more into the function too if you really wanted. </p>\n\n<p>Another option would be to make it a member function on the JobApplicantAndJob class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T16:17:28.827",
"Id": "70424",
"Score": "0",
"body": "That's a fairly overkill method name, and not even PascalCase."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T01:06:54.417",
"Id": "41020",
"ParentId": "40982",
"Score": "4"
}
},
{
"body": "<p>I would go with a rule generation solution if this is liable to grow. </p>\n\n<pre><code>EmailRules _rules;\nstring emailLetterPath = GetEmailPath();\nstring GetEmailPath()\n{\n string path = rejectedPath;\n EmailRule rule = _rules.GetActingRule(path);\n\n if(rule != null) path = rule.Path;\n\n return path; \n}\n\n\n\nvoid CreateEmailRules()\n{\n _rules = new EmailRulesImpl();\n _rules.add(new ManagerOrRepresentative(),TC1Path);\n _rules.add(new OutsideSales(),TC2Path);\n}\n</code></pre>\n\n<p>This is just a primer, allows the separation of rule creation from the actual parsing code. Does allow the extensibility of making smaller rules that you could combine to make aggregate rules etc...</p>\n\n<p>Finally it means you can make rules sets by instantiating different rule managers depending on situations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T15:02:02.330",
"Id": "72301",
"Score": "0",
"body": "For a simple, short method like the one in the quesion, this seems way too overengineered to me. YAGNI."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T10:32:47.047",
"Id": "41055",
"ParentId": "40982",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "40988",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T17:57:07.223",
"Id": "40982",
"Score": "3",
"Tags": [
"c#",
"asp.net"
],
"Title": "Job applicant email system"
}
|
40982
|
<p>I have the following code and it's taking quite some time to run. I'm getting an <code>Out of Memory Exception</code> due to the high volume of answers there are. Is there any way I could speed it up?</p>
<pre><code>var controlStrings = answerControlStrings.Where(a => a.ControlN.Substring(a.ControlN.IndexOf('_') + 1, a.ControlN.Length - a.ControlN.IndexOf('_') - 1).Equals(newAnswer.QVar, StringComparison.InvariantCultureIgnoreCase));
if (controlStrings.Count() > 0)
{
newAnswer.CatiControlStrings.Add("en", controlStrings.Where(c => c.CultureN.Contains("cati") && c.CultureN.Contains("en")).ToList());
newAnswer.WebControlStrings.Add("en", controlStrings.Where(c => c.CultureN.Contains("web") && c.CultureN.Contains("en")).ToList());
newAnswer.CatiControlStrings.Add("es", controlStrings.Where(c => c.CultureN.Contains("cati") && c.CultureN.Contains("es")).ToList());
newAnswer.WebControlStrings.Add("es", controlStrings.Where(c => c.CultureN.Contains("web") && c.CultureN.Contains("es")).ToList());
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T18:29:31.030",
"Id": "70243",
"Score": "0",
"body": "Is this called in some kind of loop? How is this data used? It would be helpful if you gave us more context here. How many answers are there? Please give us more information!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T21:46:52.560",
"Id": "70270",
"Score": "0",
"body": "If you posted more code, including what type `answerControlStrings` is, including how and/or how often this is called, including which statement is executing if/when an exception is thrown, and including what \"high volume of answers there are\" means more exactly, then the answer[s] might be more helpful."
}
] |
[
{
"body": "<p>You're iterating through controlStrings 4 times (because you have 4 Where clauses).</p>\n\n<p>It might be better to rewrite this as a for loop:</p>\n\n<pre><code>foreach (var c in controlStrings)\n{\n var cultureN = c.CultureN;\n\n if (cultureN.Contains(\"cati\") && cultureN.Contains(\"en\"))\n ... add c to CatiControlStrings;\n\n if (cultureN.Contains(\"web\") && cultureN.Contains(\"en\"))\n ... add c to WebControlStrings;\n\n ... and the same for Spanish.\n}\n</code></pre>\n\n<p>You can also call Contains fewer times:</p>\n\n<pre><code>foreach (var c in controlStrings)\n{\n var cultureN = c.CultureN;\n\n bool cati = cultureN.Contains(\"cati\");\n bool web = cultureN.Contains(\"web\");\n if (!cati && !web)\n continue;\n bool en = cultureN.Contains(\"en\");\n bool es = cultureN.Contains(\"es\");\n\n if (cati && en)\n ... add c to CatiControlStrings;\n\n if (web && en)\n ... add c to WebControlStrings;\n\n ... and the same for Spanish.\n}\n</code></pre>\n\n<p>Also your Count() statement may be expensive and unnecessary.</p>\n\n<p>You're calculating IndexOf twice for every string.</p>\n\n<p>And you're creating a new Substring for every string you test. Instead of creating a substring, use one of the overloads of String.Compare which lets you compare substrings. </p>\n\n<p>Alternatively something like this might be better (because it doesn't use Substring and is simpler than using IndexOf with Compare:</p>\n\n<pre><code>string compareWith = \"_\" + newAnswer.QVar;\nvar controlStrings = answerControlStrings.Where(a => a.ControlN.EndsWith(compareWith,\n StringComparison.InvariantCultureIgnoreCase));\n</code></pre>\n\n<p><a href=\"http://philosopherdeveloper.wordpress.com/2011/02/16/garbage-garbage-everywhere/\" rel=\"nofollow noreferrer\">Garbage, garbage, everywhere</a> says that using a <code>Where</code> will generate a lot of temporary objects. I don't understand why you're getting \"out of memory\" sometimes, but rewriting even your first statement to use less Linq might help (or at least make the cause your \"out of memory\" exception clearer).</p>\n\n<pre><code>foreach (var a in controlStrings)\n{\n if (a.ControlN.EndsWith(compareWith, StringComparison.InvariantCultureIgnoreCase))\n {\n // the add-to-dictionary code above\n }\n}\n</code></pre>\n\n<p>Reading <a href=\"https://stackoverflow.com/q/7133013/49942\">C# Does Lambda => generate garbage?</a> (including comments to the accepted answer), Linq generates temporary garbage.</p>\n\n<p>I have a suspicion, after reading <a href=\"http://msdn.microsoft.com/en-us/library/ee851764(v=vs.110).aspx\" rel=\"nofollow noreferrer\">Garbage Collection and Performance</a>, that maybe the framework doesn't garbage-collect before throwing 'out of memory'; my guess is that:</p>\n\n<ul>\n<li>Garbage collection runs when it feels like it</li>\n<li>Garbage collection runs on a separate thread, without pausing/blocking your threads</li>\n<li>Unlike Java, C# will/may not stop to garbage collect immediately before/instead of throwing 'out of memory exception'</li>\n<li>Therefore if your thread generates too much garbage too fast (i.e. faster than the garbage is collected), it may throw.</li>\n</ul>\n\n<p>An alternative theory is that garbage remains uncollectable inside the lambda instances until your <code>var controlStrings</code> goes out of scope.</p>\n\n<p>Simplifying your code to use less Linq and no Substring instances should produce less garbage, which might help to avoid throwing the exception.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T11:49:05.957",
"Id": "70374",
"Score": "0",
"body": "If you nest the if's with 'cultureN.Contains(\"en\")' at the top you cut out one of the contains calls."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T12:03:16.037",
"Id": "70376",
"Score": "0",
"body": "Thank you: I edited to remove several of the Contains calls."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T19:44:38.510",
"Id": "40995",
"ParentId": "40984",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "40995",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T18:03:18.020",
"Id": "40984",
"Score": "1",
"Tags": [
"c#",
"performance",
"linq",
"hash-map"
],
"Title": "Making adding to a dictionary more efficient?"
}
|
40984
|
<p>I'm implementing basic sorting algorithms to learn them, and coding, better. Criticisms and possible optimizations welcome.</p>
<pre><code>import unittest
import random
def merge_sort(seq):
"""Accepts a mutable sequence. Utilizes merge_sort to sort in place, return
a sorted sequence"""
if len(seq) == 1:
return seq
else:
#recursion: break sequence down into chunks of 1
mid = len(seq)/2
left = merge_sort(seq[:mid])
right = merge_sort(seq[mid:])
i, j, k = 0, 0, 0 #i= left counter, j= right counter, k= master counter
#run until left or right is out
while i < len(left) and j < len(right):
#if current left val is < current right val; assign to master list
if left[i] < right[j]:
seq[k] = left[i]
i += 1; k += 1
#else assign right to master
else:
seq[k] = right[j]
j += 1; k += 1
#handle remaining items in remaining list
remaining = left if i < j else right
r = i if remaining == left else j
while r < len(remaining):
seq[k] = remaining[r]
r += 1; k += 1
return seq
class test_mergesort(unittest.TestCase):
def test_mergesort(self):
test = [random.randrange(0, 10000) for _ in range(2000)]
self.assertEqual(merge_sort(test), sorted(test))
if __name__ == '__main__':
unittest.main()
</code></pre>
|
[] |
[
{
"body": "<p>if you are looking for places to improve your code, i noticed that in this:</p>\n\n<pre><code> while i < len(left) and j < len(right):\n #if current left val is < current right val; assign to master list\n if left[i] < right[j]:\n seq[k] = left[i]\n i += 1; k += 1\n #else assign right to master\n else:\n seq[k] = right[j]\n j += 1; k += 1\n</code></pre>\n\n<p>you have k += 1 in both scenarios since it always occurs but you could also just put it outside of the if statement:</p>\n\n<pre><code> while i < len(left) and j < len(right):\n #if current left val is < current right val; assign to master list\n if left[i] < right[j]:\n seq[k] = left[i]\n i += 1;\n #else assign right to master\n else:\n seq[k] = right[j]\n j += 1;\n k += 1\n</code></pre>\n\n<p>It just generally looks nicer and makes more sense</p>\n\n<p>Also, one more piece of criticism, you handle the remaining items interestingly, but it is a bit confusing the way you try to make it work for both left and right when it could easily just be done individually which is a lot more readable and less confusing.</p>\n\n<p>you do this:</p>\n\n<pre><code> #handle remaining items in remaining list\n remaining = left if i < j else right\n r = i if remaining == left else j\n\n while r < len(remaining):\n seq[k] = remaining[r]\n r += 1; k += 1\n</code></pre>\n\n<p>whereas I would recommend something like this:</p>\n\n<pre><code> #handle remaining items in remaining list\n\n while i < len(left):\n seq[k] = left[i]\n i += 1; k+= 1;\n\n while j < len(right):\n seq[k] = right[j]\n j += 1; k+= 1;\n</code></pre>\n\n<p>The clever part about this is that already either the left or right array is done, so at most only one of the while loops are called so we do not have to worry aobut them both being called</p>\n\n<p>as pointed out below, this might not be in the spirit of the activity, but if you are using python 2.6+, there is already a merge function built in, and it can be achieved in a much smaller amount of code:</p>\n\n<pre><code>from heapq import merge\n\ndef merge_sort(m):\n if len(m) <= 1:\n return m\n\n middle = len(m) / 2\n left = m[:middle]\n right = m[middle:]\n\n left = merge_sort(left)\n right = merge_sort(right)\n return list(merge(left, right))\n</code></pre>\n\n<p>sidenote: even if you do not want to use externally defined methods, the above example is actually a very good example of very nice and readable code, and so what would be best in terms of clean coding would be to do that and build your own merge function from what you have written so far</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T21:48:02.237",
"Id": "70272",
"Score": "1",
"body": "Using [`heapq.merge`](http://docs.python.org/3/library/heapq.html#heapq.merge) seems like it would be contrary to the spirit of the OP's exercise (that is, learning how merge sort works)! I mean, if you're going to use `heapq.merge`, why not just use `sorted`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T21:48:53.950",
"Id": "70273",
"Score": "1",
"body": "that is true; I also have a bunch of tips for his coding style though"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T21:35:56.140",
"Id": "41005",
"ParentId": "40986",
"Score": "5"
}
},
{
"body": "<p>Just a couple of comments.</p>\n\n<ol>\n<li><p>Your base case should be <code>if len(seq) <= 1: return seq</code>, not <code>if len(seq) == 1: return seq</code>.</p></li>\n<li><p>If you're striving for efficiency, you shouldn't create so many intermediate sequences. Have a look at <a href=\"https://codereview.stackexchange.com/questions/40585/is-this-non-recursive-mergesort-efficient-and-a-good-way-to-simulate-the-recursi/40718#40718\">this</a> for a solution which uses only a single temporary array (it's C#, but the difference is just syntactic).</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T23:33:18.503",
"Id": "41018",
"ParentId": "40986",
"Score": "2"
}
},
{
"body": "<p>You currently have:</p>\n\n<pre><code>i, j, k = 0, 0, 0 #i= left counter, j= right counter, k= master counter\n</code></pre>\n\n<p>Don't write minified code. Use variable names.</p>\n\n<pre><code>left_counter, right_counter, master_counter = 0, 0, 0\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T09:30:08.713",
"Id": "48467",
"ParentId": "40986",
"Score": "8"
}
},
{
"body": "<p>The way you handle the remaining items is confusing as ASKASK pointed out. </p>\n\n<p>You could've just said:</p>\n\n<pre><code>#handle remaining items in remaining list\nseq[k:] = left[i:] + right[j:]\n</code></pre>\n\n<p>Either left[i:] or right[j:] will be empty, so adding them will give you the remaining list. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-06T18:47:07.073",
"Id": "113078",
"ParentId": "40986",
"Score": "3"
}
},
{
"body": "<p><strong>Reducing nesting</strong></p>\n\n<p>It is easier to not use <code>else</code> in a recursive function after the base case. If the base case condition is verified, then the function ends and the rest of the function is not run anyway.</p>\n\n<pre><code>def merge_sort(seq):\n if len(seq) <= 1: # Credit to Rafe for the base-case\n return seq\n mid = ...\n ...\n</code></pre>\n\n<p>Nesting means complexity, reducing it is desirable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-06T20:54:03.333",
"Id": "113088",
"ParentId": "40986",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T18:17:48.533",
"Id": "40986",
"Score": "8",
"Tags": [
"python",
"algorithm",
"beginner",
"sorting",
"mergesort"
],
"Title": "Merge Sort Algorithm in Python"
}
|
40986
|
<p>It all works exactly as it should. It finds data from today, finds unique emails and puts them in an array. I then check the data again from today, against the emails to total up different values. Then output those values to a sheet.</p>
<p>I'm sure there might be better methods to do what I wish. Such as only going through the data once, not using 3 arrays, etc. But it does all seem to work.</p>
<pre><code>function todayByPerson() {
var emailColumn =1;
var dateColumn = 2;
var findColumn = 4;
var comFind = "Yes - Complete (going ahead)";
var ansFind = "No Answer";
var intFind = "No - Not interested in taking part";
var cbFind = "Callback";
var tolFind = "Temp Offline (If TOL do not continue)";
var target = "Today";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var targetSheet = ss.getSheetByName(target);
var sheet = ss.getSheetByName('Form Responses');
var values = sheet.getDataRange().getValues();
var today = new Date();
var thisMorning = today;
thisMorning.setHours(0);
thisMorning.setMinutes(0);
var archive = [];
var names = [];
var data = [];
var completed = 0;
var noAnswer = 0;
var callBack = 0;
var notInterested = 0;
var tempOffline = 0;
var totCom = 0;
var totAns = 0;
var totCal = 0;
var totNot = 0;
var totTol = 0;
for (var counter = 1; counter < values.length; counter++) {
var testDate = new Date(values[counter][dateColumn -1]);
if (testDate < thisMorning) {
continue;
}
if (archive.some(function (element, index, array) {
return values[counter][emailColumn - 1] == element[emailColumn - 1];
})) {
continue;
}
archive.push(values[counter]);
}
var archiveLength = archive.length;
for (i=0;i< archiveLength;i++) {
names.push(archive[i][0]);
}
for (i=0; i<names.length;i++) {
for (var counter = 1; counter < values.length; counter++) {
var testDate = new Date(values[counter][dateColumn -1]);
if (testDate < thisMorning) {
continue;
}
if (values[counter][emailColumn -1] == names[i] &&
values[counter][findColumn -1] == comFind) {
completed++;
totCom++;
}
if (values[counter][emailColumn -1] == names[i] &&
values[counter][findColumn -1] == ansFind) {
noAnswer++;
totAns++;
}
if (values[counter][emailColumn -1] == names[i] &&
values[counter][findColumn -1] == cbFind) {
callBack++;
totCal++;
}
if (values[counter][emailColumn -1] == names[i] &&
values[counter][findColumn -1] == intFind) {
notInterested++;
totNot++;
}
if (values[counter][emailColumn -1] == names[i] &&
values[counter][findColumn -1] == tolFind) {
tempOffline++;
totTol++;
}
}
var attempts = noAnswer+callBack+completed+notInterested+tempOffline;
var success = completed/attempts*100;
data.push([names[i], attempts, completed, noAnswer, callBack, notInterested, tempOffline, success]);
var completed = 0;
var noAnswer = 0;
var callBack = 0;
var notInterested = 0;
var tempOffline = 0;
}
var totAtt = totCom+totAns+totCal+totNot+totTol;
var headers =[["Name", "Attempted", "Completed", "No Answer", "Callback", "Not Interested", "Temp Offline", "Success Rate"]];
var footers =[["Totals", totAtt, totCom, totAns, totCal, totNot, totTol, totCom/totAtt*100]];
targetSheet.getRange(1,1,1,headers[0].length).setValues(headers);
targetSheet.getRange(1,1,1,headers[0].length).setBackgroundColor("#43b9ff");
targetSheet.getRange(1,1,1,headers[0].length).setFontColor("#a60303");
targetSheet.getRange(1,1,1,headers[0].length).setFontWeight("bold");
targetSheet.getRange(2,1).offset(0, 0, data.length, data[0].length).setValues(data);
targetSheet.getRange(data.length+2, 1, 1, footers[0].length).setValues(footers);
targetSheet.getRange(data.length+2, 1, 1, footers[0].length).setBackgroundColor("#43b9ff");
targetSheet.getRange(data.length+2, 1, 1,footers[0].length).setFontColor("#a60303");
targetSheet.getRange(data.length+2, 1, 1,footers[0].length).setFontWeight("bold");
}
</code></pre>
<p>EDIT</p>
<p>After I posted the above, I was working on another addition to this, something to change emails into nicer looking names for the report.
All emails are in the following format.</p>
<p>firstname.lastname@email-domain.co.uk</p>
<p>so here is the additional snippet.</p>
<pre><code>var cleanName = names[i].replace("@email-domain.co.uk","");
var cleanName = cleanName.replace("."," ");
var cleanName = cleanName.charAt(0).toUpperCase() + cleanName.slice(1);
var space = cleanName.search(" ");
var cleanName = cleanName.substr(0,space+1)+ cleanName.charAt(space+1).toUpperCase() + cleanName.slice(space+2);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T20:12:07.740",
"Id": "70253",
"Score": "0",
"body": "A thought has struck me, I'll have to fill entire sheet white, and set font black before colouring ranges.\nOr sheet will end up all stripey as data changes."
}
] |
[
{
"body": "<p>You keep repeating <code>if (values[counter][emailColumn -1] == names[i] &&</code> and <code>values[counter][findColumn -1]</code> , how about doing that just once ?</p>\n\n<p>You will end up with this more readable, faster code:</p>\n\n<pre><code>if (values[counter][emailColumn -1] == names[i]){\n\n var value = values[counter][findColumn -1];\n\n if (value == comFind) {\n completed++;\n totCom++;\n }\n\n if (value == ansFind) {\n noAnswer++;\n totAns++;\n }\n\n if (value == cbFind) {\n callBack++;\n totCal++;\n }\n\n if (value == intFind) {\n notInterested++;\n totNot++;\n }\n\n if (value == tolFind) {\n tempOffline++;\n totTol++;\n }\n}\n</code></pre>\n\n<p>Furthermore, there are a number of problems with your variables ( redeclaring again or not declaring ), please use jshint.com to check those out. At the very least, you ought to group your <code>var</code>s on top, ideally with one comma-chained <code>var</code> statement.</p>\n\n<p>Since headers and footers have the same color scheme, you might want to consider having a function to set the color for a range. This also makes it faster, since you are then not calculating the range over and over.</p>\n\n<pre><code>function setColors( range ){\n range.setBackgroundColor(\"#43b9ff\");\n range.setFontColor(\"#a60303\");\n range.setFontWeight(\"bold\");\n}\n</code></pre>\n\n<p>Also, your naming could be a bit more informative, I assume <code>totTol</code> stands for <code>totalTotal</code> which is an unfortunate name. You also have 0 lines of comment.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T17:12:08.180",
"Id": "70431",
"Score": "0",
"body": "thank you for the reply and suggestions. I'm very new to Javascript, so always looking to learn. I'll try to implement the changes you have suggested and get back to you.\n\nI redeclared vars below again, such as var tempOffline = 0;\nso i could reset the counter per person.\n\nThe var tolTot stands for tempOffline Total, I didn't want to use temp as a var or name.\n\nMany thanks for the feedback and help :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T17:17:20.060",
"Id": "70433",
"Score": "0",
"body": "You can just call `tempOffline = 0`, you do not need `var`, for someone new to JS, your code is quite good."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T17:43:30.597",
"Id": "70441",
"Score": "0",
"body": "Ahhh, awesome, rookie error, I don't need to redeclare vars. Just change value.\nNever seen jshint.com, just checked it, great link. Bookmarked!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T02:09:35.110",
"Id": "70544",
"Score": "0",
"body": "I managed to implement all but one of your suggestions and things are much better. Wish i could post revised code here, not enough space. One thing I didn't get 100% (only been learning Javascript since xmas) is \"you ought to group your vars on top, ideally with one comma-chained var statement.\" you stated. Something like var ss, sheet, values, valuesLength, counter, archive = [];???\n\nOK, so possibly/surely/100% stupid question, but why? If you have to go and define most of them anyways or give them a values? I'd be writing them twice, or no?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T16:58:31.267",
"Id": "41084",
"ParentId": "40987",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "41084",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T18:17:58.603",
"Id": "40987",
"Score": "4",
"Tags": [
"javascript",
"beginner",
"datetime",
"google-apps-script",
"google-sheets"
],
"Title": "Script for generating a report in Google-Spreadsheets. Looks for various values to check and count"
}
|
40987
|
<p>Please review this code.</p>
<pre><code> import java.awt.*;
import javax.swing.*;
public class Snake_Ladder {
public static void main(String[] args) {
new Snake_Ladder();
}
public Snake_Ladder(){
int i;
JFrame frame = new JFrame();
JPanel pane = new JPanel();
GridLayout experimentLayout = new GridLayout(11,0);
pane.setLayout(experimentLayout);
for(i=100;i>=91;i--){
pane.add(new JButton(" " +i));
}
for(i=81;i<=90;i++){
pane.add(new JButton(" " +i));
}
for(i=80;i>=71;i--){
pane.add(new JButton(" " +i));
}
for(i=61;i<=70;i++){
pane.add(new JButton(" " +i));
}
for(i=60;i>=51;i--){
pane.add(new JButton(" " +i));
}
for(i=41;i<=50;i++){
pane.add(new JButton(" " +i));
}
for(i=40;i>=31;i--){
pane.add(new JButton(" " +i));
}
for(i=21;i<=30;i++){
pane.add(new JButton(" " +i));
}
for(i=20;i>=11;i--){
pane.add(new JButton(" " +i));
}
for(i=1;i<=10;i++){
pane.add(new JButton(" " +i));
}
frame.add(pane);
frame.setSize(1200,1400);
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T19:29:51.303",
"Id": "70249",
"Score": "3",
"body": "Close voters: Even though this question is asking for some feature to be added (which is off-topic), the current code does work and really **needs** to be reviewed! I think we should review this without answering how to add the wanted feature!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T20:23:53.587",
"Id": "70257",
"Score": "0",
"body": "Edited question to make it on-topic. (Sorry, I just had to)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T20:29:15.040",
"Id": "70258",
"Score": "0",
"body": "We only review code here, we won't write code for you. Once you have figured out how to add background image you can come back and post a new question, with the suggestions you see below included."
}
] |
[
{
"body": "<p>Unfortunately your question about \"How to...\" is off-topic for this site but I feel that your code really <strong>needs</strong> to be reviewed as there are some things that can be improved.</p>\n\n<ul>\n<li><p><strong>Don't import .*</strong> Only use the imports that you need. If you need to import <code>JButton</code>, import <code>JButton</code>, don't import all other classes within the same package.</p></li>\n<li><p>Fix your indentation and spacing <code>for (i = 100; i >= 91; i--) {</code> is a lot more readable than what you currently have.</p></li>\n</ul>\n\n<p>Also, use an extra indentation step (one tab / four spaces) after each <code>{</code> and go back one indentation step after each <code>}</code>. Applying this, your code will look like:</p>\n\n<pre><code>for (i = 61; i <= 70; i++) {\n pane.add(new JButton(\" \" + i));\n}\n</code></pre>\n\n<p>To make your IDE do the indentation for you:</p>\n\n<ul>\n<li><p>If you are using Eclipse, select all your code and press either <kbd>Ctrl</kbd> + <kbd>I</kbd> or <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>F</kbd>.</p></li>\n<li><p>If you are using Netbeans, select all your code and press <kbd>Alt</kbd> + <kbd>Shift</kbd> + <kbd>F</kbd></p></li>\n</ul>\n\n<p>Update, your for-loop can be written as only one loop (even though it's quite many variables and this code possibly needs it's own review...)</p>\n\n<pre><code>int COUNT = 100;\nint last10s = 0;\nfor (int i = 0; i < COUNT; i++) {\n int decreasing = COUNT - i;\n int even10 = i / 10;\n if (decreasing % 10 == 0)\n last10s = decreasing;\n boolean shouldDecrease = even10 % 2 == 0;\n int increasing = last10s - 9 + i % 10;\n int chosen = shouldDecrease ? decreasing : increasing;\n pane.add(new JButton(\" \" + chosen));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T07:13:45.710",
"Id": "70336",
"Score": "0",
"body": "Simon, Why Should I import only JButtons not all other classes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T07:20:07.100",
"Id": "70337",
"Score": "0",
"body": "@SajalArora It will pollute your namespace, when you press `Ctrl + Space` if you are using an IDE, which I hope you are, you will see a whole lot of other classes that you're not using. I think of this as the main reason, but there are probably other good reasons as well."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T19:34:07.047",
"Id": "40994",
"ParentId": "40990",
"Score": "6"
}
},
{
"body": "<p>The vast majority of your code looks like this</p>\n\n<pre><code>for(i=20;i>=11;i--){\n pane.add(new JButton(\" \" +i));\n}\nfor(i=1;i<=10;i++){\n pane.add(new JButton(\" \" +i));\n}\n</code></pre>\n\n<p>The only differences are that values in the for loop. You should create a function that contains the repeated code.</p>\n\n<pre><code>void addButtonsUp(JPanel pane, int start, int stop) {\n for(i=start;i<=stop;i++){\n pane.add(new JButton(\" \" +i));\n }\n}\nvoid addButtonsDown(JPanel pane, int start, int stop) {\n for(i=start;i>=stop;i--){\n pane.add(new JButton(\" \" +i));\n }\n}\n</code></pre>\n\n<p>This will cut the big block of 30 lines down to 10. It also makes the code more readable. I didn't realize that you were alternating between counting up and count down until I started working on my answer. When your eyes see a section of code that looks repetitive, your brain assumes that is the case and continues on. If there was a small bug in the 3rd for loop, it would not stand out. Moving the actual looping into a function means that the structure can only be wrong in one place.</p>\n\n<p>However, just calling these methods directly can still be improved. There are a lot of <a href=\"http://en.wikipedia.org/wiki/Magic_number_%28programming%29\" rel=\"nofollow\">magic numbers</a> in the code. The values that specify the start and stop values are very structured, but there is nothing in the code to indicate that. What you can do is to use another loop to make the calls to <code>addButtonsUp()</code> and <code>addButtonsDown()</code>.</p>\n\n<pre><code>void createSnakeGrid(JPanel pane, int max, int min, int step) {\n for (int i = max; i > min; i+=step*2) {\n addButtonsDown(pane, i, i+step);\n addButtonsUp(pane, i+(step*2), i+step);\n }\n}\n</code></pre>\n\n<p>And now you can call a single function that will construct the entire grid by passing in the values that matter (100, 1, -10). I did not extensively test <code>createSnakeGrid()</code>, so it might not be completely correct. But you should be able to get the intent from what is there.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T20:20:35.330",
"Id": "40999",
"ParentId": "40990",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "40994",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T19:02:08.720",
"Id": "40990",
"Score": "0",
"Tags": [
"java",
"swing",
"awt"
],
"Title": "A whole bunch of JButtons"
}
|
40990
|
<p>I have the following function, intended to take standard dice notation (XdY+Z) and return a (sort of) random number based on the input. Are there any bugs/bad ideas/optimizable sections I am missing?</p>
<pre><code>function dieRoll(dice) {
if (/^[\d+]?d\d+[\+|\-]?\d*$/.test(dice) == false) { //Regex validate
return "Invalid dice notation"; //Return if input invalid
}
if(dice[0]=="d") { //If the first character is a d (dY)
dice = "1"+dice; //Add a 1
}
var minus = dice.search(/\-/); //Search for minus sign
if (minus == -1 && dice.search(/\+/) == -1) { //If no minus sign and no plus sign (XdY)
dice += '+0'; //Add a +0
}
if (minus == -1) { //If no minus sign (XdY+Z)
var dicesplit = dice.split('+'); //Split for plus sign
var modifier = dicesplit[1] * 1; //Number to add to total
} else { //If there is a minus sign (XdY-Z)
var dicesplit = dice.split('-'); //Split for minus sign
var modifier = ("-" + dicesplit[1]) * 1; //Number to add to total
}
var diesplit = dicesplit[0].split('d'); //Take the first section (XdY) and split for d
var howmany = diesplit[0] * 1; //Number of dice to roll
var diesize = diesplit[1] * 1; //How many sides per die
var total = 0; //Total starts as 0
for (var i = 0; i < howmany; i++) { //Loop a number of times equal to the number of dice
total += Math.floor(Math.random() * diesize) + 1; //Random number between 1 and diesize
}
total += modifier; //Add the modifier
return total; //Return the final total
}
</code></pre>
|
[] |
[
{
"body": "<p>You validate the input string against a regular expression, but then you manually parse it again the hard way. Instead, you should use parentheses within the regular expression to define capturing groups.</p>\n\n<p>I also think that your regular expression is not quite correct. Optional digits <em>X</em> preceding \"d\" should be <code>\\d*</code> or <code>(\\d+)?</code>. An optional ±<em>Z</em> should be <code>([+-]\\d+)?</code>.</p>\n\n<pre><code>function dieRoll(dieSpec) {\n var match = /^(\\d+)?d(\\d+)([+-]\\d+)?$/.exec(dieSpec);\n if (!match) {\n throw \"Invalid dice notation: \" + dieSpec;\n }\n\n var howMany = (typeof match[1] == 'undefined') ? 1 : parseInt(match[1]);\n var dieSize = parseInt(match[2]);\n var modifier = (typeof match[3] == 'undefined') ? 0 : parseInt(match[3]);\n\n …\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T20:09:50.077",
"Id": "70252",
"Score": "0",
"body": "The two corrections you suggested are valid points; thanks! The group-capturing RegEx seems to work as well. I'm a little confused by the next bit - what exactly are the `? 1 :` and `? 0 :` parts doing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T20:17:33.627",
"Id": "70254",
"Score": "0",
"body": "If omitted, you want the _X_ to default to 1, and _Z_ to default to 0."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T19:49:35.347",
"Id": "40996",
"ParentId": "40993",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "40996",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T19:28:21.307",
"Id": "40993",
"Score": "3",
"Tags": [
"javascript",
"performance",
"regex",
"random",
"dice"
],
"Title": "Dice notation roller in JavaScript"
}
|
40993
|
<p>After programming in Haskell for a while, I've gotten attached to a functional style. This is clearly evident in the code for my genetic algorithm. </p>
<p>Could you provide me with some hints as to how I can make this code more <em>pythonic</em>? By that, I mean provide some method of organisation rather than throwing a bunch of functions around. Any other recommendations are also welcome.</p>
<pre><code>import copy
import matplotlib.pyplot as pyplot
import random
def create_member(genes):
return (sum(genes), genes)
def shuffle(pool):
pool_shuffled = copy.deepcopy(pool)
random.shuffle(pool_shuffled)
return pool_shuffled
def calculate_pool_fitness(pool):
return sum([member[0] for member in pool])
def calculate_member_fitness(member):
return sum(member[1])
def recalculate_fitneses(pool):
return [(calculate_member_fitness(member), member[1]) for member in pool]
def select_members_roulette(pool, count):
selection = []
while len(selection) < count:
member = select_member_roulette(pool)
selection.append(copy.deepcopy(pool[member]))
return selection
def select_member_roulette(pool):
drop = random.randint(0, calculate_pool_fitness(pool))
total_fitness = 0
for member in range(0, len(pool)):
total_fitness += pool[member][0]
if total_fitness >= drop:
return member
def mutate_gene(gene, rate=1):
return 1 - gene if random.random() <= rate else gene
def mutate_genes(genes, rate=1):
return [mutate_gene(gene, rate) for gene in genes]
def mutate_member(member, rate=1):
return member[0], mutate_genes(member[1], rate)
def mutate_pool(pool, rate=1):
return [mutate_member(member, rate) for member in pool]
def create_random_gene():
return random.choice([0, 1])
def create_random_genes(size):
return [create_random_gene() for _ in range(size)]
def crossover_genes(mother, father, rate=1):
if random.random() <= rate:
split = random.randint(1, len(mother))
daughter = mother[:split] + father[split:]
son = father[:split] + mother[split:]
else:
daughter = copy.deepcopy(mother)
son = copy.deepcopy(father)
return daughter, son
def crossover_members(mother, father, rate=1):
daughter_genes, son_genes = crossover_genes(mother[1], father[1])
return [(mother[0], daughter_genes), (father[0], son_genes)]
def crossover_pool(pool, rate=1):
children = []
# select every two elements for crossover
for mother, father in zip(pool[::2], pool[1::2]):
children.extend(crossover_members(mother, father, rate))
return children
def generate_pool(size, gene_size):
pool = []
for member in range(0, size):
genes = create_random_genes(gene_size)
pool.append(create_member(genes))
return pool
def evolve(pool, rate_crossover=0.9, rate_mutation=0.01):
successors = copy.deepcopy(pool)
# perform roulette selection whilst keeping best member
member_alpha = copy.deepcopy(max(successors, key=lambda member: member[0]))
successors = select_members_roulette(pool, len(pool) - 1)
successors.append(member_alpha)
successors = shuffle(successors)
successors = crossover_pool(successors, rate_crossover)
successors = mutate_pool(successors, rate_mutation)
successors = recalculate_fitneses(successors)
return successors
def main():
random.seed
pyplot.figure(figsize=(14, 8), dpi=400)
axgraph=pyplot.subplot(111)
pool_size = 50
gene_size = 50
generations = 100
pool = generate_pool(pool_size, gene_size)
for generation in range(0, generations):
pool = evolve(pool)
axgraph.scatter(generation, sum([member[0] for member in pool]))
pyplot.grid(True)
pyplot.axis([0, generations, 0, pool_size * gene_size])
pyplot.savefig('genetic_algorithms.png')
main()
if __name__ == '__main__':
main()
</code></pre>
|
[] |
[
{
"body": "<p>I have been facing the same issue for a few months, even though I didn't write that much functional code before switching. Please take my comments with a grain of salt even if I say \"do <strong>this</strong>\" instead of \"<strong>this</strong> might help but I'm not sure\".</p>\n\n<ul>\n<li><p>Use dictionaries instead of tuples:</p>\n\n<pre><code>def create_member(genes):\n return {'sum': sum(genes), 'genes': genes}\n</code></pre></li>\n<li><p>Use generators instead of list-expressions:</p>\n\n<pre><code>def mutate_pool(pool, rate=1):\n for member in pool:\n yield mutate_member(member, rate)\n</code></pre>\n\n<p>Yay, lazy lists! (kind of...)</p></li>\n<li><p>Write code for the next person which will be reading it. You shouldn't put comments only where you had some trouble (\"[::2] selects one gene out of two\") but try to make any function easy to understand and modify in isolation.</p></li>\n<li><p>Prefer longer functions and document them using docstrings. A nice function name is usually <strong>not</strong> enough for documentation:</p>\n\n<pre><code>def mutate_genes(genes, rate):\n \"\"\"\n Given a list of genes, flip some of them according to rate.\n \"\"\"\n for gene in genes:\n yield 1 - gene if random.random() <= rate else gene\n\ndef mutate_pool(pool, rate=1):\n \"\"\"\n Returns a new pool of member where every bit in every gene could have been\n flipped according to rate.\n \"\"\"\n for member in pool:\n yield member[0], mutate_genes(member[1], rate)\n</code></pre>\n\n<p>Of course those examples are a bit artificial but they do feel more pythonic. You don't have to document every function, just think about your readers. :)</p></li>\n<li><p>Read nice Python code. I'd recommend <a href=\"https://github.com/django/django/blob/master/django/core/cache/backends/memcached.py\" rel=\"nofollow\">Django</a> and <a href=\"https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cross_decomposition/pls_.py\" rel=\"nofollow\">scikit-learn</a> (Those are links to specific files that I chose randomly.)</p></li>\n</ul>\n\n<p>I think it's worthwhile to try to force yourself to write pythonic code for some time so that you can tell what's nice in \"the Python way\" and what's actually better in a functional style.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T13:06:36.787",
"Id": "41062",
"ParentId": "41004",
"Score": "4"
}
},
{
"body": "<ul>\n<li><code>random.seed</code> is a bug: add parentheses to actually call the function.</li>\n<li>Use <code>collections.namedtuple</code> so you can write <code>member.fitness</code> instead of the less readable <code>member[0]</code></li>\n<li><code>copy.deepcopy</code> should not be necessary in a functional approach</li>\n<li>Keeping the genes in a tuple instead of a list would make the member tuple fully immutable, in line with the functional approach. This eliminates the need to deep-copy objects as you can safely copy just references.</li>\n</ul>\n\n<p>After these changes <code>create_member</code> becomes like this:</p>\n\n<pre><code>import collections\nMember = collections.namedtuple(\"Member\", \"fitness genes\")\n\ndef create_member(genes):\n genes = tuple(genes)\n return Member(sum(genes), genes)\n</code></pre>\n\n<p>In some places you create members without calling <code>create_member</code>. Be sure to change them, for example:</p>\n\n<pre><code>def mutate_member(member, rate=1):\n return create_member(mutate_genes(member.genes, rate))\n</code></pre>\n\n<ul>\n<li>With immutable members there is no need to recalculate fitnesses. You can delete such functions.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T18:22:18.800",
"Id": "41093",
"ParentId": "41004",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "41062",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-02-05T21:35:04.773",
"Id": "41004",
"Score": "5",
"Tags": [
"python",
"data-visualization",
"genetic-algorithm"
],
"Title": "Genetic algorithm in Python that plots its evolution"
}
|
41004
|
<p>I had a situation when I needed to move all array elements in circular fashion. When I say this, I mean:</p>
<pre><code>0 1 2 3
1 2 3 0
2 3 0 1
3 0 1 2
</code></pre>
<p>The array:</p>
<pre><code>var players = ["hash1","hash2","hash3","hash4"];
</code></pre>
<ul>
<li><code>Players</code> is the array that contains user hashes and their place on the table. Table is round, so array must rotate in circular fashion.</li>
<li><code>Step</code> dictates by how much it should move.</li>
</ul>
<p>I came up with following algorithm (if you can call that, probably not) that works fine. I was just wondering if there was a more efficient way. Or cleaner way to do same?</p>
<p>The <code>offset</code> variable is probably wrongly named; I couldn't come up with a better name.</p>
<pre><code>var step = 0 // 3,2,1,0
var offset = 0;
var players_new = [];
for (var i = 0; i <= players.length - 1; i++) {
if (i + step <= players.length - 1) {
players_new[i + step] = players[i];
offset++;
} else {
players_new[i - offset] = players[i];
}
};
</code></pre>
<p>I tested many different versions, and looks like vazha's version is the fastest all around, except in Firefox.</p>
<p><a href="http://jsperf.com/rotate-array-javascript" rel="noreferrer">jsperf</a></p>
<p>Since I'm using this code in node.js, which uses the Chrome engine, results are important.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T21:38:02.823",
"Id": "70266",
"Score": "2",
"body": "Why not leave the data as-is and use `%`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T21:40:49.470",
"Id": "70267",
"Score": "0",
"body": "@MattBall Can you illustrate? I'm not following."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T22:37:42.147",
"Id": "70283",
"Score": "0",
"body": "If you haven't already see http://stackoverflow.com/questions/1985260/javascript-array-rotate"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T09:25:38.807",
"Id": "70358",
"Score": "1",
"body": "Yea it seems like `shift()` is the performance killer and reading the specs, shift is a generic method that reads properties of the array to determine how to shift it. So in a all rounder way shift is easy but your solution only works for your use case. It is impressive performance increase in your case :) I hope your Array contains millions of players :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T09:34:33.120",
"Id": "70362",
"Score": "0",
"body": "@ppumkin yep, shift is the culprit. thanks for the heads up :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T14:34:25.807",
"Id": "70401",
"Score": "0",
"body": "I was wondering about that, how many players are you expecting and how often are you planning to call this? Mayhaps rotating the array is not the best thing to do."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T22:01:16.647",
"Id": "70527",
"Score": "0",
"body": "@konijn well, I cannot give you numbers beforehand, but it is major part of the game. This problem was more like a mental challenge to play with minor optimization, that might not be so important down the road, but makes gray matter in the brain work. This is why I enjoy programming. I think programming is not just about finding the solution, but finding smart one and enjoying the process. I might be too drunk atm, but you get the point."
}
] |
[
{
"body": "<p>You should use <code>shift</code> and <code>push</code></p>\n\n<pre><code>function rotate( array , times ){\n while( times-- ){\n var temp = array.shift();\n array.push( temp )\n }\n}\n\n//Test\nvar players = ['Bob','John','Mack','Malachi'];\nrotate( players ,2 )\nconsole.log( players );\n</code></pre>\n\n<p><code>shift</code> removes the first element, <code>push</code> adds an element at the end.\nI am not sure whether you are using players_new because you do not know how to modify the original array or because you do not want to modify the original. If you do not want to modify the original array you could:</p>\n\n<pre><code>function rotate( array , times ){\n array = array.slice();\n while( times-- ){\n var temp = array.shift();\n array.push( temp )\n }\n return array;\n}\n\n//Test\nvar players = ['Bob','John','Mack','Malachi'];\nconsole.log( rotate( players ,2 ) );\n</code></pre>\n\n<p>Finally, if you meant to declare an array, you should have <code>var players_new = [];</code>, not <code>var players_new = {};</code>. Plus <code>players_new</code> is an unfortunate name.</p>\n\n<p>Golfic edition:</p>\n\n<pre><code>while(times--)array.push(array.shift());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T21:44:57.227",
"Id": "70268",
"Score": "0",
"body": "I need to read more about built in capabilities of javascript :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T21:51:53.093",
"Id": "70275",
"Score": "0",
"body": "what would you call players_new? p.s. I need original array too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T21:59:16.270",
"Id": "70277",
"Score": "0",
"body": "Probably I would use `seatings` and `newSeatings` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T22:03:48.527",
"Id": "70278",
"Score": "0",
"body": "Thanks. Btw, my version is much faster than shift and push you proposed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T22:05:36.640",
"Id": "70279",
"Score": "0",
"body": "Take a look, maybe I'm doing something wrong. But your proposed solution is 63% slower. http://jsperf.com/rotate-array"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T22:10:13.237",
"Id": "70282",
"Score": "0",
"body": "And it gets progressively slower when there are more players in the original array."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T14:06:41.170",
"Id": "70395",
"Score": "0",
"body": "looks like we have a winner http://jsperf.com/rotate-array-javascript"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T21:40:59.810",
"Id": "41008",
"ParentId": "41006",
"Score": "11"
}
},
{
"body": "<p>Sometimes it is a good idea to abstract this sort of problem. In many languages doing array-based shifts is very expensive.</p>\n\n<p>Do you need to rotate the array? Why not just virtually 'rotate' your pointer....</p>\n\n<pre><code>for (int turn = 0; turn < 10; turn++) {\n\n console.log(\"First player is \" + players[(turn + 0) % players.length]);\n console.log(\"Last player is \" + players[(turn + players.length - 1) % players.length]);\n\n}\n</code></pre>\n\n<p>Alternatively, if you need to create the full array for other reasons, consider the slice and concat:</p>\n\n<pre><code>for (turn = 0; turn < 10; turn++) {\n var offset = turn % players.length;\n console.log(offset);\n var playturn = players.slice(offset).concat(players.slice(0, offset));\n console.log(playturn.join(\", \"));\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T23:19:12.707",
"Id": "70287",
"Score": "0",
"body": "I like your 2nd suggestion is smart, +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T08:45:54.637",
"Id": "70350",
"Score": "0",
"body": "@konijn Well smart, but 80% slower than my solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T08:46:12.623",
"Id": "70351",
"Score": "0",
"body": "http://jsperf.com/rotate-array/3"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T11:19:23.123",
"Id": "70372",
"Score": "0",
"body": "@salivan I am surprised it is that much slower, but it **is** my plan-B suggestion. Plan-A is to use the modulo on the index to just 'logically' rotate the array. It requires a different type of support-code outside the function"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T14:05:16.963",
"Id": "70394",
"Score": "0",
"body": "looks like we have a winner: http://jsperf.com/rotate-array-javascript"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T22:34:53.357",
"Id": "41012",
"ParentId": "41006",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T21:36:03.497",
"Id": "41006",
"Score": "14",
"Tags": [
"javascript",
"array"
],
"Title": "Rotating array members"
}
|
41006
|
<p>I've done some reading about implementing AES256 and deriving a key from a password. If I understand correctly:</p>
<ul>
<li>I want to generate a new salt (for the key) and a new IV (for the encrypted message) for every new message. </li>
<li>It should also not be a problem sending the salt and the IV together with the message.</li>
</ul>
<p>I decided to pack everything together in one byte array where the first 16 bytes is the salt, the next 16 bytes is the IV and the rest is the encrypted message. This with a key length of 256 bits and 20000 iterations for generating the key. I also encode the whole thing in Base64 for transmission.</p>
<p>Can this approach be improved? Knowing that I'm limited to 256 bytes for the complete message (salt+iv+message).</p>
<pre><code>public class app {
public static void main(String[] args) throws Exception {
int iterations = 20000;
int keyLength = 32;
byte[] salt = getRandomBytes(16);
byte[] iv = getRandomBytes(16);
char[] password = "password_here".toCharArray();
byte[] payload = "payload_here".getBytes();
byte[] key = deriveKey(iterations, keyLength, salt, iv, password);
byte[] encrypted = encrypt(iv, key, payload);
byte[] bytes = concatBytes(salt, iv, encrypted);
String output = Base64.encodeBytes(bytes);
int outputLength = output.getBytes().length;
System.out.println(outputLength + "\n" + output);
}
private static byte[] deriveKey(int iterations, int length, byte[] salt, byte[] iv, char[] password)
throws InvalidKeySpecException, NoSuchAlgorithmException {
PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, length * 8);
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] key = skf.generateSecret(spec).getEncoded();
return key;
}
private static byte[] getRandomBytes(int length) throws NoSuchAlgorithmException {
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[length];
sr.nextBytes(salt);
return salt;
}
private static byte[] concatBytes(byte[]... arrays) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
for (byte[] array : arrays)
outputStream.write(array);
return outputStream.toByteArray();
}
private static byte[] encrypt(byte[] iv, byte[] key, byte[] text) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException,
BadPaddingException {
AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
SecretKeySpec newKey = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
return cipher.doFinal(text);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T21:50:10.150",
"Id": "70274",
"Score": "0",
"body": "Question - if you are limited to 256 bytes, why Base64 encode it? What is the protocol you are using on the 'internet', can it be a byte-stream?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T21:55:04.503",
"Id": "70276",
"Score": "0",
"body": "Good question. It will be via HTTP (JSON)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T22:09:48.633",
"Id": "70281",
"Score": "0",
"body": "You will likely get much better answers on Security.SE or Cryptography.SE, as this is kind of niche knowledge."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T08:17:07.697",
"Id": "70344",
"Score": "0",
"body": "Thanks Jeff, I cross posted it to Cryptography: http://crypto.stackexchange.com/q/14354/11843"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T22:17:51.913",
"Id": "72189",
"Score": "1",
"body": "@ndsc: Could you edit the question in a way that does not make existing answers meaningless, please?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T00:10:22.263",
"Id": "72207",
"Score": "2",
"body": "You can post new code by appending to the end of the question or by asking a new question: see [Can I edit my own question to include suggested changes from answers?](http://meta.codereview.stackexchange.com/a/1483/34757)"
}
] |
[
{
"body": "<p>A few, mostly minor notes:</p>\n\n<ol>\n<li>\n\n<pre><code>\"payload_here\".getBytes();\n</code></pre>\n\n<p><code>getBytes()</code> should have been called with a <code>Charset</code>. Otherwise it uses the platform's default charset which can vary from platform to platform and could result to data loss and/or other bugs.</p></li>\n<li><p>You have local variable called <code>salt</code> inside the <code>getRandomBytes</code> method. It's a little bit confusing since the same method is called for <code>iv</code> too:</p>\n\n<pre><code>byte[] salt = new byte[length];\n</code></pre></li>\n<li><p>The <code>encrypt</code> method could throw six different types of exceptions. It's a little bit too much. All of them is a subclass of <code>GeneralSecurityException</code>. I'd use that instead, I don't think that clients want to handle those six different types differently.</p></li>\n<li><p>According to the <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367\">Code Conventions for the Java Programming Language</a> class names should start with uppercase letters. </p>\n\n<ul>\n<li><a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367\">Code Conventions for the Java Programming Language, 9 - Naming Conventions</a></li>\n<li><em>Effective Java, 2nd edition</em>, <em>Item 56: Adhere to generally accepted naming conventions</em></li>\n</ul></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T21:00:49.270",
"Id": "72182",
"Score": "1",
"body": "Thanks for your notes! I have since updated my code and I've edited it above. I agree with the exceptions. I have yet to write a good solution for that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-17T20:07:52.943",
"Id": "41908",
"ParentId": "41007",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T21:39:48.440",
"Id": "41007",
"Score": "5",
"Tags": [
"java",
"cryptography"
],
"Title": "Encrypting a payload for transmission over HTTP. AES256 with PBKDF2"
}
|
41007
|
<p>I've written an implementation of a dynamic array in C, but I'm not sure if my implementation is correct... This is what I'm worried about: if I add an element, will it remain in the collection? This problem has arisen from my (apparently) limited knowledge on void pointers. I haven't found any answers to my question online...</p>
<p>The List struct is defined like this:</p>
<pre><code>typedef struct list
{
/**
* C-style array containing the data in this list.
*/
void** data;
/**
* Amount of elements currently present in this list.
*/
unsigned int size;
/**
* Amount of elements that could be present in this list (i.e. size + number of empty spots).
*/
unsigned int capacity;
} List;
</code></pre>
<p>So far so good?</p>
<p>Now, when I want to add an element to a list <code>l</code>, I call <code>List_Add(&l, &element)</code>...</p>
<pre><code>void List_Add(List* list, void* element)
{
if (list->data == NULL)
{
return;
}
if (list->size == list->capacity)
{
// Double the data array of list.
list->data = realloc(list->data, 2 * list->capacity * sizeof(void*));
list->capacity *= 2;
}
if (list->data != NULL)
{
list->data[list->size] = element;
++(list->size);
}
}
</code></pre>
<p><em>By the way: yes, list->data is malloced before calling this function</em>.</p>
<p>I've done some testing with adding elements, but I'm not sure if it's entirely correct. If I were to call this function with an element created on the stack (example below), would it continue to work for the entirety of the program's lifetime?</p>
<p><em>Example</em></p>
<pre><code>List l;
List_Init(&l);
int i = 1;
List_Add(&l, &i);
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>If I were to call this function with an element created on the stack (example below), would it continue to work for the entirety of the program's lifetime?</p>\n</blockquote>\n\n<p>No, it wouldn't:</p>\n\n<ul>\n<li>i is created on the stack</li>\n<li>pointer to i is saved in the list</li>\n<li>i disappears and stack is reused when caller goes out of scope (now list is pointing to garbage)</li>\n</ul>\n\n<p>Your List can be used to store:</p>\n\n<ul>\n<li>Objects created on the heap (using malloc)</li>\n<li>Global/static objects</li>\n<li>Local stack objects, but only if they are removed again before they go out of scope.</li>\n</ul>\n\n<p>For example:</p>\n\n<pre><code>List l;\nList_Init(&l);\nint i = 1;\nint* ptr_i = (int*)malloc(sizof(int));\n*ptr_i = i;\nList_Add(&l, ptr_i);\n// *ptr_i will remain until someone calls free(ptr_i)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T13:32:04.660",
"Id": "70385",
"Score": "0",
"body": "Lesson learned: whenever you are writing any form of [ADT](http://en.wikipedia.org/wiki/Abstract_data_type), make it work with hard copies of the data, rather than with pointers to data outside the ADT."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T22:20:45.613",
"Id": "41011",
"ParentId": "41009",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41011",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T22:09:39.823",
"Id": "41009",
"Score": "3",
"Tags": [
"c",
"pointers"
],
"Title": "C dynamic array and pointers"
}
|
41009
|
<p>I've implemented a common wrapper pattern I've seen for the .NET cache class using generics as follows:</p>
<pre><code>private static T CacheGet<T>(Func<T> refreashFunction, [CallerMemberName]string keyName = null)
{
if (HttpRuntime.Cache[keyName] == null)
HttpRuntime.Cache.Insert(keyName, refreashFunction(), null, DateTime.UtcNow.AddSeconds(600), System.Web.Caching.Cache.NoSlidingExpiration);
return (T)HttpRuntime.Cache[keyName];
}
</code></pre>
<p>It could then be called like so:</p>
<pre><code>public static Dictionary<string, string> SomeCacheableProperty
{
get
{
return CacheGet(() =>
{
Dictionary<string, string> returnVal = AlotOfWork();
return returnVal;
});
}
}
</code></pre>
<p>However, the <code>CacheGet</code> method could be implemented using dynamic:</p>
<pre><code>private static dynamic CacheGet(Func<object> refreashFunction, [CallerMemberName]string keyName = null)
{
if (HttpRuntime.Cache[keyName] == null)
HttpRuntime.Cache.Insert(keyName, refreashFunction(), null, DateTime.UtcNow.AddSeconds(600), System.Web.Caching.Cache.NoSlidingExpiration);
return HttpRuntime.Cache[keyName];
}
</code></pre>
<p>The questions I have:</p>
<ol>
<li><p>Is there a technically (or philosophically) superior preference between these two implementations?</p></li>
<li><p>Are these different at runtime?</p></li>
<li><p>If they are both left in, which one is being called in the getter method?</p></li>
</ol>
|
[] |
[
{
"body": "<p>First of all, I think you misspelled <code>refresh</code> as <code>refreash</code>.</p>\n<p>Second, your usage can probably be simplified</p>\n<pre><code>CacheGet(AlotOfWork);\n</code></pre>\n<p>Finally, you might want to check if <code>refreshFunction</code> returns null and maybe log a warning then as that function returning null would cause a cache miss every time.</p>\n<p>Now to answer your specific questions.</p>\n<ol>\n<li><p>I'll say it, the generic implementation is better. <code>dynamic</code> is a great trapdoor when you get really bogged down with generics or anonymous types and there's neat things you can do with it (<a href=\"https://github.com/SamSaffron/dapper-dot-net\" rel=\"nofollow noreferrer\">see Dapper</a>) but it still has some gotchas. For example, I do not think your function with <code>dynamic</code> will work in most cases.</p>\n<p><code>HttpRuntime.Cache</code> expects and returns <code>object</code> types meaning all types are being downcast or <a href=\"http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx\" rel=\"nofollow noreferrer\">boxed</a>. Therefore, if your function returns a <code>User</code> object, what is stored is still an <code>object</code> and what is returned from the cache is downcast likewise. Therefore your <code>user.Username</code> property will not be available until you cast, <em>even though</em> it's dynamic.</p>\n</li>\n<li><p>Yes. The generic version - with some subtle yet real differences - will run as if it was written for the type you're filling <code><T></code> with. The dynamic version will just be a "value" and let the DLR figure out how to invoke members (which again, unless you're calling <code>ToString()</code> or <code>GetHashCode()</code>, will fail). <code>dynamic</code> will also be slower as the runtime binding has to be done every time, though admittedly this is unlikely to be any sort of bottleneck.</p>\n</li>\n<li><p>Obviously I'm going to say always use the generic version in this case.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T22:57:04.823",
"Id": "70285",
"Score": "0",
"body": "Thanks for the help and recommendations. The context for the question assumes that the calls to CacheGet will be wrapped by a property 'getter'. In your User example, the getter seems to cast it implicitly (properties are available via intellisense and it compiles and runes correctly). Also: Question #3 was about which version 'would' be called if both where present (as overloads), not what 'should' be called (that was question #1)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T23:10:14.437",
"Id": "70286",
"Score": "0",
"body": "@evilertoaster Ah I see, I believe the more specific generic version would take precedence but I'm not 100% sure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T16:20:47.373",
"Id": "70426",
"Score": "0",
"body": "He also mis-PascalCased 'a lot' in his fake generic method name."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T15:07:22.387",
"Id": "72302",
"Score": "1",
"body": "I think you misunderstand how `dynamic` work. If I understand you correctly, something like `object objectUser = new User(); dynamic dynamicUser = objectUser; Console.WriteLine(dynamicUser.UserName);` shouldn't work. But it does. There is no such thing as “`dynamic`, but downcast to `object`”."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T15:13:33.953",
"Id": "72306",
"Score": "0",
"body": "@svick Hmm, you're right. I would have thought that would error but it does not. I have definitely run into issues with this in years past however, I'll try to find an example."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T22:38:13.773",
"Id": "41013",
"ParentId": "41010",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41013",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T22:10:23.370",
"Id": "41010",
"Score": "10",
"Tags": [
"c#",
"generics",
"cache"
],
"Title": "Cache wrapper - Generics vs Dynamic"
}
|
41010
|
<p>I created this testimonial on <a href="http://codepen.io/JGallardo/pen/zGyid" rel="noreferrer">CodePen</a></p>
<p><img src="https://i.stack.imgur.com/oUzbu.png" alt="current quote"></p>
<p>I am a bit skeptical about a few things in my HTML structure. For example, I typically see testimonials enclosed in <code><div></code>s with custom classes. In my case I used a <code><blockquote></code> but had to overwrite a lot of rules. </p>
<p>Also wondering if enclosing the author in <code><strong></code> tags was wise.</p>
<p><strong>HTML</strong></p>
<pre><code><div class="wrapper">
<blockquote>
&ldquo;Such cool. Much awesome. WOW&rdquo;
</blockquote>
<p class="author">
&ndash;
<strong>Doge</strong>,
<a href="#">The Moon</a>
</p>
</div>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>/* == resets == */
body { margin: 0; padding: 0; }
/* == project == */
body {
background: none repeat scroll 0% 0% rgb(240, 240, 240);
color: rgb(102, 102, 102);
font-family: "Helvetica Neue", Helvetica, Arial, Sans-serif;
font-size: 22px;
}
.wrapper {
width: 600px;
margin: 24px auto;
}
blockquote {
background-color: rgb(255, 255, 255);
border-radius: 6px;
font-family: Georgia, serif;
font-size: 22px;
line-height: 1.4;
margin: 0;
padding: 17px;
}
p.author {
background-color: transparent;
font-weight: 500;
font-size: 22px;
line-height:22px;
margin: 24px 0 0 18px;
}
strong {
color: rgb(68, 68, 68);
}
a {
color: rgb(64, 131, 169);
text-decoration: none;
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>I would say that for it to be semantically accurate, the <code>author</code> should be a part of the <code>blockquote</code>, perhaps using a <code>footer</code>.</p></li>\n<li><p>You should include a <code>cite</code> attribute if the quote has a source.</p></li>\n<li><p>The quote content should be inside a paragraph element.</p></li>\n<li><p>I guess now you don't need the wrapper any more.</p>\n\n<pre><code> <blockquote cite=\"http://knowyourmeme.com/memes/doge\">\n <p>&ldquo;Such cool. Much awesome. WOW&rdquo;</p>\n\n <footer class=\"author\">\n &ndash; \n <strong>Doge</strong>, \n <a href=\"#\">The Moon</a>\n </footer>\n </blockquote>\n</code></pre></li>\n<li><p>To make it look the same I had to change these bits of CSS:</p>\n\n<pre><code>blockquote {\n font-size: 22px;\n margin: 0;\n}\n\nblockquote p {\n background-color: rgb(255, 255, 255);\n border-radius: 6px;\n font-family: Georgia, serif;\n line-height: 1.4;\n padding: 17px;\n}\n\nfooter.author {\n background-color: transparent;\n font-weight: 500;\n font-size: 22px;\n line-height:22px;\n margin: 24px 0 0 18px;\n}\n</code></pre></li>\n<li><p><a href=\"http://codepen.io/anon/pen/ufsxA\">Here's the result</a>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T08:03:12.137",
"Id": "70340",
"Score": "3",
"body": "Such CSS. Much helpful. Wow"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T17:30:03.067",
"Id": "70437",
"Score": "0",
"body": "It was pointed out by Unor that citation should be placed outside the `<blockquote>`. [the blockquote element](http://www.w3.org/TR/2013/CR-html5-20130806/grouping-content.html#the-blockquote-element)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T18:49:56.390",
"Id": "70466",
"Score": "0",
"body": "@JGallardo That's not what it says... The `cite` attribute is **on** the `<blockquote>` element."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T18:50:30.737",
"Id": "70467",
"Score": "0",
"body": "@JGallardo Sorry, you meant the author. I didn't read the other answer."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T01:26:29.250",
"Id": "41022",
"ParentId": "41017",
"Score": "13"
}
},
{
"body": "<ol>\n<li><p>Your use of blockquote is correct. You can pretty much use div's for anything you want, but blockquote is the preferred way for quoting other people or sources. <a href=\"http://www.w3schools.com/tags/tag_blockquote.asp\">http://www.w3schools.com/tags/tag_blockquote.asp</a></p></li>\n<li><p>Your use of strong is incorrect in my opinion. </p></li>\n</ol>\n\n<p>From <a href=\"http://www.w3schools.com/tags/tag_strong.asp\">http://www.w3schools.com/tags/tag_strong.asp</a></p>\n\n<blockquote>\n <p>In HTML 4.01, the tag defines strong emphasized text, but in\n HTML5 it defines important text.</p>\n</blockquote>\n\n<p>I don't think the person's name is important to your website. </p>\n\n<p>Your other option of course would be to use something like</p>\n\n<pre><code><span class=\"quotersname\">Doge</span>\n\n.quotersname { font-size: 18px; font-weight: 800; }\n</code></pre>\n\n<p>However, I don't think it's that big of a deal either way. But I would personally use something like the second way.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T01:28:06.013",
"Id": "41023",
"ParentId": "41017",
"Score": "12"
}
},
{
"body": "<p>Using <code>blockquote</code> would be appropriate.</p>\n\n<p><s>\nJivings <a href=\"https://codereview.stackexchange.com/a/41022/16414\">suggested</a> to include the author in the <code>blockquote</code>, but please note that this is <a href=\"http://www.w3.org/TR/2013/CR-html5-20130806/grouping-content.html#the-blockquote-element\" rel=\"nofollow noreferrer\">not allowed in HTML5 (CR)</a>:</p>\n\n<blockquote>\n <p>Attribution for the quotation, if any, must be placed outside the <code>blockquote</code> element.\n </s></p>\n</blockquote>\n\n<p><strong>UPDATE:</strong> The <a href=\"http://www.w3.org/TR/2014/CR-html5-20140204/grouping-content.html#the-blockquote-element\" rel=\"nofollow noreferrer\">new HTML5 CR</a> changed this rule:</p>\n\n<blockquote>\n <p>[…] optionally with a citation which must be within a <code>footer</code> or <code>cite</code> element […]</p>\n</blockquote>\n\n<p>(<a href=\"http://www.w3.org/TR/2014/CR-html5-20140204/text-level-semantics.html#the-cite-element\" rel=\"nofollow noreferrer\"><code>cite</code></a> was also changed, so that it can be used for person names now.)</p>\n\n<p>So these are allowed now:</p>\n\n\n\n<pre class=\"lang-html prettyprint-override\"><code><blockquote>\n <p>Such cool. Much awesome. WOW.</p>\n <footer class=\"author\">Doge</footer>\n</blockquote>\n\n<blockquote>\n <p>Such cool. Much awesome. WOW.</p>\n <cite class=\"author\">Doge</cite>\n</blockquote>\n\n<blockquote>\n <p>Such cool. Much awesome. WOW.</p>\n <footer>\n <cite class=\"author\">Doge</cite>\n </footer>\n</blockquote>\n</code></pre>\n\n<hr>\n\n<p>Using <code>strong</code> is not appropriate in all cases, but there might be cases where it could be used. Remember that it represents \"<a href=\"http://www.w3.org/TR/2013/CR-html5-20130806/text-level-semantics.html#the-strong-element\" rel=\"nofollow noreferrer\">strong importance</a>\".</p>\n\n<p>In some other cases, the <a href=\"http://www.w3.org/TR/2013/CR-html5-20130806/text-level-semantics.html#the-b-element\" rel=\"nofollow noreferrer\"><code>b</code> element</a> could be used.</p>\n\n<p>If you need an element for the person’s name suitable for all contexts/situations, you’d have to go with <a href=\"http://www.w3.org/TR/2013/CR-html5-20130806/text-level-semantics.html#the-span-element\" rel=\"nofollow noreferrer\"><code>span</code></a>.</p>\n\n<hr>\n\n<p>Depending in which context the testimonial is published, you might consider to use the <a href=\"http://www.w3.org/TR/2013/CR-html5-20130806/grouping-content.html#the-figure-element\" rel=\"nofollow noreferrer\"><code>figure</code> element</a>.</p>\n\n<p>If you use <code>figure</code> (or a sectioning element like <code>article</code>) for a testimonial, you should enclose the author in a <a href=\"http://www.w3.org/TR/2013/CR-html5-20130806/sections.html#the-footer-element\" rel=\"nofollow noreferrer\"><code>footer</code> element</a>. (See the <a href=\"https://stackoverflow.com/a/21489636/1591669\">last example in my answer</a> to a different question.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T18:59:56.843",
"Id": "70474",
"Score": "0",
"body": "Nice! I hadn't read that section. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T19:22:47.350",
"Id": "70482",
"Score": "0",
"body": "@Jivings, does that change your answer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T19:41:41.907",
"Id": "70487",
"Score": "0",
"body": "@JGallardo Yes, you should abide by the HTML5 spec."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T13:57:01.767",
"Id": "41068",
"ParentId": "41017",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "41022",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T23:21:05.483",
"Id": "41017",
"Score": "17",
"Tags": [
"html",
"css"
],
"Title": "Testimonial section with HTML tags"
}
|
41017
|
<p>I tried to make a calculator in Java and have added some stuff. I'm a beginner and have learned yesterday how to make buttons.</p>
<pre><code>import java.awt.Dimension;
import javax.swing.*;
import java.awt.Toolkit;
import java.awt.event.*;
public class JavaCalculatorCopy extends JFrame{
JPanel Panel = new JPanel();
JTextArea Input = new JTextArea(1,16);
JTextArea Output = new JTextArea(1,16);
JTextArea Debug = new JTextArea(5,16);
JButton Button0 = new JButton("0");
JButton Button1 = new JButton("1");
JButton Button2 = new JButton("2");
JButton Button3 = new JButton("3");
JButton Button4 = new JButton("4");
JButton Button5 = new JButton("5");
JButton Button6 = new JButton("6");
JButton Button7 = new JButton("7");
JButton Button8 = new JButton("8");
JButton Button9 = new JButton("9");
JButton ButtonDecimalPoint = new JButton(".");
JButton ButtonAns = new JButton("Ans");
JButton ButtonMakeNegative = new JButton("(-)");
JButton ButtonPlus = new JButton("+");
JButton ButtonMinus = new JButton("-");
JButton ButtonTimes = new JButton("*");
JButton ButtonDividedBy = new JButton("/");
JButton ButtonSquared = new JButton("^2");
JButton ButtonPower = new JButton("^");
JButton ButtonSquareRoot = new JButton("√");
JButton ButtonEquals = new JButton("=");
JButton ButtonReset = new JButton("Reset");
String InputString;
String FirstValue = new String();
String SecondValue = new String();
int whatOperator = 20;
double outputNumber;
double AnsValue;
double FirstNumber;
double SecondNumber;
boolean OutputInUse = false;
public static void main(String[] args){
new JavaCalculatorCopy();
}
public JavaCalculatorCopy(){
SetDebugScreen();
this.setSize(220, 390);
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension dim = tk.getScreenSize();
int xPos = (dim.width / 2) - (this.getWidth() / 2);
int yPos = (dim.height / 2) - (this.getHeight() / 2);
this.setLocation(xPos, yPos);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("De Wombat-Calculator");
Panel.add(Input);
ListenForButton lForButton = new ListenForButton();
Button9.addActionListener(lForButton);
Button8.addActionListener(lForButton);
Button7.addActionListener(lForButton);
ButtonPlus.addActionListener(lForButton);
Button4.addActionListener(lForButton);
Button5.addActionListener(lForButton);
Button6.addActionListener(lForButton);
ButtonMinus.addActionListener(lForButton);
Button1.addActionListener(lForButton);
Button2.addActionListener(lForButton);
Button3.addActionListener(lForButton);
ButtonTimes.addActionListener(lForButton);
Button0.addActionListener(lForButton);
ButtonAns.addActionListener(lForButton);
ButtonEquals.addActionListener(lForButton);
ButtonDividedBy.addActionListener(lForButton);
ButtonSquareRoot.addActionListener(lForButton);
ButtonPower.addActionListener(lForButton);
ButtonDecimalPoint.addActionListener(lForButton);
ButtonMakeNegative.addActionListener(lForButton);
ButtonSquared.addActionListener(lForButton);
ButtonReset.addActionListener(lForButton);
Panel.add(Button7);
Panel.add(Button8);
Panel.add(Button9);
Panel.add(ButtonPlus);
Panel.add(Button4);
Panel.add(Button5);
Panel.add(Button6);
Panel.add(ButtonMinus);
Panel.add(Button1);
Panel.add(Button2);
Panel.add(Button3);
Panel.add(ButtonTimes);
Panel.add(Button0);
Panel.add(ButtonAns);
Panel.add(ButtonEquals);
Panel.add(ButtonDividedBy);
Panel.add(ButtonSquareRoot);
Panel.add(ButtonPower);
Panel.add(ButtonDecimalPoint);
Panel.add(ButtonMakeNegative);
Panel.add(ButtonSquared);
Panel.add(Output);
Panel.add(ButtonReset);
Panel.add(Debug);
this.add(Panel);
this.setVisible(true);
}
private class ListenForButton implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getSource() == Button0){
SetButton("0");
}else if(e.getSource() == Button1){
SetButton("1");
}else if(e.getSource() == Button2){
SetButton("2");
}else if(e.getSource() == Button3){
SetButton("3");
}else if(e.getSource() == Button4){
SetButton("4");
}else if(e.getSource() == Button5){
SetButton("5");
}else if(e.getSource() == Button6){
SetButton("6");
}else if(e.getSource() == Button7){
SetButton("7");
}else if(e.getSource() == Button8){
SetButton("8");
}else if(e.getSource() == Button9){
SetButton("9");
}else if(e.getSource() == ButtonMakeNegative){
SetButton("-");
}else if(e.getSource() == ButtonDecimalPoint){
SetButton(".");
}else if(e.getSource() == ButtonPlus){
SetButton(" + ", 0, 1);
}else if(e.getSource() == ButtonMinus){
SetButton(" - ", 1, 1);
}else if(e.getSource() == ButtonTimes){
SetButton(" * ", 2, 1);
}else if(e.getSource() == ButtonDividedBy){
SetButton(" / ", 3, 1);
}else if(e.getSource() == ButtonPower){
SetButton("^", 4, 1);
}else if(e.getSource() == ButtonSquared){
SetButton("^2", 6, 1);
}else if(e.getSource() == ButtonSquareRoot){
SetButton("√", 5, 0);
}else if(e.getSource() == ButtonEquals){
if(SecondValue.equals("")|SecondValue.equals("-")){
}else{
FirstNumber = Double.parseDouble(SecondValue);
}
if(whatOperator != 7){
SecondNumber = Double.parseDouble(FirstValue);
}
if(whatOperator == 0){
outputNumber = FirstNumber + SecondNumber;
}else if(whatOperator == 1){
outputNumber = FirstNumber - SecondNumber;
}else if(whatOperator == 2){
outputNumber = FirstNumber * SecondNumber;
}else if(whatOperator == 3){
outputNumber = FirstNumber / SecondNumber;
}else if(whatOperator == 4){
outputNumber = Math.pow(FirstNumber, SecondNumber);
}else if(whatOperator == 5){
if(SecondValue.equals("")){
outputNumber = Math.sqrt(SecondNumber);
}else if(SecondValue.equals("-")){
outputNumber = -1 * Math.sqrt(SecondNumber);
}else{
outputNumber = FirstNumber * Math.sqrt(SecondNumber);
}
}else if(whatOperator == 6){
outputNumber = Math.pow(FirstNumber, 2);
}
String AnsValue = Double.toString(outputNumber);
Output.append(AnsValue);
OutputInUse = true;
SetDebugScreen();
}else if(e.getSource() == ButtonReset){
Reset();
}else if(e.getSource() == ButtonAns){
SetButton("Ans");
FirstValue = Double.toString(AnsValue);
}
}
}
private void SetDebugScreen(){
Debug.setText("FirstValue: " + FirstValue + "\nSecondValue: " + SecondValue + "\nAns Value: " + AnsValue + "\nwhatOperator: " + whatOperator);
}
public void Reset() {
Input.setText("");
Output.setText("");
FirstValue = "";
SecondValue = "";
whatOperator = 20;
OutputInUse = false;
SetDebugScreen();
}
public void SetButton(String i, int j, int k) {
CheckOutput(k);
if(whatOperator == 20){
Input.append(i);
whatOperator = j;
PassData();
}else if(whatOperator == 2){
Input.append(i);
whatOperator = j;
}
}
public void SetButton(String i) {
CheckOutput(0);
Input.append(i);
FirstValue += i;
}
private void PassData() {
SecondValue = FirstValue;
FirstValue = "";
}
private void CheckOutput(int h){
if(OutputInUse && h == 0){
Reset();
}else if(OutputInUse){
Reset();
FirstValue = Double.toString(AnsValue);
Input.setText("Ans");
}
}
}
</code></pre>
<p>I tried to make it as clear as possible. Could someone give me some advice on how to improve this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T00:23:37.613",
"Id": "70292",
"Score": "3",
"body": "Note: Possible bug: `if(SecondValue.equals(\"\")|SecondValue.equals(\"-\"))`"
}
] |
[
{
"body": "<p>This is more to tackle than would be easy to cover in a single answer.</p>\n\n<h2>Small items.</h2>\n\n<p>There are a couple of small items that are a problem.</p>\n\n<ul>\n<li><p>you are using capitalized names for variables.... this is against the coding style for Java. Variable names should always start with a lower-case letter. For example, your <code>Button7</code> should be <code>button7</code>.</p></li>\n<li><p><code>if(SecondValue.equals(\"\")|SecondValue.equals(\"-\"))</code> uses the <code>bitwise OR</code> operator (<code>|</code>) instead of the <code>logical OR</code> operator <code>||</code>. This produces the same effective result, in this instance, except that <code>||</code> is a short-circuit operator (if the first condition is true, it does not even evaluate the subsequent conditions), whereas the <code>|</code> operator will evaluate both sides of the expression. The problem is most apparent in situations like:</p>\n\n<pre><code>if (mystring == null || mystring.length() == 0) {\n return \"Foo\";\n}\n</code></pre>\n\n<p>the above expression will return \"Foo\" for a null <code>mystring</code>, but the situation:</p>\n\n<pre><code>if (mystring == null | mystring.length() == 0) {\n return \"Foo\";\n}\n</code></pre>\n\n<p>will throw a null-pointer exception for a null <code>mystring</code></p>\n\n<p>The use of <code>|</code> between boolean expressions is very, very unusual, and, unless it is doing bitwise logic, I would <strong>always</strong> consider it a bug.</p></li>\n<li><p>The application allows you to create broken calculations (if you are a broken user, like me). For example, entering <code>2</code> and <code>^2</code> and <code>=</code> causes a <code>NumberFormatException</code>.</p></li>\n<li><p>you are not taking in to account the <a href=\"http://docs.oracle.com/javase/tutorial/uiswing/concurrency/\">thread-model in the Swing framework</a>. All your work is being done on <a href=\"http://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html\">the EventDispatchThread</a>. In this instance, the work you are doing is relatively trivial, and probably will not impact the user experience, but, it is a really, really bad habit to start to learn... use the right threads for the job.</p></li>\n<li><p>your layout in your manager is not quite right.... I can't see the actual problem in the code, but visually, the buttons are not quite lining up vertically.... You should be <a href=\"http://docs.oracle.com/javase/tutorial/uiswing/layout/grid.html\">using the GridLayout</a>?</p></li>\n</ul>\n\n<h2>Using an appropriate structure</h2>\n\n<p>OK, that's some minor stuff to start with. The real issue, as I am sure you are aware, is that you have a <strong>lot</strong> of code duplication.</p>\n\n<p>I would strongly recommend that you separate out the display logic from the calculation engine. Right now you have a single, large, class that does both.</p>\n\n<p>The standard way to break up your program would be to use something like the <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\">Model-View-Controller (MVC)</a> system for user interaction. There is a relatively good description of the process <a href=\"http://www.oracle.com/technetwork/articles/javase/index-142890.html\">in this Java documentation</a>.</p>\n\n<p>The basic structure would be something like:</p>\n\n<ul>\n<li><p>A calculator Model class. This class contains just the mathematical guts of your application. This is your business logic. It has methods like:</p>\n\n<ul>\n<li>digit(int value)</li>\n<li>reset</li>\n<li>equals</li>\n<li>square</li>\n<li>divide</li>\n<li>addPropertyChangeListener(Listener ....)</li>\n</ul></li>\n<li><p>A calculator View class. This will have all the swing components, buttons, etc. It is what controls the display, and accepts user input. Complex designs will make the view an interface, and then have multiple implementations of the view (one for a web-site, one for a console, one for a GUI, one for an app, etc.).</p></li>\n<li><p>A calculator Controller class. This class ties the view(s) and the engine together.</p></li>\n</ul>\n\n<p>A big part of this system is the use of listeners (and interfaces). The <code>PropertyChangeListener</code> is how the model communicates with the Controller.... the controller then uses those events to trigger changes in the view(s).</p>\n\n<h2>The View</h2>\n\n<p>Most of your code duplication is related to the view. I strongly recommend that you create an enum called 'CalcButton' (or similar), and this enum looks something like:</p>\n\n<pre><code>public enum ButtonType {\n DIGIT, OPERATOR, CONTROL;\n}\n\npublic enum CalcButton {\n\n ZERO(\"0\", ButtonType.DIGIT),\n ONE(\"1\", ButtonType.DIGIT),\n .....\n NINE(\"9\", ButtonType.DIGIT),\n PLUS(\"+\", ButtonType.OPERATOR),\n .....\n EQUALS(\"=\", ButtonType.CONTROL),\n RESET(\"reset\", ButtonType.CONTROL);\n\n\n private final JButton myjbutton;\n private final ButtonType mytype;\n\n private CalcButton(String label, ButtonType btype) {\n myjbutton = new JButton(label);\n mytype = btype;\n }\n\n public final JButton getJButton() {\n return myjbutton;\n }\n\n public final ButtonType getButtonType() {\n return mytype;\n }\n\n}\n</code></pre>\n\n<p>The above is just to give you some ideas to start with..... but, with the above enum, consider the following:</p>\n\n<pre><code>CalcButton[][] calclayout = new CalcButton[][] {\n\n {CalcButton.SEVEN, CalcButton.EIGHT, CalcButton.NINE, CalcButton.PLUS},\n {CalcButton.FOUR, CalcButton.FIVE, CalcButton.SIX, CalcButton.MINUS},\n .....\n\n}\n\nJPanel panel = new JPanel(...);\n// set up appropriate Layout Manager....\n\nfor (int row = 0; row < calclayout.length; row++) {\n for (int col = 0; col < calclayout[row].length; col++) {\n CalcButton b = calclayout[row][col];\n panel.add(b.getJButton());\n b.getJButton().setActionListener(this);\n }\n}\n</code></pre>\n\n<h2>Conclusion</h2>\n\n<p>Right now, your code could do with a major refactor and shuffle. have a look at your options, and then try to bring it together in a more structured framework. Your current code has out-grown it's exoskeleton, and it's time to spread it's wings and try something different.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T21:49:26.713",
"Id": "71019",
"Score": "0",
"body": "Thanks for the information, I didn´t think I would get such a good and long answer :), unfortunately I don't understand a lot of it, I'll watch some more tutorials to get the basics right, thanks for the help."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T04:01:36.323",
"Id": "41031",
"ParentId": "41019",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "41031",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T23:46:33.453",
"Id": "41019",
"Score": "9",
"Tags": [
"java",
"beginner",
"swing",
"calculator"
],
"Title": "Java Calculator"
}
|
41019
|
<p>I'm working on a directed study project with a professor of mine helping him build out a Django based website. The website is a historical account of the people, events, projects, and organization in the computer graphics industry.</p>
<p>Since the beginning of the project (way before I started working on it) my professor has had the idea of creating a timeline of everything that has been entered into the site. The original team came up with this design.</p>
<p><img src="https://i.stack.imgur.com/VcKNJ.png" alt="timeline prototype image"></p>
<p>I worked on the project for all of last semester and started on building out this timeline feature around the middle of December. Since then I've continued to work on it till now, but on and off. I feel like that has attributed to some crappy code since I've walked into it without thinking about it for a week or two a number of times now.</p>
<p>Anyway, I've put together a JSFiddle of the current state of the project <strong><a href="http://jsfiddle.net/GowGuy47/9j98E/3/" rel="nofollow noreferrer">over here</a></strong>, which I'm hoping to get some advice and feedback on.</p>
<p>Here is the main JavaScript file:</p>
<pre><code>/*
* @Author: Gowiem
* @Date: 2013-12-17 14:21:17
*/
var Hist = Hist || {};
// Timeline Utils
//////////////////
Hist.TLUtils = (function() {
var timeConversions = { "year": 31557600000,
"month": 2628000000,
"day": 86400000 };
// Note: The following method uses memoization so it doesn't need to recalculate
// the range for a year/mod pair that it has already seen. This is definitely
// overkill, but I felt like doing this. :)
var rangeMemo = {};
var pubBuildRange = function(year, mod) {
var result = rangeMemo[year],
halfMod,
remainder,
rangeBegin,
rangeEnd;
// If we haven't seen the given year yet then continue and find the range.
if (!result) {
remainder = year % mod;
halfMod = mod / 2;
// Find the rangeBegin by using the remainder to determine if we need to start at xxx5 or xxx0
rangeBegin = remainder <= halfMod ? year - remainder : year - remainder + halfMod;
rangeEnd = rangeBegin + halfMod;
result = Hist.TLO.range(moment(rangeBegin, 'YYYY').valueOf(), moment(rangeEnd, 'YYYY').valueOf());
// Memoize the result so we don't have to do this again.
rangeMemo[year + "|" + mod] = result;
}
return result;
}
// TODO: Memoize same as above
var pubBuildMonthRange = function(date, numberOfMonths) {
var monthDate = moment(date).startOf('month');
rangeBegin = monthDate.clone().subtract('months', numberOfMonths);
rangeEnd = monthDate.clone().add('months', numberOfMonths);
result = Hist.TLO.range(rangeBegin.valueOf(), rangeEnd.valueOf());
return result;
}
var pubConvertTime = function(howMany, type) {
if (timeConversions.hasOwnProperty(type)) {
return howMany * timeConversions[type];
} else {
console.assert(false, "Hist.TLUtils.convertTime was given unknown type: ", type);
}
}
var pubRoundToDecade = function(date, shouldFloor) {
var year = date.getFullYear(),
remainder = year % 10,
roundedYear = shouldFloor ? (year - remainder) - 10 : (year - remainder) + 10,
roundedDate = new Date(date.getTime()).setFullYear(roundedYear);
return roundedDate;
}
var pubGenerateRandomId = function() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return {
buildRange: pubBuildRange,
roundToDecade: pubRoundToDecade,
convertTime: pubConvertTime,
buildMonthRange: pubBuildMonthRange,
generateRandomId: pubGenerateRandomId
}
})();
// Timeline Objects
////////////////////
Hist.TLO = Hist.TLO || {};
Hist.TLO.range = function(begin, end) {
var rangeObject = {},
beginEpoch = begin,
endEpoch = end,
begin = new Date(begin),
end = new Date(end),
differenceInYears = end.getYear() - begin.getYear();
var halfWayDate = function() {
return new Date(beginEpoch + ((endEpoch - beginEpoch)/2));
}
var toString = function() {
return "Range - begin: " + this.begin.toString() + " end: " + this.end.toString() + " halfWayDate: " + this.halfWayDate().toString();
}
// Fields
rangeObject.begin = begin;
rangeObject.end = end;
rangeObject.differenceInYears = differenceInYears;
// Methods
rangeObject.halfWayDate = halfWayDate;
rangeObject.toString = toString;
return rangeObject;
}
// Our Collection of Point Objects
Hist.TLO.pointCollection = function(pages) {
var collection = {},
allPoints = [],
current = [],
pointPositions = {},
point,
// Util Aliases
buildRange = Hist.TLUtils.buildRange,
buildMonthRange = Hist.TLUtils.buildMonthRange,
roundToDecade = Hist.TLUtils.roundToDecade,
// TLO Aliases
timelinePoint = Hist.TLO.timelinePoint,
multiPoint = Hist.TLO.multiPoint;
// Loop through the given pages and construct our timeline points
pages.forEach(function(page, idx) {
point = timelinePoint(page);
if (point.isValid()) {
allPoints.push(point);
current.push(point);
}
});
// Iterates through the timeline points to find their x and y positions
// and stores them in pointPositions for later use.
// Returns { point.id => { x: xPos, y: yPos }, ... }
var buildPointPositions = function(timelineRange) {
var pointsDup = this.current.clone(),
self = this,
count,
xPos,
pointYear,
range,
i;
this.current.forEach(function(point, outerIndex) {
count = 0;
xPos = null;
// Iterate through the dups to find the range that this point belongs in
// and how many other points are in that same range. This determined xPos
// which is the approximate year for the point and the count which is how
// high we should stack the point.
pointsDup.forEach(function(p, innerIndex) {
pointYear = point.date.year();
// Possible ranges:
// 80+ years: buckets of 5 years
// 30+ years: buckets of 4 years
// 20+ years: Buckets of 2 years
// 10+ years: Buckets of 1 year
// 4+ years: Buckets of 4 months
// 4- years: No Range, Only stack if in same month
if (timelineRange.differenceInYears >= 80) {
range = buildRange(p.date.year(), 10);
// console.log("=========== range is 80+");
} else if (timelineRange.differenceInYears >= 30) {
// console.log("=========== range is 30+");
range = buildRange(p.date.year(), 8);
} else if (timelineRange.differenceInYears >= 20) {
// console.log("=========== range is 20+");
range = buildRange(p.date.year(), 4);
} else if (timelineRange.differenceInYears >= 10) {
// console.log("=========== range is 10+");
range = buildMonthRange(p.date, 6);
} else if (timelineRange.differenceInYears >= 4) {
// console.log("=========== range is 4+");
range = buildMonthRange(p.date, 2);
} else {
// console.log("=========== range is 4-");
range = null;
}
// Check if point's date is within the range created by p
if (range && point.withinRange(range)) {
xPos = range.halfWayDate();
if (point.id !== p.id) {
count += 1;
}
} else if (point.isSameMonthAsPoint(p) && point.id !== p.id) {
xPos = p.date;
count += 1;
}
}); // End pointsDup.forEach
// Otherwise it stands alone and we should set the xPos to it's actual
// position.
if (!xPos) {
xPos = point.date;
}
// Remove the current point from pointsDup
pointsDup = hidePointWithId(point.id, pointsDup);
// Set the x and y position of the current point
self.pointPositions[point.id] = { 'x': xPos, 'y': count }
});
}
var clearPointPositions = function() {
this.pointPositions = {};
}
// TODO: Probably a smarter way of making this reusable for both 'this.current'
// and the pointsDup in buildPointPosn. Can't think of it now.
var hidePointWithId = function(pId, points) {
var pointId = parseInt(pId),
points = points || this.current;
return points.filter(function(p) {
return pointId !== p.id;
});
}
var filterInRange = function(range) {
this.current = this.allPoints.filter(function(point, idx) {
return point.withinRange(range);
});
}
var addMultiPoints = function(yearsToAdd) {
var self = this,
mPoint;
yearsToAdd = yearsToAdd.unique();
yearsToAdd.forEach(function(year, idx) {
mPoint = multiPoint(year);
self.current.push(mPoint);
self.pointPositions[mPoint.id] = { x: year, y: Hist.TL.config.maxOfStacked };
});
}
var replaceMaxStacked = function() {
var yearsToAddMultiPoint = [],
positionKeys = Object.keys(this.pointPositions),
self = this,
xPos,
yPos;
positionKeys.forEach(function(pId, idx) {
xPos = self.pointPositions[pId]['x'];
yPos = self.pointPositions[pId]['y'];
if (yPos >= Hist.TL.config.maxOfStacked) {
yearsToAddMultiPoint.push(xPos);
self.current = self.hidePointWithId(pId);
}
});
// Now that we've remove the points which were stacked too high we can
// add back the multiPoints in their place.
this.addMultiPoints(yearsToAddMultiPoint);
}
// Fields
collection.allPoints = allPoints;
collection.current = current;
collection.pointPositions = pointPositions;
// Methods
collection.buildPointPositions = buildPointPositions;
collection.clearPointPositions = clearPointPositions;
collection.filterInRange = filterInRange;
collection.hidePointWithId = hidePointWithId;
collection.replaceMaxStacked = replaceMaxStacked;
collection.addMultiPoints = addMultiPoints;
return collection;
}
// Our Point object
Hist.TLO.timelinePoint = function(page) {
var point = {};
// This is the kind of code you have to write when people use a table to
// represent a simple string. Seriously though, da fuq!
// TODO: I can do this simpler with an array.. doh.
var findType = function(categoryId) {
switch (categoryId) {
case 1:
return 'person';
case 2:
return 'project';
case 3:
return 'organization';
case 4:
return 'event';
default:
return null;
}
}
point.id = page['pk'];
point.name = page['fields']['name'] || page['name'];
point.vanityUrl = page['fields']['vanity_url'] || page['vanityUrl'];
point.description = page['fields']['description'] || page['description'];
point.date = moment(page['fields']['date_established']) || moment();
point.type = findType(page['fields']['type']) || page['type'];
point.pointImage = "/static/img/timeline/" + point.type + "-button.png";
var toString = function() {
return "Point -> id: " + this.id + " name: " + this.name + " date: " + this.date.format('l') + " type: " + this.type;
}
var isValid = function() {
return this.type != null && !!page['fields']['date_established'];
}
var withinRange = function(range) {
return this.date.isAfter(range.begin) && this.date.isBefore(range.end)
|| this.date.isSame(range.begin)
|| this.date.isSame(range.end);
}
var isSameMonthAsPoint = function(point) {
return this.date.isSame(point.date, 'year') && this.date.isSame(point.date, 'month');
}
var isSameDayAsPoint = function(point) {
return this.date.isSame(point.date, 'year') && this.date.isSame(point.date, 'month') && this.date.isSame(point.date, 'day');
}
point.toString = toString;
point.isValid = isValid;
point.withinRange = withinRange;
point.isSameMonthAsPoint = isSameMonthAsPoint;
point.isSameDayAsPoint = isSameDayAsPoint;
return point;
}
Hist.TLO.multiPoint = function(year) {
var pointDefaults = { name: "Multiple Available", vanityUrl: null,
description: "Multiple Available", type: 'multi',
fields: {} },
point = Hist.TLO.timelinePoint(pointDefaults);
point.id = Hist.TLUtils.generateRandomId();
point.date = moment(new Date(year, 5));
return point;
}
// Timeline
////////////
Hist.TL = (function() {
var margin = {top: 90, right: 30, bottom: 90, left: 30},
width = 960,
height = 300,
maxOfStacked = 4,
pointSize = 25,
yPosMargin = 30,
pointClicked = false,
timelinePoints,
brush,
xAxis,
xScale,
beginning,
ending,
chart,
// Alias our TimelineUtils methods
buildRange = Hist.TLUtils.buildRange,
buildMonthRange = Hist.TLUtils.buildMonthRange,
roundToDecade = Hist.TLUtils.roundToDecade,
// Alias our Timeline Objects
pointCollection = Hist.TLO.pointCollection,
timelinePoint = Hist.TLO.timelinePoint,
multiPoint = Hist.TLO.multiPoint;
var initD3Chart = function() {
var jsDates = timelinePoints.current.map(function(p) { return p.date.toDate(); });
beginning = roundToDecade(d3.min(jsDates), true);
ending = roundToDecade(d3.max(jsDates));
chart = d3.select('#timeline')
.attr('width', width)
.attr('height', height)
.append("g")
.attr("transform", "translate(" + margin.left + ",0)");
xScale = d3.time.scale()
.nice(d3.time.year, 100)
.domain([beginning, ending])
.range([0, width - margin.right - margin.left]);
xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom");
chart.append("g")
.attr("class", "x axis")
.attr('transform', 'translate(0,' + (height - margin.bottom) + ')')
.call(xAxis);
timelinePoints.buildPointPositions(Hist.TLO.range(beginning, ending));
// Replace the points which are stacked too high with multiPoints
timelinePoints.replaceMaxStacked();
var points = chart.selectAll(".timeline-point").data(timelinePoints.current);
points.enter()
.append("image")
.attr("class", "timeline-point")
.attr("id", function(p) { return 'point-' + p.id; })
.attr("x", getXPosition)
.attr("y", getYPosition)
.attr("cx", getXPosition)
.attr("cy", getYPosition)
.attr("height", pointSize)
.attr("width", pointSize)
.attr("xlink:href", function(p) { return p.pointImage; })
.on("mouseover", showActiveState)
.on("mouseout", hideActiveState)
.on("click", setClicked);
initContextArea();
}
var draw = function(range) {
var points;
// Create out pointPositions object
timelinePoints.clearPointPositions();
timelinePoints.buildPointPositions(range);
// Replace the points which are stacked too high with multiPoints
timelinePoints.replaceMaxStacked();
// Remove the current points
chart.selectAll(".timeline-point").remove();
// Set the newly filtered points as our new data
points = chart.selectAll(".timeline-point").data(timelinePoints.current);
points.enter()
.append("image")
.attr("class", "timeline-point")
.attr("id", function(p) { return 'point-' + p.id; })
.attr("x", getXPosition)
.attr("y", getYPosition)
.attr("cx", getXPosition)
.attr("cy", getYPosition)
.attr("height", pointSize)
.attr("width", pointSize)
.attr("xlink:href", function(p) { return p.pointImage; })
.on("mouseover", showActiveState)
.on("mouseout", hideActiveState)
.on("click", setClicked);
}
// D3 Plotting Helpers
///////////////////////
var getXPosition = function(point) {
var date = timelinePoints.pointPositions[point.id]['x'];
return xScale(date) - (pointSize / 2);
}
var getYPosition = function(point) {
// height - bottom => xAxis line
// xAxis line - yPosMargin => Starting yPos for a 0 count point
// starting yPos - (yPos[id] * pointSize) => final yPosition
return height - margin.bottom - yPosMargin - (pointSize * timelinePoints.pointPositions[point.id]['y']);
}
// SVG Brush Helpers
/////////////////////
var initContextArea = function() {
var contextWidth = 600,
contextHeight = 30,
contextTickSize = 30,
contextXAxis,
contextXScale,
contextArea,
context;
contextXScale = d3.time.scale()
.range([0, contextWidth])
.domain(xScale.domain());
contextXAxis = d3.svg.axis()
.scale(contextXScale)
.tickSize(contextTickSize)
.tickPadding(5)
.orient("bottom");
contextArea = d3.svg.area()
.interpolate("monotone")
.x(function(d) { return contextXScale(d); })
.y0(contextHeight)
.y1(0);
brush = d3.svg.brush()
.x(contextXScale)
.extent([beginning, ending])
.on("brushend", brushended);
context = d3.select("#timeline").append("g")
.attr("class", "context")
.attr("transform", "translate(" + (width / 2 - contextWidth / 2) + "," + (height - margin.bottom + 25) + ")");
context.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0,0)")
.call(contextXAxis);
gBrush = context.append("g")
.attr("class", "brush")
.call(brush)
.call(brush.event);
gBrush.selectAll("rect")
.attr('transform', 'translate(0,0)')
.attr("height", contextTickSize);
}
var brushended = function() {
var extent0 = brush.extent(),
begin = extent0[0],
end = extent0[1],
range = Hist.TLO.range(begin, end);
xScale.domain([begin, end]);
xAxis.scale(xScale);
chart.select(".x.axis").call(xAxis);
timelinePoints.filterInRange(range);
draw(range);
}
// Timeline Interaction Helpers
////////////////////////////////
// TODO: Pull out to own module and merge with Hist.TL on init
var initDomEventHandlers = function() {
// Clicked away from a point handler, sets the state to inactive
$("body").live("click", function(){
var activePoint = $('#timeline').data('active-point'),
activeEl;
setUnclicked();
if (activePoint) {
activeEl = $('#point-' + activePoint.id)[0];
hideActiveState.call(activeEl, activePoint);
}
});
}
var setClicked = function(point) {
pointClicked = true;
// Stop the event from bubbling up to body where we have a click handler to
// deactivate the current point. d3.event is the current event for this click
d3.event.stopPropagation();
}
var setUnclicked = function() {
pointClicked = false;
}
// Active State - Mousing over or clicked
var showActiveImage = function(element, point) {
var hoverImageUrl = point.pointImage.replace(/(.*)\.png/, "$1-hover.png");
d3.select(element).attr("xlink:href", hoverImageUrl);
}
var addDescriptionToPoint = function(description) {
if (description.length <= 200) {
$('.regular-point .description').text(description);
} else {
$('.regular-point .description').text(description.substring(0, 200) + "...");
}
}
var showPopup = function(element, point) {
var d3Element = d3.select(element),
leftPos = parseInt(d3Element.attr('x')),
topPos = parseInt(d3Element.attr('y')),
leftOffset,
topOffset,
popupLeft;
// Hide both popups so we aren't showing both.
$('.popup').hide();
if (point.type !== 'multi') {
// Setup the content now so we can grab the height and use it to calculate the topOffset
$('.regular-point h3').text(point.name);
addDescriptionToPoint(point.description);
$('.regular-point .date').text(point.date.format("dddd, MMMM Do YYYY"));
$('.regular-point a').attr('href', "/pages/" + point.vanityUrl);
$('.regular-point').removeClass()
.addClass(point.type)
.addClass("popup")
.addClass("regular-point")
.show();
} else {
$('.multi-point').show();
}
popupHeight = $('#popup-container').height();
leftOffset = (pointSize / 2);
topOffset = (pointSize / 2) + popupHeight + 11; // +11 px is for padding I think..
// Now that we have the offset we can find the absolute position of the popup
popupLeft = leftPos + pointSize + leftOffset + 'px';
popupTop = topPos + pointSize - topOffset + 'px';
$('#popup-container').css({ left: popupLeft, top: popupTop }).show()
}
var showActiveState = function(point) {
// We just moused into a point, clear the last clicked point (if any)
setUnclicked();
if ($('#timeline').data('active-point')) {
// Passing null here as hideActiveImage will find the element from the given point.id
hideActiveImage(null, $('#timeline').data('active-point'));
}
// Set the hover point image and configure/show the popup
showActiveImage(this, point);
showPopup(this, point);
// Store the currently active point so we can deactive it later
$('#timeline').data('active-point', point);
}
// Deactive State
//////////////////
var hideActiveImage = function(element, point) {
// If we weren't passed the element then find it by the given point.id, otherwise select it
d3El = element === null ? d3.select('#point-' + point.id) : d3.select(element);
d3El.attr("xlink:href", point.pointImage);
}
var hidePopup = function() {
$('#popup-container').hide();
}
var hideActiveState = function(point) {
// If we are currently focusing on a point (have clicked it) then we don't
// want to hide the active state.
if (!pointClicked) {
hideActiveImage(this, point);
hidePopup();
}
}
// Public Interface
////////////////////
return {
init: function() {
if (Hist.rawPages != null) {
timelinePoints = pointCollection(Hist.rawPages);
initD3Chart();
initDomEventHandlers();
}
},
config: {
maxOfStacked: maxOfStacked
}
}
})();
</code></pre>
<p><strong>The main aspect I know I need to refactor is the way I'm handling the sorting the timeline points into approximated buckets depending on how far zoomed out/in the user is.</strong> The majority of the code for that is in <code>PointCollection#buildPointPositions</code>. If anybody can give me a good idea on how I can improve that then that would be awesome, because as of right now it's a buggy nightmare and it's also slow as hell (I think it's \$O(N^2)\$; correct me if I'm wrong there) which isn't working with the amount of data that we have even on our staging site.</p>
<p>Here are a few of the other pain points I'd like to get feedback on:</p>
<ul>
<li><p>I've modeled the Timeline Objects after Douglas Crockford's "Functional Object Constructor Pattern" from <em>JavaScript: The Good Parts</em>. This is the first time I've used this pattern and I think it was a good fit for this project, but I've never heard of others using it. Any thoughts on this? </p></li>
<li><p>I use moment.js and JavaScript native Date object back and forth through out my code. Looking back on it now I think I should have just picked one and stuck with it.</p></li>
<li><p>Also, any comments on style or other patterns which you think I should avoid/add to my JavaScript tool-kit then please let me know.</p></li>
</ul>
|
[] |
[
{
"body": "<p>That's a lot of code, a small observation to start with:</p>\n\n<pre><code> var rangeMemo = {};\n var pubBuildRange = function(year, mod) {\n var result = rangeMemo[year], ..snip..;\n // If we haven't seen the given year yet then continue and find the range.\n if (!result) {\n ..snip..\n // Memoize the result so we don't have to do this again.\n rangeMemo[year + \"|\" + mod] = result;\n }\n</code></pre>\n\n<p>If you store your result under <code>year + \"|\" + mod</code> but look up thru <code>year</code>, then your memoization will not ever work.</p>\n\n<p>Also, consider using more object literal notation, this</p>\n\n<pre><code>Hist.TLO.range = function(begin, end) {\n var rangeObject = {},\n beginEpoch = begin,\n endEpoch = end,\n begin = new Date(begin),\n end = new Date(end),\n differenceInYears = end.getYear() - begin.getYear();\n\n var halfWayDate = function() {\n return new Date(beginEpoch + ((endEpoch - beginEpoch)/2));\n }\n\n var toString = function() {\n return \"Range - begin: \" + this.begin.toString() + \" end: \" + this.end.toString() + \" halfWayDate: \" + this.halfWayDate().toString();\n }\n\n // Fields\n rangeObject.begin = begin;\n rangeObject.end = end;\n rangeObject.differenceInYears = differenceInYears;\n\n // Methods\n rangeObject.halfWayDate = halfWayDate;\n rangeObject.toString = toString;\n\n return rangeObject;\n}\n</code></pre>\n\n<p>can be this:</p>\n\n<pre><code>Hist.TLO.range = function(beginEpoch, endEpoch) {\n\n return {\n begin: new Date(beginEpoch),\n end: new Date(endEpoch),\n differenceInYears: new Date(endEpoch).getYear() - Date(beginEpoch).getYear(),\n\n halfWayDate : function() {\n return new Date(beginEpoch + ((endEpoch - beginEpoch)/2));\n },\n toString = function() {\n return \"Range - begin: \" + this.begin.toString() + \" end: \" + this.end.toString() + \" halfWayDate: \" + this.halfWayDate().toString();\n }\n };\n}\n</code></pre>\n\n<p>I am still not excited about halfWayDate, why is it a function, and why is not picking up begin and end from <code>this</code>, it seems a future source of bugs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T20:40:53.790",
"Id": "70680",
"Score": "0",
"body": "The point on the bad memoization is a good catch. I originally was just keying off the year and then I changed my code a bit and forgot to update it.\n\nAs for the object literal notation, that does clean that object up a bit so I definitely agree with you. And another good point on halfWayDate being a function. That should just be a property that is only computed once. I'll make sure to change that.\n\nThanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T14:09:10.147",
"Id": "41069",
"ParentId": "41021",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T01:19:11.173",
"Id": "41021",
"Score": "2",
"Tags": [
"javascript",
"performance",
"datetime",
"sorting",
"d3.js"
],
"Title": "Approximating/Sorting groups of dates into buckets"
}
|
41021
|
<p>I'm just starting to understand the Python syntax and I created a module that does what I wanted, but really slow.</p>
<p>Here are the stats of cProfile, top 10 ordered by <code>internal time</code>:</p>
<pre><code> ncalls tottime percall cumtime percall filename:lineno(function)
1291716 45.576 0.000 171.672 0.000 geometry.py:10(barycentric_coords)
6460649 31.617 0.000 31.617 0.000 {numpy.core.multiarray.array}
2583432 15.979 0.000 15.979 0.000 {method 'reduce' of 'numpy.ufunc'
objects}
2031 12.032 0.006 193.333 0.095 geometry.py:26(containing_tet)
1291716 10.944 0.000 58.323 0.000 linalg.py:244(solve)
1291716 7.075 0.000 7.075 0.000 {numpy.linalg.lapack_lite.dgesv}
1291716 5.750 0.000 9.865 0.000 linalg.py:99(_commonType)
2583432 5.659 0.000 5.659 0.000 {numpy.core.multiarray._fastCopyAn
dTranspose}
1291716 5.526 0.000 7.299 0.000 twodim_base.py:169(eye)
1291716 5.492 0.000 12.791 0.000 numeric.py:1884(identity)
</code></pre>
<p><strong>To process data and create a 24 bitmap of 300*300 pixels it would take about 1 1/2 hour on my laptop with the latest intel i5, a SSD disk and 12gb RAM!</strong></p>
<p>I am not sure if it's a good idea to post all the code, but if not how can you get the entire picture?</p>
<p>The first thing <code>colors_PPM.py</code> does is to access a function called <code>geometry</code>.</p>
<p><code>geometry.py</code> itself calls <code>tetgen</code>, <code>tetgen.py</code> calls <code>tetgen.exe</code>.</p>
<p>The module <code>colors_PPM.py</code> reads a list in <code>targets.csv</code> and a list in <code>XYZcolorlist_D65.csv</code>, it excludes some elements of <code>XYZcolorlist_D65.csv</code> and then reads one by one the rows of <code>targets.csv</code>, performs a delaunay triangulation via <code>tetgen</code> and returns 4 <code>names[]</code> and 4 <code>bcoords[]</code>.</p>
<p>Then <code>random</code> is used to choose one <code>name</code> by a series of <code>if</code> <code>elif</code> <code>else</code> tests.</p>
<p>Finally the result is exported in a bitmap file <code>epson_gamut.pbm</code>.</p>
<p>Do you see any way this could run faster? I know it should seem quite a mess.</p>
<p><code>.csv</code> files structures examples:</p>
<p>'XYZcolorlist_D65.csv'</p>
<pre><code>255 63 127,35.5344302104,21.380721966,20.3661095969
255 95 127,40.2074945517,26.5282949405,22.7094284437
255 127 127,43.6647438365,32.3482625492,23.6181801523
255 159 127,47.1225628354,39.1780944388,22.9366615044
255 223 159,61.7379149646,62.8387601708,32.3936200864
255 255 159,70.7428790853,78.6134546144,29.5579371353
255 0 127,32.0951763469,18.3503537537,19.0863164396
255 31 127,32.281389139,18.5592317077,18.6802029444
255 191 127,52.6108977261,48.5621713952,21.7645428218
255 223 127,59.7600830083,60.9770436618,20.9338174593
...
</code></pre>
<p>'targets.csv'</p>
<pre><code>30,5,3
30.34,5,3
30.68,5,3
31.02,5,3
31.36,5,3
31.7,5,3
32.04,5,3
32.38,5,3
32.72,5,3
33.06,5,3
33.4,5,3
33.74,5,3
...
</code></pre>
<p>This is <code>geometry.py</code>:</p>
<pre><code>#geometry.py
import numpy as np
import numpy.linalg as la
import tetgen
def barycentric_coords(vertices, point):
T = (np.array(vertices[:-1])-vertices[-1]).T
v = np.dot(la.inv(T), np.array(point)-vertices[-1])
v.resize(len(vertices))
v[-1] = 1-v.sum()
return v
def tetgen_of_hull(points):
tg_all = tetgen.TetGen(points)
hull_i = set().union(*tg_all.hull)
hull_points = [points[i] for i in hull_i]
tg_hull = tetgen.TetGen(hull_points)
return tg_hull, hull_i
def containing_tet(tg, point):
for i, tet in enumerate(tg.tets):
verts = [tg.points[j] for j in tet]
bcoords = barycentric_coords(verts, point)
if (bcoords >= 0).all():
return i, bcoords
return None, None
</code></pre>
<p>This is <code>tetgen.py</code>:</p>
<pre><code>#tetgen
import tempfile, subprocess, os
class TetGen:
def __init__(self, points):
self.points = points
node_f = tempfile.NamedTemporaryFile(suffix=".node", delete=False);
node_f.write("%i 3 0 0\n" % len(points))
for i, point in enumerate(points):
node_f.write("%i %f %f %f\n" % (i, point[0], point[1], point[2]))
node_f.close()
subprocess.call(["tetgen", node_f.name], stdout=open(os.devnull, 'wb'))
#subprocess.call(["C:\Users\gary\Documents\eclipse\Light Transformer Setup\tetgen", node_f.name], stdout=open(os.devnull, 'wb'))
ele_f_name = node_f.name[:-5] + ".1.ele"
face_f_name = node_f.name[:-5] + ".1.face"
ele_f_lines = [line.split() for line in open(ele_f_name)][1:-1]
face_f_lines = [line.split() for line in open(face_f_name)][1:-1]
self.tets = [map(int, line[1:]) for line in ele_f_lines]
self.hull = [map(int, line[1:]) for line in face_f_lines]
if __name__ == '__main__':
from pprint import pprint
points = [(0,0,0),(0,0,1),(0,1,0),(0,1,1),(1,0,0),(1,0,1),(1,1,0),(1,1,1)]
tg = TetGen(points)
pprint(tg.tets)
pprint(tg.hull)
</code></pre>
<p>And this is the module <code>colors_PPM.py</code>:</p>
<pre><code>import geometry
import csv
import numpy as np
import random
import cv2
S = 0
img = cv2.imread("MAP.tif", -1)
height, width = img.shape
ppm = file("epson gamut.ppm", 'w')
ppm.write("P3" + "\n" + str(width) + " " + str(height) + "\n" + "255" + "\n")
# PPM file header
all_colors = [(name, float(X), float(Y), float(Z))
for name, X, Y, Z in csv.reader(open('XYZcolorlist_D65.csv'))]
tg, hull_i = geometry.tetgen_of_hull([(X,Y,Z) for name, X, Y, Z in all_colors])
colors = [all_colors[i] for i in hull_i]
print ("thrown out: "
+ ", ".join(set(zip(*all_colors)[0]).difference(zip(*colors)[0])))
targets = ((float(X), float(Y), float(Z))
for X, Y, Z in csv.reader(open('targets.csv')))
for target in targets:
X, Y, Z = target
target_point = (np.array([X,Y,Z]))
tet_i, bcoords = geometry.containing_tet(tg, target_point)
if tet_i == None:
ppm.write(str("255 255 255") + "\n")
continue
# not in gamut
else:
A = bcoords[0]
B = bcoords[1]
C = bcoords[2]
D = bcoords[3]
R = random.uniform(0,1)
names = [colors[i][0] for i in tg.tets[tet_i]]
if R <= A:
S = names[0]
elif R <= A+B:
S = names[1]
elif R <= A+B+C:
S = names[2]
else:
S = names[3]
ppm.write(str(S) + "\n")
print "done"
ppm.close()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T10:50:01.310",
"Id": "70370",
"Score": "0",
"body": "Did you [profile](http://docs.python.org/2/library/profile.html)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T11:11:14.677",
"Id": "70371",
"Score": "0",
"body": "sorry but I dont know how to do that, I'm still quite a beginner... :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T11:48:24.300",
"Id": "70373",
"Score": "0",
"body": "This code is in such a mess that it's expecting way too much of us to try to figure out what it does and why it's slow, especially since we don't have your tetgen program. You need to do more work here: in particular, which bit is slow? Is it the initial `tetgen_of_hull`? Or is it the later loop over the `targets`? As Janne says, it would be worth starting by learning to use the profiler."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T15:33:30.233",
"Id": "70414",
"Score": "0",
"body": "[See the manual](http://docs.python.org/2.7/library/profile.html#instant-user-s-manual), paragraph starting \"The file cProfile can also be invoked as a script to profile another script.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T15:57:31.807",
"Id": "70421",
"Score": "0",
"body": "@Janne Karila @Gareth Rees Thanks, I added the cProfile report: major time is spent in the module `geometry.py`"
}
] |
[
{
"body": "<h3>1. Introduction</h3>\n\n<p>Thanks for running the profiler. As you can see from the output, most of the runtime is being spent in your <code>containing_tet</code> function.</p>\n\n<p>The first thing to say is that you have made this question unnecessarily difficult for us because your functions have no documentation. We have to read and reverse-engineer your code to try to figure out what the purpose of each function is. Python allows you to write a \"docstring\" for each function in which you explain what the function does, what arguments it takes, and what values it returns.</p>\n\n<p>It looks to me as though <code>containing_tet</code> tries to find a tetrahedron containing <code>point</code>, and it does so by computing the <a href=\"http://en.wikipedia.org/wiki/Barycentric_coordinate_system\" rel=\"noreferrer\">barycentric coordinates</a> of <code>point</code> within each tetrahedron and checking that all the coordinates are non-negative.</p>\n\n<p>So you could have written:</p>\n\n<pre><code>def containing_tet(tg, point):\n \"\"\"If point is inside the i'th tetrahedron in tg, return the pair\n (i, bcoords) where bcoords are the barycentric coordinates of\n point within that tetrahedron. Otherwise, return (None, None).\n\n \"\"\"\n</code></pre>\n\n<p>and so on for your other functions. Writing this kind of documentation\nwill help your colleagues (and you in a few months when you have\nforgotten all the details).</p>\n\n<h3>2. Diagnosis</h3>\n\n<p>Why is <code>containing_tet</code> slow? Well, you say that you are calling it\nmany times, and each time it has to repeat some work. First, it\ncollects the vertices of each tetrahedron:</p>\n\n<pre><code>verts = [tg.points[j] for j in tet]\n</code></pre>\n\n<p>and then in <code>barycentric_coords</code> it computes the transform matrix:</p>\n\n<pre><code>T = (np.array(vertices[:-1])-vertices[-1]).T\n... la.inv(T) ...\n</code></pre>\n\n<p>but these computations will be the same every time (they do not depend on <code>point</code>). It would be best to compute them just once.</p>\n\n<p>Then you need to reorganize your code so that each operation is\n<em>vectorized</em>: that is, you should read all the targets into a NumPy\narray, and then compute the barycentric coordinates for all the\ntargets at once.</p>\n\n<h3>3. Using scipy.spatial</h3>\n\n<p>Having written the above, however, I am wondering why you did not use <a href=\"http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.Delaunay.html#scipy.spatial.Delaunay\" rel=\"noreferrer\"><code>scipy.spatial.Delaunay</code></a>? Is it because <a href=\"http://wias-berlin.de/software/tetgen/\" rel=\"noreferrer\">TetGen</a> does a better job?</p>\n\n<p>Since I don't have a copy of TetGen handy, if I had to write this code I would generate the triangulations like this:</p>\n\n<pre><code>>>> import numpy as np\n>>> import scipy.spatial\n>>> points = np.array([(0,0,0),(0,0,1),(0,1,0),(0,1,1),(1,0,0),(1,0,1),(1,1,0),(1,1,1)])\n>>> tri = scipy.spatial.Delaunay(points)\n>>> tri.simplices\narray([[3, 2, 4, 0],\n [3, 1, 4, 0],\n [3, 6, 2, 4],\n [3, 6, 7, 4],\n [3, 5, 1, 4],\n [3, 5, 7, 4]], dtype=int32)\n</code></pre>\n\n<p>and then if I have an array of targets to query:</p>\n\n<pre><code>>>> targets = np.array([[.1,.1,.1], [.9,.9,.9], [.1,.6,.7], [.4,.9,.1]])\n</code></pre>\n\n<p>I can find which tetrahedron each point belongs to by calling <a href=\"http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.Delaunay.find_simplex.html#scipy.spatial.Delaunay.find_simplex\" rel=\"noreferrer\"><code>scipy.spatial.Delaunay.find_simplex</code></a>:</p>\n\n<pre><code>>>> tetrahedra = tri.find_simplex(targets)\n>>> tetrahedra\narray([0, 3, 1, 2], dtype=int32)\n</code></pre>\n\n<p>And then I can find the barycentric coordinates of each point within its tetrahedron like this:</p>\n\n<pre><code>>>> X = tri.transform[tetrahedra,:3]\n>>> Y = targets - tri.transform[tetrahedra,3]\n>>> b = np.einsum('ijk,ik->ij', X, Y)\n>>> bcoords = np.c_[b, 1 - b.sum(axis=1)]\n>>> bcoords\narray([[ 0.1, 0. , 0.1, 0.8],\n [ 0.1, 0. , 0.8, 0.1],\n [ 0.6, 0.1, 0.1, 0.2],\n [ 0.1, 0.3, 0.5, 0.1]])\n</code></pre>\n\n<p>This is essentially following the recipe in the <a href=\"http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.Delaunay.html#scipy.spatial.Delaunay\" rel=\"noreferrer\"><code>scipy.spatial.Delaunay</code></a> documentation, except that I transform each point using the affine transformation for the tetrahedron it was found in. Note that in the final result, all the barycentric coordinates are in the range 0–1 as you would expect.</p>\n\n<p>The bit of the computation that is tricky to figure out how to vectorize is the computation of <code>b</code>. <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html\" rel=\"noreferrer\"><code>numpy.dot</code></a> computes the <em>dot product of two arrays</em>, but here I need an <em>array of dot products</em>. I could loop over the elements of <code>X</code> and <code>Y</code> in Python, like this:</p>\n\n<pre><code>>>> b = np.array([x.dot(y) for x, y in zip(X, Y)])\n</code></pre>\n\n<p>but that would be using slow Python iteration rather than fast NumPy vector operations. Hence the rather hairy use of <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html\" rel=\"noreferrer\"><code>numpy.einsum</code></a>.</p>\n\n<p>Note that you'll have to do something about the points that were not found in any tetrahedron. <a href=\"http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.Delaunay.find_simplex.html#scipy.spatial.Delaunay.find_simplex\" rel=\"noreferrer\"><code>scipy.spatial.Delaunay.find_simplex</code></a> returns <code>-1</code> for these points. You could mask out the points you need, as <a href=\"http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays\" rel=\"noreferrer\">described here</a>, or you could try using a <a href=\"http://docs.scipy.org/doc/numpy/reference/maskedarray.html\" rel=\"noreferrer\">masked array</a>. (Or try both and see which is faster.)</p>\n\n<h3>4. Answers to questions</h3>\n\n<p>In comments you asked:</p>\n\n<ol>\n<li><p>What is vectorization? See the \"<a href=\"http://docs.scipy.org/doc/numpy/user/whatisnumpy.html\" rel=\"noreferrer\">What is NumPy?</a>\" section of the NumPy documentation, in particular the section starting:</p>\n\n<blockquote>\n <p>Vectorization describes the absence of any explicit looping, indexing, etc., in the code - these things are taking place, of course, just “behind the scenes” (in optimized, pre-compiled C code).</p>\n</blockquote>\n\n<p>Taking advantage of NumPy vector operations is the whole point for using NumPy. For example, this program computes 9 million multiplications and additions in Python:</p>\n\n<pre><code>>>> v = np.arange(3000)\n>>> sum(i * j for i in v for j in v)\n20236502250000\n</code></pre>\n\n<p>It takes about ten seconds on this computer. But the corresponding operation in NumPy:</p>\n\n<pre><code>>>> np.sum(np.outer(v, v))\n20236502250000\n</code></pre>\n\n<p>is about 100 times faster, because the loops involved in this computation run in fast machine code and not in slow Python code. So when you are working on a program in NumPy, you need to scrutinize every Python loop — that is, every <code>for</code> statement — to see if you can turn it into a single NumPy operation.</p></li>\n<li><p>How to structure your code? See §5 below. Notice how using NumPy efficiently requires us to turn the code \"inside out\". Instead of looping over the targets at top level, and in each loop iteration performing a series of operations on that one target, we lift the series of operations up to top level and make each operation run over all elements of a NumPy array.</p></li>\n<li><p>How to read the colors from the colorlist CSV? In NumPy each array must have a single data type (that's one the requirements for NumPy to be able to process them quickly). So you must read the names into one array and the points into another array. An easy way to do this is to call <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html\" rel=\"noreferrer\"><code>numpy.loadtxt</code></a> twice:</p>\n\n<pre><code>>>> colors = np.loadtxt('XYZcolorlist_D65.csv', usecols=(0,), delimiter=',', \n... converters={0:lambda s:s.split()}, dtype=np.uint8)\n>>> colors[:5]\narray([[255, 63, 127],\n [255, 95, 127],\n [255, 127, 127],\n [255, 159, 127],\n [255, 223, 159]], dtype=uint8)\n>>> points = np.loadtxt('XYZcolorlist_D65.csv', usecols=(1,2,3), delimiter=',')\n>>> points[:5]\narray([[ 35.53443021, 21.38072197, 20.3661096 ],\n [ 40.20749455, 26.52829494, 22.70942844],\n [ 43.66474384, 32.34826255, 23.61818015],\n [ 47.12256284, 39.17809444, 22.9366615 ],\n [ 61.73791496, 62.83876017, 32.39362009]])\n</code></pre></li>\n</ol>\n\n<h3>5. Revised code.</h3>\n\n<pre><code>import numpy as np\nimport scipy.spatial\n\n# Configuration.\nPOINTS_FILENAME = 'XYZcolorlist_D65.csv'\nTARGETS_FILENAME = 'targets.csv'\nOUTPUT_FILENAME = 'gamut.ppm'\nDEFAULT_COLOR = np.array([[255, 255, 255]], dtype=np.uint8)\n\n# Load colors\ncolors = np.loadtxt(POINTS_FILENAME, usecols=(0,), delimiter=',', \n converters={0:lambda s:s.split()}, dtype=np.uint8)\n\n# Load points\npoints = np.loadtxt(POINTS_FILENAME, usecols=(1, 2, 3), delimiter=',')\n\n# Load targets\ntargets = np.loadtxt(TARGETS_FILENAME, delimiter=',')\nntargets = len(targets)\n\n# Compute Delaunay triangulation of points.\ntri = scipy.spatial.Delaunay(points)\n\n# Find the tetrahedron containing each target (or -1 if not found)\ntetrahedra = tri.find_simplex(targets)\n\n# Affine transformation for tetrahedron containing each target\nX = tri.transform[tetrahedra, :3]\n\n# Offset of each target from the origin of its containing tetrahedron\nY = targets - tri.transform[tetrahedra, 3]\n\n# First three barycentric coordinates of each target in its tetrahedron.\n# The fourth coordinate would be 1 - b.sum(axis=1), but we don't need it.\nb = np.einsum('...jk,...k->...j', X, Y)\n\n# Cumulative sum of barycentric coordinates of each target.\nbsum = np.c_[b.cumsum(axis=1), np.ones(ntargets)]\n\n# A uniform random number in [0, 1] for each target.\nR = np.random.uniform(0, 1, size=(ntargets, 1))\n\n# Randomly choose one of the tetrahedron vertices for each target,\n# weighted according to its barycentric coordinates, and get its\n# color.\nC = colors[tri.simplices[tetrahedra, np.argmax(R <= bsum, axis=1)]]\n\n# Mask out the targets where we failed to find a tetrahedron.\nC[tetrahedra == -1] = DEFAULT_COLOR\n\n# Determine width and height of image.\n# (Since I don't have your TIFF, this is the best I can do!)\nwidth, height = 1, ntargets\n\n# Write output as image in PPM format.\nwith open(OUTPUT_FILENAME, 'wb') as ppm:\n ppm.write(\"P3\\n{} {}\\n255\\n\".format(width, height).encode('ascii'))\n np.savetxt(ppm, C, fmt='%d')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T19:23:32.387",
"Id": "70483",
"Score": "0",
"body": "Thank you for this nice answer and the time you spent on it, and sorry for the lack of documentation. It's the first time I hear about \"vectorizing\" a code, could you be more explicit? So far - and letting apart scipy.spacial - I understand that in `colors_PPM.py` I should put `tet_i, bcoords = geometry.containing_tet(tg, target_point)` outside (before) the `for` loop, is that correct? Or is it that I should rewrite entirely `verts = [tg.points[j] for j in tet]` in `geometry` and make 2 separate `def` functions out of `containing_tet(tg, point):` ??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T19:57:41.880",
"Id": "70494",
"Score": "1",
"body": "See revised answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T21:29:36.313",
"Id": "70520",
"Score": "0",
"body": "PS just added the `.csv` file structures in the question"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T22:33:16.967",
"Id": "70528",
"Score": "0",
"body": "I simplified my question below with the nice upgrades you provided, could you please check it out? Maybe I better open a new question? What do you think? Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T23:07:29.973",
"Id": "70532",
"Score": "1",
"body": "I've explained how to load the data. As for a new question, for best results you should [wait until you have got the code *working* before asking a new question here at Code Review](http://codereview.stackexchange.com/help/on-topic). But while you are still struggling with NumPy, I am sure the good folks at [Stack Overflow](http://stackoverflow.com) would be happy to help answer your questions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T23:17:31.993",
"Id": "70533",
"Score": "0",
"body": "Ok, I didn't know the rule, sorry. Thanks a lot, I will do that!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T23:18:47.137",
"Id": "70534",
"Score": "1",
"body": "No problem. I hope I have been able to help, and good luck with your project."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T17:41:02.883",
"Id": "41089",
"ParentId": "41024",
"Score": "13"
}
}
] |
{
"AcceptedAnswerId": "41089",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T01:37:26.583",
"Id": "41024",
"Score": "13",
"Tags": [
"python",
"performance",
"numpy",
"python-2.x",
"computational-geometry"
],
"Title": "Faster computation of barycentric coordinates for many points"
}
|
41024
|
<p>This is my take at the current <a href="/questions/tagged/code-challenge" class="post-tag" title="show questions tagged 'code-challenge'" rel="tag">code-challenge</a>, <a href="https://codereview.meta.stackexchange.com/questions/1471/weekend-challenge-reboot">Ultimate Tic-Tac-Toe</a>, at least the <em>presentation</em> part.</p>
<p>As I chose to write a WPF application for my game, and this is my very first time fiddling with a <code>UniformGrid</code> and <code>ItemsControl</code>, I'd like to know if I've done any beginner mistakes.</p>
<h3>MainWindow</h3>
<pre><code><Window x:Class="TicTactics.UI.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TicTactics.UI"
xmlns:app="clr-namespace:TicTactics;assembly=TicTactics"
Title="TicTactics" Height="600" Width="600">
<Window.Resources>
<Style x:Key="GlassBorder" TargetType="{x:Type Border}">
<Setter Property="CornerRadius" Value="4" />
<Setter Property="BorderBrush" Value="DarkSlateBlue" />
<Setter Property="BorderThickness" Value="1.5" />
<Setter Property="Margin" Value="4" />
<Setter Property="Border.Background">
<Setter.Value>
<LinearGradientBrush>
<GradientStop Offset="0.0" Color="White" />
<GradientStop Offset="0.425" Color="AliceBlue" />
<GradientStop Offset="0.5" Color="PaleTurquoise" />
<GradientStop Offset="0.99" Color="White" />
</LinearGradientBrush>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="GridBorder" TargetType="{x:Type Border}">
<Setter Property="CornerRadius" Value="4" />
<Setter Property="BorderBrush" Value="SlateBlue" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Margin" Value="2" />
<Setter Property="Border.Background" Value="#AAF0F8FF" />
<Style.Triggers>
<Trigger Property="Border.IsMouseOver" Value="True">
<Setter Property="BorderThickness" Value="2" />
<Setter Property="Background" >
<Setter.Value>
<SolidColorBrush Color="{DynamicResource {x:Static SystemColors.HotTrackColorKey}}"/>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="20" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="20" />
<RowDefinition Height="*" />
<RowDefinition Height="20" />
</Grid.RowDefinitions>
<ItemsControl Grid.Row="1" Grid.Column="1" ItemsSource="{Binding Board.Cells}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="3" Columns="3" MinWidth="360"
MinHeight="{Binding Path=MinWidth, RelativeSource={RelativeSource Self}}"
Width="{Binding Path=ActualHeight, RelativeSource={RelativeSource Self}}" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="SmallBoard">
<Border Style="{StaticResource GlassBorder}">
<Border Style="{StaticResource GridBorder}">
<local:SmallBoardView DataContext="{Binding Value}" />
</Border>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Window>
</code></pre>
<h3>SmallBoardView</h3>
<pre><code><UserControl x:Class="TicTactics.UI.SmallBoardView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:TicTactics.UI"
xmlns:app="clr-namespace:TicTactics;assembly=TicTactics"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<Style x:Key="CellBorder" TargetType="{x:Type Border}">
<Setter Property="CornerRadius" Value="4" />
<Setter Property="BorderBrush" Value="SlateBlue" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Padding" Value="2" />
<Setter Property="Margin" Value="2" />
<Setter Property="Border.Background" Value="#6AFFFFFF" />
<Style.Triggers>
<Trigger Property="Border.IsMouseOver" Value="True">
<Setter Property="BorderThickness" Value="2" />
<Setter Property="BorderBrush" >
<Setter.Value>
<SolidColorBrush Color="{DynamicResource {x:Static SystemColors.HotTrackColorKey}}"/>
</Setter.Value>
</Setter>
<Setter Property="Background" Value="AliceBlue" />
</Trigger>
</Style.Triggers>
</Style>
</UserControl.Resources>
<Grid>
<ItemsControl ItemsSource="{Binding Cells}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="3" Columns="3" Width="{Binding Path=ActualHeight, RelativeSource={RelativeSource Self}}" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="BoardCell">
<Border Style="{StaticResource CellBorder}">
<Image Source="{Binding Value.Value, Converter={local:CellValueImageConverter}}" Stretch="Uniform" />
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</UserControl>
</code></pre>
<hr>
<h3>Result</h3>
<p><img src="https://i.stack.imgur.com/UEnEh.png" alt="enter image description here"></p>
<p>As the window gets resized, the game board and its contents scale perfectly well, all I'm missing is <code>MinWidth</code> and <code>MinHeight</code> values to prevent the user from making the window so small the grid gets clipped.</p>
<p>Anything else?</p>
<hr>
<p>There's also <a href="https://codereview.stackexchange.com/questions/41029/tictactics-gameboard-logic">some C# code to be reviewed for this project</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T17:28:55.997",
"Id": "71653",
"Score": "0",
"body": "Why do the large squares have double borders?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T23:39:37.040",
"Id": "71732",
"Score": "0",
"body": "@svick I guess higher transparency on the inner border would make it more obvious, the outer border has an angle gradient; the inner border makes it more (too much?) subtle. Both have a small margin, which makes the boards appear to have a double border. Shortly put, it's intentional... but I'm no UI/UX designer, feel free to suggest a better-looking \"glass\" effect :)"
}
] |
[
{
"body": "<ol>\n<li><code><Setter Property=\"Border.Background\" Value=\"#AAF0F8FF\" /></code> - <code>Border.</code> prefix should be redundant, as you specify target type in <code>Style</code>.</li>\n<li><code><Image Source=\"{Binding Value.Value, Converter={local:CellValueImageConverter}}\" Stretch=\"Uniform\" /></code> a) i think in such simple cases where you have like two possible states a <code>DataTrigger</code> is superior to spawning yet another converter. b) wasnt <code>Value</code> nullable? Wont it throw an exception if <code>HasValue == false</code>? </li>\n</ol>\n\n<p>Apart from that your markup looks pretty clean to me.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T09:14:57.643",
"Id": "41047",
"ParentId": "41026",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "41047",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T02:55:55.823",
"Id": "41026",
"Score": "10",
"Tags": [
"c#",
"game",
"wpf",
"xaml",
"community-challenge"
],
"Title": "TicTactics Presentation"
}
|
41026
|
<p>I'm using meteor and angular. Since I can't add modules after the angular bootstrap, I made a workaround and somewhat not satisfied with the way it was coded.</p>
<p>How can I improve this?:</p>
<pre><code>(function() {
var controllers = ngMeteor.newControllers,
filters = ngMeteor.newFilters,
directives = ngMeteor.newDirectives,
services = ngMeteor.newServices
ngMeteor.config(function($controllerProvider) {
for (var prop in controllers) {
if (controllers.hasOwnProperty(prop)) {
$controllerProvider.register(prop, controllers[prop]);
}
}
});
ngMeteor.config(function($filterProvider) {
for (var prop in controllers) {
if (filters.hasOwnProperty(prop)) {
$filterProvider.register(prop, filters[prop]);
}
}
});
for (var prop in directives) {
if (directives.hasOwnProperty(prop)) {
ngMeteor.directive(prop, directives[prop]);
}
}
for (var prop in services) {
if (services.hasOwnProperty(prop)) {
ngMeteor.services(prop, services[prop]);
}
}
})();
</code></pre>
<p>The variables above will just have the same structure. For example:</p>
<pre><code>/* Controllers */
ngMeteor.newControllers = {
MainCtrl: function($scope) {
// ...
},
SubCtrl: function($scope) {
// ...
}
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T04:25:08.027",
"Id": "70313",
"Score": "0",
"body": "No dog-balls! Use `}());` instead of `})()` to remove ambiguity."
}
] |
[
{
"body": "<p>Lets say you defined a module like so after the bootstrap:</p>\n\n<pre><code>myModule = angular.module('myModule',[]);\n</code></pre>\n\n<p>You can inject this module into ngMeteor after the bootstrap like so:</p>\n\n<pre><code>ngMeteor.requires.push('myModule');\n</code></pre>\n\n<p>You could easily group your controllers, directives, filters and services into separate modules and then add them to your app level module using this method. However, grouping your controllers, directives, filters and services into separate modules and then injecting it into your app level module is only one of many possible ways to organise your AngularJS app. If you're using AngularJS with MeteorJS, it would be easier to simply attach your controllers, directives, filters and services to the ngMeteor module because you have the ability to scatter these in whatever combination of javascript files as you like without having to enumerate them in your app level module. </p>\n\n<p>For example, each controller could be in a separate javascript file and they could all be located in a folder called controller. Each controller javascript file would look something like this:</p>\n\n<pre><code>ngMeteor.controller('someControllerName',[$scope,function(){...}]);\n</code></pre>\n\n<p>Alternatively, you could put all controllers, directives, filters and services specific to a particular route into a javascript file under that route's folder. For example, lets say you have a route called \"post\", you could have a folder called post, and in your post folder you could have post.html, post.css and post.js, and the post.js would look something like this:</p>\n\n<pre><code>ngMeteor\n.controller('someControllerName',[$scope,function(){...}])\n.directive('someDirectiveName',[$scope,function(){...}])\n.filter('someFilterName',[$scope,function(){...}])\n.service('someServerName',[$scope,function(){...}]);\n</code></pre>\n\n<p>At the end of the day though, its personal preference and ngMeteor is flexible enough to allow you to structure your app in multiple ways.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T13:12:40.580",
"Id": "41064",
"ParentId": "41027",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "41064",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T02:59:16.140",
"Id": "41027",
"Score": "2",
"Tags": [
"javascript",
"angular.js",
"meteor"
],
"Title": "Angularjs Module Registration Structure"
}
|
41027
|
<p><strong>I am having a huge brain fart with efficiency right now.</strong></p>
<p>The idea here is if I have a static <code>table</code> (unfortunately formatted this way with the data I've received), how would I appropriately <code>append</code> a <code>select option dropdown</code> with every value from the table categorized easily?</p>
<p>I currently have it working, but it seems as if I could make it more efficient than my current statement. I have the feeling with all the <code>DOM</code> manipulation I have going on, if I tried to use this on a table with <strong>thousands</strong> of items it would lag the browser. Let's get to the code.</p>
<p><strong>JS Fiddle:</strong> <a href="http://jsfiddle.net/z2V2p/1/" rel="nofollow">http://jsfiddle.net/z2V2p/1/</a></p>
<p><strong>HTML:</strong></p>
<pre><code><table id='data'>
<tr>
<td>Item 1</td>
<td>Value 1</td>
<td>Prop 1</td>
</tr>
<tr >
<td>Item 2</td>
<td>Value 2</td>
<td>Prop 2</td>
</tr>
<tr >
<td>Item 3</td>
<td>Value 3</td>
<td>Prop 3</td>
</tr>
</table>
<select id="item"></select>
<select id="value"></select>
<select id="prop"></select>
</code></pre>
<p><strong>Javascript/jQuery:</strong></p>
<pre><code>$('tr td').each(function() {
var $this = $(this);
var text = $this.text();
var select = '<option value="'+text+'">'+text+'</option>';
switch($this.index()){
case 0:
$('#item').append(select);
break;
case 1:
$('#value').append(select);
break;
case 2:
$('#prop').append(select);
break;
default:
alert('Unexpected Error.');
}
});
</code></pre>
<hr>
<p><strong>So, I suppose the questions are:</strong></p>
<ul>
<li>Is there any easy way to make this more efficient?</li>
<li>Perhaps utilizing an <code>array</code> to cache the values, and <code>append</code> them
from that?</li>
<li>Or is there an easier method of using <code>index</code> of the items instead of
my <code>switch case</code> that would render quicker and be more expandable for further <code>td</code>s if they were implemented?</li>
</ul>
<p>I appreciate all of the help.</p>
<p><strong>I've considered just ultimately converting the darn table to a <code>json</code> object, but I figured I'd reach out here first.</strong> <em>(this will deploy thousands of times per week, and I don't want anything hard coded.)</em></p>
<p><strong>Looking for a way to add every <code>TD</code> in its <code>index</code> of its <code>TR</code> to be appended to an existing <code>select option</code> based on the <code>index</code> value.</strong></p>
<h3>Basically re-categorize columns of <code>td</code> elements.</h3>
|
[] |
[
{
"body": "<p>We can do some thing like this <a href=\"http://jsfiddle.net/z2V2p/11/\" rel=\"nofollow\">http://jsfiddle.net/z2V2p/11/</a></p>\n\n<pre><code><script>\n var dataArray = [];\n\n dataArray[0] = ['item','Item 1','Item2','Item3','Item4'];\n dataArray[1] = ['value','Value 1','Value 2','Value 3','Value 6','Value 5'];\n dataArray[2] = ['prop','Prop 1','Prop 2','Prop 3','Prop 6','Prop 5','Prop 6'];\n</script>\n</code></pre>\n\n<p>by this way we will remove the table and now the dom will be happy :)<br>\nif you noticed the id of the select had been added to the array now we can remove the switch too by this code: </p>\n\n<pre><code>for(i=0; i < dataArray.length; i++){\n $select = $('#'+dataArray[i][0]);\n for(i2=1; i2 < dataArray[i].length; i2++){\n var option = '<option value=\"'+dataArray[i][i2]+'\">'+dataArray[i][i2]+'</option>';\n $select.append(option);\n }\n}\n</code></pre>\n\n<p>but now we have a problem with loop inside loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T05:15:34.797",
"Id": "70322",
"Score": "0",
"body": "Well, the idea is to capture every item inside of a **500** 3 `td` (3 items) `table`. I don't want to hard code **500** values inside my code..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T05:21:00.350",
"Id": "70323",
"Score": "0",
"body": "My point being, if I use a function to convert this table into different arrays, isn't that harder to accomplish than my code for the `client`? I mean, find `DOM` objects into `array`, then `parse` `array` into `DOM` seems like duplicate effort."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T05:33:21.357",
"Id": "70325",
"Score": "0",
"body": "We might as well just $domObject = $domObject(converted) right...?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T05:49:08.613",
"Id": "70330",
"Score": "0",
"body": "So what i understand now that we have:\nformatted data as `table` > 3 `tr` > multiple `td` and we cannot change this format, are me right ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T05:50:54.657",
"Id": "70331",
"Score": "0",
"body": "Well, I'm happy to use this as it works in .42s when live with 40k items. I just like to expand. So, how can we make it .10 seconds by removing a step of DOM manipulation? **Answering your Q, pretend its 10,000 `tr` and all have 3 `td` items**. Its just an efficiency question, as I feel I could expand the `switch` case more manageable and expandable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T06:15:38.597",
"Id": "70332",
"Score": "0",
"body": "Sorry but i have another Q. Could we remove `table` from our code ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T06:19:14.103",
"Id": "70333",
"Score": "0",
"body": "and then get the data as `[]` or json"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T06:21:28.350",
"Id": "70334",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/12882/discussion-between-saad-shahd-and-nicholas-hazel)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T07:43:10.047",
"Id": "70339",
"Score": "0",
"body": "Appeciate the offer, but `table` is the **use case**."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T08:48:11.593",
"Id": "70352",
"Score": "0",
"body": "now i cannot do any thing and i wish to be there an answer to this Topic :)"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T04:12:23.890",
"Id": "41032",
"ParentId": "41028",
"Score": "2"
}
},
{
"body": "<p>First little thing: var names are important. So </p>\n\n<pre><code>var option = '<option value=\"'+text+'\">'+text+'</option>';\n</code></pre>\n\n<p>Second and main. When we are making webapps with JS, the main perfomance rule is: </p>\n\n<p><strong>Reduce access to DOM</strong> </p>\n\n<p>I tried you code with 15000 tr's in Firefox and Chrome. I wrapped you code with</p>\n\n<pre><code>console.time('DOM');\n...\nconsole.timeEnd('DOM');\n</code></pre>\n\n<p>Results was:</p>\n\n<ul>\n<li>Chrome - about 5000ms </li>\n<li>Firefox - about 20000ms</li>\n</ul>\n\n<p>Then i replaced <code>$.append()</code> with just strings concatenation</p>\n\n<pre><code>console.time('String');\nvar itemOptions = '', valueOptions = '', propOptions = '';\n$('tr td').each(function() {\n var $this = $(this);\n var text = $this.text();\n var option = '<option value=\"'+text+'\">'+text+'</option>';\n switch($this.index()){\n case 0:\n itemOptions += option;\n break;\n case 1:\n valueOptions += option;\n break;\n case 2:\n propOptions += option;\n break;\n default:\n alert('Unexpected Error.');\n }\n});\n$('#item').append(itemOptions);\n$('#value').append(valueOptions);\n$('#prop').append(propOptions);\nconsole.timeEnd('String');\n</code></pre>\n\n<p>Results:</p>\n\n<ul>\n<li>Chrome - about 1100ms (bravo, Chrome :))</li>\n<li>Firefox - about 4000ms</li>\n</ul>\n\n<p>If you will change your data source to a JSON or something, next optimisation will not need, but you can set first argument of <code>.each()</code> method (index of all td elements) to avoid using <code>.index()</code>. I noticed about 300-500ms of speed increase. So the last version is </p>\n\n<pre><code>console.time('String');\nvar itemOptions = '', valueOptions = '', propOptions = '';\n$('tr td').each(function(index) {\n var $this = $(this);\n var text = $this.text();\n var option = '<option value=\"'+text+'\">'+text+'</option>';\n var modulo = index % 3;\n switch(modulo){\n case 0 :\n itemOptions += option;\n break;\n case 1:\n valueOptions += option;\n break;\n case 2:\n propOptions += option;\n break;\n default:\n alert('Unexpected Error.');\n }\n});\n$('#item').append(itemOptions);\n$('#value').append(valueOptions);\n$('#prop').append(propOptions);\nconsole.timeEnd('String');\n</code></pre>\n\n<p>Results:</p>\n\n<ul>\n<li>Chrome - about 850ms</li>\n<li>Firefox - about 3500ms</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T19:06:35.943",
"Id": "41097",
"ParentId": "41028",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T03:19:33.473",
"Id": "41028",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "Append table cells to select boxes in indexed order"
}
|
41028
|
<p>This is my take at the current <a href="/questions/tagged/code-challenge" class="post-tag" title="show questions tagged 'code-challenge'" rel="tag">code-challenge</a>, <a href="https://codereview.meta.stackexchange.com/questions/1471/weekend-challenge-reboot">Ultimate Tic-Tac-Toe</a>.</p>
<p>It all started with a <code>CellValue</code> and a <code>BoardPosition</code>:</p>
<pre><code>/// <summary>
/// Identifies the players, or the possible values a cell can take.
/// </summary>
public enum CellValue
{
X,
O
}
/// <summary>
/// Identifies the possible board positions.
/// </summary>
public enum BoardPosition
{
TopLeft,
Top,
TopRight,
Left,
Center,
Right,
BottomLeft,
Bottom,
BottomRight
}
</code></pre>
<p><em>"Wait"</em>, I hear you say - <em>"an enum for board positions?"</em> - Absolutely! That allowed me to define a <code>BoardCell</code> interface:</p>
<pre><code>public interface IBoardCell
{
BoardPosition Position { get; }
CellValue? Value { get; set; }
event EventHandler<CellValueChangedEventArgs> CellValueChanged;
}
</code></pre>
<p>Inspired by WPF and <code>INotifyPropertyChanged</code>, I'm using events to communicate a change of a cell's value to whoever might be interested (that's the parent board):</p>
<pre><code>public class CellValueChangedEventArgs : EventArgs
{
private BoardPosition _position;
BoardPosition Position { get { return _position; } }
private CellValue? _value;
CellValue? Value { get { return _value; } }
public CellValueChangedEventArgs(BoardPosition position, CellValue? value)
{
_position = position;
_value = value;
}
}
</code></pre>
<h3>BoardBase[TCell]</h3>
<p>Very early in the design process I realized most of the "bigger board" functionality was also needed in the "smaller boards", so I wrote a generic abstract class where the type parameter determines the type of cell:</p>
<pre><code>public abstract class BoardBase<TCell> : IBoardCell
where TCell : IBoardCell
{
private readonly IDictionary<BoardPosition, TCell> _cells;
private readonly BoardEvaluator _evaluator;
protected BoardBase(BoardEvaluator evaluator, ICellFactory<TCell> cellFactory)
{
_evaluator = evaluator;
_cells = Enum.GetValues(typeof(BoardPosition))
.Cast<BoardPosition>()
.ToDictionary(position => position, position => cellFactory.Create(position));
RegisterCellEvents();
}
private void RegisterCellEvents()
{
foreach (var cell in _cells.Values)
{
cell.CellValueChanged += BoardCellValueChanged;
}
}
private void BoardCellValueChanged(object sender, EventArgs e)
{
_winner = _evaluator.Evaluate(_cells, out _winningPositions);
if (_winner != null)
{
OnCellValueChanged();
}
}
public event EventHandler<CellValueChangedEventArgs> CellValueChanged;
private void OnCellValueChanged()
{
if (CellValueChanged != null)
{
var args = new CellValueChangedEventArgs(_position, Value);
CellValueChanged(this, args);
}
}
public IReadOnlyDictionary<BoardPosition, TCell> Cells { get { return new ReadOnlyDictionary<BoardPosition, TCell>(_cells); } }
public virtual TCell this[BoardPosition position]
{
get { return _cells[position]; }
set
{
_cells[position] = value;
_winner = _evaluator.Evaluate(_cells, out _winningPositions);
if (_winner != null) OnCellValueChanged();
}
}
public CellValue? Value
{
get { return _winner; }
set { throw new NotSupportedException(); }
}
public bool IsPlayable()
{
return _cells.Values.Any(cell => !cell.Value.HasValue);
}
private CellValue? _winner;
public CellValue? Winner { get { return _winner; } }
private IEnumerable<BoardPosition> _winningPositions;
public IEnumerable<BoardPosition> WinningPositions
{
get { return _winningPositions; }
}
private BoardPosition _position;
public BoardPosition Position
{
get { return _position; }
}
}
</code></pre>
<p>This class is "implemented" like this:</p>
<pre><code>public class GameBoard : BoardBase<SmallBoard>
{
public GameBoard(BoardEvaluator evaluator, BoardFactory boardFactory)
: base(evaluator, boardFactory)
{ }
}
public class SmallBoard : BoardBase<BoardCell>
{
public SmallBoard(BoardEvaluator evaluator, BoardCellFactory cellFactory)
: base(evaluator, cellFactory)
{ }
}
</code></pre>
<p>...which essentially gives a meaningful alias to the generic class. Not sure it's <em>really</em> needed.</p>
<h3>Cell Factories</h3>
<p>I like abstract factories. This allows me to generate the entire board, simply by enumerating the <code>BoardPosition</code> values:</p>
<pre><code>public interface ICellFactory<TCell> where TCell : IBoardCell
{
TCell Create(BoardPosition position);
}
public class BoardFactory : ICellFactory<SmallBoard>
{
private readonly BoardEvaluator _evaluator;
private readonly BoardCellFactory _cellFactory;
public BoardFactory(BoardEvaluator evaluator, BoardCellFactory cellFactory)
{
_evaluator = evaluator;
_cellFactory = cellFactory;
}
public SmallBoard Create(BoardPosition position)
{
return new SmallBoard(position, _evaluator, _cellFactory);
}
}
public class BoardCellFactory : ICellFactory<BoardCell>
{
public BoardCell Create(BoardPosition position)
{
return new BoardCell(position);
}
}
</code></pre>
<h3>BoardEvaluator</h3>
<p>The logic that determines whether a board has a winner, and what <code>BoardPosition</code> values contain the winning moves, is encapsulated in this <code>BoardEvaluator</code> class:</p>
<pre><code>public class BoardEvaluator
{
private readonly Tuple<BoardPosition, BoardPosition, BoardPosition>[]
_wins = new Tuple<BoardPosition, BoardPosition, BoardPosition>[]
{
// horizontal wins
Tuple.Create(BoardPosition.TopLeft, BoardPosition.Top, BoardPosition.TopRight),
Tuple.Create(BoardPosition.Left, BoardPosition.Center, BoardPosition.Right),
Tuple.Create(BoardPosition.BottomLeft, BoardPosition.Bottom, BoardPosition.BottomRight),
// vertical wins
Tuple.Create(BoardPosition.TopLeft, BoardPosition.Left, BoardPosition.BottomLeft),
Tuple.Create(BoardPosition.Top, BoardPosition.Center, BoardPosition.Bottom),
Tuple.Create(BoardPosition.TopRight, BoardPosition.Right, BoardPosition.BottomRight),
// diagonal wins
Tuple.Create(BoardPosition.TopLeft, BoardPosition.Center, BoardPosition.BottomRight),
Tuple.Create(BoardPosition.BottomLeft, BoardPosition.Center, BoardPosition.TopRight)
};
public CellValue? Evaluate<TCell>(IDictionary<BoardPosition, TCell> cells, out IEnumerable<BoardPosition> positions)
where TCell : IBoardCell
{
if (Enum.GetValues(typeof(BoardPosition)).Length != cells.Count) throw new ArgumentException("Invalid cell count.", "cells");
var winning = Enum.GetValues(typeof(CellValue)).Cast<CellValue>()
.Select(value => WinningPositions(cells, value))
.SingleOrDefault(tuple => tuple != null);
positions = winning != null
? new[] { winning.Item1, winning.Item2, winning.Item3 }
: null;
return winning != null
? cells[winning.Item1].Value // all 'winning' positions have the same value.
: null;
}
private Tuple<BoardPosition, BoardPosition, BoardPosition> WinningPositions<TCell>(IDictionary<BoardPosition, TCell> cells, CellValue? value)
where TCell : IBoardCell
{
return _wins.SingleOrDefault(win => cells[win.Item1].Value == value
&& cells[win.Item2].Value == value
&& cells[win.Item3].Value == value);
}
}
</code></pre>
<p>I think this is where the <code>enum</code> positions deliver their payload, especially in terms of readability. I have to admit, I'm really not crazy about <code>out</code> parameters. I can live with this one, but I'd love to see it gone and turned into a regular return value... or maybe sometimes an <code>out</code> parameter is ok? Is this such a situation?</p>
<hr>
<p>That's about it for now. I also have a <code>IPlayer</code> interface, but that's not implemented yet so I'll keep that for when I want to get the <em>playability</em> reviewed (game mechanics/logic).</p>
<p>So, is this what <a href="/questions/tagged/clean-code" class="post-tag" title="show questions tagged 'clean-code'" rel="tag">clean-code</a> looks like? What could be improved?</p>
<p>(I also have some <a href="https://codereview.stackexchange.com/questions/41026/tictactics-presentation">XAML to be reviewed for this project</a></p>
|
[] |
[
{
"body": "<ol>\n<li><p>I can see some code duplication. For example this</p>\n\n<pre><code>private void BoardCellValueChanged(object sender, EventArgs e)\n{\n _winner = _evaluator.Evaluate(_cells, out _winningPositions);\n if (_winner != null)\n {\n OnCellValueChanged();\n }\n}\n</code></pre>\n\n<p>looks a lot like this</p>\n\n<pre><code>set\n{\n _cells[position] = value;\n _winner = _evaluator.Evaluate(_cells, out _winningPositions);\n if (_winner != null) OnCellValueChanged();\n}\n</code></pre></li>\n<li><p>I do not like this enum</p>\n\n<pre><code>public enum CellValue\n{\n X,\n O\n}\n</code></pre>\n\n<p>for two reasons. First: it doesn't have a third value for \"empty\" cells. This leads to huge amout of <code>CellValue?</code> all over the place. Having a third state will remove those and imrove code readability. Second: i do not like <code>X</code> and <code>O</code> as member names. I cant say i do not understand those, but there is something fishy about this naming. :) I think <code>Tic</code> and <code>Toc</code> would be much better.</p></li>\n<li><p>Why throw an exception? Why cant you remove the setter? Is this property supposed to be virtual?</p>\n\n<pre><code>public CellValue? Value\n{\n get { return _winner; }\n set { throw new NotSupportedException(); }\n}\n</code></pre></li>\n<li><p><code>public CellValue? Winner { get { return _winner; } }</code> - i think you should either change this property name, or change type to <code>IPlayer</code>. Semantically cell being a winner doesnt make much sense.</p></li>\n<li><p>In general i am not sure i can follow how will you derive from <code>BoardBase</code>. <code>IsPlayable</code> implementation for small board doesnt make sense (shouldn't you check for winner instead?). Same goes for <code>Position</code> for large board. I have no idea how <code>Value</code> is going to be used for either boards, and what <code>Value</code> means (not very descriptive). Etc.</p></li>\n<li><p>As for <code>BoardEvaluator</code> i have a few minor concerns. a) I hate <code>Tuple</code>s, <code>Pair</code>s, etc. with all my heart and soul. :) THey have this ability to turn even simple code into a mess. This is probably a matter of taste, but i think a simple arrays would be much more readable. b) I do not like multiple <code>winning != null</code>, it makes code hard to follow. A simple <code>if</code> would be better.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T14:49:28.327",
"Id": "70405",
"Score": "0",
"body": "The `CellValue` enum might be better off called `PlayerToken` - I'm also using it in my `IPlayer` interface (not in this post) to determine whether a player is playing \"X\" or \"O\". Thus, I didn't want to include a \"non-value\" in that enum, and making a cell's value a `Nullable<CellValue>` seemed semantically correct. Speaking of semantics, it's also what drove the decision of using `Tuple<T1,T2,T3>` over anything else (which I *did* consider) - the tuple, as ugly as it is, seemed the only semantically correct approach in this case. Nice review, you bring very good points! Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T08:04:28.623",
"Id": "41045",
"ParentId": "41029",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p>It all started with a CellValue and a BoardPosition</p>\n</blockquote>\n\n<p>You could use <code>bool?</code> for a ternary CellValue; but a named enum makes it more self-documenting.</p>\n\n<p>You could code your BoardPosition as a bunch of <a href=\"http://en.wikipedia.org/wiki/Flyweight_pattern\" rel=\"nofollow\">flyweights</a>:</p>\n\n<pre><code>public class BoardPosition // or struct\n{\n public int Row { get; private set; }\n public int Column { get; private set; }\n\n public static BoardPosition TopLeft = new BoardPosition() { Row = 0; Column = 0; };\n ... etc ...\n\n // Implicit conversion to int allows it to be used as indexer into array of cells\n public static implicit operator int(BoardPosition self)\n {\n return self.Column + (3 * self.Row);\n }\n\n // Could similarly define a constructor-operator to convert from int\n // http://msdn.microsoft.com/en-us/library/85w54y0a.aspx\n}\n</code></pre>\n\n<blockquote>\n <p>That allowed me to define a BoardCell interface</p>\n</blockquote>\n\n<p>You could use shorter names:</p>\n\n<ul>\n<li>CellValue -> State or Owner or Player</li>\n<li>BoardPosition -> Position or Location</li>\n<li>IBoardCell -> Cell</li>\n<li>BoardBase -> Cells or BoardT</li>\n</ul>\n\n<blockquote>\n <p>CellValueChangedEventArgs</p>\n</blockquote>\n\n<p>You can make this slightly shorter by using <a href=\"http://msdn.microsoft.com/en-us/library/bb384054.aspx\" rel=\"nofollow\">auto-implemented properties</a>:</p>\n\n<pre><code>public class CellValueChangedEventArgs : EventArgs\n{\n public BoardPosition Position { get; private set; }\n public CellValue? Value { get; private set; }\n\n public CellValueChangedEventArgs(BoardPosition position, CellValue? value)\n {\n Position = position;\n Value = value;\n }\n}\n</code></pre>\n\n<blockquote>\n <p>BoardBase[TCell]</p>\n</blockquote>\n\n<p>Why is this <code>abstract</code> when it contains no abstract methods?</p>\n\n<p>Instead of <code>ICellFactory<TCell> cellFactory</code> using a factory interface, you could define <code>Func<TCell, BoardPosition> cellFactory</code> using a factory delegate.</p>\n\n<p>It's confusing the find member data at the top and at the bottom of the class definition.</p>\n\n<p>Use <code>#region</code> to specify which methods of BoardBase are implementing members defined in / required by IBoardCell.</p>\n\n<p>The <code>Value</code> property would be better named <code>Winner</code>.</p>\n\n<p>IsPlayable should perhaps be false on a won board.</p>\n\n<p>It was surprising to see IDictionary instead of a single- or two-dimensional array.</p>\n\n<p><code>this[BoardPosition position] { set { ... } }</code> requires the user to create a new cell which they can pass-in. That's difficult and error-prone IMO. Instead they should be allowed to try to alter the CellValue of an existing cell.</p>\n\n<blockquote>\n <p>I'm really not crazy about out parameters. I can live with this one, but I'd love to see it gone</p>\n</blockquote>\n\n<p>You could pass-in an <code>Action<IEnumerable<BoardPosition>></code> instead:</p>\n\n<pre><code>_winner = _evaluator.Evaluate(_cells, found => _winningPositions = found);\n</code></pre>\n\n<p>Or return a <code>Pair<CellValue, IEnumerable<BoardPosition>></code></p>\n\n<p>Or pass-in <code>this</code> so that evaluator can set the WinningPositions property of the passed-in BoardBase.</p>\n\n<hr>\n\n<p>Of the above, IMO the most important review comment is to get rid of <code>TCell this[BoardPosition position] { set { ... } }</code>.</p>\n\n<p>CellValueChangedEventArgs needn't be a subclass of EventArgs. The only property it needs is IBoardCell which contains the new location and new value of the cell.</p>\n\n<p>BoardCellValueChanged could do something with the parameter[s] it's being passed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T14:41:48.937",
"Id": "70402",
"Score": "0",
"body": "Nice review. `BoardBase<TCell>` is abstract because I din't want it directly instantiated - looking at my `GameBoard : BoardBase<SmallBoard>` and `SmallBoard : BoardBase<BoardCell>` classes/stubs I'm starting to think you're right, I don't need it to be abstract. It's just `GameBoard` seemed more descriptive than `BoardBase<SmallBoard>`... but I can see how it isn't."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T14:48:13.880",
"Id": "70404",
"Score": "1",
"body": "`I din't want it directly instantiated` Just make its constructor protected, then."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T15:03:59.090",
"Id": "70407",
"Score": "0",
"body": "The indexer *does* violate POLS a little; it works specifically to avoid having to create a new cell: I can use it like `gameBoard[BoardPosition.Center][BoardPosition.Left] = CellValue.X`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T15:48:53.820",
"Id": "70419",
"Score": "0",
"body": "@lol.upvote Don't you need a (new) BoardCell or a SmallBoard on the right-hand side of that assignment expression, not a CellValue? Post some unit-test code which shows how you use the APIs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T01:17:56.857",
"Id": "70542",
"Score": "0",
"body": "I lied. I need to add `.Value` before making the assignment. The indexer gets/sets `TCell` that's why. It's confusing because I don't call that setter. I call the getter and assign the value of that TCell. The indexer should be get-only, I wrote that setter for nothing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T01:35:12.157",
"Id": "70543",
"Score": "1",
"body": "@lol.upvote Exactly. And by letting user-code poke new state into a cell, therefore Cell needs to use an event handler to notify Game when the cell's state has changed. For that reason (to avoid the complexity of bubbling state change via event handler) I was inspired to ensure that state can only be changed via a method of Game: so that Game knows when state is being changed, and can implement preconditions (detecting illegal plays) and post-conditions (updating winners). If someone plays illegally you might detect that in your event handler, and restore to previous state (!) before throwing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T17:39:33.593",
"Id": "71657",
"Score": "0",
"body": "“CellValueChangedEventArgs needn't be a subclass of EventArgs.” [The Framework Design Guidelines](http://msdn.microsoft.com/en-us/library/vstudio/ms229011) say that it should. One reason is it means you have a single handler for multiple events with different `EventArgs`."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T11:05:24.400",
"Id": "41056",
"ParentId": "41029",
"Score": "3"
}
},
{
"body": "<p>I like it, </p>\n\n<p>especially the enums.</p>\n\n<p>Although the Tuple evaluator is super hard to parse.</p>\n\n<p>Definitely think it would be better to wrap that in a <code>WinCondition</code> interface or something which contains the relevant enum flag.</p>\n\n<p>besides if memory serves you can perform flag concatenation for a cleaner compare.</p>\n\n<pre><code>BoardPosition winPosition = BoardPosition.TopLeft | BoardPosition.Top | BoardPosition.TopRight;\n</code></pre>\n\n<p>and make a list of them:</p>\n\n<pre><code>_winPositions.Any(position => position == currentPosition)\n</code></pre>\n\n<p>or something....</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T14:43:43.360",
"Id": "70403",
"Score": "0",
"body": "That looks like an interesting approach that takes advantage of the very nature of enums. I like this idea. Very much."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T11:42:44.900",
"Id": "41058",
"ParentId": "41029",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41056",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T03:44:11.607",
"Id": "41029",
"Score": "10",
"Tags": [
"c#",
"game",
"community-challenge",
"tic-tac-toe"
],
"Title": "TicTactics GameBoard Logic"
}
|
41029
|
<p>While I should probably be using Dependency Injection via <a href="http://www.ninject.org/">Ninject</a> or a similar project, I have been attempting to implement an abstract factory design that would provide me with the following easy to read and use syntax:</p>
<pre><code>UniversalFactory.Factory<IFoo>.Create<FooImpl>(... parameters ...);
</code></pre>
<p>I'm throwing this experiment on here in order to solicit some constructive feedback both with implementation logic and design reasoning.</p>
<p>Here is my current implementation:</p>
<pre><code>public class UniversalFactory
{
private readonly IFactory<IFoo> FooFactoryEx;
public UniversalFactory()
{
FooFactoryEx = new FooFactory();
}
public IFactory<T> Factory<T>()
{
if (typeof (T) == typeof (IFoo))
return (IFactory<T>)FooFactoryEx;
return null;
}
}
public interface IFactory<in TF>
{
T Create<T>(params object[] p) where T : TF;
}
public class FooFactory : IFactory<IFoo>
{
public T Create<T>(params object[] p) where T : IFoo
{
if (typeof(T) == typeof(FooImpl))
{
var id = Convert.ToInt32(p[0]);
return (T)FooImpl.Create(id);
}
return default(T);
}
}
public interface IFoo
{
// Some interface
}
public class FooImpl : IFoo
{
public int Id { get; set; }
private FooImpl(int id)
{
Id = id;
}
public static IFoo Create(int id)
{
var foo = new FooImpl(id);
return foo;
}
}
</code></pre>
<p>This code allows a UniversalFactory to be instantiated and the following to be invoked successfully:</p>
<pre><code>UniversalFactory.Factory<IFoo>().Create<FooImpl>(1);
</code></pre>
<p>My reasoning for this approach:</p>
<ol>
<li>All construction is easily identifiable via the call to UniversalFactory.</li>
<li>Factories are invoked based on the interface implementation being constructed, hiding all details about the specific factory being used from the new object request.</li>
<li>The object type and its construction parameters are clearly identifiable in the request.</li>
<li>Object construction stays in each class, and any additional updates to other objects at construction time can take place in the factory method.</li>
</ol>
<p>My current implementation has (at a minimum) the following flaws:</p>
<ol>
<li>There is no compile-time safety that ensures IFoo is implemented by an IFactory. Only that FooImpl implements IFoo is ensured.</li>
<li>UniversalFactory.Factory has to add a check for every interface supported by a factory</li>
<li>Individual factories have to invoke static Create() methods within each class. It would be better if the static create could be invoked in a generic way, and Create(params object[] p) somehow mapped to Create(int a, string b, ...) as needed.</li>
</ol>
<p>Thoughts? Feedback? Is this approach unnecessary or too complex? Hopefully this experiment is, at the least, interesting to a couple of other SO folk out there.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T04:31:04.987",
"Id": "70315",
"Score": "0",
"body": "obligatory: http://discuss.joelonsoftware.com/default.asp?joel.3.219431.12"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T18:59:39.880",
"Id": "70473",
"Score": "0",
"body": "I do love his blog, and I agree with the sentiment. However this is just an experiment with generics and factories and not a serious implementation. Trying to learn by seeing how much I can do with these tools, before actually using a DI framework."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T20:05:39.697",
"Id": "71699",
"Score": "0",
"body": "Soo, how is `UniversalFactory.Factory<IFoo>().Create<FooImpl>(1)` any better than `new FooImpl(1)` (assuming it was public)?"
}
] |
[
{
"body": "<p>Well what you are trying to do is not strictly speaking an abstract factory. For it to be an abstract factory the use case should look like this:</p>\n\n<pre><code>UniversalFactory.Factory<IFoo> // client has no idea about IFactory<IFoo> implementation\n .Create(... parameters ...); // client has no idea about IFoo implementation, returns IFoo\n</code></pre>\n\n<p>Ideally, you should not even need to pass parameters. That is why you are building factories after all. To delegate object creation.</p>\n\n<p>Other minor remarks:</p>\n\n<ol>\n<li><code>where T : TF</code> - those are not very descriptive names for generic arguments. Perhaps you can come up with better naming.</li>\n<li><code>var id = Convert.ToInt32(p[0]);</code> - i'm not sure i like <code>Convert</code> here. It might hide bugs and misusages. I think that strong cast is better in that case.</li>\n<li><p><code>public static IFoo Create(int id)</code> - i don't see any reason to use factory method.</p>\n\n<pre><code>public class FooImpl : IFoo\n{\n public int Id { get; private set; }\n\n public FooImpl(int id)\n {\n Id = id;\n }\n}\n</code></pre>\n\n<p>this looks a lot cleaner. Also i think <code>Id</code> setter should be always private.</p></li>\n</ol>\n\n<p>Overall, i think unless you are doing it for studying purposes, you should just grab an existing DI library, as you've metioned yourself :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T19:03:21.500",
"Id": "70475",
"Score": "0",
"body": "I agree with the remarks, so thanks. I would like to hear more reasoning on why passing in parameters is a bad idea in this case? What if there is more then ID assignment and tracking, and there are required configuration options that need to be known at creation-time? Is that a flaw in the object construction logic, or is the assumption that such a scenario would not arise?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T05:53:06.670",
"Id": "70570",
"Score": "0",
"body": "@jmblack, well, using `params object[] p` nullifies the abstraction (you are passing concrete parameters for concrete implementation of `IFoo`) and does not simplify object creation (calling `new FooImpl(...)` is just as easy if not easier). And those are two main reason people use factories (abstraction and dependency injection). However, if, for example, `IFoo` whould contain an `Id` property which should be set by client, i think it is ok to pass strongly typed `id` parameter to Create method, as every implementation will need it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T20:26:36.457",
"Id": "70772",
"Score": "0",
"body": "I ended up reworking a lot of my test code based on this feedback. I ran into a new error while doing such though, and have posted that question to SO here (in case you're interested or want to weigh in there or here): http://stackoverflow.com/questions/21651411"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T05:42:14.120",
"Id": "41036",
"ParentId": "41030",
"Score": "2"
}
},
{
"body": "<p>The code is really well written but that is a LOT of power to give one class. \nIt has essentially created a dependency bottleneck. </p>\n\n<p>Most of the advantages of factories is the ability to swap/change/update implementations without extraneous recompiling or changing.</p>\n\n<p>Although here you are calling the Universal Factory (which as an implementation can't be changed without recompiling every class using it)</p>\n\n<p>Second, you are calling the direct implementation in the call itself. this means that you are also dependent on that.</p>\n\n<p>You correctly asserted the correct approach is probably a DI system. \nAlternatively you could stick with the factory and go with something like</p>\n\n<pre><code>IGlobalFactory factory;//Possibly constructor initialized\n\nIFoo bar = factory.Create<IFoo>();\n</code></pre>\n\n<p>Whereby the <code>GlobalFactoryImpl</code> is Injected and provides a factory with implementation of your IFoo.</p>\n\n<p>It is usually a bad idea to let your main class be aware there is a <code>FooImpl</code> in this way the <code>GlobalFactoryImpl</code>can return FooImpl when called but a <code>GlobalFooBlargFactoryImpl</code> can return a <code>FooBlargImpl</code> , you still get the ability to swap out implementation but everything is a little more obfuscated.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T19:04:46.680",
"Id": "70477",
"Score": "0",
"body": "UniversalFactory was intended to be a singleton or static, and it would only contain generic logic that would never change. This would allow it to act as the universal entry point for all object creation. You bring up some good points. I may rework this some more and add a V2 edit to the OP for further comments. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T19:08:23.177",
"Id": "70478",
"Score": "0",
"body": "The other issue that I didn't even realize I have, that you pointed out, is the dependency on FooImpl. What I was trying to do here was to have IFoo implemented by FooImpl, FooImpl2, and FooImpl3 and be able to request any of these (or any other implementation of IFoo) from arbitrary locations."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T09:40:41.563",
"Id": "41050",
"ParentId": "41030",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T03:57:56.637",
"Id": "41030",
"Score": "6",
"Tags": [
"c#",
"generics",
"factory-method"
],
"Title": "Abstract Factory Experiment"
}
|
41030
|
<p>I've written a solution to <a href="http://projecteuler.net/problem=41">Euler 41</a>:</p>
<blockquote>
<p>We shall say that an n-digit number is pandigital if it makes use of
all the digits 1 to n exactly once. For example, 2143 is a 4-digit
pandigital and is also prime.</p>
<p>What is the largest n-digit pandigital prime that exists?</p>
</blockquote>
<p>But it feels like I could compress the code down instead of having 30 lines of for loops. To briefly explain how it works:</p>
<p>I generate all pandigital numbers through the generate function which features 9 nested for loops which continue if their value is equal to a higher loop or if they would make a number longer than what is required. The generated numbers are then prime checked. This is a bruteforce method.</p>
<pre><code>var time = new Date;
var buffer = [];
var greatest = 0;
function isPrime(number) {
var s = Math.sqrt(number);
for (var b = 2; b <= s; b++) {
if (number % b === 0) {
return false;
}
}
return true;
}
function push(array) {
buffer.push(array.join(''));
}
function generate(length) {
var max = length;
for (var u = 1; u <= max; u++) {
if (max === 1) {
push([u]);
}
for (var i = 1; i <= max; i++) {
if (i === u || max < 2) {
continue;
}
if (max === 2) {
push([u, i]);
}
for (var o = 1; o <= max; o++) {
if (o === i || o === u || max < 3) {
continue;
}
if (max === 3) {
push([u, i, o]);
}
for (var p = 1; p <= max; p++) {
if (p === i || p === o || p === u || max < 4) {
continue;
}
if (max === 4) {
push([u, i, o, p]);
}
for (var a = 1; a <= max; a++) {
if (a === i || a === o || a === p || a === u || max < 5) {
continue;
}
if (max === 5) {
push([u, i, o, p, a]);
}
for (var s = 1; s <= max; s++) {
if (s === a || s === p || s === o || s === i || s === u || max < 6) {
continue;
}
if (max === 6) {
push([u, i, o, p, a, s]);
}
for (var d = 1; d <= max; d++) {
if (d === s || d === a || d === p || d === o || d === i || d === u || max < 7) {
continue;
}
if (max === 7) {
push([u, i, o, p, a, s, d]);
}
for (var f = 1; f <= max; f++) {
if (f === d || f === s || f === a || f === p || f === o || f === i || f === u || max < 8) {
continue;
}
if (max === 8) {
push([u, i, o, p, a, s, d, f]);
}
for (var g = 1; g <= max; g++) {
if (g === f || g === d || g === s || g === a || g === p || g === o || g === i || g === u || max < 9) {
continue;
}
push([u, i, o, p, a, s, d, f, g]);
}
}
}
}
}
}
}
}
}
}
for (var i = 1; i <= 8; i++) {
generate(i);
}
for (var i = buffer.length - 1; i >= 0; i--) {
if (isPrime(buffer[i])) {
greatest = buffer[i];
break;
}
}
var time1 = new Date;
console.log(greatest, 'took:', time1 - time, 'ms');
</code></pre>
|
[] |
[
{
"body": "<p>I think this is a bit over engineered. Let's talk our way through the problem.</p>\n\n<ul>\n<li>By definition we know the highest pandigital number is 987654321.</li>\n<li>We need to loop through each odd number between 1 and 987654321.</li>\n<li><p>We need to test each number as a prime.\nHere's a nice optimised <code>isPrime</code> function from <a href=\"https://stackoverflow.com/a/17390131/334274\">here</a>.</p>\n\n<pre><code>function isPrime(number) {\n var start = 2;\n while (start <= Math.sqrt(number)) {\n if (number % start++ < 1) return false;\n }\n return number > 1;\n}\n</code></pre></li>\n<li><p>If it is prime we need to test each number is pandigital. We should only need to loop once. If we make a set of the digits in a number, then the length of the set will be equal to the total count of digits in the number.</p>\n\n<pre><code>function isPandigital(number) {\n var numStr = number.toString(),\n digits = [];\n\n for (var digit in numStr) {\n\n if (numStr.hasOwnProperty(digit) && digits.indexOf(digit) === -1) \n digits.push(digit);\n }\n\n return digits.length === numStr.length;\n}\n</code></pre></li>\n<li><p>Then you just need to write the loop:</p>\n\n<pre><code>var pandigitalPrimes = [];\n\nfor (var n = 1; n <= 987654321; n+=2) {\n if (isPrime(n) && isPandigital(n)) pandigitalPrimes.push(n);\n}\n</code></pre></li>\n<li><p>Now it's your job to optimise these ideas so that this process doesn't take absolutely forever.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T12:29:08.693",
"Id": "70379",
"Score": "2",
"body": "Maybe it's a bit under-engineered. :) \"Optimise these ideas\" means \"Use the [Sieve of Erastothene](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes)\" which is a bit different than simply looping over all numbers."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T09:23:34.980",
"Id": "41048",
"ParentId": "41037",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "41048",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T06:02:50.177",
"Id": "41037",
"Score": "5",
"Tags": [
"javascript",
"project-euler",
"node.js",
"primes"
],
"Title": "Project Euler #41 - pandigital prime"
}
|
41037
|
<p>This is my attempt at the <a href="https://codereview.meta.stackexchange.com/a/1472/23788">Ultimate Tic-Tac-Toe code challenge</a>.</p>
<p>It uses jQuery to build out the game grid and find the states of all the "buttons" (actually <code><div></code>s) when calculating whether or not someone has won an individual board or the entire game.</p>
<p>This version follows the recommendation that a filled board that is a draw does not count for either player.</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>Ultimate Tic-Tac-Toe</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"> </script>
<style type="text/css">
body { text-align: center; }
div { display: inline-block; }
.grid { padding: 5px; border: solid 1px #300; }
.current-grid { background-color: #ff0; }
.button { background-color: #eee; width: 25px; height: 25px; margin: 5px;
text-align: center; vertical-align: middle; font-size: 25px; }
.X-won { background-color: #cfc; }
.O-won { background-color: #cdf; }
.no-win { background-color: #ccc; }
.X-selected { color: #080; }
.O-selected { color: #008; }
#game { position: absolute; left: 0px; right: 0px; }
</style>
<script type="text/javascript">
<!--
var isXTurn = true;
var currentGrid = -1;
$(function() {
$('body').append('<div id="game"></div>');
for (var i = 0; i < 9; i++) {
$('#game').append('<div class="grid" id="grid' + i + '"></div>');
if (i % 3 == 2) {
$('#game').append('<br />');
}
for (var j = 0; j < 9; j++) {
$('#grid' + i).append('<div class="button" id="button' + i + '-' + j + '"></div>');
if (j % 3 == 2) {
$('#grid' + i).append('<br />');
}
}
}
$('.button').click(function() {
var parent = $(this).parent();
var me = isXTurn ? 'X' : 'O';
if ($(this).is('.X-selected, .O-selected') || parent.is('.X-won, .O-won') ||
(currentGrid >= 0 && parent.attr('id') != 'grid' + currentGrid)) {
return;
}
$(this).addClass(me + '-selected').html(me);
if (checkForWin($(this), ('.' + me + '-selected'))) {
parent.addClass(me + '-won');
if (checkForWin(parent, ('.' + me + '-won'))) {
window.alert(me + ' won!');
resetGame();
return;
}
else if ($('.grid.X-won, .grid.O-won, .grid.no-win').length == 9) {
window.alert('The game is a draw!');
resetGame();
return;
}
}
else if (parent.children('.X-selected, .O-selected').length == 9) {
parent.addClass('no-win');
}
currentGrid = +($(this).attr('id').slice(-1));
$('.grid').removeClass('current-grid');
if ($('#grid' + currentGrid).is('.X-won, .O-won, .no-win')) {
currentGrid = -1;
}
else {
$('#grid' + currentGrid).addClass('current-grid');
}
isXTurn = !isXTurn;
});
function checkForWin(elem, match) {
var index = +(elem.attr('id').slice(-1));
var prefix = '#' + (elem.hasClass('button') ? elem.attr('id').slice(0, 8) : 'grid');
// Check rows
if (elem.nextUntil('br').add(elem.prevUntil('br')).filter(match).length == 2) {
return true;
}
// Check columns
if ($(prefix + (index % 3)).add($(prefix + (index % 3 + 3))).add($(prefix + (index % 3 + 6))).filter(match).length == 3) {
return true;
}
// Check diagonals
if ($(prefix + 0).add($(prefix + 4)).add($(prefix + 8)).filter(match).length == 3) {
return true;
}
if ($(prefix + 2).add($(prefix + 4)).add($(prefix + 6)).filter(match).length == 3) {
return true;
}
return false;
}
});
function resetGame() {
isXTurn = true;
currentGrid = -1;
$('div').removeClass('X-won O-won no-win current-grid X-selected O-selected');
$('.button').html('');
}
//-->
</script>
</head>
<body>
<h1>Ultimate Tic-Tac-Toe!</h1>
<p><a href="#" onclick="resetGame()">Restart</a></p>
</body>
</html>
</code></pre>
<p>It also passes the W3C validators for HTML and CSS, which is a bonus warm fuzzy.</p>
|
[] |
[
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li>I would use the HTML 5 tags, they are cleaner and more appropriate:<br>\n <code><!DOCTYPE html></code><br>\n <code><html></code><br>\nYour code validates perfectly as HTML5</li>\n<li>The UI setup probably deserves it's own function</li>\n<li>There is no separation of concerns ( more specifically logic and UI ) in your <code>click</code> handler, also you are using the UI as your data model, which is iffy.</li>\n<li>I love how short <code>resetGame</code> is</li>\n<li>A lot of the numbers are hard coded, you seem <em>so</em> close to do any number of boards, if you were to polish this code further, I would suggest you look into that</li>\n</ul>\n\n<p>For fun I made it run on jsbin : <a href=\"http://jsbin.com/rohe/3\" rel=\"nofollow\">http://jsbin.com/rohe/3</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T00:21:49.367",
"Id": "70536",
"Score": "0",
"body": "I've incorporated your recommendations, thanks a lot for the input. I understand the concern about using the UI as the data model, but because the UI and the state of the game are so tightly bound (there is very little in the model that doesn't have a 1-to-1 correspondence with a visual representation in the UI) that it seemed silly to separate the two where they could potentially drift out of sync. It does make the click handler more complex than I would like and if the game was more complex I think then it would be worth separating the two."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T13:47:53.897",
"Id": "41065",
"ParentId": "41038",
"Score": "10"
}
},
{
"body": "<p>Just about everything I pointed out on a <a href=\"https://codereview.stackexchange.com/a/40895/26722\">review for the same challenge</a> applies here (are you sure you didn't just copy this guy?).</p>\n\n<p>Attaching an event handler to each and every button element is highly inefficient (and fairly common mistake made by jQuery programmers). Instead, you should be using event delegation. A single event handler attached to the board itself is all you need to catch events on the descendant elements.</p>\n\n<p>Using JavaScript to generate markup is inefficient: the more you can generate up front, the better. Unless your intent was to let the users decide how many tiles the board should have...</p>\n\n<p>Validating HTML is pretty easy to do when your page contains virtually no markup. Semantically speaking, the generated board rather poor. There's no reason to ever use a <code><br /></code> between block level elements. If you need to force wrapping (because you've made them inline-bock), adjust the width of the parent element instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T16:00:04.430",
"Id": "70422",
"Score": "2",
"body": "Generating with JS keeps it DRY, your claims of inefficiency run counter to actually running the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T19:03:51.370",
"Id": "70476",
"Score": "0",
"body": "@konijn So you think that generating the markup via JavaScript is *faster* (or just as fast) as having the markup in the document? It is possible to by DRY by generating it on the server side."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T19:32:04.420",
"Id": "70486",
"Score": "0",
"body": "@cimmamon, I am saying that a human could not tell the difference, we are talking about shaving off milliseconds."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T20:34:07.970",
"Id": "70507",
"Score": "0",
"body": "@konijn You'll nitpick about one optimization recommendation, but not the other? The user is unlikely to notice the difference between a single event handler vs an event handler on every element (since there aren't enough elements to make the page feel slow), too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T20:40:57.970",
"Id": "70508",
"Score": "0",
"body": ";) I was nitpicking on both actually. The generation also increases DRYness so I called that out specifically."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T00:43:18.230",
"Id": "70541",
"Score": "0",
"body": "Now that you mention it, the `<br />` in between `div`s is semantically dubious, however it does enable easy searching within a row without wrapping each row in another `div`. Generating the markup on the page is best for this example because it doesn't require any server-side code and in the revised version it does allow for users to change the number of board tiles. Event delegation may be a good idea for a future optimization, though."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T15:19:47.007",
"Id": "41076",
"ParentId": "41038",
"Score": "6"
}
},
{
"body": "<ul>\n<li><p>You're making a few DOM elements with jQuery, which is fine. However instead of nasty strings like this;</p>\n\n<blockquote>\n<pre><code> $('#game').append('<div class=\"grid\" id=\"grid' + i + '\"></div>');\n</code></pre>\n</blockquote>\n\n<p>Consider creating the elements and modifying attributes using the jQuery functions, and then appending them <strong>to</strong> the game board. </p>\n\n<pre><code>$('<div id=\"grid>')\n .addClass('grid' + i)\n .appendTo('#game');\n</code></pre>\n\n<p>I find it's almost always more legible and easier to understand when you use <code>appendTo</code> rather than <code>append</code>.</p></li>\n<li><p>You reuse a few jQuery selectors. It's always better to store the elements than to look them up from the DOM each time. <code>var $game = $('#game');</code></p></li>\n<li><p>Your reset function includes this gem: <code>$('div')</code>. This is one of the worst selectors possible! It will select every <code>div</code> on the page! Since you only want to select the ones in your game then use a selector with context: <code>$('div', $game)</code>. Or better still, use a class.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T00:28:56.570",
"Id": "70538",
"Score": "1",
"body": "I didn't realize that you could pass in context with a selector, which made changing the code to support multiple games on one page much easier. I did pull out some of the reused jQuery selectors as well. I believe `$(this)` is still cheap so I didn't pull that out, but I could be wrong. I did strip out the closing tag from my appends, but I didn't feel that using `appendTo` instead of `append` was significantly more readable, nor modifying attributes after creation. That's just my personal preference, though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T04:02:01.493",
"Id": "70558",
"Score": "0",
"body": "I've fixed many functions in our code to reuse a selector variable for exactly the optimization reason you specify. Do you happen to have a link that addresses this *across* functions? IOW, is it better to store the jQuery object for use later *across UI events* vs. looking it up on each click?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T08:16:31.810",
"Id": "70583",
"Score": "0",
"body": "@DavidHarkness If you're going to reuse a selector a lot, then it's better to store it as a variable. Remember each time you call `$('')` jQuery has to search the DOM for the element."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T09:50:00.393",
"Id": "70588",
"Score": "0",
"body": "@Jivings Yes, I expect that outweighs the bytes required to maintain a reference to the selector."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T07:16:59.840",
"Id": "71219",
"Score": "0",
"body": "@DavidHarkness Memory is not so much an issue as speed."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T19:12:17.007",
"Id": "41098",
"ParentId": "41038",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T06:03:52.010",
"Id": "41038",
"Score": "11",
"Tags": [
"javascript",
"jquery",
"html",
"css",
"community-challenge"
],
"Title": "Ultimate Tic-Tac-Toe Challenge"
}
|
41038
|
<p>I am creating an application in Java that runs at scheduled intervals and it transfer files from one server to another server.</p>
<p>For <code>SFTP</code> I'm using <code>jSch</code>, and my server and file details came from Database.</p>
<p>My code is working fine but its performance is not good because I'm using too many <code>loops</code> in my code.</p>
<p>Is there any way to increase performance of my code?</p>
<pre><code>public class FileTransferThread implements Runnable {
public static final Logger log = Logger.getLogger(FileTransferThread.class.getName());
private Session hibernateSession_source;
private Session hibernateSession_destination;
private List<nr_rec_backup_rule> ruleObjList = new ArrayList<>();
private Map<String, List<String>> filesMap = new HashMap<>();
private int i = 1;
@Override
public void run() {
try {
hibernateSession_destination = HibernateUtilReports.INSTANCE.getSession();
// Getting Active rules from (nr_rec_backup_rule)
Criteria ruleCriteria = hibernateSession_destination.createCriteria(nr_rec_backup_rule.class);
ruleCriteria.add(Restrictions.eq("status", "active"));
List list = ruleCriteria.list();
for (Object object : list) {
nr_rec_backup_rule ruleObj = (nr_rec_backup_rule) object;
ruleObjList.add(ruleObj);
}
System.out.println("List of Rule Objs : " + ruleObjList);
getTargetServerAuthentication();
} catch (Exception e) {
log.error("SQL ERROR ======== ", e);
} finally {
hibernateSession_destination.flush();
hibernateSession_destination.close();
hibernateSession_source.flush();
hibernateSession_source.close();
}
}
private void getTargetServerAuthentication() throws Exception {
if (ruleObjList.size() > 0) {
JSch jsch = new JSch();
hibernateSession_source = HibernateUtilSpice.INSTANCE.getSession();
for (nr_rec_backup_rule ruleObj : ruleObjList) {
//getting authentication details for backupserver from table "contaque_servers"
String backupHost = ruleObj.getBackupserver();
Criteria crit = hibernateSession_source.createCriteria(contaque_servers.class);
crit.add(Restrictions.eq("server_ip", backupHost));
ProjectionList pList = Projections.projectionList();
pList.add(Projections.property("machineUser"));
pList.add(Projections.property("machinePassword"));
pList.add(Projections.property("machinePort"));
crit.setProjection(pList);
Object uniqueResult = crit.uniqueResult();
if (uniqueResult != null) {
Object[] serverDetails = (Object[]) uniqueResult;
String backupUser = (String) serverDetails[0];
String backupPassword = (String) serverDetails[1];
int backupPort = (int) serverDetails[2];
//creating connection to backup server
com.jcraft.jsch.Session sessionTarget = null;
ChannelSftp channelTarget = null;
try {
sessionTarget = jsch.getSession(backupUser, backupHost, backupPort);
sessionTarget.setPassword(backupPassword);
sessionTarget.setConfig("StrictHostKeyChecking", "no");
sessionTarget.connect();
channelTarget = (ChannelSftp) sessionTarget.openChannel("sftp");
channelTarget.connect();
System.out.println("Target Channel Connected");
//Getting fileName from table "contaque_recording_log" using campName and Dispositions
String[] split = ruleObj.getDispositions().split(", ");
Criteria criteria = hibernateSession_source.createCriteria(contaque_recording_log.class);
criteria.add(Restrictions.eq("campName", ruleObj.getCampname()));
criteria.add(Restrictions.in("disposition", Arrays.asList(split)));
criteria.setProjection(Projections.property("fileName"));
List list = criteria.list();
for (Iterator it = list.iterator(); it.hasNext();) {
String completeFileAddress = (String) (it.next());
if (completeFileAddress != null) {
int index = completeFileAddress.indexOf("/");
String serverIP = completeFileAddress.substring(0, index);
String filePath = completeFileAddress.substring(index, completeFileAddress.length()) + ".WAV";
if (filesMap.containsKey(serverIP)) {
List<String> sourceList = filesMap.get(serverIP);
sourceList.add(filePath);
} else {
List<String> sourceList = new ArrayList<String>();
sourceList.add(filePath);
filesMap.put(serverIP, sourceList);
}
}
}
//getting authentication details for source-server from table "contaque_servers"
if (filesMap.size() > 0) {
for (Map.Entry<String, List<String>> entry : filesMap.entrySet()) {
String sourceHost = entry.getKey();
List<String> fileList = entry.getValue();
Criteria srcCriteria = hibernateSession_source.createCriteria(contaque_servers.class);
srcCriteria.add(Restrictions.eq("server_ip", sourceHost));
ProjectionList pList1 = Projections.projectionList();
pList1.add(Projections.property("machineUser"));
pList1.add(Projections.property("machinePassword"));
pList1.add(Projections.property("machinePort"));
srcCriteria.setProjection(pList1);
Object uniqueResult1 = srcCriteria.uniqueResult();
if (uniqueResult1 != null) {
Object[] srcServer = (Object[]) uniqueResult1;
String srcUser = (String) srcServer[0];
String srcPassword = (String) srcServer[1];
int srcPort = (int) srcServer[2];
//creating connection to source server
com.jcraft.jsch.Session sessionSRC = jsch.getSession(srcUser, sourceHost, srcPort);
sessionSRC.setPassword(srcPassword);
sessionSRC.setConfig("StrictHostKeyChecking", "no");
sessionSRC.connect();
ChannelSftp channelSRC = (ChannelSftp) sessionSRC.openChannel("sftp");
channelSRC.connect();
System.out.println("Source Channel Connected");
try {
fileTransfer(channelSRC, channelTarget, ruleObj, fileList);
} finally {
channelSRC.exit();
channelSRC.disconnect();
sessionSRC.disconnect();
}
} else {
log.error("IN ELSE ======== Source server dosen't exists in table 'contaque_servers'");
}
}
}
} catch (JSchException e) {
log.error("Error Occured ======== Connection not estabilished", e);
} finally {
if (channelTarget != null && sessionTarget != null) {
log.error("exiting channel and session");
channelTarget.exit();
channelTarget.disconnect();
sessionTarget.disconnect();
} else {
log.error("Error Occured ======== Connection not estabilished");
}
}
}
}
}
}
private void fileTransfer(ChannelSftp channelSRC, ChannelSftp channelTarget, nr_rec_backup_rule ruleObj, List<String> fileList) {
for (String filePath : fileList) {
System.out.println("i === " + i++);
int fileNameStartIndex = filePath.lastIndexOf("/") + 1;
String fileName = filePath.substring(fileNameStartIndex);
System.out.println("File Name : " + fileName);
System.out.println("File Path: " + filePath);
System.out.println("Backup Path : " + ruleObj.getBackupdir() + fileName);
try {
InputStream get = channelSRC.get(filePath);
channelTarget.put(get, ruleObj.getBackupdir() + fileName);
} catch (SftpException e) {
log.error("Error Occured ======== File or Directory dosen't exists === " + filePath);
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T09:11:45.003",
"Id": "70354",
"Score": "0",
"body": "Do you connect and disconnect from the FTP each time in the loop? It looks like it? I can't tell because it seems you have 2 or 3 loops doing something."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T09:23:44.517",
"Id": "70357",
"Score": "0",
"body": "I have to create a new connection to FTP each time when I got a new `sourceHost` and `backupHost`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T09:27:28.377",
"Id": "70359",
"Score": "0",
"body": "Yea - I see that now. But you manage files on the existing connection. Where are you experiencing performance issues and what is the sympton?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T09:31:12.287",
"Id": "70360",
"Score": "1",
"body": "The only thing I can see is that you can start the upaloders on separate threads, so you can upload 2,5 or 10 files at the same time - if your inter allows it. Otherwise I cannot really see any bottleneck in the code."
}
] |
[
{
"body": "<p>At face value it appears that there can be only one place where the major bottleneck is: the actual file transfer. Your code does the following:</p>\n\n<ul>\n<li>builds up a bunch of source files to copy</li>\n<li>creates a 'target' destination for the file copy</li>\n<li>goes through each source</li>\n<li>for each source, it 'downloads' the files one at a time</li>\n<li>as it downloads each file, it uploads it to the target.</li>\n</ul>\n\n<p>While this whole task may be running in a separate thread, it is by no means multi-threaded.</p>\n\n<p>The probable bottleneck here is the amount of CPU time required to decrypt the data from the source, and re-encrypt it to the destination.</p>\n\n<p>It is likely, also, that close behind the CPU bottleneck (perhaps even in front of it) is the network transfer speeds you can get in a single socket connection.</p>\n\n<p>I would suggest four things to do, and possibly a combination of them:</p>\n\n<ol>\n<li>try to set up a system where you can sfp direct from the source to the destination without needing to process the file in between. You have ssh access to them both, so it should not be that hard to create a script on the source, and run that script with some parameters that copies the file to the destination.</li>\n<li>Use BlowFish encryption algorithm for the transfer. It is rumoured that blowfish is faster than the other algorithms, and, by the sounds of it, it should be fine for your use case.</li>\n<li>Wrap the InputStream you get from jsch in a BufferedInputStream</li>\n<li>spread the load of the decrypt/encrypt on multiple threads.</li>\n</ol>\n\n<p>The most effective option will be 1, but the most fun to write will be 4....</p>\n\n<p>Something like:</p>\n\n<ul>\n<li><p>create a method that takes the details required to copy a single file....</p>\n\n<pre><code>public Boolean copyFile(Session source, Session target, String sourcefile, String targetfile) throws IOException {\n // connect to the source\n .....\n // connect to the target\n .....\n // get a BufferedInputStream on the source\n .....\n // copy the stream to the target\n .....\n return Boolean.TRUE; // success.\n}\n</code></pre></li>\n<li><p>instead of populating a <code>filesMap</code> Map, do something like:</p>\n\n<pre><code>ExecutorService threadpool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());\nList<Future<Boolean>> transfers = new ArrayList<>();\n....\n final Session source = ......;\n final Session target = ......;\n final String sourcefile = ....;\n final String targetfile = ....;\n transfers.add(threadpool.submit(new Callable<Boolean>() {\n public Boolean call() throws IOException {\n return copyFile(source, target, sourcefile, targetfile);\n }\n });\n\n....\n// all copy actions are submitted now... so we wait for the threadpool.\nthreadpool.shutdown(); // orderly shutdown, all tasks are completed.\nfor (Future<Boolean> fut : transfers) {\n try {\n fut.get();\n } catch (Exception ioe) {\n LOGGER.warn(\"Unable to transfer file: \" + ioe.getMessage(), ioe);\n }\n}\n// all copies have been attempted, in parallel.\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T13:10:32.773",
"Id": "41063",
"ParentId": "41041",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "41063",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T07:42:18.710",
"Id": "41041",
"Score": "7",
"Tags": [
"java",
"optimization",
"performance",
"multithreading"
],
"Title": "Creating a thread for file transfer"
}
|
41041
|
<p>I wrote Clojure code which takes named params and has to generate 2 .csv files as output.</p>
<p>Please review it.</p>
<pre><code>(ns my_cli_clojure.core
(:gen-class :main true))
(require '[clojure.data.csv :as csv]
'[clojure.java.io :as io]
'[me.raynes.fs :as fs]
'[clojure.tools.cli :refer [cli] :as c])
(defn write_csv_data [& {:keys [data outfile]
:or {data ""
outfile ""}}]
(csv/write-csv outfile
data))
(defn -main
[& args]
(let [[options args banner]
(c/cli args
["-d" "-dome" "Dome Identifier" :default "dome1"]
["-p" "-principal" "Principal code" :default "kraft"]
["-o" "-output-directory" "Output file" :default "."]
["-h" "-help" "Show Help" :flag true :default false])]
(when (:help options)
(println banner)
(System/exit 0))
(let [output_directory (:output-directory options)]
(if-not (fs/exists? output_directory)
(fs/mkdirs output_directory))
(doseq [n (clojure.string/split (:dome options) #",")]
(let [dome_identifier (first (clojure.string/split n #"-"))]
(with-open [out-file (io/writer (clojure.string/join "/" [output_directory
(clojure.string/join "." [dome_identifier "csv"])]))]
(write_csv_data :data [["dome_identifier" "name"]
[dome_identifier (first (reverse (clojure.string/split n #"-")))]] :outfile out-file))
(with-open [dome_principal_file (io/writer (clojure.string/join "/" [output_directory
(clojure.string/join "." ["dome_principal" dome_identifier "csv"])]))]
(write_csv_data :data [(clojure.string/split "dome_identifier principal_code currency_code active latitude longitude" #"\s")
[dome_identifier (:principal options) "" "t" "" ""]] :outfile dome_principal_file)))))))
</code></pre>
|
[] |
[
{
"body": "<p>Everything looked pretty good in general, until I got to the <code>(let [output_directory ...</code> part, then your indentation got all wonky! Part of the problem is that there are a couple of really long lines, and it's difficult to keep them short when you're nested so many layers deep into an S-expression. Shortening your lines and making sure that everything lines up from line-to-line in an intuitive way will solve this.</p>\n\n<p>First of all, I believe it is idiomatic to include all your <code>use</code>/<code>require</code>/<code>import</code> statements within the namespace definition, like so:</p>\n\n<pre><code>(ns my_cli_clojure.core\n (:require [clojure.data.csv :as csv]\n [clojure.java.io :as io]\n [me.raynes.fs :as fs]\n [clojure.tools.cli :refer [cli] :as c]\n [clojure.string :as s])\n (:gen-class :main true))\n</code></pre>\n\n<p>Notice that I added <code>[clojure.string :as s]</code> -- this abbrevation will come in handy in shortening some of the later lines, in which you have a lot of fully-qualified references to <code>clojure.string</code> methods.</p>\n\n<p>Next, just an aesthetic spacing tweak here:</p>\n\n<pre><code>(defn write-csv-data [& {:keys [data outfile] :or {data \"\", outfile \"\"}}]\n (csv/write-csv outfile data))\n</code></pre>\n\n<p>Your code was fine, I just find my version easier to read at a glance. I generally try to avoid using line-breaks whenever the code I'm writing looks sufficiently compact on less lines. When the lines start getting long, I will think more about where it would make the most sense to break them up. (I also renamed write_csv_data to write-csv-data; it's idiomatic in Clojure to name symbols using hyphens instead of underscores)</p>\n\n<p>More spacing adjustments here:</p>\n\n<pre><code>(defn -main [& args]\n (let [[options args banner]\n (c/cli args\n [\"-d\" \"-dome\" \"Dome Identifier\" :default \"dome1\"]\n [\"-p\" \"-principal\" \"Principal code\" :default \"kraft\"]\n [\"-o\" \"-output-directory\" \"Output file\" :default \".\"]\n [\"-h\" \"-help\" \"Show Help\" :flag true :default false])]\n</code></pre>\n\n<p>Here is how I would tackle the part at the end:</p>\n\n<pre><code>(let [out-dir (:output-directory options)]\n (if-not (fs/exists? out-dir)\n (fs/mkdirs out-dir))\n (doseq [n (s/split (:dome options) #\",\")]\n (let [dome-id (first (s/split n #\"-\"))]\n (with-open [out-file (io/writer (str out-dir \"/\" dome-id \".csv\"))]\n (write-csv-data :data [[\"dome_identifier\" \"name\"]\n [dome-id (last (s/split n #\"-\"))]] \n :outfile out-file))\n (with-open [dome-principal-file \n (io/writer (str out-dir \"/dome_principal.\" dome-id \".csv\"))]\n (write-csv-data :data [[\"dome_identifier\" \"principal_code\" \n \"currency_code\" \"active\" \"latitude\" \"longitude\"]\n [dome-id (:principal options) \"\" \"t\" \"\" \"\"]] \n :outfile dome-principal-file)))))))\n</code></pre>\n\n<p>Changes:</p>\n\n<ol>\n<li>I shortened a few symbol names, like output_directory => out-dir and dome_identifier => dome-id. </li>\n<li>I changed the two parts with the pattern like <code>(s/join \"/\" [out-dir (s/join \".\" [dome-id \"csv\"])])</code> to <code>(str out-dir \"/\" dome-id \".csv\")</code>, which is more concise and easier to read. Keep it simple!</li>\n<li>I simplified <code>(first (reverse (s/split n #\"-\")))</code> to <code>(last (s/split n #\"-\"))</code>.</li>\n<li>There's a part of your code where you created a list of strings by doing something like this: <code>(s/split \"first-string second-string third-string fourth-string\" #\"\\s+\")</code>. That's clever, but the downside is that it leaves you with a long string that you can't break in order to shorten your lines. In this case, I think it makes more sense just to type e.g. <code>[\"first-string\" \"second-string\" \"third-string\" \"fourth-string\"]</code>.</li>\n</ol>\n\n<p>Hope that helps!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-03-18T18:20:53.840",
"Id": "44687",
"ParentId": "41042",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T07:56:03.997",
"Id": "41042",
"Score": "4",
"Tags": [
"clojure",
"csv"
],
"Title": "Generating two .csv files from named parameters"
}
|
41042
|
<p>Is there anything that can be done to improve this code? Even if its using a comepltey different technique.</p>
<p>This code gets a list of vanruns with rules, cutoff time and fittinging time offset. We pass in the date (either now or for future that works out the best vanrun time) We want the latest cutofftime in that day for the same warehouse. Generally is this code OK for long term use or should it be broken down more? or possibly the entire logic is flawed? Use different mechanics? Just a review if anything seriously bad is happening. </p>
<pre><code>private ServiceData.Models.CalculatedCutOff VarnRunEngine(List<Models.VanRunPrototype.VanRun> vanRuns, DateTime matchDate)
{
//get the date we are interested in
System.DayOfWeek dayOfWeek = matchDate.DayOfWeek;
DateTime dateOfWeekLoop = new DateTime(matchDate.Ticks);
if (vanRuns == null | (vanRuns != null && vanRuns.Count == 0))
throw new Exception("There are no Vanruns available to work out fitting times");
Models.VanRunPrototype.VanRun vr = null;
int loopkill = 0;
while (true)
{
loopkill += 1;
var _vrs = vanRuns.Where(v => v.DayOfWeek == (int)dateOfWeekLoop.DayOfWeek).ToList();
var _vrss = _vrs.Where(v => v.CutOff > dateOfWeekLoop.TimeOfDay).ToList();
var _vrsss = _vrss.OrderBy(t => t.CutOff).ToList();
if (_vrsss != null && _vrsss.Count > 0)
{
foreach (var v in _vrsss)
{
if (v.CutOff > DateTime.Now.TimeOfDay &&
(vr == null || (vr.FittingFor <= v.FittingFor && (v.CutOff > vr.CutOff && v.WareHouseID == vr.WareHouseID))))
{
vr = v;
}
}
vr = vr ?? _vrsss.First();
break;
}
//Go to next morning
dateOfWeekLoop = dateOfWeekLoop.Date + new TimeSpan(8, 0, 0); //For 8 in da morning? or 00:00??
dateOfWeekLoop = dateOfWeekLoop.AddDays(1);
if (loopkill > 14)
throw new Exception("Infinite loop");
}
DateTime co = dateOfWeekLoop.Date + vr.CutOff;
return new TyresAndServiceData.Models.CalculatedCutOff()
{
CutOffTime = co,
FittingFor = co.AddMinutes(vr.FittingIn).AddMinutes(vr.FittingInAdjust ?? 0),
QueryDate = matchDate,
WareHouseID = vr.WareHouseID ?? 0
};
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T12:23:46.133",
"Id": "70377",
"Score": "3",
"body": "Hello, and welcome to Code Review! Could you at least explain what the code does? Thanks!"
}
] |
[
{
"body": "<p>There are somethings that I want to point out, that you are doing slightly wrong. </p>\n\n<ul>\n<li>The first one is the argument checking. Argument checking should always be the first thing you do in your code, unless it is an expensive operation or you can't do it in a straight forward manner. In your case you don't have those reasons, so move your argument checking to the beginning. You should also use <code>ArgumentException</code> when your arguments are invalid instead of <code>Exception</code>.</li>\n<li>The second one is that you are not following the <code>camelCase</code> convetion for your variables, you are using <code>_camelCase</code> convention which applies to instance fields. Even if you are following your own convention which is not bad, I would not recommend a <code>_camelCase</code> convention.</li>\n<li>You shouldn't call the method ToList from LINQ so often. Calling the method ToList transforms what may be a lazy collection to a eager collection (which occupy the memory).</li>\n</ul>\n\n<p>Here follows the review I made to your code, I post some comments regarding some decisions I made. The code I provide may be further reviewed but I think this is a fair starting point. </p>\n\n<pre><code>ServiceData.Models.CalculatedCutOff VarnRunEngine(List<Models.VanRunPrototype.VanRun> vanRuns, DateTime matchDate)\n{\n if (vanRuns == null || vanRuns.Count == 0)\n throw new ArgumentException(\"There are no Vanruns available to work out fitting times\", vanRuns);\n\n System.DayOfWeek dayOfWeek = matchDate.DayOfWeek;\n DateTime dateOfWeekLoop = new DateTime(matchDate.Ticks);\n Models.VanRunPrototype.VanRun vr = null;\n int maxIterations = 14;\n for(int i = 0; i < maxIterations && vr == null; ++i)\n {\n var vrs = vanRuns.Where(v => v.DayOfWeek == (int)dateOfWeekLoop.DayOfWeek &&\n v.CutOff > dateOfWeekLoop.TimeOfDay)\n .OrderBy(t => t.CutOff);\n\n //vrs will never be null, it may be empty though\n //But you don't really have to check count because you will be iterating it, meaning that there is no problem\n //if vrs is empty. But if you want to preserve this check for any reason you could use vrs.Any()\n //if (vrs != null && vrs.Count() > 0)\n //{\n foreach (var v in vrs)\n {\n if ((vr == null || (vr.FittingFor <= v.FittingFor && \n v.CutOff > vr.CutOff && \n v.WareHouseID == vr.WareHouseID)))\n\n {\n vr = v;\n }\n }\n\n vr = vr ?? vrs.First();\n //}\n\n //Go to next morning\n dateOfWeekLoop = dateOfWeekLoop.Date + new TimeSpan(8, 0, 0);\n dateOfWeekLoop = dateOfWeekLoop.AddDays(1);\n }\n\n if(vr == null){\n throw new Exception(string.Format(\"Couldn't calculate CutOff in {0} iterations\", maxIterations));\n }\n\n DateTime co = dateOfWeekLoop.Date + vr.CutOff;\n return new TyresAndServiceData.Models.CalculatedCutOff()\n {\n CutOffTime = co,\n FittingFor = co.AddMinutes(vr.FittingIn).AddMinutes(vr.FittingInAdjust ?? 0),\n QueryDate = matchDate,\n WareHouseID = vr.WareHouseID ?? 0\n };\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T15:45:45.530",
"Id": "70416",
"Score": "0",
"body": "Thanks. I usually follow `camelCase` but that linq I was just trying to debug each query. I am not sure how to debug Linq during a breakpoint in the running code. So I just named those variables for temporary use, using `_` prefix. Thanks for this. Definitely looks allot easier to read."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T16:38:58.433",
"Id": "70627",
"Score": "0",
"body": "Thanks. I cleaned up my code and implemented some more logic but essentially I used your advise and the code is easier to look at. I will also implement `ArgumentException` more often too and try to call `.ToList` less often :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T18:41:35.100",
"Id": "70660",
"Score": "1",
"body": "Your welcome, I'm glad that it was useful."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T14:28:20.087",
"Id": "41071",
"ParentId": "41057",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41071",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T11:39:42.243",
"Id": "41057",
"Score": "7",
"Tags": [
"c#"
],
"Title": "Figuring out delivery times"
}
|
41057
|
<p>I'm preparing for an exam on C++, as part of my preparation I want to implement a generic map without using anything from the STD for educational purposes.</p>
<p>Before jumping into implementation of everything, I want to know that the skeleton for my Map is solid and I use templates and template inheritance correctly.</p>
<p>Above is the skeleton of my Map. I would like to get an opinion about that skeleton.</p>
<pre><code>#ifndef MAP_H_
#define MAP_H_
template <class K, class V>
class Map {
public:
/*
Map c'tors and d'tors.
*/
Map(); //C'tor
Map(const Map& map); //Copy c'tor
~Map(); //D'tor
/*
Map methods
*/
void insert(const K& key, const V& value);
bool isIn(const K& key) const;
void remove(const K& key);
void clear();
bool isEmpty();
int size() const;
template <class F>
Map filter(F& filterFunction);
/*
Map methods using Iterators
*/
class Iterator;
class ConstIterator;
Map::ConstIterator begin() const;
Map::ConstIterator end() const;
Map::Iiterator begin();
Map::Iterator end();
/*
Map operators
*/
const DataType& operator[](const KeyType key) const;
DataType& operator[](const KeyType key);
};
/*
Map::Pair class
*/
template <class K, class V>
class Map<K,V>::Pair {
};
/*
Map::Iterator class
*/
template <class K, class V>
class Map<K,V>::Iterator {
//to do
};
/*
Map::ConstIterator class
*/
template <class K, class V>
class Map<K,V>::ConstIterator : public Map<K,V>::Iterator {
//to do
};
/*
Map c'tors, methods and operators implementation
*/
//to do
#endif /* MAP_H_ */
</code></pre>
<hr>
|
[] |
[
{
"body": "<p>Here are some small things you could di in order to improve your design:</p>\n\n<ul>\n<li>First of all, you have a typo: you wrote <code>Map::Iiterator begin();</code> instead of <code>Map::Iterator begin();</code>.</li>\n<li>You use <code>KeyType</code> and <code>DataType</code> but do not even declare them.</li>\n<li>For client code that uses generic code, it would be great if the name of the functions and subtypes were consistent with the STL. That means that you should be using <code>empty()</code>, <code>iterator</code>, <code>const_iterator</code>, etc...</li>\n<li>The STL also defines subtypes like <code>value_type</code>, <code>reference_type</code>, <code>size_type</code>, etc... It would be better if you provided those too :)</li>\n<li>Since you are using C++11, you could also provide the member functions <code>cbegin</code> and <code>cend</code>, for the same reason (consistency with standard containers).</li>\n<li>You could have used <code>std::size_t</code> for the <code>size()</code> function (or even better, <code>Map<K, V>::size_type</code>), but using such an unsigned type can also lead to some unexpected problems. I wasn't able to find any relevant article, otherwise I would have linked one.</li>\n<li><code>operator[]</code> should take its elements by <code>const&</code>. You probably don't want to copy entire <code>std::string</code> instances when using this function.</li>\n<li>Last but not least, I have no idea what your function <code>filter</code> is supposed to do. My guess is that it returns a filtered version of the <code>Map</code>, in which case the name <code>filtered</code> may be more suitable. Otherwise, if it filters the current map in place, it should probably return a <code>Map&</code> instead of a <code>Map</code>. Anyway, you better document it to remove the potential ambiguities. Moreover, we don't know whether the filter function filters the <code>Map</code> on its keys or on its values.</li>\n</ul>\n\n<p>Well, otherwise, I don't think there are obvious errors in the design. There are probably some other things that can be improved, but generally speaking it's not bad :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T14:24:57.853",
"Id": "41654",
"ParentId": "41059",
"Score": "5"
}
},
{
"body": "<p>The one thing that immediately jumped at me: <code>ConstIterator</code> should <em>not</em> inherit from <code>Iterator</code>. If you want to reuse code, do it the other way around, but I would recommend even against that. Instead, try to make a common template.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T16:11:54.877",
"Id": "41662",
"ParentId": "41059",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "41654",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T11:49:48.867",
"Id": "41059",
"Score": "6",
"Tags": [
"c++",
"c++11",
"template"
],
"Title": "Template data types implementation"
}
|
41059
|
<p>Generally, UI code is painful and full of kludges (at least, mine was like that). Recently I have decided to put an end to it and try to learn how to write good and reusable UI code. </p>
<p>So here is the pattern (in a general sense of word) I came up with when subclassing UIViews: </p>
<ol>
<li>Subviews are properties and are initialized lazily;</li>
<li>Lazy initialization creates subviews with specific configuration;</li>
<li>Some of the parameters – especially platform-specific or those regarding the appearance – are extracted to class methods that are easily overridable in case it is needed;</li>
<li>Positioning is done in -layoutSubviews</li>
<li>Custom views = custom and more contextual delegate protocols</li>
<li>To display app-specific models, it is possible to use a category on the view providing a method to bind model fields and view fields together (to avoid cluttering the controller.)</li>
</ol>
<p>So far it has proven itself to be rather effective and producing compact code. Moreover, UI code is more segmented, each part doing its job and nothing more.</p>
<p>I would like to know whether it is done right and whether this pattern can be followed. Also it would be great to know if there are any possible pitfalls with it I don't see.</p>
<p><strong>IMInputField.h</strong></p>
<pre><code>#import <UIKit/UIKit.h>
//----------------------------------------------------
#pragma mark - Delegate Protocol
//----------------------------------------------------
@class IMInputField;
@protocol IMInputFieldDelegate <NSObject>
- (void)inputFieldChangedText:(IMInputField *)field;
- (void)inputFieldBecameFirstResponder:(IMInputField *)field;
- (void)inputFieldResignedFirstResponder:(IMInputField *)field;
@end
//----------------------------------------------------
#pragma mark - Class
//----------------------------------------------------
@interface IMInputField : UIView
@property (nonatomic) NSString *text;
@property (nonatomic) UIView *inputAccessory;
@property (nonatomic, assign) BOOL exitWithReturn;
@property (nonatomic, weak) IBOutlet id<IMInputFieldDelegate> delegate;
@end
</code></pre>
<p><strong>IMInputField.m</strong></p>
<pre><code>#import "IMInputField.h"
@interface IMInputField () <UITextViewDelegate>
@property (nonatomic, strong) UIImageView *backgroundImageView;
@property (nonatomic, strong) UITextView *textView;
@end
@implementation IMInputField
@dynamic inputAccessory, text;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setupAppearance];
}
return self;
}
- (void)awakeFromNib
{
[self setupAppearance];
}
- (void)setupAppearance
{
self.backgroundColor = [UIColor clearColor];
}
//----------------------------------------------------
#pragma mark - Elements
//----------------------------------------------------
+ (UIImage *)backgroundImage
{
UIImage *ret = [[UIImage alloc] init];
if ([UIDevice im_is_iOS7]) {
ret = [UIImage stretchableImageNamed:@"textfield_background.png"];
}
else /* iOS 6 and older */ {
ret = [UIImage stretchableImageNamed:@"text_field.png"];
}
return ret;
}
+ (UIFont *)defaultFont
{
return [UIFont systemFontOfSize:17];
}
+ (UIEdgeInsets)textInsets
{
UIEdgeInsets ret = UIEdgeInsetsZero;
if ([UIDevice im_appPlatformIsIPad]) {
ret = UIEdgeInsetsMake(4, 6, -4, -6);
}
else /* iPhone */ {
ret = UIEdgeInsetsMake(0, 3, 0, -3);
}
return ret;
}
//----------------------------------------------------
#pragma mark - Structural
//----------------------------------------------------
- (UIImageView *)backgroundImageView
{
if (_backgroundImageView == nil) {
_backgroundImageView = [[UIImageView alloc] initWithImage:[self.class backgroundImage]];
_backgroundImageView.backgroundColor = [UIColor clearColor];
[self addSubview:_backgroundImageView];
[self sendSubviewToBack:_backgroundImageView];
}
return _backgroundImageView;
}
- (UITextView *)textView
{
if (_textView == nil) {
_textView = [[UITextView alloc] initWithFrame:CGRectZero];
_textView.delegate = self;
_textView.autocorrectionType = UITextAutocorrectionTypeNo;
_textView.font = [self.class defaultFont];
_textView.backgroundColor = [UIColor clearColor];
_textView.contentInset = [self.class textInsets];
[self addSubview:_textView];
[self bringSubviewToFront:_textView];
}
return _textView;
}
//----------------------------------------------------
#pragma mark - Layout
//----------------------------------------------------
- (void)layoutSubviews
{
[super layoutSubviews];
self.backgroundImageView.frame = self.bounds;
self.textView.frame = self.bounds;
}
//----------------------------------------------------
#pragma mark - Delegate Communication
//----------------------------------------------------
- (void)reportTextChanged
{
if ([_delegate respondsToSelector:@selector(inputFieldChangedText:)]) {
[_delegate inputFieldChangedText:self];
}
}
- (void)reportResignedFirstResponder
{
if ([_delegate respondsToSelector:@selector(inputFieldResignedFirstResponder:)]) {
[_delegate inputFieldResignedFirstResponder:self];
}
}
- (void)reportBecameFirstResponder
{
if ([_delegate respondsToSelector:@selector(inputFieldBecameFirstResponder:)]) {
[_delegate inputFieldBecameFirstResponder:self];
}
}
//----------------------------------------------------
#pragma mark - UITextViewDelegate
//----------------------------------------------------
- (BOOL)textView:(UITextView *)textView
shouldChangeTextInRange:(NSRange)range
replacementText:(NSString *)text
{
BOOL ret = YES;
if (self.exitWithReturn && [text isEqualToString:@"\n"]) {
ret = NO;
[textView resignFirstResponder];
}
return ret;
}
- (void)textViewDidChange:(UITextView *)textView
{
[self reportTextChanged];
}
- (void)textViewDidBeginEditing:(UITextView *)textView
{
[self reportBecameFirstResponder];
}
- (void)textViewDidEndEditing:(UITextView *)textView
{
[self reportResignedFirstResponder];
}
//----------------------------------------------------
#pragma mark - Properties
//----------------------------------------------------
- (NSString *)text
{
return self.textView.text;
}
- (void)setText:(NSString *)text
{
[self.textView setText:text];
}
- (UIView *)inputAccessory
{
return self.textView.inputAccessoryView;
}
- (void)setInputAccessory:(UIView *)inputAccessory
{
[self.textView setInputAccessoryView:inputAccessory];
}
</code></pre>
|
[] |
[
{
"body": "<p>The first thing that stands out to me immediately is the lack of <code>@required</code>/<code>@optional</code> in the <code>@protocol</code>.</p>\n\n<p>This is mostly a readability thing, but you should certainly mark each of your methods to make your intent explicit. Once you've done this, internally, you can skip the <code>respondsToSelector:</code> check for any methods marked as <code>@required</code>.</p>\n\n<hr>\n\n<p>I'm not familiar with these:</p>\n\n<ul>\n<li><code>im_is_iOS7</code></li>\n<li><code>im_appPlatformIsIPad</code></li>\n</ul>\n\n<p>I mean, I can guess at what they do. Are they part of UIDevice and I just don't know about them? If so, ignore this. But if not...</p>\n\n<p>They're not defined in either of your files, and I see no <code>#imports</code>. If you want this code to truly be reusable, everything needs to be self-contained. You can create a <code>UIDevice</code> class category in this same <code>.m</code> if you only need to add a couple methods to it.</p>\n\n<hr>\n\n<p>The three methods in your section labeled <code>Elements</code> could be improved using a model something like this:</p>\n\n<pre><code>+ (UIImage *)backgroundImage {\n static UIImage *ret = nil;\n\n if (!ret) {\n if ([UIDevice im_is_iOS7]) {\n ret = [UIImage stretchableImageNamed:@\"textfield_background.png\"];\n } else /* iOS 6 and older */ {\n ret = [UIImage stretchableImageNamed:@\"text_field.png\"];\n }\n }\n\n return ret;\n}\n</code></pre>\n\n<p>This pattern can be applied to all three methods. There's no need to go through the process of creating or reassigning these values each time the method is called. Background image is only different depending on iOS version, which won't change while your app is running. And textInserts is only different depending on whether or not the device is an iPad... and that will never change. And default font never changes.</p>\n\n<p>There's not a big difference here, but using this pattern, you'll run ever so slightly faster, and potentially be using a bit less memory.</p>\n\n<hr>\n\n<pre><code>[self addSubview:_textView];\n[self bringSubviewToFront:_textView];\n</code></pre>\n\n<p>I'm quite sure the <code>bringSubviewToFront</code> is redundant here. <code>addSubview:</code> adds the view at the front. The only place I can imagine <code>bringSubviewToFront</code> is perhaps if you added an <code>else</code> to match <code>if (_textView == nil)</code>. If <code>_textView</code> isn't nil, then we can at least make sure it's the front-most view.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T03:38:01.250",
"Id": "42101",
"ParentId": "41066",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "42101",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T13:51:25.837",
"Id": "41066",
"Score": "5",
"Tags": [
"objective-c",
"ios",
"gui",
"cocoa-touch"
],
"Title": "UIView subclass"
}
|
41066
|
<p>I've been a procedural PHP programmer for a long time but I'm getting to learn OOP and would like some advice. I'm designing a class which currently is composed mainly of simple getters/setters, but I'm not quite sure if I'm designing my class in the best way possible.</p>
<p>The getters require accessing a database to pull the requested information, so I'm checking if a property has been set first before running the query which seems like a good idea to me but I'm not sure.</p>
<p>I think I could make use of DI by type hinting the $connect parameter and using a DAL but this is not a public facing API and we're never going to use a different database engine so I'm not sure it's worth the trouble. I'm using a proprietary database engine which has a bug preventing me using PDO and parametrised queries. I'm also not sure if I should be try/catching/throwing exceptions inside class methods.</p>
<p>Here is a sample of the code below, there are more methods/properties but they all follow the same basic structure. I would very much appreciate any and all commentary.</p>
<pre><code>class Patient {
// Database connector
private $connect;
protected $_connection;
public $dmg_ID;
public $LNK_ID;
public $dailyLNK_ID;
public function __construct($connect, $lnkid, $dlkid = NULL) {
$this->_connection = $connect;
unset($connect);
// Patient requires a LNK_ID but not always a daily link ID
$this->LNK_ID = $lnkid;
if (!is_null($dlkid) && is_numeric($dlkid)) {
$this->dailyLNK_ID = $dlkid;
}
}
public function getDmgID() {
if ($this->dmg_ID) return $this->dmg_ID;
$sql = "SELECT lnk_dmgID FROM LINK WHERE lnk_ID=".$this->LNK_ID;
try {
$result = odbc_exec($this->_connection,$sql);
if($result) {
$dmgID = odbc_fetch_array($result);
}
else {
throw new RuntimeException("Failed to connect.");
}
}
catch (RuntimeException $e) {
print("Exception caught: $e");
}
return $this->dmg_ID = $dmgID['LNK_DMGID'];
}
public function setDmgID() {
if (!$this->dmg_ID) return false;
$sql = "UPDATE LINK SET lnk_dmgID=".$this->dmg_ID." WHERE lnk_ID=".$this->LNK_ID;
try {
$result = odbc_exec($this->_connection,$sql);
if(!$result) {
throw new RuntimeException("Failed to connect.");
}
}
catch (RuntimeException $e) {
print("Exception caught: $e");
}
return true;
}
...
</code></pre>
|
[] |
[
{
"body": "<p>OOP is definitely the way to go. The best advise I can offer is to read the book \"Clean Code\" by Uncle Bob. The code there is in Java but all principles apply equally to any other language.</p>\n\n<p>I would definitely abstract the DB interface so I can use for any other database, even if you don't plan it in the next future. I have posted <a href=\"https://codereview.stackexchange.com/questions/37349/in-memory-data-cache-architecture-for-data-transfer\">small data store architecture code</a> that may help you.</p>\n\n<p>From a look at your code, I am a bit confused by the naming <code>connect</code> and <code>connection</code> and the latter stores <code>$connect</code> in the constructor. Maybe give a more descriptive names (one of the top recommendations in the mentioned book).</p>\n\n<ul>\n<li><p>Why are you unsetting <code>$connect</code>?</p></li>\n<li><p>The names such as <code>$LNK_ID</code> are cryptic for reader.</p></li>\n<li><p>I would reserve a separate class dealing with the database via thin interface (see my post) and let other classes only talk to that class instead of DB directly.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T14:56:10.497",
"Id": "70406",
"Score": "0",
"body": "Thanks for the response. This is for a company that is very heavily invested in the current database engine and cannot change without rewriting their entire software suite. Would not building a DAL in this instance violate YAGNI? I'm unsetting $connect because it contains the data necessary to connect to the DB and was taught it's good practice to get unset once it's no longer needed. $LNK_ID is literally the name of the database field it refers to although I do agree the mixing of upper/lower case with/without underscores is confusing. Thanks for your responses :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T18:52:52.193",
"Id": "70469",
"Score": "1",
"body": "@Roy PHP is a scripting language with scripts usually run for limited time, after which all your memory will be cleared, so really no need to unset unless you have a serious reason to. Especially your variable is even local to the function. I'd even say it is a dangerous practice - too easy to create a bug by switching rows. This is more of a JavaScript kind of problem but then again, not with local variables."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T18:56:40.973",
"Id": "70471",
"Score": "1",
"body": "@Roy Concerning database field names, in a well structured code, that belongs to your model that mirrors your DB structure. Ideally this should be encapsulated into classes dealing with your models and the rest of your code should not know about their specifics, rather talking to your model classes via well-named API that you can understand without knowing the interior of those classes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T09:21:29.830",
"Id": "70585",
"Score": "0",
"body": "Thanks for your comments! I'll remove the unset. For my education, what would be a situation where unset() would be useful then? I inherited the database and have no say in the structure but again I am 100% sure the db engine will not be changing for various business reasons. In this situation is there a point to abstracting away the DB so much? Seems very much YAGNI - direct SQL queries remove all overheard from constructing some sort of bespoke ORM."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T12:38:54.133",
"Id": "70607",
"Score": "0",
"body": "@Roy `unset` can be useful to quickly remove keys (or move to different keys) on your model (or its clone) before passing it to persistent storage. Or whenever you want to remove keys of objects or assoc. arrays."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T12:41:33.553",
"Id": "70608",
"Score": "0",
"body": "Abstracting is always good for your own sanity and to enforce separation of concerns. You may get into another project and use parts of your code there rather than writing from scratch, can save you lots of time and pain. It also makes testing and bug localization much easier."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T14:15:00.297",
"Id": "41070",
"ParentId": "41067",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T13:54:10.703",
"Id": "41067",
"Score": "3",
"Tags": [
"php",
"object-oriented"
],
"Title": "PHP class design with methods requiring database access"
}
|
41067
|
<p>Would it be better to convert the array in the following code to</p>
<pre><code>$langs = array("en", "de", "fr");
</code></pre>
<p>and then reusing the values for both <code>$folder</code> and <code>$flag</code>? If so, how then would my foreach (or maybe a while?) loop be written?</p>
<pre><code><?php
$langs = array(
"en/" => "en.png",
"de/" => "de.png",
"fr/" => "fr.png"
);
$self = $_SERVER['REQUEST_URI'];
$pattern = "{^.*/}i";
$links = array();
foreach ($langs as $folder => $flag) {
$url = preg_replace($pattern, "$folder", $self);
$link = "<li><a href=\"../$url\"><img src=\"../img/$flag\"></a></li>";
array_push($links, $link);
}
echo implode($links) . "\n";
?>
</code></pre>
<p>I'm trying to "fool proof" the code, by effectively limiting the folder structures and file names that can be used, as I create a basic template of files for quick rolling out of our websites. If you can see any other improvements, that would be much appreciated.</p>
|
[] |
[
{
"body": "<p>You can definitely simplify this, as the only part of each element of <code>$langs</code> that changes is the two-letter language code. Something like this would work:</p>\n\n<pre><code><?php\n$langs = array(\n \"en\",\n \"de\",\n \"fr\"\n);\n$self = $_SERVER['REQUEST_URI'];\n$pattern = \"{^.*/}i\";\n$links = array();\nforeach ($langs as $code) {\n $url = preg_replace($pattern, \"$code/\", $self);\n $link = \"<li><a href=\\\"../$url\\\"><img src=\\\"../img/$code.png\\\"></a></li>\";\n array_push($links, $link);\n}\necho implode($links) . \"\\n\";\n?>\n</code></pre>\n\n<p>You just use a non-associative array and append <code>/</code> or <code>.png</code> where needed; much cleaner.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T17:13:06.643",
"Id": "70432",
"Score": "0",
"body": "Thank you. Once you see it written out, you realise it's so simple yet so effective!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T15:52:02.940",
"Id": "41079",
"ParentId": "41075",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "41079",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T15:14:52.833",
"Id": "41075",
"Score": "4",
"Tags": [
"php",
"array"
],
"Title": "Simplifying an associative array()"
}
|
41075
|
<p>This is another entry for <a href="https://codereview.meta.stackexchange.com/a/1472/34757">The Ultimate Tic-Tac-Toe</a> review.</p>
<p>My design criteria were:</p>
<ul>
<li>A DLL which encapsulates the data, i.e. the game state</li>
<li>Don't include the GUI, nor the decision-making (game-playing) logic</li>
<li>Be careful not to allow corrupted state</li>
<li>Make it as small (few lines of code) as possible</li>
</ul>
<p>Here's the DLL code:</p>
<pre><code>using System;
using System.Collections.Generic;
namespace UltimateTicTacToe.Model
{
// Cell only contains its state, not its own location
// true -> "O"
// false -> "X"
// null -> (not played yet)
// Immutable because it's a struct.
public struct Cell
{
readonly bool? state;
public bool? State { get { return state; } }
public Cell(bool state) { this.state = state; }
}
// A trivial struct with fly-weight static instances
// Immutable because it's a struct.
// Short, constant-length names like 'L00' so that they line up well.
public struct Location
{
readonly int row;
readonly int column;
public int Row { get { return row; } }
public int Column { get { return column; } }
public Location(int row, int column)
{
this.row = row;
this.column = column;
}
public static Location L00 = new Location(0, 0);
public static Location L01 = new Location(0, 1);
public static Location L02 = new Location(0, 2);
public static Location L10 = new Location(1, 0);
public static Location L11 = new Location(1, 1);
public static Location L12 = new Location(1, 2);
public static Location L20 = new Location(2, 0);
public static Location L21 = new Location(2, 1);
public static Location L22 = new Location(2, 2);
internal static List<Location> All = new List<Location>()
{
L00, L01, L02,
L10, L11, L12,
L20, L21, L22
};
// Simpler than overriding Equals etc.
// http://stackoverflow.com/a/1502479/49942
public bool Matches(Location rhs)
{
return (this.row == rhs.row) && (this.column == rhs.column);
}
}
// Class so it may be null.
// Says who won a game or quadrant,
// and which were the winning locations.
public class Winner
{
public bool Player { get; private set; }
public Location[] Locations { get; private set; }
public Winner(bool player, Location[] locations)
{
Player = player;
Locations = locations;
}
}
// public so be careful not to expose too much.
// Not abstract so this could be used as private
// member data instead of as a public superclass.
public class BoardT<TCell>
{
readonly TCell[,] cells = new TCell[3, 3];
// this delegate emulates (is used instead of)
// `protected abstract bool? getCellState(TCell cell);`
readonly Func<TCell, bool?> getCellState;
public Winner Winner { get; private set; }
// This list could be a member of Location instead.
static List<Location[]> lines = new List<Location[]>()
{
new Location[]{ Location.L00, Location.L01,Location.L02},
new Location[]{ Location.L10, Location.L11,Location.L12},
new Location[]{ Location.L20, Location.L21,Location.L22},
new Location[]{ Location.L00, Location.L10,Location.L20},
new Location[]{ Location.L01, Location.L11,Location.L21},
new Location[]{ Location.L02, Location.L12,Location.L22},
new Location[]{ Location.L00, Location.L11,Location.L22},
new Location[]{ Location.L02, Location.L11,Location.L20}
};
protected BoardT(Func<TCell, bool?> getCellState)
{
this.getCellState = getCellState;
}
// Public get for Cell in Quadrant and for Qhadrant in Game.
// Protected set can only be accessed via subclass.
public TCell this[Location location]
{
get { return cells[location.Row, location.Column]; }
protected set { cells[location.Row, location.Column] = value; }
}
// Invoked by subclass at the end of each Play.
protected void Recalculate()
{
foreach (var line in lines)
{
bool? isWon = this.isWon(line);
if (isWon.HasValue)
{
this.Winner = new Winner(isWon.Value, line);
return;
}
}
}
// private helper for Recalculate.
bool? isWon(Location[] line)
{
bool? rc = null;
foreach (Location location in line)
{
bool? cellState = getCellState(this[location]);
if (!cellState.HasValue)
return null;
if (!rc.HasValue)
rc = cellState;
else if (rc.Value != cellState.Value)
return null;
}
return rc;
}
// might be full before it's won
public bool IsFull
{
get { return !Location.All.Exists(location => !getCellState(this[location]).HasValue); }
}
}
// Quadrant is a Board of Cell instances
public class Quadrant : BoardT<Cell>
{
internal Quadrant()
: base(getCellState)
{
}
static bool? getCellState(Cell cell)
{
return cell.State;
}
internal void Play(Location location, bool cellState)
{
if (this[location].State.HasValue)
throw new Exception("Already played on this cell");
this[location] = new Cell(cellState);
Recalculate();
}
}
public enum Variant
{
// Helpful for short unit tests,
// allows one player to play too often.
Cheat,
Normal,
// See "crazy" variant on http://mathwithbaddrawings.com/2013/06/16/ultimate-tic-tac-toe/
// not currently implemented.
Crazy
}
public class PreviousPlay
{
public Location QuadrantLocation { get; private set; }
public bool Player { get; private set; }
internal PreviousPlay(Location quadrantLocation, bool player)
{
QuadrantLocation = quadrantLocation;
Player = player;
}
}
// Game is a Board of Quadrant instances.
public class Game : BoardT<Quadrant>
{
readonly Variant variant;
public PreviousPlay PreviousPlay { get; private set; }
public Game(Variant variant)
: base(getCellState)
{
Location.All.ForEach(location => base[location] = new Quadrant());
this.variant = variant;
}
static bool? getCellState(Quadrant quadrant)
{
if (quadrant.Winner == null)
return null;
return quadrant.Winner.Player;
}
public void Play(Location quadrantLocation, Location cellLocation, bool cellState)
{
switch (variant)
{
case Variant.Cheat:
break;
case Variant.Normal:
if (PreviousPlay == null)
// first player
break;
if (PreviousPlay.Player == cellState)
throw new Exception("This player has already played");
Quadrant requiredQuadrant = base[PreviousPlay.QuadrantLocation];
bool canPlay = (requiredQuadrant.Winner == null) &&
// testing the isFull condition wasn't in the game specs but is required
!requiredQuadrant.IsFull;
if (canPlay && !PreviousPlay.QuadrantLocation.Matches(quadrantLocation))
throw new Exception("Not playing in the required quadrant");
break;
case Variant.Crazy:
default:
throw new NotImplementedException();
}
Quadrant quadrant = base[quadrantLocation];
quadrant.Play(cellLocation, cellState);
Recalculate();
PreviousPlay = new PreviousPlay(cellLocation, cellState);
}
}
}
</code></pre>
<p>I decided to do without events (i.e. callbacks) in the implementation: for example, cell doesn't tell quadrant when the cell state changes (the quadrant only knows because it's the quadrant which is modifying the cell).</p>
<p>Here's some user code (from a separate project):</p>
<pre><code>using System;
using UltimateTicTacToe.Model;
namespace UltimateTicTacToe
{
class Program
{
static void Main(string[] args)
{
test1();
test2();
test3();
}
static void test3()
{
// TODO test a game which exercises the Quadrant.IsFull property.
}
static void test2()
{
Game game = new Game(Variant.Normal);
game.Play(Location.L00, Location.L11, false);
// try to play out of turn
bool failed = false;
try
{
game.Play(Location.L11, Location.L11, false);
failed = true;
}
catch (Exception) { }
assert(!failed);
// try to play in the wrong quadrant
try
{
game.Play(Location.L22, Location.L11, true);
failed = true;
}
catch (Exception) { }
assert(!failed);
// try to play properly
game.Play(Location.L11, Location.L11, true);
}
static void test1()
{
Game game = new Game(Variant.Cheat);
Quadrant quadrant = game[Location.L00];
assert(quadrant.Winner == null);
// play a row on top-left
game.Play(Location.L00, Location.L00, false);
game.Play(Location.L00, Location.L01, false);
game.Play(Location.L00, Location.L02, false);
assert(quadrant.Winner.Player == false);
assert(quadrant[Location.L00].State == false);
assert(quadrant[Location.L22].State == null);
assert(game.Winner == null);
// play a column in center
game.Play(Location.L11, Location.L00, false);
game.Play(Location.L11, Location.L10, false);
game.Play(Location.L11, Location.L20, false);
// play a diagonal on bottom-right
game.Play(Location.L22, Location.L02, false);
game.Play(Location.L22, Location.L11, false);
game.Play(Location.L22, Location.L20, false);
assert(game.Winner.Player == false);
}
static void assert(bool b)
{
if (!b)
throw new Exception();
}
}
}
</code></pre>
<p>Is there a more idiomatic way to code that <code>assert</code> function at the bottom, when I want to assert in a release build?</p>
|
[] |
[
{
"body": "<p>Here's a bug:</p>\n\n<ul>\n<li>Someone can play on an already-won quadrant (is this allowed by the rules?).</li>\n<li>If they play on an empty space of an already-won quadrant they can 'win again' i.e. trigger the Recalculate logic and potentially get a different Winner.</li>\n</ul>\n\n<hr>\n\n<p>Cell state is <code>bool?</code> and Player is a corresponding <code>bool</code>.</p>\n\n<p>It makes sense (code would be more readable) to replace bool with an <code>enum Player { X, O }</code>, remove the <code>struct Cell</code> definition altogether, and use <code>BoardT<Player?></code> as the subclass (or member data) of Quadrant.</p>\n\n<hr>\n\n<p>The <code>bool canPlay</code> calculation could be a <code>internal bool CanPlay { get {...}}</code> property of Quadrant.</p>\n\n<p><code>public bool CanPlay(Location quadrantLocation)</code> (which depends on the <code>PreviousPlay</code> in <code>Game</code>) should be a public method of <code>Game</code>, because the UI will want it in order to know whether to render each quadrant as playable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T15:56:06.483",
"Id": "41080",
"ParentId": "41078",
"Score": "13"
}
},
{
"body": "<p>nullable bools give me a weird twitchy feeling behind my eyeballs.</p>\n\n<p>If you need three states you should really wrap it in something like a Enum.</p>\n\n<p>EDIT:\nsomebody already said that. oops.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T17:01:29.890",
"Id": "70430",
"Score": "1",
"body": "Isn't this answer more of a comment?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T18:08:23.120",
"Id": "70453",
"Score": "7",
"body": "@lol.upvote: This is codereview. Comments on coding choices are what answers should be."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T00:25:00.393",
"Id": "70537",
"Score": "0",
"body": "I think it should be two states and a null: there are two players; a played cell identifies the player who played it; in the API that specifies which player is playing, the player can't be the 3rd value. So `void Play(Location location, Player player)` is the method, cell state is of type `Player?`, and Player is a two-valued enum."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T09:34:03.220",
"Id": "70587",
"Score": "2",
"body": "@ChrisW think of it this way, many use 'null' to represent blank or empty, but it works better to think of it as a fail state. null means something you expected to be there...wasn't. I live by defensive programming. each class I write is a black box. I do validation on all incomming arguments and throw exceptions if invalid. Then I write my code free of constant validation. accepting invalid data leads to unexpected results."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T16:14:40.653",
"Id": "70622",
"Score": "0",
"body": "I agree with you about null, in C++; I like to distinguish between a pointer (can be null) and a reference (cannot be), and prefer references. That's a problem with C# classes: reference to classes can always be null. IMO however that's not a problem with C# `Nullable<T>`. You can assign a `T` to a `Nullable<T>` but not vice versa. A statement like `if (nullablePlayer == Player.X)` won't compile: you need to use the `Value` and `HasValue` properties, e.g. `if (nullablePlayer.Value == Player.X)` so you can't accidentally ignore the fact that a nullable struct may be null."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T16:17:16.900",
"Id": "70624",
"Score": "0",
"body": "Anyway, I guess you're recommending two separate enums, e.g. `enum Player { X, O }` and `enum CellState { X, O, None }`, with some explicit conversion from Player to CellState and vice versa?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T20:58:28.377",
"Id": "80649",
"Score": "0",
"body": "@ChrisW Sorry for a late reply, just read up here. Using two different enums like that isn't good IMO. Using `None` also in `Player` works fine to me. Did you take a look at the Java version I made and my `TTPlayer` enum?"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T16:47:11.653",
"Id": "41083",
"ParentId": "41078",
"Score": "8"
}
},
{
"body": "<p>Why do you hardcode the board initialization (you have 9 LOCs for initializing possible locations, 8 LOCs for initializing possible lines...)? It takes a lot of LOCs, and make the code less maintainable (what if you want to play 4x4?). You can initialize the possible Locations using loops, and you can calculate the lines on-the-fly (go over all rows, go over all columns, go over diagonals). I would even consider doing away with the <code>Location</code> struct altogether, and use actual [row,column] to indicate a location.</p>\n\n<p>Another small point - I think you should rename the class <code>PreviousPlay</code> - the name suggests more of a member name (a state) than a class name. If you don't like to use <code>Play</code>, maybe <code>HistoricPlay</code>?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T17:28:48.590",
"Id": "70635",
"Score": "0",
"body": "The board is initialized in one statement, `Location.All.ForEach`. I hardcode Location instances in order to give **names** to [flyweight instances](http://en.wikipedia.org/wiki/Flyweight_pattern) for example `L00` and `L02`, so user code (e.g. unit tests called from main) can refer to `Location.L00` as a short-hand/convenience, instead of always creating new Locations e.g. `new Location(0,0)`. `PreviousPlay` is indeed a member name or state of `Game`. Maybe I should call it `Play` or `Turn` or `Move` and pass one instance of it to the `Game.Play` method, instead of passing 3 parameters."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T17:32:34.310",
"Id": "70637",
"Score": "1",
"body": "A better shorthand for `Location.L00` might be `{0, 0}`..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T17:36:53.773",
"Id": "70638",
"Score": "0",
"body": "What kind of expression is `{0, 0}`: can you show an example of a statement in which it's included? IMO `var foo = {0,0};` doesn't compile."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T18:10:05.450",
"Id": "70650",
"Score": "0",
"body": "My C# is a little rusty, but I think that `int[] foo = {0,0}` will compile..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T19:15:32.513",
"Id": "70666",
"Score": "0",
"body": "Yes you're right, it will (I'm surprised). But `var foo = {0,0};` won't. And if I define a `void bar(int[] foo){}` then calling `bar({0,0})` won't compile; I need to call it as `bar(new int[]{0,0});`. Passing an integer in the range 1 through 9 would be easier."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T19:20:51.530",
"Id": "70669",
"Score": "0",
"body": "Does `bar(new []{0,0})` work?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T19:32:15.063",
"Id": "70673",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/12908/discussion-between-chrisw-and-uri-agassi)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T07:07:21.533",
"Id": "41136",
"ParentId": "41078",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41080",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T15:43:36.987",
"Id": "41078",
"Score": "16",
"Tags": [
"c#",
"game",
"community-challenge"
],
"Title": "Ultimate Tic-Tac-Toe data model"
}
|
41078
|
<p>I recently got rejected at a job interview for submitting this:</p>
<p><a href="https://bitbucket.org/gnerr/password-validator" rel="nofollow">https://bitbucket.org/gnerr/password-validator</a></p>
<p>The interviewer asked for a password validation library that was configurable via Spring, with the following default validations:</p>
<blockquote>
<ul>
<li>Must consist of a mixture of lowercase letters and numerical digits only, with at least one of each.</li>
<li>Must be between 5 and 12 characters in length.</li>
<li>Must not contain any sequence of characters immediately followed by the same sequence.</li>
</ul>
</blockquote>
<p>Unfortunately they never told me why my implementation is bad, so would someone be kind enough to tell me what I did wrong here?</p>
<p>Here's the main validation class for the library:</p>
<pre><code>package dm.passwordvalidator;
import java.util.ArrayList;
import java.util.List;
/**
* @author dm
*
*/
public class PasswordValidator {
private List<ValidationRule> rules;
/**
* Runs all your validation rules and returns true if it's valid, false otherwise
* @param inPassword
* @return boolean true if valid, false if otherwise
*/
public boolean validate(String inPassword) {
for (ValidationRule rule : this.getRules()) {
if (!rule.validate(inPassword)) {
return false;
}
}
return true;
}
/**
* Runs all your validation rules and returns a {@link ValidationResult} with messages if
* the password was invalid
* @param inPassword
* @return {@link ValidationResult} The validation result
*/
public ValidationResult validateWithMessages(String inPassword) {
ValidationResult returnValue = new ValidationResult();
List<String> messages = new ArrayList<String>();
for (ValidationRule rule : this.getRules()) {
if (!rule.validate(inPassword)) {
messages.add(rule.getMessage());
}
}
if (messages.size() > 0) {
returnValue.setValid(false);
}
returnValue.setMessages(messages);
return returnValue;
}
public List<ValidationRule> getRules() {
return this.rules == null ? this.getDefaultRules() : this.rules;
}
public void setRules(List<ValidationRule> inRules) {
this.rules = inRules;
}
private List<ValidationRule> getDefaultRules() {
List<ValidationRule> returnValue = new ArrayList<ValidationRule>();
returnValue.add(new RegexValidationRule("(?!(.+?)\\1).*", DefaultValidatorMessages.NO_CYCLES));
returnValue.add(new RegexValidationRule("[a-z0-9]+", DefaultValidatorMessages.LOWERCASE_AND_NUMBERS));
returnValue.add(new RegexValidationRule(".*[a-z].*", DefaultValidatorMessages.LOWERCASE_AND_NUMBERS));
returnValue.add(new RegexValidationRule(".*[0-9].*", DefaultValidatorMessages.LOWERCASE_AND_NUMBERS));
returnValue.add(new RegexValidationRule(".{5,15}", DefaultValidatorMessages.FIVE_AND_TWELVE));
return returnValue;
}
}
</code></pre>
<p>The library is configurable as beans like this:</p>
<pre><code><bean id="lengthRule" class="dm.passwordvalidator.RegexValidationRule">
<property name="regex" value=".{5,15}"/>
<property name="message" value="Your password needs to be between 5 to 15 characters"/>
</bean>
<bean id="passwordValidator" class="dm.passwordvalidator.PasswordValidator">
<property name="rules">
<list>
<ref bean="lengthRule" />
</list>
</property>
</bean>
</code></pre>
|
[] |
[
{
"body": "<p>Putting this as an anwer, because it took a while to find it:</p>\n\n<p>I took your code, and put it through some tests..... I made the tests up based on the 'rules'. This is the sort of thing any interviewer will do:</p>\n\n<pre><code>public static void main(String[] args) {\n String[] positive = {\"12345abc\", \"1a2b3c4d\", \"1234567890ab\", \"1234a\"};\n String[] negative = {\"\", \"1\", \"1a\", \"123567890\", \"abcdefghij\", \"abcdEfgh1\", \"abcabc123\", \"123a\", \"1234567890abc\"};\n\n\n PasswordValidator validator = new PasswordValidator();\n\n for (String pos : positive) {\n ValidationResult result = validator.validateWithMessages(pos);\n if (!result.isValid()) {\n System.out.println(\"Claims that '\" + pos + \"' is not valid!: \" + result.getMessages());\n }\n }\n\n for (String neg : negative) {\n if (validator.validate(neg)) {\n System.out.println(\"Claims that '\" + neg + \"' is valid (but it is not)!\");\n }\n }\n}\n</code></pre>\n\n<p>When I ran that test, it <strong>passed</strong> the password: <code>\"1234567890abc\"</code> which is 13 characters long, and the rules say the limit is 12.</p>\n\n<p>Checking your Regex, I see you mis-typed the range-limit on the match: <code>\".{5,15}\"</code></p>\n\n<p>Hate to be the bearer of bad news, but an interviewer could look at this as being an indication that you are not 'detail-oriented', and dismiss the application immediately.</p>\n\n<p>For what it's worth, I look at your code and feel it has a strong structure, a reusable and extensible model. Generally good. Perhaps overkill, but that's OK.</p>\n\n<p>But, bottom line, if your code does not meet the specification, you can expect to be moved down the pile of applicants ...... </p>\n\n<p>P.S. It also blew up on a null password, which I removed from my test because I did not think it was 'fair', but regardless, you should handle null input gracefully.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T17:21:10.000",
"Id": "41085",
"ParentId": "41082",
"Score": "11"
}
},
{
"body": "<p>It looks fine. Some minor improvement idea:</p>\n\n<ol>\n<li><p>The first regexp rule (<code>(?!(.+?)\\\\1).*</code>) is really hard to understand. I'd create a named local variable for it to explain its intent.</p>\n\n<p>Some reference: <em>Chapter 6. Composing Methods</em>, <em>Introduce Explaining Variable</em> in <em>Refactoring: Improving the Design of Existing Code</em> by Martin Fowler:</p>\n\n<blockquote>\n <p>Put the result of the expression, or parts of the expression, \n in a temporary variable with a name that explains the purpose.</p>\n</blockquote>\n\n<p>Furthermore, <em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G19: Use Explanatory Variables</em>.</p></li>\n<li><p><code>!messages.isEmpty()</code> would be a little bit more readable than <code>messages.size() > 0</code>.</p></li>\n<li><p>Comments like this are unnecessary:</p>\n\n<pre><code>* @param inPassword\n</code></pre></li>\n<li><p>I'd consider moving the default values to a separate class to fulfill the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">single responsibility principle</a>. Currently it could be changed because of changes in password validation or changes in the default validation rules.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T04:43:30.253",
"Id": "41267",
"ParentId": "41082",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41085",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T16:35:14.043",
"Id": "41082",
"Score": "8",
"Tags": [
"java",
"interview-questions",
"validation",
"dependency-injection",
"spring"
],
"Title": "Spring password validator library"
}
|
41082
|
<p>Runs smoothly, however valgrind is showing "possibly lost: 544 bytes in 2 blocks".
This is my first time doing a lot of things here so I might be making multiple mistakes. </p>
<p>Please let me know if anything needs to be fixed, or if I should just do something completely different for whatever reason.</p>
<pre><code>/* protosynth
*
* Throughout the source code, "frequency" refers to a Hz value,
* and "pitch" refers to a numeric musical note value with 0 representing C0, 12 for C1, etc..
*
* compiled with:
* gcc -Wall protosynth.c -o protosynth `sdl2-config --cflags --libs` -lm
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "SDL.h"
const double ChromaticRatio = 1.059463094359295264562;
const double Tao = 6.283185307179586476925;
Uint32 sampleRate = 48000;
Uint32 frameRate = 60;
Uint32 floatStreamLength = 1024;// must be a power of two, decrease to allow for a lower syncCompensationFactor to allow for lower latency, increase to reduce risk of underrun
Uint32 samplesPerFrame; // = sampleRate/frameRate;
Uint32 msPerFrame; // = 1000/frameRate;
double practicallySilent = 0.001;
Uint32 audioBufferLength = 48000;// must be a multiple of samplesPerFrame (auto adjusted upwards if not)
float *audioBuffer;
SDL_atomic_t audioCallbackLeftOff;
Sint32 audioMainLeftOff;
Uint8 audioMainAccumulator;
SDL_AudioDeviceID AudioDevice;
SDL_AudioSpec audioSpec;
SDL_Event event;
SDL_bool running = SDL_TRUE;
typedef struct {
float *waveform;
Uint32 waveformLength;
double volume; // multiplied
double pan; // 0 to 1: all the way left to all the way right
double frequency; // Hz
double phase; // 0 to 1
} voice;
/* _
| |
___ _ __ ___ __ _| | __
/ __| '_ \ / _ \/ _` | |/ /
\__ \ |_) | __/ (_| | <
|___/ .__/ \___|\__,_|_|\_\
| |
|_|
*/
void speak(voice *v) {
float sample;
Uint32 sourceIndex;
double phaseIncrement = v->frequency/sampleRate;
Uint32 i;
if (v->volume > practicallySilent) {
for (i=0; (i+1)<samplesPerFrame; i+=2) {
v->phase += phaseIncrement;
if (v->phase > 1) v->phase -= 1;
sourceIndex = v->phase*v->waveformLength;
sample = v->waveform[sourceIndex]*v->volume;
audioBuffer[audioMainLeftOff+i] += sample*(1-v->pan); //left channel
audioBuffer[audioMainLeftOff+i+1] += sample*v->pan; //right channel
}
}
else {
for (i=0; i<samplesPerFrame; i+=1)
audioBuffer[audioMainLeftOff+i] = 0;
}
audioMainAccumulator++;
}
double getFrequency(double pitch) {
return pow(ChromaticRatio, pitch-57)*440;
}
int getWaveformLength(double pitch) {
return sampleRate / getFrequency(pitch)+0.5f;
}
void buildSineWave(float *data, Uint32 length) {
Uint32 i;
for (i=0; i < length; i++)
data[i] = sin( i*(Tao/length) );
}
void logSpec(SDL_AudioSpec *as) {
printf(
" freq______%5d\n"
" format____%5d\n"
" channels__%5d\n"
" silence___%5d\n"
" samples___%5d\n"
" size______%5d\n\n",
(int) as->freq,
(int) as->format,
(int) as->channels,
(int) as->silence,
(int) as->samples,
(int) as->size
);
}
void logVoice(voice *v) {
printf(
" waveformLength__%d\n"
" volume__________%f\n"
" pan_____________%f\n"
" frequency_______%f\n"
" phase___________%f\n",
v->waveformLength,
v->volume,
v->pan,
v->frequency,
v->phase
);
}
void logWavedata(float *floatStream, Uint32 floatStreamLength, Uint32 increment) {
printf("\n\nwaveform data:\n\n");
Uint32 i=0;
for (i=0; i<floatStreamLength; i+=increment)
printf("%4d:%2.16f\n", i, floatStream[i]);
printf("\n\n");
}
/* _ _ _____ _ _ _ _
| (_) / ____| | | | | | |
__ _ _ _ __| |_ ___ | | __ _| | | |__ __ _ ___| | __
/ _` | | | |/ _` | |/ _ \| | / _` | | | '_ \ / _` |/ __| |/ /
| (_| | |_| | (_| | | (_) | |___| (_| | | | |_) | (_| | (__| <
\__,_|\__,_|\__,_|_|\___/ \_____\__,_|_|_|_.__/ \__,_|\___|_|\_\
*/
void audioCallback(void *unused, Uint8 *byteStream, int byteStreamLength) {
float* floatStream = (float*) byteStream;
Sint32 localAudioCallbackLeftOff = SDL_AtomicGet(&audioCallbackLeftOff);
Uint32 i;
for (i=0; i<floatStreamLength; i++) {
floatStream[i] = audioBuffer[localAudioCallbackLeftOff];
localAudioCallbackLeftOff++;
if ( localAudioCallbackLeftOff == audioBufferLength )
localAudioCallbackLeftOff = 0;
}
//printf("localAudioCallbackLeftOff__%5d\n", localAudioCallbackLeftOff);
SDL_AtomicSet(&audioCallbackLeftOff, localAudioCallbackLeftOff);
}
/*_ _ _
(_) (_) |
_ _ __ _| |_
| | '_ \| | __|
| | | | | | |_
|_|_| |_|_|\__|
*/
int init() {
SDL_Init(SDL_INIT_AUDIO | SDL_INIT_TIMER);
SDL_AudioSpec want;
SDL_zero(want);// btw, I have no idea what this is...
want.freq = sampleRate;
want.format = AUDIO_F32;
want.channels = 2;
want.samples = floatStreamLength;
want.callback = audioCallback;
AudioDevice = SDL_OpenAudioDevice(NULL, 0, &want, &audioSpec, SDL_AUDIO_ALLOW_FORMAT_CHANGE);
if (AudioDevice == 0) {
printf("\nFailed to open audio: %s\n", SDL_GetError());
return 1;
}
printf("want:\n");
logSpec(&want);
printf("audioSpec:\n");
logSpec(&audioSpec);
if (audioSpec.format != want.format) {
printf("\nCouldn't get Float32 audio format.\n");
return 2;
}
sampleRate = audioSpec.freq;
floatStreamLength = audioSpec.size/4;
samplesPerFrame = sampleRate/frameRate;
msPerFrame = 1000/frameRate;
audioMainLeftOff = samplesPerFrame*8;
SDL_AtomicSet(&audioCallbackLeftOff, 0);
if (audioBufferLength % samplesPerFrame)
audioBufferLength += samplesPerFrame-(audioBufferLength % samplesPerFrame);
audioBuffer = malloc( sizeof(float)*audioBufferLength );
return 0;
}
int onExit() {
SDL_CloseAudioDevice(AudioDevice);
//free(audioBuffer);//not necessary?
SDL_Quit();
return 0;
}
/* _
(_)
_ __ ___ __ _ _ _ __
| '_ ` _ \ / _` | | '_ \
| | | | | | (_| | | | | |
|_| |_| |_|\__,_|_|_| |_|
*/
int main(int argc, char *argv[]) {
float syncCompensationFactor = 0.0016;// decrease to reduce risk of collision, increase to lower latency
Sint32 mainAudioLead;
Uint32 i;
voice testVoiceA;
voice testVoiceB;
voice testVoiceC;
testVoiceA.volume = 1;
testVoiceB.volume = 1;
testVoiceC.volume = 1;
testVoiceA.pan = 0.5;
testVoiceB.pan = 0;
testVoiceC.pan = 1;
testVoiceA.phase = 0;
testVoiceB.phase = 0;
testVoiceC.phase = 0;
testVoiceA.frequency = getFrequency(45);// A3
testVoiceB.frequency = getFrequency(49);// C#4
testVoiceC.frequency = getFrequency(52);// E4
Uint16 C0waveformLength = getWaveformLength(0);
testVoiceA.waveformLength = C0waveformLength;
testVoiceB.waveformLength = C0waveformLength;
testVoiceC.waveformLength = C0waveformLength;
float sineWave[C0waveformLength];
buildSineWave(sineWave, C0waveformLength);
testVoiceA.waveform = sineWave;
testVoiceB.waveform = sineWave;
testVoiceC.waveform = sineWave;
//logVoice(&testVoiceA);
//logWavedata(testVoiceA.waveform, testVoiceA.waveformLength, 10);
if ( init() ) return 1;
SDL_Delay(42);// let the tubes warm up
SDL_PauseAudioDevice(AudioDevice, 0);// unpause audio.
while (running) {
while( SDL_PollEvent( &event ) != 0 ) {
if( event.type == SDL_QUIT ) {
running = SDL_FALSE;
}
}
for (i=0; i<samplesPerFrame; i++) audioBuffer[audioMainLeftOff+i] = 0;
//printf("audioMainLeftOff___________%5d\n", audioMainLeftOff);
speak(&testVoiceA);
speak(&testVoiceB);
speak(&testVoiceC);
if (audioMainAccumulator > 1) {
for (i=0; i<samplesPerFrame; i++) {
audioBuffer[audioMainLeftOff+i] /= audioMainAccumulator;
}
}
audioMainAccumulator = 0;
audioMainLeftOff += samplesPerFrame;
if (audioMainLeftOff == audioBufferLength) audioMainLeftOff = 0;
mainAudioLead = audioMainLeftOff - SDL_AtomicGet(&audioCallbackLeftOff);
if (mainAudioLead < 0) mainAudioLead += audioBufferLength;
//printf("mainAudioLead:%5d\n", mainAudioLead);
if (mainAudioLead < floatStreamLength) printf("An audio collision may have occured!\n");
SDL_Delay( mainAudioLead*syncCompensationFactor );
}
onExit();
return 0;
}
</code></pre>
<p>EDIT:</p>
<p>After doing some more research on my valgrind errors, I came to the conclusion that there wasn't much I could do other than suppress them. Here is my suppression file:</p>
<pre><code>{
<from SDL_TimerInit>
Memcheck:Leak
match-leak-kinds: possible
fun:calloc
fun:allocate_dtv
fun:_dl_allocate_tls
fun:pthread_create@@GLIBC_2.2.5
fun:SDL_SYS_CreateThread
fun:SDL_CreateThread
fun:SDL_TimerInit
fun:SDL_InitSubSystem
fun:init
fun:main
}
{
<from SDL_AudioInit>
Memcheck:Leak
match-leak-kinds: possible
fun:calloc
fun:allocate_dtv
fun:_dl_allocate_tls
fun:pthread_create@@GLIBC_2.2.5
fun:pa_thread_new
fun:pa_threaded_mainloop_start
fun:pa_simple_new
fun:PULSEAUDIO_Init
fun:SDL_AudioInit
fun:SDL_InitSubSystem
fun:init
fun:main
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T18:11:17.743",
"Id": "70455",
"Score": "5",
"body": "ASCII art comments? That just repeat the names of the functions? Argh, my eyes..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T18:58:59.430",
"Id": "70472",
"Score": "0",
"body": "haha, sorry, Ant. Those are just to make it easier to navigate until I break it down into multiple files. Then I won't need them."
}
] |
[
{
"body": "<h1>Things you did well</h1>\n\n<ul>\n<li><p>Nicely formatted, easy to read.</p></li>\n<li><p>Use of <code>typedef</code> with structures.</p></li>\n</ul>\n\n<h1>Things you could improve</h1>\n\n<h3>Preprocessor:</h3>\n\n<ul>\n<li><p>Since <code>SDL.h</code> isn't one of your own pre-defined header files, you should be searching for it in directories pre-designated by the compiler (since that is where it should be stored).</p>\n\n<pre><code>#include <SDL/SDL.h>\n</code></pre>\n\n<p>In <a href=\"http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf\" rel=\"nofollow noreferrer\">the C standard</a>, §6.10.2, paragraphs 2 to 4 state:</p>\n\n<blockquote>\n <ul>\n <li><p>A preprocessing directive of the form</p>\n\n<pre><code>#include <h-char-sequence> new-line\n</code></pre>\n \n <p>searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the <code><</code> and <code>></code> delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined.</p></li>\n <li><p>A preprocessing directive of the form</p>\n\n<pre><code>#include \"q-char-sequence\" new-line\n</code></pre>\n \n <p>causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the <code>\"</code> delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read</p>\n\n<pre><code>#include <h-char-sequence> new-line\n</code></pre>\n \n <p>with the identical contained sequence (including <code>></code> characters, if any) from the original\n directive.</p></li>\n <li><p>A preprocessing directive of the form</p>\n\n<pre><code>#include pp-tokens new-line\n</code></pre>\n \n <p>(that does not match one of the two previous forms) is permitted. The preprocessing tokens after <code>include</code> in the directive are processed just as in normal text. (Each identifier currently defined as a macro name is replaced by its replacement list of preprocessing tokens.) The directive resulting after all replacements shall match one of the two previous forms. The method by which a sequence of preprocessing tokens between a <code><</code> and a <code>></code> preprocessing token pair or a pair of <code>\"</code> characters is combined into a single header name preprocessing token is implementation-defined.</p></li>\n </ul>\n \n <p><strong>Definitions:</strong></p>\n \n <ul>\n <li><p>h-char: any member of the source character set except the new-line character and <code>></code></p></li>\n <li><p>q-char: any member of the source character set except the new-line character and <code>\"</code></p></li>\n </ul>\n</blockquote>\n\n<p>Don't forget to include <code>-lSDL</code> with <code>gcc</code> to link your code to the SDL library.</p></li>\n</ul>\n\n<h3>Variables/Initialization:</h3>\n\n<ul>\n<li><p>Tao is simple 2π, as you have defined in your code.</p>\n\n<blockquote>\n<pre><code>const double Tao = 6.283185307179586476925;\n</code></pre>\n</blockquote>\n\n<p>However, π is a <a href=\"https://www.gnu.org/software/libc/manual/html_node/Mathematical-Constants.html\" rel=\"nofollow noreferrer\">mathematically defined constant in <code>math.h</code></a>. Since you are already using that header, you should utilize the predefined constant.</p>\n\n<pre><code>const double TAO = 2 * M_PI;\n</code></pre></li>\n</ul>\n\n<h3>Memory:</h3>\n\n<ul>\n<li><p>You allocate memory to <code>audioBuffer()</code>, but then never <code>free()</code> it,</p>\n\n<blockquote>\n<pre><code>audioBuffer = malloc( sizeof(float)*audioBufferLength );\n// free(audioBuffer); //not necessary?\n</code></pre>\n</blockquote>\n\n<p>This would be my guess as to what valgrind is whining about. You should always have freed all memory that you have allocated before you exit your program; we want to avoid memory leaks. </p>\n\n<p>Now to adress your comment as to whether or not that line of code is necessary, since you are exiting your program anyways. It depends on the operating system. The majority of modern (and all major) operating systems will free memory not freed by the program when it ends.</p>\n\n<p>Relying on this is bad practice and it is better to <code>free()</code> it explicitly. The issue isn't just that your code looks bad. You may decide you want to integrate your small program into a larger, long running one. Then a while later you have to spend hours tracking down memory leaks. </p>\n\n<p>Relying on a feature of an operating system also makes the code less portable.</p></li>\n</ul>\n\n<h3>Syntax/Styling:</h3>\n\n<ul>\n<li><p>Right now you are using <code>Uint32</code> to represent an unsigned 32 bit integer, but <code>uint32_t</code> is the type that's defined by the C standard.</p>\n\n<pre><code>uint32_t sampleRate = 48000;\n</code></pre></li>\n<li><p>Define <code>i</code> within your <code>for</code> loops, not outside.<sup>(C99)</sup></p>\n\n<pre><code>for (uint32_t i = 0; (i+1) < samplesPerFrame; i += 2)\n</code></pre></li>\n<li><p><code>typedef struct</code>s typically have a capitalized name by standard conventions.</p>\n\n<pre><code>typedef struct \n{\n float *waveform;\n Uint32 waveformLength;\n double volume; // multiplied\n double pan; // 0 to 1: all the way left to all the way right\n double frequency; // Hz\n double phase; // 0 to 1\n} Voice;\n</code></pre></li>\n<li><p>Declare <em>all</em> of your parameters as <code>void</code> when you don't take in any arguments.</p>\n\n<pre><code>int init(void)\n</code></pre></li>\n<li><p>You aren't using the parameters specified in <code>main()</code>.</p>\n\n<blockquote>\n<pre><code>int main(int argc, char *argv[])\n</code></pre>\n</blockquote>\n\n<p>Declare them as <code>void</code> if you aren't going to use them.</p>\n\n<pre><code>int main(void)\n</code></pre></li>\n<li><p>Use <a href=\"http://www.cplusplus.com/reference/cstdio/puts/\" rel=\"nofollow noreferrer\"><code>puts()</code></a> instead of <code>printf()</code> when you aren't formatting your output.</p>\n\n<blockquote>\n<pre><code>printf(\"\\n\\nwaveform data:\\n\\n\");\n</code></pre>\n</blockquote>\n\n<pre><code>puts(\"Waveform data: \");\n</code></pre></li>\n<li><p>Remove <code>!= 0</code> in some of your conditional tests for maximum C-ness.</p></li>\n</ul>\n\n<h3>Comments:</h3>\n\n<ul>\n<li><p>Your ASCII art comments... hurt my eyes.</p>\n\n<blockquote>\n<pre><code>/* _ _ _____ _ _ _ _ \n | (_) / ____| | | | | | | \n __ _ _ _ __| |_ ___ | | __ _| | | |__ __ _ ___| | __\n / _` | | | |/ _` | |/ _ \\| | / _` | | | '_ \\ / _` |/ __| |/ /\n | (_| | |_| | (_| | | (_) | |___| (_| | | | |_) | (_| | (__| < \n \\__,_|\\__,_|\\__,_|_|\\___/ \\_____\\__,_|_|_|_.__/ \\__,_|\\___|_|\\_\\\n*/\n</code></pre>\n</blockquote>\n\n<p>You said in the comments that: <em>\"Those are just to make it easier to navigate until I break it down into multiple files. Then I won't need them.\"</em> </p>\n\n<p>Let me suggest another alternative that you can keep around: documenting your code with <a href=\"http://www.doxygen.nl/index.html\" rel=\"nofollow noreferrer\">Doxygen</a>. Replacing your ASCII art comments with documentation of your methods will make it easier to navigate, and serve the very important purpose of stating why/how you programmed something a certain way. </p>\n\n<p>I've taken an example from <a href=\"https://codereview.stackexchange.com/q/43872/27623\">one of my previous questions</a> to use here.</p>\n\n<pre><code>/**\n * @fn static void json_fillToken(JsonToken *token, JsonType type, int start, int end)\n * @brief Fills token type and boundaries.\n * @param token\n * @param type\n * @param start\n * @param end\n */\nstatic void json_fillToken(JsonToken *token, JsonType type, int start, int end)\n{\n token->type = type;\n token->start = start;\n token->end = end;\n token->size = 0;\n}\n</code></pre></li>\n<li><p>Remove old commented out code.</p>\n\n<blockquote>\n<pre><code>//logVoice(&testVoiceA);\n//logWavedata(testVoiceA.waveform, testVoiceA.waveformLength, 10);\n</code></pre>\n</blockquote>\n\n<p>It serves almost no purpose, and makes your code look cluttered.</p></li>\n<li><p>Besides your ASCII art comments and your old commented out code, you have only a few other comments throughout your source code. See <a href=\"http://blog.codinghorror.com/coding-without-comments/\" rel=\"nofollow noreferrer\">this blog post here</a> as to why and how you should comment throughout your code.</p></li>\n</ul>\n\n<h3>Exiting:</h3>\n\n<ul>\n<li><p>You have a function dedicated to termination, and you call it right before you close down your program.</p>\n\n<blockquote>\n<pre><code>int onExit() {\n SDL_CloseAudioDevice(AudioDevice);\n //free(audioBuffer);//not necessary?\n SDL_Quit();\n return 0;\n}\n</code></pre>\n</blockquote>\n\n<p>I think you could make great use of the <a href=\"http://www.cplusplus.com/reference/cstdlib/atexit/\" rel=\"nofollow noreferrer\"><code>atexit()</code></a> function in your code. The <code>atexit()</code> function registers a function to be called at normal program termination. Though if you decide to use this, you may want to rename <code>onExit()</code> to something such as <code>cleanup()</code> or something similar.</p>\n\n<pre><code>int main(void)\n{\n ...\n atexit(cleanup);\n return 0;\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T04:31:33.850",
"Id": "77503",
"Score": "6",
"body": "`However, π is a mathematically defined constant in math.h.` Not according to the standard, it's not. It's a very common extension, but it's not guaranteed to be defined."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-18T07:43:49.710",
"Id": "77516",
"Score": "0",
"body": "Thanks! I went ahead and made a lot of the changes you suggested. The `free(audioBuffer)` line wasn't the source of the valgrind error, but I've uncommented it anyway for the other reasons you mentioned, and added more info regarding this in my original post. Also, `<SDL/SDL.h>` didn't work, but `<SDL.h>` did."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T19:52:19.770",
"Id": "449529",
"Score": "0",
"body": "`M_PI` is non-standard. See https://stackoverflow.com/questions/26065359/m-pi-flagged-as-undeclared-identifier"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-19T08:35:45.563",
"Id": "505779",
"Score": "0",
"body": "C++20 has finally added `std::numbers::pi` in the `<numbers>` header."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-03-18T02:05:01.603",
"Id": "44635",
"ParentId": "41086",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "44635",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T17:32:38.853",
"Id": "41086",
"Score": "12",
"Tags": [
"c",
"lock-free",
"atomic",
"audio"
],
"Title": "Play some sine waves with SDL2"
}
|
41086
|
<p>I am practicing for interviews and I tried solving the problem on my own and got a solution. I was wondering how can I improve the performance and memory on this program?</p>
<p>The problem performs addition on linked list nodes. The nodes are <code>1s->10s->100s->...</code>. The goal of this program is to perform addition on two of these linked lists. The output should be a linked list of the same format.</p>
<p>Example:</p>
<pre><code> 1 -> 4 -> 3
+ 1 -> 5 -> 9 -> 2
</code></pre>
<p>Linked list output:</p>
<pre><code>2 -> 9 -> 2 -> 3
</code></pre>
<p>Here is my code:</p>
<pre><code>public class prob2_5 {
/*
* You have two numbers represented by a linked list, where each node contains a single digit.
* The digits are stored in reverse order, such that the 1's digit is at the head of the list.
* Write a function that adds the two numbers and returns the sum as a linked list
*
*/
public static LinkedListNode addLists(LinkedListNode l1, LinkedListNode l2) {
int l1sum = 0;
int l2sum = 0;
int multiplier = 1;
while(l1 != null) {
l1sum = l1sum + l1.value*multiplier;
multiplier = multiplier*10;
l1 = l1.next;
}
multiplier = 1;
while(l2 != null) {
l2sum = l2sum + l2.value*multiplier;
multiplier = multiplier*10;
l2 = l2.next;
}
int total = l2sum + l1sum;
char[] totalnum = (total + "").toCharArray();
int len = totalnum.length;
LinkedListNode tail = new LinkedListNode(totalnum[len - 1] - '0');
LinkedListNode newNode;
LinkedListNode prevNode = tail;
System.out.print(totalnum);
for (int i = len - 2; i >= 0; i--) {
newNode = new LinkedListNode(totalnum[i] - '0');
prevNode.next = newNode;
prevNode = newNode;
}
return tail;
}
}
</code></pre>
<p>Here is my linked list class:</p>
<pre><code>public class LinkedListNode {
LinkedListNode next;
int value;
public LinkedListNode(int value) {
this.next = null;
this.value = value;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T18:25:04.427",
"Id": "70459",
"Score": "0",
"body": "What is your `LinkedListNode` implementation? Could you provide a runnable example? I didn't really understand your explanation completely."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T18:34:36.127",
"Id": "70460",
"Score": "0",
"body": "Sorry Ill add more to my post"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T18:38:24.237",
"Id": "70463",
"Score": "1",
"body": "OK, now I understand. 143 really represents the number 341, and 1592 is 2951. 2951 + 341 = 3292, which is 2923 backwards."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T18:48:14.653",
"Id": "70465",
"Score": "0",
"body": "yes exactly! =D"
}
] |
[
{
"body": "<p>I believe you are missing the point of the exercise - instead of 'decoding' the input numbers, and then 're-encoding' the output number - you are supposed to iteratively get to the answer by going over the nodes of both lists:</p>\n\n<pre><code>public static LinkedListNode addLists(LinkedListNode l1, LinkedListNode l2) {\n return addLists(0, l1, l2);\n}\n\nprivate static LinkedListNode addLists(int carryOver, LinkedListNode l1, LinkedListNode l2) {\n // stop conditions\n if (l1 == null && l2 == null && carryOver == 0) {\n return null;\n }\n if (l1 == null) {\n l1 = new LinkedListNode(0);\n }\n if (l2 == null) {\n l2 = new LinkedListNode(0);\n }\n\n // iteration\n int addedValue = l1.value + l2.value + carryOver;\n carryOver = 0;\n\n if (addedValue >= 10) {\n addedValue -= 10;\n carryOver = 1;\n }\n\n l3 = new LinkedListNode(addedValue);\n\n // recursion\n l3.next = addLists(carryOver, l1.next, l2.next);\n\n return l3;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T19:58:35.693",
"Id": "70496",
"Score": "3",
"body": "Instead of `l1 = new LinkedListNode(0)`, I'd suggest creating a null object: `private static final NULL_NODE = new LinkedListNode(0);`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T18:50:56.603",
"Id": "41096",
"ParentId": "41090",
"Score": "8"
}
},
{
"body": "<p><a href=\"https://codereview.stackexchange.com/a/41096/31503\">Uri has a good answer</a>, this answer is just to add a second spin on the problem....</p>\n\n<p>Recursion is a good tool to have, but it is not necessarily the best tool for all occasions. In this instance, it's a toss-up.... but the iterative solution to this problem is perhaps a simpler thing to read..... and should be considered. Additionally, in many cases an iterative solution will outperform a recursive solution. In this case, again, it is a toss-up because the lists will be so short.... but, if the list <em>was</em> long, the recursive approach will fail with a stack-overflow... the iterative approach will keep trucking though.</p>\n\n<pre><code>public static final LinkedListNode add(LinkedListNode a, LinkedListNode b) {\n // this pointer points to the result, it is not the actual result.\n final LinkedListNode pointer = new LinkedListNode(0);\n\n int carry = 0;\n LinkedListNode cursor = pointer;\n while (a != null || b != null) {\n int digitsum = carry;\n if (a != null) {\n digitsum += a.value;\n a = a.next;\n }\n if (b != null) {\n digitsum += b.value;\n b = b.next;\n }\n cursor.next = new LinkedListNode(digitsum % 10);\n carry = digitsum / 10;\n cursor = cursor.next;\n }\n if (carry != 0) {\n cursor.next = new LinkedListNode(carry);\n }\n\n // don't return the dummy pointer, return the actual result\n return pointer.next;\n}\n</code></pre>\n\n<p>Some side-notes:</p>\n\n<ul>\n<li>the variables <code>l1</code> and <code>l2</code> are not great names....</li>\n<li>The <code>LinkedListNode</code> should probably have a <code>final</code> value, and there should be getters for the value and next, and a setter for the next.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T23:31:41.440",
"Id": "41119",
"ParentId": "41090",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "41096",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T18:15:43.483",
"Id": "41090",
"Score": "11",
"Tags": [
"java",
"performance",
"linked-list",
"memory-management"
],
"Title": "Linked list arithmetic"
}
|
41090
|
<p>I have tried to write a function like <code>memcpy</code>. It copies <code>sizeof(long)</code> bytes at a time.</p>
<p>What surprised me is how inefficient it is. It's just 17% more efficient than the naivest implementation with <code>-O3</code>. With optimizations off it's a lot faster than the naivest, so perhaps the compiler is doing this automatically?</p>
<p>It will copy 1 byte at a time until one of the addresses is aligned, then it will copy <code>sizeof(long)</code> and then 1 byte at a time to avoid writing beyond the bounds.</p>
<p>How can I make this faster?</p>
<pre><code>#include <stdlib.h>
#define THRESHOLD sizeof(long)
static size_t min(size_t a, size_t b)
{
return (a > b) ? a : b;
}
static void big_copy(void *dest, const void *src, size_t iterations)
{
long *d = dest;
const long *s = src;
size_t eight = iterations / 8;
size_t single = iterations % 8;
while(eight > 0){
*d++ = *s++;
*d++ = *s++;
*d++ = *s++;
*d++ = *s++;
*d++ = *s++;
*d++ = *s++;
*d++ = *s++;
*d++ = *s++;
--eight;
}
while(single > 0){
*d++ = *s++;
--single;
}
}
static void small_copy(void *dest, const void *src, size_t iterations)
{
char *d = dest;
const char *s = src;
while(iterations > 0){
*d++ = *s++;
--iterations;
}
}
void *copy_memory(void *dest, const void *src, size_t size)
{
//Small size is handled here
if(size < THRESHOLD){
small_copy(dest, src, size);
return dest;
}
//Start copying 8 bytes as soon as one of the pointers is aligned
size_t bytes_to_align = min((size_t)dest % sizeof(long), (size_t)src % sizeof(long));
void *position = dest;
//Align
if(bytes_to_align > 0){
small_copy(position, src, bytes_to_align);
position = (char *)position + bytes_to_align;
src = (char *)src + bytes_to_align;
size -= bytes_to_align;
}
//How many iterations can be done
size_t safe_big_iterations = size / sizeof(long);
size_t remaining_bytes = size % sizeof(long);
//Copy most bytes here
big_copy(position, src, safe_big_iterations);
position = (char *)position + safe_big_iterations * sizeof(long);
src = (char *)src + safe_big_iterations * sizeof(long);
//Process the remaining bytes
small_copy(position, src, remaining_bytes);
return dest;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-05-23T21:54:55.220",
"Id": "311900",
"Score": "0",
"body": "I think it should be noted that in the Internet, this very code has been presented as an example of a not obvious UB. See http://blog.regehr.org/archives/1307 , especially section Chunking Optimizations Are Broken. I’m a layman, but the concern seems to me to be either well-founded."
}
] |
[
{
"body": "<p>The last time I saw source for a C run-time-library implementation of <code>memcpy</code> (Microsoft's compiler in the 1990s), it used the algorithm you describe: but it was written in assembly. It might (my memory is uncertain) have used <code>rep movsd</code> in the inner loop.</p>\n\n<p>Your code says, <code>//Start copying 8 bytes as soon as one of the pointers is aligned</code>. When you're performance-testing you should know (because that's when you might expect the best performance) whether both buffers are aligned.</p>\n\n<p>On the subject of alignment there as an interesting (but unrelated to your question) question here on StackOverflow: <a href=\"https://stackoverflow.com/q/21038965/49942\">Why speed of memcpy() drops dramatically every 4KB?</a></p>\n\n<p>I vaguely understand what kind of an effect you're looking for in your code. I don't know what assembler your compiler is actually producing.</p>\n\n<p>The accepted answer to this StackOverflow question demonstrates the kind of assembly that is used nowadays: <a href=\"https://stackoverflow.com/a/1715385/49942\">Very fast memcpy for image processing?</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T19:13:13.197",
"Id": "41099",
"ParentId": "41094",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41099",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T18:28:50.233",
"Id": "41094",
"Score": "7",
"Tags": [
"c",
"performance",
"reinventing-the-wheel"
],
"Title": "memcpy() implementation"
}
|
41094
|
<p>I have created a script for going a multiple select option in Angular without using a <code>select</code> box that you have to hold control in order to select multiple items.</p>
<p>Demo: <a href="http://jsfiddle.net/qwertynl/xfw9f/" rel="nofollow">http://jsfiddle.net/qwertynl/xfw9f/</a></p>
<p><a href="https://github.com/qwertynl/AngularJS-Switcharoo/tree/9866f0485d9055465d65371b8a139aeebd9e9747" rel="nofollow">Code on GitHub</a></p>
<p>Here is my code:</p>
<p>Javascript:</p>
<pre><code>var switcharoo = angular.module('switcharoo', []).directive('multiSelect', function(){
return {
restrict: 'E',
scope: {
items: '=',
default: '=',
leftTitle: '@',
rightTitle: '@'
},
templateUrl: "switcharoo.html",
link: function(scope) {
scope.switchItem = function(item) {
var index = scope.default.indexOf(item);
if(index == -1) {
//add it in
scope.default.push(item);
}
else {
//remove it
scope.default.splice(index, 1);
}
}
}
};
})
switcharoo.directive('switchitem', function() {
return {
restrict: 'E',
scope: {
value: '='
},
template: '<div>{{value}}</div>'
};
});
</code></pre>
<p>HTML Template:</p>
<pre><code><style>
.switchBox .entBox {
overflow:auto;height:8em; width:190px;border:1px solid black;float:left;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;
}
.switchBox .entBox div:hover {
background-color: #908f8f;
}
.switchBox .eBox2.entBox {
background-color: #ccc9c9;
}
</style>
<label>
<table>
<tr>
<th>{{leftTitle}}</th>
<th>{{rightTitle}}</th>
</tr>
<tr class="switchBox">
<td>
<div class="entBox eBox1">
<switchitem ng-repeat="(key, value) in items" ng-if="default.indexOf(key) == -1" value="value" ng-click="switchItem(key)"></switchitem>
</div>
</td>
<td>
<div class="entBox eBox2">
<switchitem ng-repeat="(key, value) in items" ng-if="default.indexOf(key) > -1" value="value" ng-click="switchItem(key)"></switchitem>
</div>
</td>
</tr>
</table>
</label>
</code></pre>
<p>Is there anything I can do to make my code slicker?</p>
|
[] |
[
{
"body": "<p>I really like your code, I only have 2 minor observations:</p>\n\n<ul>\n<li><p>I understand the part where <code>default</code> has the default items. I am not sure that after initialization you should keep referring to the <code>default</code> variable ( from a naming perspective ), maybe call it <code>selection</code> instead of <code>default</code> ?</p></li>\n<li><p>Related to the previous point, <code>ng-if=\"default.indexOf(key) == -1\"</code> and <code>ng-if=\"default.indexOf(key) > -1\"</code> only make sense during initialization. In my mind, it would be ideal to provide a <code>isSelected( key )</code> that you can use for the <code>ng-if</code>. Not to mention that it will remove a <code>></code> out of your HTML attribute and look better in Markup ;)</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T19:47:13.640",
"Id": "70488",
"Score": "0",
"body": "Yea, I realize now that it should be called \"selected\" and not default. I'll try using a function instead for the `ng-if`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T19:51:37.500",
"Id": "70490",
"Score": "0",
"body": "Does this look better? http://jsfiddle.net/qwertynl/xfw9f/15/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T19:54:27.803",
"Id": "70491",
"Score": "0",
"body": "If you go for slickness, then I would go for `return ~scope.selected.indexOf(item);` other than that, looks good to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T19:54:57.233",
"Id": "70492",
"Score": "0",
"body": "What does the tilde (`~`) do?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T19:56:39.437",
"Id": "70493",
"Score": "0",
"body": "Bitwise NOT, converts -1 to 0, convert anything else to not-zero,"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T19:58:22.873",
"Id": "70495",
"Score": "0",
"body": "idk if I want to do that. It is a little hard to read and understand if you do not know what it does."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T20:05:42.363",
"Id": "70497",
"Score": "0",
"body": "NO worries, just a suggestion ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T20:33:42.907",
"Id": "70506",
"Score": "0",
"body": "I just updated the [Github code](https://github.com/qwertynl/AngularJS-Switcharoo) with code from the fiddle"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T19:46:23.960",
"Id": "41102",
"ParentId": "41095",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T18:30:53.147",
"Id": "41095",
"Score": "6",
"Tags": [
"javascript",
"angular.js"
],
"Title": "Angular JS Switcharoo multiple select module"
}
|
41095
|
<p>I tried to make the code for implementation of first-come first-serve job scheduling algorithm as used by operating systems.</p>
<p>How can I make it better?</p>
<p>I am using turbo C++ compiler</p>
<pre><code>#include<conio.h>
#include<iostream.h>
#include<dos.h>
struct process//contains information about processes in waiting queue
{
int waitt;
int etime;
char name[32];
struct process * next;
};
void inc( struct process * q)//increases wait time of all processes in wait queue
{
while(q!=0)
{
q->waitt++;
q=q->next;
}
}
int pop(struct process** q)//remove process from wait queue to run state returns wait time of process
{
int wait=(*q)->waitt;
struct process* t=*q;
*q=(*q)->next;
delete t;
return wait;
}
void addnode(struct process** q)//add new process to wait queue
{
struct process *temp=new (struct process);
cout<<"\nEnter process name ";
cin>>temp->name;
do
{
cout<<"\nEnter process execution time ";
cin>>temp->etime;
}while(temp->etime<=0);//to check valid input for process burst time
temp->next=0;
temp->waitt=0;
if(*q==0)
*q=temp;
else
{
struct process* t=*q;
while(t->next!=0)
t=t->next;
t->next=temp;
}
}
int main(void)
{
clrscr();
int e=1,wait=0,p=0,tt=1;
struct process* q=0,*t;
//add first process
addnode(&q);
e=q->etime;//Burst time of runing process
cout<<"\nProcess "<<q->name<<" startedafter a wait time of "<<q->waitt;
cout<<" time units \n";
p++;
wait=pop(&q);
do
{
//to check addition of new process
if(kbhit())
addnode(&q);
//increase wait time of waiting processes
inc(q);
//decrement time left for finishing of process
e--;
if(e==0)//if process ended
{
if(q!=0)/*if process is left in wait queue remove next process from wait queue and add its wait time to total time*/
{
e=q->etime;
cout<<"\n"<<q->name<<" started after a wait time of "<<q->waitt<<"time units\n";
p++;
wait+=pop(&q);
}
}
delay(100);
cout<<tt++<<" ";//to show total time units since start of first process
}while(q!=0||e!=0);//if process ended also no process in wait queue end loop
cout<<"\n\nTotal no. of prcesses executed ="<<p;
cout<<"\nTotal wait time for all prcesses executed ="<<wait;
cout<<"\nAverage wait time for prcesses executed ="<<wait/(float)p;
getch();
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T20:06:54.190",
"Id": "70499",
"Score": "0",
"body": "Did you mean to tag this as [c]? This hardly looks like [c++] (except for `cin` and `cout`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T20:10:49.710",
"Id": "70501",
"Score": "0",
"body": "I highly doubt this compiles. `<iostream.h>`? Calling `cout` and `cin` with no `std::` or `using namespace std;`? Is this working code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T20:11:52.567",
"Id": "70502",
"Score": "0",
"body": "I was using the old turbo compiler"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T20:15:05.083",
"Id": "70504",
"Score": "0",
"body": "Oh, okay. Make sure that is stated in the question when appropriate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T20:47:54.543",
"Id": "70509",
"Score": "2",
"body": "Several questions: Is this program your end-goal, or is this a starting point that you intend to expand off of later? If you want to study queueing behavior, why tie it to actual clock time by using delay? You'd do better to track simulated time and update it by the desired delay amount, e.g., `simulated_time += 100;` whenever there's something that involves delay in your model. I'd suggest using variable names that are more descriptive than e, p, q, t, or tt. Lose the `inc` function by storing the entry/arrival time in the queue rather than the wait: wait = time at pop - entry time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T17:21:16.447",
"Id": "70632",
"Score": "1",
"body": "Not really a C++ program. C with std::cout. Note: `int main(void)` is not a legal declaration for `main`. Use `int main()`"
}
] |
[
{
"body": "<p>I think this question would actually benefit from both a C review (just change the <code>cout</code>'s to <code>printf</code>, etc) and a C++ review since you seem to be using a very C-orientated programming style. </p>\n\n<p>This post will be a C++ review.<br>\nPlease note that the Turbo C++ compiler is not available to me, so my suggestions will revolve around the C++98/03 standard.</p>\n\n<p>My first bit of advice would be to switch to an object-oriented approach.<br>\nTurn <code>process</code> into a class and create a second class, <code>process_queue</code>. </p>\n\n<p>In <code>process</code>, replace <code>char name [32]</code> with <code>std::string name</code>. This way, you don't have to worry about buffer overflows. </p>\n\n<p>Refactor <code>inc()</code>, <code>pop()</code>, and <code>addnode()</code> into member functions for the new class <code>process_queue</code>.</p>\n\n<p>Make <code>pop()</code> return a <code>process</code> instead of an <code>int</code>. This is because you have a queue of <code>process</code>s, not a queue of <code>int</code>s.</p>\n\n<p>Rename <code>inc()</code> to something more readable like <code>increment_all_wait_times()</code>. That's a long name, but your code will be self-documenting. </p>\n\n<p>Take out the user-input logic from <code>inc()</code>, <code>pop()</code>, and <code>addnode()</code>.<br>\nThis will improve their flexibility. \n<a href=\"http://www.codinghorror.com/blog/2007/03/curlys-law-do-one-thing.html\" rel=\"nofollow noreferrer\">A function should only do one thing, and do it well</a>.</p>\n\n<p>For function parameters, prefer the use of references over the use of pointers.<br>\nThis will save you from having to check for <code>NULL</code>.</p>\n\n<p>Here is an idea of what a <code>process</code> class might look like: </p>\n\n<pre><code>class process\n{\npublic:\n process (const std::string &name, const int burst_time = 0, const int wait_time = 0) ;\n\n // getters\n std::string name () const ;\n int burst_time () const ;\n int wait_time () const ;\n const process* next () const ;\n process* next () ;\n\n void decrement_burst_time (const int time) ;\n\nprivate:\n int burst_time_;\n int wait_time_;\n std::string name_;\n process *next_;\n\n friend std::ostream& operator<< (std::ostream &os, const process &proc) ; \n friend class process_queue ;\n};\n</code></pre>\n\n<p>This would encapsulate your variables and (for the most part) make them read-only.<br>\nBecause the <code>process_queue</code> class is tightly coupled with this class, I would make it a <a href=\"http://en.wikipedia.org/wiki/Friend_class\" rel=\"nofollow noreferrer\">friend class</a>. There are two versions of the <code>next()</code> method for the sake of <a href=\"http://www.parashift.com/c++-faq/const-correctness.html\" rel=\"nofollow noreferrer\">const-correctness</a>. </p>\n\n<p>Here is an idea of what a <code>process_queue</code> class might look like: </p>\n\n<pre><code>class process_queue\n{\npublic:\n process_queue () ;\n ~process_queue () ;\n\n bool empty () const ;\n void add_node (const process &proc) ;\n void increment_all_wait_times (const int wait) ;\n process pop () ;\n size_t size () const ;\n\n friend std::ostream & operator<< (std::ostream &os, const process_queue &pq) ;\n\nprivate:\n size_t size_ ;\n process *head_;\n process *tail_; // for O(1) insertions\n}; \n</code></pre>\n\n<p>This, once again, encapsulates your variables while still providing useful functionality. </p>\n\n<p>Here's what a constructor implementation might look like:</p>\n\n<pre><code>process::process (const std::string &name, const int burst_time, const int wait_time) \n : name_ (name), burst_time_ (burst_time), wait_time_ (wait_time), next_ (NULL)\n{\n}\n</code></pre>\n\n<p>What you see here is a <a href=\"http://www.cprogramming.com/tutorial/initialization-lists-c++.html\" rel=\"nofollow noreferrer\">constructor initialization list</a>. It is important to initialize your variables or else you may suffer from subtle bugs.</p>\n\n<p>Here is a destructor for the <code>process_queue</code> class:</p>\n\n<pre><code>process_queue::~process_queue ()\n{\n while (size_ > 0) {\n this->pop () ;\n }\n}\n</code></pre>\n\n<p>This makes sure all of our resources (memory in this case) are cleaned up when an instance of this class goes out of scope. This strategy is called <a href=\"https://stackoverflow.com/questions/2321511/what-is-meant-by-resource-acquisition-is-initialization-raii\">RAII</a>. RAII is important for writing <a href=\"https://stackoverflow.com/questions/1853243/c-do-you-really-write-exception-safe-code\">exception-safe</a> code.</p>\n\n<p>Here is an example implementation of all of the above combined (somewhat sloppily): </p>\n\n<pre><code>#include <iostream>\n#include <string>\n#include <stdexcept>\n\nclass process_queue ;\n\nclass process\n{\npublic:\n process (const std::string &name, const int burst_time = 0, const int wait_time = 0) ;\n\n std::string name () const ;\n int burst_time () const ;\n int wait_time () const ;\n const process* next () const ;\n process* next () ;\n\n void decrement_burst_time (const int time) ;\n\nprivate:\n int burst_time_;\n int wait_time_;\n std::string name_;\n process *next_;\n\n friend std::ostream& operator<< (std::ostream &os, const process &proc) ; \n friend class process_queue ;\n};\n\nprocess::process (const std::string &name, const int burst_time, const int wait_time) \n : name_ (name), burst_time_ (burst_time), wait_time_ (wait_time), next_ (NULL)\n{\n}\n\nstd::string process::name () const\n{\n return name_ ;\n}\n\nint process::burst_time () const\n{\n return burst_time_ ;\n}\n\nint process::wait_time () const\n{\n return wait_time_ ;\n}\n\nconst process* process::next () const\n{\n return next_ ;\n}\n\nprocess* process::next ()\n{\n return next_ ;\n}\n\nvoid process::decrement_burst_time (const int time)\n{\n burst_time_ -= time ;\n}\n\nstd::ostream & operator<< (std::ostream &os, const process &proc)\n{\n os << \"{Name = \" << proc.name ()\n << \", Wait time = \" << proc.wait_time ()\n << \", Burst time = \" << proc.burst_time ()\n << \", Next = \" ;\n\n if (proc.next () != NULL) {\n os << proc.next ()->name () ;\n }\n\n else {\n os << \"None\" ;\n }\n\n os << \"}\" ;\n\n return os ;\n}\n\nclass process_queue\n{\npublic:\n process_queue () ;\n ~process_queue () ;\n\n bool empty () const ;\n void add_node (const process &proc) ;\n void increment_all_wait_times (const int wait) ;\n process pop () ;\n size_t size () const ;\n\n friend std::ostream & operator<< (std::ostream &os, const process_queue &pq) ;\n\nprivate:\n size_t size_ ;\n process *head_;\n process *tail_; // for O(1) insertions\n};\n\nprocess_queue::process_queue () : head_ (NULL), tail_ (NULL), size_ (0)\n{\n}\n\nvoid process_queue::add_node (const process &proc)\n{\n process *temp = new process (proc) ;\n\n if (tail_ != NULL) {\n tail_->next_ = temp ;\n\n if (head_ == tail_) {\n head_->next_ = temp ;\n }\n\n tail_ = tail_->next_ ; \n }\n\n else {\n tail_ = temp ;\n head_ = tail_ ;\n }\n\n ++size_ ;\n}\n\nvoid process_queue::increment_all_wait_times (const int wait)\n{\n process *temp = head_ ;\n\n while (temp != NULL) {\n temp->wait_time_ += wait ;\n temp = temp->next_ ;\n }\n}\n\n// Pops the head off.\nprocess process_queue::pop ()\n{\n if (head_ == NULL) {\n throw std::range_error (\"process_queue::pop() called while the process_queue was empty.\") ;\n }\n\n process ret = *head_ ;\n process *temp = head_ ;\n head_ = head_->next_ ;\n delete temp ;\n --size_ ;\n\n return ret ;\n}\n\nbool process_queue::empty () const\n{\n return (size_ == 0) ;\n}\n\nsize_t process_queue::size () const\n{\n return size_ ;\n}\n\nstd::ostream & operator<< (std::ostream &os, const process_queue &pq)\n{\n process *temp = pq.head_ ;\n\n while (temp != NULL) {\n os << *temp << \"\\n\" ;\n temp = temp->next () ;\n }\n\n return os ;\n}\n\nprocess_queue::~process_queue ()\n{\n while (size_ > 0) {\n this->pop () ;\n }\n}\n\nnamespace scheduler\n{\n void run_first_come_first_serve (process_queue &pq)\n {\n std::cout << \"Running first-come-first-serve scheduler with no preemption.\" \"\\n\" ;\n\n while (pq.empty () == false) {\n process proc = pq.pop () ;\n\n std::cout << \"Running \" << proc.name () << \"\\n\" ;\n\n std::cout << proc.name () << \" finished running after \" << (proc.burst_time () + proc.wait_time ()) << \" ns.\" \"\\n\" ; \n pq.increment_all_wait_times (proc.burst_time ()) ;\n\n std::cout << \"Queue:\\n\" << pq << \"\\n\" ;\n }\n }\n}\n\nint main(void)\n{\n process notepad (\"notepad.exe\", 500) ;\n process firefox (\"firefox.exe\", 1500) ;\n process excel (\"excel.exe\", 100) ;\n process visual_studio (\"visual studio.exe\", 200) ;\n process super_virus (\"super virus.exe\", 1000) ;\n\n process_queue pq ;\n pq.add_node (notepad) ;\n pq.add_node (firefox) ;\n pq.add_node (excel) ;\n pq.add_node (visual_studio) ;\n pq.add_node (super_virus) ;\n\n scheduler::run_first_come_first_serve (pq) ;\n\n return 0 ;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T17:25:01.200",
"Id": "70633",
"Score": "1",
"body": "That pretty good. The only difference I personally would make is removing all the getter functions. There is no need to expose the internal details of the class like this. You only use it for printing so create custom printing functions that have accesses to the internals (usually `operator>>` is a friend and can accesses the details anyway). By doing this you improve encapsulation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T15:37:51.757",
"Id": "71636",
"Score": "0",
"body": "@LokiAstari How would the function declarations look like? Are you suggesting something like this: `std::string print_burst_time() const` or `std::ostream& print_...`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T17:52:47.293",
"Id": "71660",
"Score": "0",
"body": "The standard way to do it is: `friend std::ostream& operator<<(std::ostream&, process const&)` and `friend std::istream& operator>>(std::istream&, process&)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T18:50:21.750",
"Id": "71670",
"Score": "0",
"body": "@LokiAstari I already overloaded those operators in this answer though. The only way to get rid of the getters that I can see would be to turn `namespace scheduler` into a `class scheduler` and have `process` be a friend class. I'm open to ideas though if you have a better way."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T00:44:13.997",
"Id": "41122",
"ParentId": "41101",
"Score": "11"
}
},
{
"body": "<p>I'm going to assume that you just want to model the behavior of a first-come-first-served single-server queue and don't plan on extending it. If so, there's an almost trivial solution:</p>\n\n<pre><code>int number_entities = 100;\nfloat arrival_time = 0.0, end_svc_time = 0.0, begin_svc_time;\nfor(int i = 0; i < number_entities; ++i) {\n arrival_time += interarrival_time();\n begin_svc_time = fmaxf(arrival_time, end_svc_time);\n end_svc_time = begin_svc_time + svc_time();\n /* delay in queue is begin_svc_time - arrival_time */\n /* delay in system is end_svc_time - arrival_time */\n}\n</code></pre>\n\n<p>Basically, each customer arrives at a time determined by the prior arrival and your model of inter-arrival times. They can either begin service immediately if the prior customer is done, or have to wait until the prior customer's service gets completed. They finish and depart the system service-time time units after they begin. Lather, rinse, repeat.</p>\n\n<p>The functions for <code>interarrival_time()</code> and <code>svc_time()</code> can be backed by any mechanism you like - constant or tabled values, values read in from one or more files, or random number generation.</p>\n\n<p>If you don't want to run for a specified number of customers, replace the <code>for</code> with a time-based <code>while</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T18:23:09.867",
"Id": "41175",
"ParentId": "41101",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "41122",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T19:24:29.973",
"Id": "41101",
"Score": "11",
"Tags": [
"c++",
"queue"
],
"Title": "First-come first-serve job scheduling algorithm"
}
|
41101
|
<p>A week ago, I have asked how to <a href="https://codereview.stackexchange.com/questions/40964/simplifying-this-form-validation-script/41001?noredirect=1#41001">simplify a form validation</a>. From the answers, the code now is improved. Can anyone please share their opinion on the approach used below and advise me if there is a better way to cut it?</p>
<pre><code>//Create object to hold the different error messages
var errorMessage = new Object();
errorMessage.required = "This field can not be empty";
errorMessage.email = "Please enter a valid email address";
errorMessage.number = "Please only enter numbers in this field";
errorMessage.min = "This field should be minimum ";
errorMessage.max = "This field should be maximum ";
errorMessage.date = "Please use the date format outlined above";
$("#contactForm").submit(function(event) {
event.preventDefault();
if (mtdValidate()) {
$submit = $(this).find('button[id="submit"]');
$inputs = $(this).find('input, textarea, select, label');
var posting = $.post($(this).attr('action'), $('#contactForm').serialize());
posting.done(function(data) {
$('span.error').remove();
if (data == "1") {
$submit.text('Sent. Thank You!');
$submit.add($inputs).addClass('sent').prop('disabled', true);
} else {
$submit.after('<span style="display: inline-block; padding: 15px 5px; color: #bd3d3d">Failed to send the message, please try again later.</span>');
$submit.text('Try Again');
}
});
}
});
$("#contactForm input, #contactForm textarea").blur(function() {
console.log("we blur now");
if ( $(this).hasClass("required") ) {
if ($.trim($(this).val()) == "") {
manageErrorMessage( $(this), errorMessage.required);
isFormValid = false;
}
} else if ($(this).hasClass("email")) {
var emailRegEx = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var emailIn = $.trim($(this).val());
if (emailRegEx.test(emailIn) == false) {
manageErrorMessage( $(this), errorMessage.email);
isFormValid = false;
}
} else if ($(this).hasClass("number")) {
var numRegEx = /^[0-9]+/;
var numIn = $.trim($(this).val());
if (numRegEx.test(numIn) == false) {
manageErrorMessage( $(this), errorMessage.number);
isFormValid = false;
}
} else if ($(this).hasClass("date")) {
var dateRegEx = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
var dateIn = $.trim($(this).val());
if (dateRegEx.test(dateIn) == false) {
manageErrorMessage( $(this), errorMessage.date);
isFormValid = false;
}
}
});
function mtdValidate() {
//Form is treated as being valid until validation fails
var isFormValid = true;
//Reset Error Messages on each submit press
resetErrorMessages();
//Loop through fields marked as required
$("#contactForm input.required").each(function() {
if ($.trim($(this).val()) == "") {
manageErrorMessage( $(this), errorMessage.required);
isFormValid = false;
}
});
//Loop through fields marked as email
$("#contactForm input.email").each(function() {
var emailRegEx = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var emailIn = $.trim($(this).val());
if (emailRegEx.test(emailIn) == false) {
manageErrorMessage( $(this), errorMessage.email);
isFormValid = false;
}
});
//Loop through fields marked as number
$("#contactForm input.number").each(function() {
var numRegEx = /^[0-9]+/;
var numIn = $.trim($(this).val());
if (numRegEx.test(numIn) == false) {
manageErrorMessage( $(this), errorMessage.number);
isFormValid = false;
}
});
//Loop through fields marked as date
$("#contactForm input.date").each(function() {
var dateRegEx = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
var dateIn = $.trim($(this).val());
if (dateRegEx.test(dateIn) == false) {
manageErrorMessage( $(this), errorMessage.date);
isFormValid = false;
}
});
//Loop through fields marked with min and max classes
$("#contactForm input").each(function() {
if ( $(this).attr("class") ) {
if( $(this).attr("class").match(/min[0-9]+/) ) {
var minClass = $(this).attr("class").match(/min[0-9]+/).toString();
minVal = parseInt(minClass.match(/[0-9]+/));
if ( $.trim($(this).val().length) < minVal ) {
manageErrorMinMax($(this), errorMessage.min, minVal);
isFormValid = false;
}
}
if ( $(this).attr("class").match(/max[0-9]+/) ) {
var maxClass = $(this).attr("class").match(/max[0-9]+/).toString();
maxVal = parseInt(maxClass.match(/[0-9]+/));
if ( $.trim($(this).val().length) > maxVal ) {
manageErrorMinMax($(this), errorMessage.max, maxVal);
isFormValid = false;
}
}
}
});
return isFormValid;
}
function resetErrorMessages() {
$("span.error").remove();
$("input .error").removeClass("error");
}
function manageErrorMessage(that, errorMessageIn) {
$(that).addClass('error');
if ( !$(that).next().is("span") ) {
$(that).after('<span class="error"></span>');
}
$(that).next().html(errorMessageIn);
}
function manageErrorMinMax(that, errorMessageIn, value) {
$(that).addClass('error');
if ( !$(that).next().is("span") ) {
$(that).after('<span class="error"></span>');
}
$(that).next().html(errorMessageIn + value + " charaters long.");
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>I'd almost always rather use object literals <code>{}</code> than <code>new Object()</code> for this. Much less verbose and easier to read.</p>\n\n<pre><code>var errorMessage = {\n required : \"This field can not be empty\",\n email : \"Please enter a valid email address\",\n number : \"Please only enter numbers in this field\",\n min : \"This field should be minimum \",\n max : \"This field should be maximum \",\n date : \"Please use the date format outlined above\"\n};\n</code></pre></li>\n<li><p>You use <code>$('#contactForm')</code> a lot. Save it, and use it as context to your other selectors:</p>\n\n<pre><code>var $form = $('#contactForm'); // for example this will return all \nvar $inputs = $('input', $form); // inputs that are decendants of $form\n</code></pre>\n\n<p>Also notice how I prefix variables with <code>$</code> to denote that they contain jQuery objects. Makes it easier to tell the difference between vars.</p></li>\n<li><p>If you have form elements that need to be validated via regexes, have you thought about putting them in the DOM as <code>data</code> attributes? This keeps formatting rules in one place.</p>\n\n<pre><code><input type=\"text\" class=\"number\" data-validation=\"/^[0-9]+/\" />\n</code></pre>\n\n<p>It also means you don't have to do those multiple iterations. Also, if you use <code>$(this)</code> more than once, save it as a var.</p>\n\n<pre><code>$('input', $form).each(function () {\n var $el = $(this); \n var regex = new RegEx($el.data('validation'));\n [...]\n});\n</code></pre></li>\n<li><p>You could use a callback in your <code>$.post</code> to save creating the variable;</p>\n\n<pre><code> $.post($(this).attr('action'), $('#contactForm').serialize(), \n function (data) {\n $('span.error').remove();\n [...]\n });\n</code></pre></li>\n<li><p>This is daft:</p>\n\n<blockquote>\n<pre><code> if (dateRegEx.test(dateIn) == false) {\n manageErrorMessage( $(this), errorMessage.date);\n isFormValid = false;\n }\n</code></pre>\n</blockquote>\n\n<p>No need to check against <code>false</code>, it is false.</p>\n\n<pre><code> if (dateRegEx.test(dateIn)) {\n [...]\n }\n</code></pre></li>\n<li><p>One more.... Thanks to <code>Hydrothermal</code> for making me realise.\nThis statement will return true if <code>data</code> is any state of truthy because the values are coerced.</p>\n\n<blockquote>\n<pre><code> if (data == \"1\") {\n</code></pre>\n</blockquote>\n\n<p>For example:</p>\n\n<pre><code> true == \"1\" // true\n 1 == \"1\" // true\n</code></pre>\n\n<p>It might be that this doesn't matter in this case, but you should always use <code>===</code> to compare values by identity rather than equality.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T20:05:27.047",
"Id": "41105",
"ParentId": "41103",
"Score": "6"
}
},
{
"body": "<p>It's more of a best practices thing than an actual issue, but you should usually use <code>===</code> instead of <code>==</code> when doing comparisons. <code>===</code> is a \"strict\" comparison, and is a little more predictable in its behavior. <a href=\"https://stackoverflow.com/a/359509/2789699\">This StackOverflow answer</a> is an excellent explanation of why, if you're curious.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T21:12:12.427",
"Id": "70514",
"Score": "0",
"body": "Also there are some dodgey comparisons going on like this: `data == \"1\"`. Should data be a String or an number? Does it matter? This statement tells me nothing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T21:13:53.090",
"Id": "70515",
"Score": "0",
"body": "Haha, also `(data == \"1\")` is true if `data` is truthy."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T20:50:06.723",
"Id": "41109",
"ParentId": "41103",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T19:47:11.193",
"Id": "41103",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"html",
"form"
],
"Title": "Simplifying this form validation script - version 2"
}
|
41103
|
<p><strong>Related tag: <a href="/questions/tagged/fun" class="post-tag" title="show questions tagged 'fun'" rel="tag">fun</a></strong></p>
<p>It all started with a small group of CR addicts that were discussing questions in <a href="https://chat.stackexchange.com/rooms/8595/the-2nd-monitor">The 2nd Monitor</a> (the site's main chatroom), when a <a href="https://codereview.stackexchange.com/users/31503/rolfl">monkey</a> proposed the idea:</p>
<blockquote>
<p><em>OK, weekend challenge.... we all solve the Rock Paper Scissors Lizzard Spock problem with our 'favourite' language, and we all have to post a question here with our solution to be reviewed.</em></p>
</blockquote>
<p>And so the <a href="/questions/tagged/weekend-challenge" class="post-tag" title="show questions tagged 'weekend-challenge'" rel="tag">weekend-challenge</a> tag was born. We grew fond of it, and for several weeks in a row <a href="https://codereview.meta.stackexchange.com/questions/1201/cr-weekend-challenge">a new challenge was being voted upon</a>.</p>
<p>That was December 2013. </p>
<p><a href="/questions/tagged/community-challenge" class="post-tag" title="show questions tagged 'community-challenge'" rel="tag">community-challenge</a> is <a href="https://codereview.meta.stackexchange.com/questions/1471/weekend-challenge-reboot">slightly different</a>. Participants have an entire month to submit entries, and while the <a href="https://codereview.meta.stackexchange.com/a/1472/23788">first challenge</a> was also decided in chat, subsequent ones will be voted upon by the community, on the meta site.</p>
<p>The <a href="/questions/tagged/weekend-challenge" class="post-tag" title="show questions tagged 'weekend-challenge'" rel="tag">weekend-challenge</a> has now been made a synonym of the more general <a href="/questions/tagged/community-challenge" class="post-tag" title="show questions tagged 'community-challenge'" rel="tag">community-challenge</a>.</p>
<p>Over time the <a href="/questions/tagged/community-challenge" class="post-tag" title="show questions tagged 'community-challenge'" rel="tag">community-challenge</a> concept may evolve and that is a 'good thing'™</p>
<hr>
<h2>About <a href="/questions/tagged/community-challenge" class="post-tag" title="show questions tagged 'community-challenge'" rel="tag">community-challenge</a>:</h2>
<p><strong>Why?</strong> For the heck of it.</p>
<p><strong>Who?</strong> Everyone that <s><em>thinks</em> they can</s> <em>wants to</em> implement the challenge with the best code they can write.</p>
<p><strong>What?</strong> That's agreed upon by the community (that's YOU!) voting on the meta site.</p>
<p><strong>How?</strong> That's the beauty of it. Sky's the limit. <a href="https://codereview.stackexchange.com/q/37448/23788"><em>Some take it literally</em></a>.</p>
<p><strong>When?</strong> Pay attention to the <strong>Community Bulletin</strong> when you pay us a visit:</p>
<p><img src="https://i.stack.imgur.com/8lz9X.png" alt="CB"></p>
<p><s>Late entries will be downvoted to oblivion</s> Entries can be submitted anytime, but we'd prefer this being a timely event, be it only to measure and correlate the site's metrics:</p>
<blockquote>
<p><img src="https://i.stack.imgur.com/UzDo9.png" alt="CR Activity Graph, April 2011 - January 2014"></p>
<p><sub><a href="https://data.stackexchange.com/codereview/query/161411/site-activity-and-votegraph#graph" rel="nofollow noreferrer">https://data.stackexchange.com/codereview/query/161411/site-activity-and-votegraph#graph</a></sub></p>
</blockquote>
<hr>
<h1>FAQ.</h1>
<p><strong>Q. <a href="https://codegolf.stackexchange.com">Code Golf & Programming Puzzles Stack Exchange</a> has a <a href="/questions/tagged/code-challenge" class="post-tag" title="show questions tagged 'code-challenge'" rel="tag">code-challenge</a> tag. Isn't this overlapping?</strong></p>
<p>A. No. This comment is very good at explaining why:</p>
<blockquote>
<p>@BenVoigt The first two 'on-topic' requirements for PCG are <em>An objective primary winning criterion, so that it is possible to indisputably decide which entry should win.</em> and <em>A clear specification of what constitutes a correct submission. Test cases are highly encouraged.</em></p>
<p>These two requirements are <strong>expressly avoided</strong> for our challenges. We have <strong>no winners</strong>, and we have <strong>no specific 'correct submission'</strong>. – <a href="https://codereview.stackexchange.com/users/31503/rolfl">rolfl</a> <a href="https://codereview.meta.stackexchange.com/questions/1471/weekend-challenge-reboot/1472?noredirect=1#comment4409_1471">7 hours ago</a></p>
</blockquote>
<hr>
<p><strong>Q. Why is every challenge a <a href="/questions/tagged/game" class="post-tag" title="show questions tagged 'game'" rel="tag">game</a>?</strong></p>
<p>A. Simply because coding a small game is fun, and if you were asked to come up with a project idea that you could implement and post for peer review in a single weekend, you'd probably think of ...a small game. That's all there is to it. Nothing prohibits proposing <em>something different</em>, the idea with the most votes at the end of the voting period becomes the current <a href="/questions/tagged/community-challenge" class="post-tag" title="show questions tagged 'community-challenge'" rel="tag">community-challenge</a>.</p>
<hr>
<p><strong>Q. So everyone codes the same thing. Aren't these posts likely to be duplicates?</strong></p>
<p>A. *There are as many ways to implement a solution in one language, as there are programmers implementing the solution in that language**. There is no language constraint whatsoever; these code review challenges can be an opportunity to fiddle with a new language and IDE (although they're not likely to be as easy as the average "Hello, World!").</p>
<hr>
<p><strong>Q. I code crap, I'm scared.</strong></p>
<p>A. <strong>You're not alone.</strong></p>
<p><img src="https://i.stack.imgur.com/52lvU.png" alt="You're not alone"></p>
<p>This is why you're here: to share some real working code you've written and would like to get peer reviewed. Don't be scared, nobody bites. Not even the monkeys. <strong>You're here to learn - we all are</strong>. If you're a beginner and would like to tell the community to be more... <em>gentle and understanding about the mess you've put yourself into</em>, don't hesitate to stick a <a href="/questions/tagged/beginner" class="post-tag" title="show questions tagged 'beginner'" rel="tag">beginner</a> tag on your post.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-02-06T20:08:32.557",
"Id": "41106",
"Score": "0",
"Tags": null,
"Title": null
}
|
41106
|
Reviewing code is fun! Use this tag to identify your post as an entry to the current community challenge. See the Community Bulletin, or browse the CR Meta site for more info. Typically you should also tag community-challenge questions with the [game] tag as well.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-02-06T20:08:32.557",
"Id": "41107",
"Score": "0",
"Tags": null,
"Title": null
}
|
41107
|
<p>I have the following code which I have written due to the fact the Microsoft's Sanitizer is now to aggressive.</p>
<p>What I'm trying to do is as follows.</p>
<ol>
<li>Create a whitelist of HTML tags I want to keep</li>
<li>After the tags have been converted, run the text through the sanitizer and remove any tags I do not require.</li>
<li>After that, remove any tags that have either id's or classes inside them</li>
<li>Finally convert the tags back. </li>
</ol>
<p>My code is below, and it would be much appreciated if someone with more experience can have a look over it and give me some feedback.</p>
<pre><code>string txt = "<h1>Keep as sanitizer removes</h1><p>keep</p><p class=\"remove\">remove class</p><br/><script>remove</script>";
var whiteList = new List<Word>();
whiteList.Add(new Word() { SearchWord = "<p>", ReplaceWord = "&lt;p&gt;" });
whiteList.Add(new Word() { SearchWord = "</p>", ReplaceWord = "&lt;/p&gt;" });
whiteList.Add(new Word() { SearchWord = "<h1>", ReplaceWord = "&lt;h1&gt;" });
whiteList.Add(new Word() { SearchWord = "</h1>", ReplaceWord = "&lt;/h1&gt;" });
whiteList.Add(new Word() { SearchWord = "<br/>", ReplaceWord = "&lt;br/&gt;" });
whiteList.ForEach(w => txt = txt.Replace(w.SearchWord, w.ReplaceWord));
var remove = Sanitizer.GetSafeHtmlFragment(txt);
whiteList.ForEach(w => remove = remove.Replace(w.ReplaceWord, w.SearchWord));
var again = RegexHelpers.StripHtmlAttributes(remove);
var tt = again;
public static string StripHtmlAttributes(string s)
{
const string pattern = @"\s.+?=[""'].+?[""']";
var result = Regex.Replace(s, pattern, string.Empty);
return result;
}
</code></pre>
|
[] |
[
{
"body": "<p>You could simplify the declaration of the tags you want to keep, as it is very structured:</p>\n\n<pre><code>var whitelist = new List<string>(new string[] { \"p\", \"h1\", \"br\" });\n\nforeach (var w in whitelist) {\n txt = txt.Replace(\"<\" + w + \">\", \"&lt;\" + w + \"&gt;\")\n .Replace(\"<\" + w + \"/>\", \"&lt;\" + w + \"/&gt;\"));\n}\n\nvar remove = Sanitizer.GetSafeHtmlFragment(txt);\n\nforeach (var w in whitelist) {\n remove = remove.Replace(\"&lt;\" + w + \"&gt;\", \"<\" + w + \">\")\n .Replace(\"&lt;\" + w + \"/&gt;\", \"<\" + w + \"/>\"));\n}\n\nvar again = RegexHelpers.StripHtmlAttributes(remove);\n\nvar tt = again;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T16:48:58.250",
"Id": "41163",
"ParentId": "41111",
"Score": "3"
}
},
{
"body": "<p>Apparently, in general a regex isn't the right tool to parse HTML. I'm not sure why that is, but the fact that ...</p>\n\n<p><a href=\"https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags#comment1612303_1732395\"><code><a href=\"foo\" title=\"5>3\"> Oops </a></code></a></p>\n\n<p>... is a valid tag might have something to do with it.</p>\n\n<p>Therefore, to parse HTML, some people recommend you use a tool like <a href=\"http://htmlagilitypack.codeplex.com/\" rel=\"nofollow noreferrer\">Html Agility Pack</a>.</p>\n\n<hr>\n\n<p>Your code looks safe to me because of the way it's white-listing.</p>\n\n<p>But some specific problems with it include:</p>\n\n<ul>\n<li>You don't whitelist tags which have any attributes, e.g. <code><h1 id=\"foo\"></code></li>\n<li>Any <code>&gt;h1&lt;</code> in the original text will be converted to <code><h1></code></li>\n</ul>\n\n<p>To guard against the second problem, you might try to convert <code>&</code> to <code>&amp;</code> first, and then convert it back again.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T14:42:53.987",
"Id": "70952",
"Score": "0",
"body": "Hi ChrisW thanks for reply, this section of code StripHtmlAttributes(string s) removes all elements from tags so if <h1 id=\"foo\"> was entered, only <h1> would be returned Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T14:47:09.480",
"Id": "70955",
"Score": "0",
"body": "It seems to me that you're not calling StripHtmlAttributes until after you call `whiteList.ForEach(w => txt = txt.Replace` ... and therefore your replace will fail to replace any whitelisted elements which contain an attribute."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T16:57:46.143",
"Id": "70983",
"Score": "0",
"body": "Hi ChrisW thanks just tested again and I see what you mean, thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T20:17:38.533",
"Id": "71701",
"Score": "0",
"body": "Actually, parsing code like that using regular expressions is not a problem. The reason why HTML is not a regular language is nesting: you can't parse something like `<i><b><i>oops</i></b></i>` using regular expressions."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T17:50:31.123",
"Id": "41170",
"ParentId": "41111",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "41163",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T21:17:19.447",
"Id": "41111",
"Score": "2",
"Tags": [
"c#",
"regex"
],
"Title": "Whitelist HTML tags Microsoft Sanitizer and custom Regex"
}
|
41111
|
<p>I've got some pretty simple validation that I'm working on, but it seems like I'm repeating myself a bunch of times. There has to be a better way of doing this. I'm simply checking if there is a value filled in for specific fields and apply a color if the value isn't filled in. There are also other areas where the validation is different where I'm checking a valid phone number. So I couldn't simply apply this to all inputs. Here's some of my code:</p>
<pre><code>var x = $();
var pass = true;
function validateForm(){
x = $('input#zip').val();
if (x == null || x == "") {
$('#ziplabel').css('color','#fff');
pass = false;
} else {
$('#ziplabel').css('color','#444');
}
x = $('input#fname').val();
if (x == null || x == "") {
$('#fnamelabel').css('color','#fff');
pass = false;
} else {
$('#fnamelabel').css('color','#444');
}
x = $('input#lname').val();
if (x == null || x == "") {
$('#lnamelabel').css('color','#fff');
pass = false;
} else {
$('#lnamelabel').css('color','#444');
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Yup, you can iterate the input fields. For this sort of thing you should also be using classes, instead of inline CSS. Using jQuery <code>.each</code> and <code>.togggleClass</code> you can create something like this: </p>\n\n<pre><code>function validate () {\n\n $('#form input').each(function () {\n var $el = $(this)\n $el.prev('label').toggleClass('invalid', $el.val()); \n });\n\n}\n</code></pre>\n\n<p>And your stylesheet has a rule like this;</p>\n\n<pre><code>label {\n color: #444;\n}\n\nlabel.invalid {\n color: #fff;\n}\n</code></pre>\n\n<p>If you want to check if the form was valid then you can check for the existence of a field with that class. <code>$('#form input.invalid').length</code>. Or you can set a boolean in the each function if you want to separate the logic from the HTML.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T04:46:02.607",
"Id": "70563",
"Score": "1",
"body": "You could avoid the caching line if you use `$(this).prev('label').toggleClass('invalid',this.value)`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T21:29:11.567",
"Id": "41114",
"ParentId": "41112",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "41114",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T21:22:23.390",
"Id": "41112",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "Checking for a value on selectors"
}
|
41112
|
<p>I wrote this code to clean up some of the space on our file server. We've got 15 years of legacy data that nobody accesses or changes or cares about that we have to keep regardless. I'd rather have it not sitting on our main file server so that I don't have to add an additional TB to it annually. This script goes through the file structure, finds files that haven't been touched in 4 years and copies them to slower storage, then replaces the source file with a symlink. </p>
<p>I'm new to PowerShell, so any pointers regarding style or a better way to do things would be nice. I know that my way of bracing things is wrong and that closing curly braces should be indented one less level, but I don't care and find this easier to deal with.</p>
<pre><code>param(
[string]$Dir = "",
[string]$ArchiveDrive = ""
)
if ($ArchiveDrive -eq ""){
$hostname = hostname
$ArchiveDrive = "\\Archives\"+$hostname+"\"+$Dir[0]+"\"
}
import-module PSCX
import-module new-symlink
$FileList = @()
$SourceDrive = $dir[0] + ":\"
$date = Get-Date -Format yyyy-MM-dd
$ErrLog = "C:\ErrorLog $date.txt"
$DelLog = "C:\DelLog $date.txt"
$PathWarning = "C:\_PROBLEMS DETECTED.txt"
function BuildLists($dir){
$FileList = @()
$DirList = (dir $dir -recurse)
foreach ($item in $DirList){
if ( ((get-date).Subtract($item.LastWriteTime).Days-gt 1460) -eq $True) {
$FileList += $item
}
#else {write-host "$item is modified recently"}
}
return $FileList
}
function CheckPathLength($file){
if ($File.FullName.Length -ge 220){
copy $PathWarning $File.DirectoryName}
}
function ArchiveFile($SourceFile){
$DestFile = ($SourceFile.fullname.replace($SourceDrive, $ArchiveDrive))
$DestDir = ($SourceFile.DirectoryName.replace($SourceDrive, $ArchiveDrive))
mkdir -Path $DestDir 2>$ErrLog
copy $SourceFile.FullName $DestFile
}
function HashCheckFile($SourceFile){
$DestFile = $SourceFile.FullName.replace($SourceDrive, $ArchiveDrive)
$SourceHash = get-hash($SourceFile.fullname)
$DestHash = get-hash("$DestFile")
return $SourceHash.HashString -eq $DestHash.HashString
}
function DeleteFIle($File){
del $file.fullname
}
function LinkFile($Sourcefile){
$SourceFilePath = $Sourcefile.fullname
$DestFile = ($sourcefilepath.replace($SourceDrive, $ArchiveDrive))
New-Symlink -path $DestFile $SourceFile.fullname -file 1>$errlog
}
function CheckPathLength($file){
if ($File.FullName.Length -ge 220){
copy $PathWarning $File.DirectoryName}
}
function ReplicateFile($file){
if ($file.Attributes -eq "Directory"){continue}
ArchiveFile($File)
if (HashCheckFile($File)){
DeleteFile($File)
LinkFile($File)
}
}
function Archive($FileList){
foreach ($File in $FileList){
CheckPathLength($file)
ReplicateFile($File)
}
}
function RunArchiving($dir){
$FileList = BuildLists($dir)
Archive($FileList)
}
function UnArchive(){}
RunArchiving($dir)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T22:44:31.643",
"Id": "71192",
"Score": "0",
"body": "Well, on the off chance that someone wants to use this code, or looks at it later I've updated it to address a few of the issues that we experienced while running this. You'll also need to update remote computers to follow remote symlinks to remote paths. This can be done by doing `fsutil behavior set SymlinkEvaluation r2r:1` and verified by doing `fsutil behavior query SymlinkEvaluation` at an admin prompt, or via GPO (**Computer Config>Policies>Admin Templates>System>FileSystem>Selectively allow the evaluation of a symbolic link**)."
}
] |
[
{
"body": "<p>Not bad at all. Nice to see functions but perhaps you have too many.</p>\n\n<p>Do you really need this as a function? </p>\n\n<pre><code>function DeleteFIle($File){\n del $file.fullname \n}\n</code></pre>\n\n<p>This function is listed twice but is only called once. It could have probably stayed in the Archive function.</p>\n\n<pre><code>function CheckPathLength($file){\n if ($File.FullName.Length -ge 220){\n copy $PathWarning $File.DirectoryName\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-06T19:12:22.283",
"Id": "52654",
"ParentId": "41113",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T21:24:50.937",
"Id": "41113",
"Score": "5",
"Tags": [
"beginner",
"windows",
"powershell"
],
"Title": "Script which migrates files to secondary storage and symlinks them"
}
|
41113
|
<p>I wrote this prototype after reading the Wikipedia article on hooking. I didn't bother to read any of the code examples listed there because, well, I just didn't. I don't have a good excuse.</p>
<p>The documentation in this file should tell you enough about its purpose and intended usage. I'm looking for a confirmation of whether I even understand what hooks are and how they should be used. I'm also curious about any sort of preferred method of implementation or any way that I could improve these two objects (<code>Hook</code> and <code>OnHook</code>).</p>
<pre><code>"""Implement hooks with a simple interface using decorators.
The Hook class creates a function that can be placed in code as an
anchoring point for as yet undetermined functionality, while the
OnHook function creates the interface to that functionality.
To create a hook, use the @Hook decorator on an empty function of
your chosen name. The function's __call__ method will be generated
by the decorator. Then, create a function that accepts a function
as an argument and adds it to the targets callback by using @OnHook.
OnHook expects the target hook as an argument.
Example:
@Hook # decorator, no args
def my_hook(): pass # empty func, no params
@OnHook(my_hook) # decorator, hook as arg
def on_my_hook(func): pass # empty func, func as param
To add a callback to the new hook, use:
on_my_hook(my_callback)
When the hook is executed, your callback will be executed along with
any other callbacks that have been registered.
Written 2014-02-02 by Jack Stout.
"""
class Hook:
"""Decorator to create a hook."""
def __init__(self, func):
self.callbacks = []
def __call__(self):
for callback in self.callbacks:
callback()
def OnHook(target):
"""Decorator to create an interface to a hook.
Requires a target hook as only argument.
"""
def decorator(func):
def add_callback(func):
target.callbacks.append(func)
return add_callback
return decorator
# Here I've created two hooks with interfaces which would be used
# immediately before and after a hypothetical initiative() function.
@Hook
def pre_initiative(): pass
@OnHook(pre_initiative)
def on_pre_initiative(func): pass
@Hook
def post_initiative(): pass
@OnHook(post_initiative)
def on_post_initiative(func): pass
# Two dummy functions are created and are added to the hooks' callback lists.
def dummy_func_1():
print("Inside pre_initiative!")
on_pre_initiative(dummy_func_1)
def dummy_func_2():
print("Inside post_initiative!")
on_post_initiative(dummy_func_2)
# These print functions reveal what has been registered in the hook.
print(pre_initiative.callbacks)
# This function call is what we would see in production code.
pre_initiative()
print(post_initiative.callbacks)
post_initiative()
</code></pre>
<p><strong>Less important but related:</strong></p>
<p>This is a prototype but I'm working on a game project that could benefit from this method of quickly attaching function pointers to upcoming state changes. While working on this file, I was imagining the first phase in a tabletop combat encounter where the players and game master roll initiatives and determine the combat order. If a character were to gain a power that allowed them to adjust their initiative roll after everyone has rolled, it would require only a call to <code>on_post_initiative(power_name)</code>. When <code>initiative()</code> completes, <code>post_initiative()</code> would fire and execute <code>power_name()</code>.</p>
<p>Before getting any feedback, if I were to revisit this code I would add the ability to include arguments to be used with the callback, i.e. <code>on_post_initiative(power_name, character_name)</code>.</p>
|
[] |
[
{
"body": "<p>This appears to be an implementation of something akin to the <a href=\"http://en.wikipedia.org/wiki/Observer_pattern\" rel=\"nofollow\">observer pattern</a>. Your implementation is straightforward enough, but there are two things that jump out at me.</p>\n\n<p>First, I'm surprised that this involves two top-level decorators? I think I would rather see a pattern similar to what <a href=\"http://docs.python.org/3/library/functions.html#property\" rel=\"nofollow\"><code>property</code></a> provides. Namely, rather than exposing both <code>@Hook</code> and <code>@OnHook</code>, make <code>@Hook</code> add an attribute to the function that can itself, as a decorator, hook other functions to the first (implementation left as an exercise):</p>\n\n<pre><code>@Hook\ndef pre_initiative(): pass\n\n@pre_initiative.when_called # or preferred name\ndef dummy_func_1(): print(\"pre-initiative!\")\n</code></pre>\n\n<p>Second, I'm a little confused about your larger use case. Do hooks have a chance to change the inputs or outputs of the hooked function? Are you working on this project with other people who may be more used to some particular approach? (If so, it's easier for them to work with if it matches the approach they expect.) Are these phases easier to implement as functions called on an instance or a subclass?</p>\n\n<pre><code>class Player:\n def pre_initiative(self): pass\n def post_initiative(self): pass\n\ndef encounter(players):\n for player in players:\n player.pre_initiative()\n for player in players:\n player.post_initiative()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T16:28:47.303",
"Id": "70740",
"Score": "0",
"body": "You've left me plenty to study. After some reading, it looks like you're exactly right in nesting `OnHook` within the object returned by `Hook`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T16:32:53.280",
"Id": "70742",
"Score": "0",
"body": "As for using this in my current project: It seems like a reasonable method of modifying game state without modifying any code within the game. I'll be able to drop resources into a folder and link them into whichever code I need to. In this case, I'll only add hooks as the need arises, but can do so without putting the code at risk."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T02:47:10.813",
"Id": "41201",
"ParentId": "41115",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T21:38:59.740",
"Id": "41115",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"callback",
"meta-programming"
],
"Title": "Hooking with Python3 Decorators"
}
|
41115
|
<p>I am creating a blog concept with this layout on <a href="http://codepen.io/JGallardo/pen/tfFCL" rel="nofollow noreferrer">CodePen</a></p>
<p><img src="https://i.stack.imgur.com/ML3eu.png" alt="screenshot"></p>
<p>Here is my current code in development</p>
<pre><code><article class="post">
<h2>Skating Down Venice Beach</h2>
<img src="http://s1.favim.com/orig/20/skate-skateboard-skinny-jeans-vans-Favim.com-205640.jpg">
<a href="#" class="readMore">
<i class="fa fa-list-ul"></i>
</a>
<div class="hide">
<h4>Venice Beach</h4>
<p>Literally trust fund Helvetica dreamcatcher selfies. Pinterest aesthetic organic Echo Park artisan meggings tousled Tumblr, Pitchfork gentrify raw denim yr you probably haven't heard of them banjo. Street art Wes Anderson ethnic ethical authentic, High Life swag ennui. Wolf cardigan fingerstache gentrify, PBR&B cray XOXO vegan deep v tote bag ethnic. Banh mi you probably haven't heard of them seitan meh Austin iPhone. High Life wolf Tonx, dreamcatcher lo-fi seitan ethnic pop-up fingerstache whatever. Trust fund Portland ethnic church-key, Tumblr squid hoodie dreamcatcher +1 seitan.</p>
</div>
</article>
</code></pre>
<p>When I move to production, I will use a MustacheJS template in Meteor. So was planning on this </p>
<pre><code><template name="posts">
<article class="post">
<h2>{{title}}</h2>
<img src="{{{imgUrl}}}">
<a href="#" class="readMore">
<i class="fa fa-list-ul"></i>
</a>
<div class="hide">
<h4>{{city}}</h4>
{{{content}}}
</div>
</article>
</template>
</code></pre>
<p>Is there any room for improvement here? for example, will I be better off using <code><li></code>s? or should I perhaps change anything else?</p>
|
[] |
[
{
"body": "<p>Your <code>img</code> is missing the <a href=\"http://www.w3.org/TR/2013/CR-html5-20130806/embedded-content-0.html#alt\" rel=\"nofollow\"><code>alt</code> attribute</a>.</p>\n\n<hr>\n\n<pre><code><a href=\"#\" class=\"readMore\">\n <i class=\"fa fa-list-ul\"></i>\n</a>\n</code></pre>\n\n<p>I assume that here a graphic will be inserted via CSS? Then this will not be accessible by users without CSS support, and it will probably not be accessible by screen reader and/or keyboard users. The link should have content, i.e., an <code>img</code> (with <code>alt</code> attribute) or text (\"Read more\") (which can be visually hidden, if required).</p>\n\n<p>Also, you shouldn’t use the <code>i</code> element in such a case (as your use doesn’t match <a href=\"http://www.w3.org/TR/2013/CR-html5-20130806/text-level-semantics.html#the-i-element\" rel=\"nofollow\"><code>i</code>’s definition</a>). Go with <code>span</code> if you need an element.</p>\n\n<hr>\n\n<p>Why did you skip a heading level (from <code>h2</code> to <code>h4</code>)? Either use <code>h3</code> for the second heading, or go with <code>h1</code> everywhere (but then you need to use sectioning elements explicitly!):</p>\n\n<pre><code><article>\n <h1>Skating Down Venice Beach</h1>\n\n <section>\n <h1>Venice Beach</h1>\n </section>\n</article>\n</code></pre>\n\n<p>If the text titled \"Venice Beach\" is just some general information about it (not unique to this image), consider to use the <a href=\"http://www.w3.org/TR/2013/CR-html5-20130806/sections.html#the-aside-element\" rel=\"nofollow\"><code>aside</code> element</a> instead of <code>section</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T02:32:46.293",
"Id": "70545",
"Score": "0",
"body": "`aside` instead of `section` ? I never used it. And i sued `i` because that is common with font awesome, but I will look into it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T02:35:46.623",
"Id": "70546",
"Score": "1",
"body": "@JGallardo: `i` is often used by icon fonts, yes, but I’d say they are all wrong (some say it sounds so nice: `i` → icon; others say it’s for saving bytes: 1 char in `i` vs. 4 chars in `span` … ha, ha). AFAIR Bootstrap did use `i` in previous version, too, but [now they go with `span`](http://getbootstrap.com/components/#glyphicons-how-to-use) (as they should! ;))."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T02:20:30.550",
"Id": "41124",
"ParentId": "41118",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "41124",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T22:34:42.410",
"Id": "41118",
"Score": "5",
"Tags": [
"html",
"meteor",
"mustache"
],
"Title": "Review of HTML markup for this blog concept"
}
|
41118
|
<p>Recently I am working on batch to make a very simple command line interface.</p>
<p>The code looks like this:</p>
<pre><code>@echo off
echo Simple command-line interface
echo.
:input.get
set /p input="COMMAND\>"
set input5=%input:~0,5%
if "%input%"=="something" goto something
if "%input5%"=="echo " goto echo
:echo
set content=%input:~5%
echo.%content%
goto input.get
:something
::do something
goto input.get
</code></pre>
<p>Is this really a good way to do it? I have posted a question about "How to check whether labels exist" in stack overflow, but if i input "echo hi" then it will be nearly impossible to check the tag.</p>
<p>Is it good to use both ways? (check whether label exist -> if not exist -> do "if" check)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T06:06:24.650",
"Id": "70572",
"Score": "0",
"body": "I'd change 'if \"%input5%\"==\"echo \" goto echo' to 'if not \"%input5%\"==\"echo \" goto input.err', and create an input.err subroutine that prompts the user to try again. What you have will lead to an unhelpful echo that doesn't let them know they did anything wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T09:52:43.670",
"Id": "70824",
"Score": "0",
"body": "if it is an infinite loop then the users cannot go back to main menu, and that will be a HUGE problem. restarting costs tile, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-21T16:20:35.313",
"Id": "135291",
"Score": "0",
"body": "A quick thing I would really do is change comments from `::` to `REM` . `::` was used for ending labels a while ago, but are no longer used for that. Using `REM` is much more acceptible. Hope I helped."
}
] |
[
{
"body": "<p>You can use a FOR /F to parse out the command from the arguments.</p>\n\n<p>I would define a variable containing a delimited list of all valid commands. Then you can use simple search and replace to validate whether the user entered command is valid.</p>\n\n<p>Addition of a new command is as easy as adding the command to the list, and creating a labeled subroutine for the new command.</p>\n\n<p>I would use CALL instead of GOTO so that each routine can easily parse the arguments. The only disadvantage is CALL will double up quoted carets (<code>\"^\"</code> becomes <code>\"^^\"</code>)</p>\n\n<p>Here is a basic framework that can easily be extended. Note that user entered <code>!</code> will be corrupted (or expanded) because of delayed expansion. There are simple ways to get around this limitation with additional code.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>@echo off\nsetlocal enableDelayedExpansion\necho Simple command-line interface\necho(\n\n:: Define all valid commands: make sure there is a space between each command\n:: and also one at beginning and end\nset \"commands= something echo exit \"\n\n:input.get\n\n:: Clear the existing value in case user hits <Enter> without entering anything\nset \"input=\"\n\n:: Get the next command\nset /p \"input=COMMAND\\>\"\n\n:: Parse command into command and arguments.\nfor /f \"tokens=1* delims= \" %%A in (\"!input!\") do (\n\n REM check if command is valid (not case sensitive) and act accordingly\n if \"!commands: %%A =!\" equ \"!commands!\" (\n echo Invalid command: %%A\n ) else if /i %%A equ exit (\n exit /b\n ) else (\n call :%%A %%B\n )\n)\necho(\ngoto input.get\n\n\n:something\necho Doing something with Arg1=[%1] and Arg2=[%2]\nexit /b\n\n:echo\necho(%*\nexit /b\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T11:10:29.747",
"Id": "71413",
"Score": "0",
"body": "I think it is good, however, i don't know NEARLY EVERYTHING about `for /f`. I know `for /l`,`for`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T22:39:29.443",
"Id": "41184",
"ParentId": "41121",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41184",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T00:44:09.023",
"Id": "41121",
"Score": "6",
"Tags": [
"batch"
],
"Title": "Making a .bat batch command-line interface"
}
|
41121
|
<p>I've tried to take the shortest, simplest path to a C# solution to the <a href="https://codereview.meta.stackexchange.com/questions/1471/weekend-challenge-reboot">Ultimate Tic-Tac-Toe challenge</a>. This implementation plays in the console. I admit the game logic could be hived off into a separate method, but I'm not sure that would be an improvement. I also admit that the fields should be tighter than <code>public</code>, but that's neither here nor there.</p>
<p>I would appreciate feedback on:</p>
<ol>
<li>How readable people find this solution;</li>
<li>Any suggestions to make the code more succinct;</li>
<li>Any other comments people would care to make.</li>
</ol>
<p></p>
<pre><code>void Main()
{
var mb = new MetaBoard();
var board = -1;
var player = Who.X;
while (WinFor(mb) == Who.Neither && mb.Boards.Any(x => WinFor(x) == Who.Neither)) {
mb.Write();
Console.WriteLine(player + " to play.");
// Choose a board if we've just started or the current board is finished.
while (board == -1 || mb[board] != Who.Neither) board = InputNum("an unfinished board");
var cell = -1;
// Choose an empty cell on the board.
while (cell == -1 || mb.Boards[board][cell] != Who.Neither) cell = InputNum("an empty cell on board " + (board + 1));
Console.WriteLine();
mb.Play(board, cell, player);
// The next board is decided by the cell just played. Swap turns between the players.
board = cell;
player = (player == Who.X ? Who.O : Who.X);
}
mb.Write();
Console.WriteLine(WinFor(mb) + " wins!");
}
static int InputNum(string what) {
var i = -1;
do {
Console.Write("Choose " + what + " [1-9]: ");
} while (!int.TryParse(Console.ReadLine().Trim(), out i) || i < 1 || 9 < i);
return i - 1;
}
enum Who { Neither, X, O }
static int[][] Lines = new int[][] {
new int[] {0,1,2}, new int[] {3,4,5}, new int[] {6,7,8},
new int[] {0,3,6}, new int[] {1,4,7}, new int[] {2,5,8},
new int[] {0,4,8}, new int[] {2,4,6}
};
interface IBoard { Who this[int i] { get; } } // Indicate who, if any, has won position i.
static Who Min(Who p, Who q) { return p == q ? p : Who.Neither; }
static Who WinFor(IBoard board) { // X if a line of three Xs, O if a line of three Os.
return Lines.Select(line => Min(board[line[0]], Min(board[line[1]], board[line[2]])))
.FirstOrDefault(who => who != Who.Neither);
}
class Board: IBoard { // A 3x3 grid of cells.
public Who[] Cells = new Who[9];
public Who this[int i] { get { return Cells[i]; } }
public void Play(int i, Who who) { Cells[i] = who; }
}
class MetaBoard: IBoard { // A 3x3 grid of boards.
public Board[] Boards = Enumerable.Range(0, 9).Select(i => new Board()).ToArray();
public Who this[int i] { get { return WinFor(Boards[i]); } }
public void Play(int i, int j, Who who) { Boards[i].Play(j, who); }
public void Write() {
Action<Who> writeCell = w => { Console.Write(w == Who.X ? 'X' : w == Who.O ? 'O' : '.'); };
var rg = Enumerable.Range(0, 3);
foreach (var rr in rg) foreach (var r in rg) foreach (var cc in rg) foreach (var c in rg) {
writeCell(Boards[cc + 3 * rr].Cells[c + 3 * r]);
if (c == 2) Console.Write(" ");
if (c == 2 && cc == 2) Console.WriteLine();
if (c == 2 && cc == 2 && r == 2) Console.WriteLine();
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>This doesn't strike me as particularly readable, although it is definitely succinct. Here are a few of the things I noticed that I think could be improved:</p>\n<ul>\n<li><p>The name <code>Min()</code> for a method that determines if someone has filled a row is very confusing.</p>\n</li>\n<li><p><code>WinFor()</code> should be a method on <code>IBoard</code> rather than a static method that takes an <code>IBoard</code>.</p>\n</li>\n<li><p>The variable names in <code>MetaBoard.Write()</code>are also confusing and something like <code>outerRow</code> and <code>innerColumn</code> would be more informative that <code>rr</code> and <code>c</code>.</p>\n</li>\n<li><p>The quadruple <code>foreach</code> loop in the <code>MetaBoard.Write()</code> scares me. I realize what it is doing, but that many nested loops is a <em>code smell</em>. You might want to create a method on <code>IBoard</code> that prints out board contents line-by-line so that you can append them to each other and control when you insert padding and newlines.</p>\n</li>\n<li><p>If you're going to do that, you may consider extracting out a <code>BoardPrinter</code> class or something similar to encapsulate that behavior.</p>\n</li>\n<li><p>The size of the board is hard-coded and although it isn't a requirement, redesigning this to support different-sized boards will make a more flexible design. (I got this idea in a review for <a href=\"https://codereview.stackexchange.com/questions/41038/\">my Ultimate Tic-Tac-Toe entry</a> and am happy I re-worked it).</p>\n<p>This will require removing <code>Lines</code> and calculating them manually. As a side note, indices for diagonals can be calculated by consecutively adding the <code>(board width + 1)</code> for downward-right and the <code>(board width - 1)</code> for downward-left diagonals. It took me a while to figure that out.</p>\n</li>\n<li><p>The use of <code>Board[]</code> as the type for the <code>MetaBoard.Boards</code> property indicates to me that the <code>IBoard</code> interface is not as useful as it should be (since <code>MetaBoard</code> is tightly coupled to <code>Board</code>). If you pull out the printing so that it can be done line-by-line as I suggested earlier, you could go back to using <code>IBoard</code>. If done carefully, you could nest <code>MetaBoard</code>s within <code>MetaBoard</code>s (for the <strong>Ultimate</strong> in Ultimate Tic-Tac-Toe).</p>\n</li>\n<li><p>I don't see where you restrict players from selecting an already completed board.</p>\n</li>\n</ul>\n<p>I know I'm basically ruining the brevity if you implement my comments, but I am impressed with how you managed to keep it so short. It was fun to review, thanks for sharing!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T03:08:28.647",
"Id": "70549",
"Score": "0",
"body": "many thanks for your comments. Just a few notes in response. `WinFor` is generic across `IBoard`s, there's no need to reproduce that code on a per-instance or a per-class basis (I'm more of a functional programmer, so my style is a bit different from your usual OO type). `MetaBoard.Write` *is* very tight; there's a sweet-spot trade-off between brevity and verbosity -- here I'm trying to channel the likes of K&R. I certainly could (easily) generalise the board size and game depth, but that would violate my principle of heading straight for the target."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T03:13:28.703",
"Id": "70550",
"Score": "0",
"body": "Two more points in response. `IBoard` is exactly what you need if you're going to generalise this to meta-meta-tic-tac-toe, etc. At the top-level you do need to know the depth of the game because you potentially have to select boards all the way down! The condition preventing the user from selecting an already completed board is `while (... || mb[board] != Who.Neither) board = InputNum(...)`. `mb[board]` denotes who, if anybody, is the winner of `board`. Thanks again!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T02:42:44.867",
"Id": "41125",
"ParentId": "41123",
"Score": "8"
}
},
{
"body": "<p>I have fully embraced Clean Code's goal of five-line methods, and my life of reading code has absolutely improved as a result. Right at the start I see this and am stumped:</p>\n\n<pre><code>while (WinFor(mb) == Who.Neither && mb.Boards.Any(x => WinFor(x) == Who.Neither)) {... \n</code></pre>\n\n<p>This is begging for</p>\n\n<pre><code>while (noOneHasWon() && noOneHasWonAnyBoard())... \n</code></pre>\n\n<p>Now clearly the second method name is not correct because you don't end the game with the first miniboard win. \nBut that's the beauty of extracting methods: incomprehensible code and possibly incorrect comments are replaced with easily-refactored method names. Mistakes in reading and coding are more readily apparent because they lie closer together.</p>\n\n<p>Doing that for every three-to-five lines of code allows you to delete all those incorrect and misleading comments while improving readability. Yes, the code might be a little longer, but it will be much faster to read and verify.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T04:24:59.263",
"Id": "70560",
"Score": "0",
"body": "Hi David, agreed: I am guilty of not taking that procedure very seriously here. When you mention \"incorrect and misleading comments\" are you referring to my comments or commenting in general?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T04:41:04.937",
"Id": "70562",
"Score": "1",
"body": "@Rafe Commenting in general. The compiler will complain if you change a method name without fixing all calls to it, but it won't if your comments become incorrect. Granted, it won't complain if a method implementation no longer matches it's name, but that's far easier to keep in sync than comments IMHO."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T04:54:15.363",
"Id": "70567",
"Score": "0",
"body": "absolutely, but comments are the ideal place to describe *intention*."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T07:34:38.693",
"Id": "70578",
"Score": "0",
"body": "Regarding the line above: I believe you have not taken into consideration the posibility of a tie!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T09:53:49.597",
"Id": "70589",
"Score": "2",
"body": "@Rafe Yes! The code describes what and how and when; comments cover who and why. ;)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T03:38:01.853",
"Id": "41128",
"ParentId": "41123",
"Score": "8"
}
},
{
"body": "<p>As the other commenters have noted, the solution is pretty decent but could be more readable. I won't reiterate the points made by others already. A few short points:</p>\n\n<ul>\n<li><p><code>new int[] {0,1,2},</code> and so on can be made less verbose. <code>new[] {0, 1, 2}</code> is legal since C# 3. The type of the array will be inferred from the contents.</p></li>\n<li><p>Suppose I told you that I wrote a program with variables <code>r</code>, <code>rr</code>, <code>c</code> and <code>cc</code>. What would you suppose that program does? Any clue? Me neither.</p></li>\n<li><p>I don't like the <code>IBoard</code> abstraction. The game is simple enough to not require an interface and a hierarchy. Your comment about generalizing to higher levels of meta-ness is a great example of premature design for generality. An excess of generality can impede understanding, is expensive to implement, and can impede the ability to edit the code later. YAGNI -- You Ain't Gonna Need It -- so don't implement it.</p></li>\n<li><p>Questions (\"who?\") are not great names for types. \"Player\" would be better.</p></li>\n<li><p>Consider using nullables to represent quantities that can be invalid values, rather than magic constants like -1. (Though keep in mind if you do that it can be unclear whether null means \"has a valid value but I don't know what it is\" and \"has no valid value at all\". Is null more like \"the sales figures for November, which are a specific value, I just don't know what it is\" or \"the name of the present king of France\"?)</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T06:39:27.590",
"Id": "70575",
"Score": "0",
"body": "thanks for your comments. Re: `rr` etc., they're just small-context iteration variables; I guess `metaRow`, `row`, etc. might be better names. Had there just been `r` and `c` in this context, would that still be confusing? Definitely agree on `IBoard`, looking again at my code: it takes up way more space than it saves. Re: nullables, I did consider them. I do wish it were possible to use general algebraic data types in C#: `null`s are horrid and, often, objects are too clumsy."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T06:24:51.550",
"Id": "41132",
"ParentId": "41123",
"Score": "8"
}
},
{
"body": "<h2>Bugs:</h2>\n\n<p>If we have a <strong>tie</strong> one of the <code>Borads</code> the game will accept/force me to play on it even if all cells are occupied.\nAlso the game won't finish if all broads are finished but there is at least one tie board on the <code>MetaBoard</code>. So there should be a distinction between unfinished board and tied board.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T07:47:18.307",
"Id": "41137",
"ParentId": "41123",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T01:10:45.140",
"Id": "41123",
"Score": "14",
"Tags": [
"c#",
"game",
"tic-tac-toe",
"community-challenge"
],
"Title": "Tic-Tactics implementation"
}
|
41123
|
<p>Instead of creating an Admin_Controller or MY_Controller I was going to try and just try out all my controllers on requirements that are needed per controller. I know this may seem like additional work but then after which I want to go back and fix it all. I wanted to know how my login looks as of right now?</p>
<p>I'm getting shocked that I've had 56 view and 3 upvotes and not one comment on the code at least.</p>
<pre><code><?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Login extends Admin_Controller
{
public function __construct()
{
parent::__construct();
$this -> load -> model('user_login_model', 'login');
$user_id = $this->session->userdata('user_id');
if ($user_id == TRUE)
{
if (is_numeric($user_id) && strlen($user_id) < 5)
{
$this->session->unset_userdata('user_id');
$this->session->sess_destroy();
current_url();
}
else
{
redirect('dashboard', 'refresh');
}
}
}
public function index()
{
$this -> template -> set_theme('saturn') -> set_layout(FALSE) -> build('admin/login');
}
public function process()
{
$output_array = $this -> general_functions -> get_default_output();
$this -> form_validation -> set_rules('email_address', 'Email Address', 'trim|required|xss_clean|valid_email');
$this -> form_validation -> set_rules('password', 'Password', 'trim|required|xss_clean|min_length[6]|max_length[12]|regex_match[/[a-z0-9]/]');
$this -> form_validation -> set_rules('remember_me', 'Remember Me', 'trim|xss_clean|integer');
if ($this -> form_validation -> run() == FALSE)
{
$output_array['data_array']['title'] = 'Form Validation Failed';
$output_array['data_array']['message'] = 'The form failed to validate. Please fix the errors and try again.';
}
else
{
$user_login_data = $this -> login -> get_by('email_address', $this -> input -> post('email_address'));
if (is_array($user_login_data) && count($user_login_data) <= 0)
{
$output_array['data_array']['title'] = 'User Not Found';
$output_array['data_array']['message'] = 'The user was not found in the database.';
}
else
{
if ($user_login_data -> user_status_id == 0)
{
$output_array['data_array']['title'] = 'User Not Verified';
$output_array['data_array']['message'] = 'The user has registered but has not validated their account.';
}
elseif ($user_login_data -> user_status_id == 900)
{
$output_array['data_array']['title'] = 'User Suspended';
$output_array['data_array']['message'] = 'The user account is current suspended.';
}
elseif ($user_login_data -> user_status_id == 901)
{
$output_array['data_array']['title'] = 'User Banned';
$output_array['data_array']['message'] = 'The user account is banned.';
}
elseif ($user_login_data -> user_status_id == 909)
{
$output_array['data_array']['title'] = 'User Pending Deletion';
$output_array['data_array']['message'] = 'The user account is pending deletion.';
}
elseif ($user_login_data -> user_status_id == 999)
{
$output_array['data_array']['title'] = 'User Deleted';
$output_array['data_array']['message'] = 'The user account was deleted.';
}
else
{
if (strtotime($user_login_data -> lock_date) > 0)
{
if (strtotime(gmdate('Y-m-d H:i:s', time())) < strtotime($user_login_data -> lock_date))
{
$output_array['data_array']['title'] = 'User Locked';
$output_array['data_array']['nessage'] = 'The user is locked out of their account.';
}
else
{
$this -> login -> update($user_login_data -> user_id, array('lock_date' => '0000-00-00 00:00:00'));
$this -> process();
}
}
else
{
$regenerated_post_password = $this -> general_functions -> regenerate_password_hash($this -> input -> post('password'), $user_login_data -> password_hash);
$failed_logins = $this -> session -> userdata('failed_logins');
if ($failed_logins == FALSE)
{
$this -> session -> set_userdata('failed_logins', 0);
$failed_logins = 0;
}
if ($regenerated_post_password !== $user_login_data -> password)
{
if ($failed_logins >= 0 && $failed_logins < 5)
{
$failed_logins++;
$this -> session -> set_userdata('failed_logins', $failed_logins);
$output_array['data_array']['title'] = 'Inccorect Login Credentials';
$output_array['data_array']['message'] = 'You supplied the wrong username and password combination.';
}
else
{
$this -> login -> update($user_login_data -> user_id, array('lock_date' => gmdate('Y-m-d H:i:s', time() + (60 * 15))));
$output_array['data_array']['title'] = 'User Locked';
$output_array['data_array']['message'] = 'The user is locked out of their account. Your account is currently locked, we apologize for the inconvienence. You must wait 15 minutes before you can log in again! An email was sent to the owner of this account. Forgotten your username or password? <a href="forgotusername">Forgot Username</a> or <a href="forgotpassword">Forgot Password</a>';
}
}
else
{
$this -> session -> unset_userdata('failed_logins');
$this -> session -> set_userdata('user_id', $user_login_data -> user_id);
$output_array['status'] = 'success';
$output_array['data_array']['title'] = 'Login Validated';
$output_array['data_array']['message'] = 'You have successfully logged in and will be redirected to the dashboard.';
}
}
}
}
}
$this -> general_functions -> publish_output($output_array['status'], $output_array['data_array'], NULL, NULL, 'json', TRUE);
}
}
</code></pre>
<p>Any thoughts? I'm looking for a few suggestions.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T12:42:55.110",
"Id": "70927",
"Score": "1",
"body": "Heres a comment.. maybe the up votes are indicative that the code looks fine and no one sees a real problem here, and like wise no one sees a point in commenting cause it look fine, why fix whats not broken? Maybe.."
}
] |
[
{
"body": "<ol>\n<li><p>Formatting is not consistent:</p>\n\n<blockquote>\n<pre><code>$this -> load -> model('user_login_model', 'login');\n$user_id = $this->session->userdata('user_id');\n</code></pre>\n</blockquote>\n\n<p>Sometimes there are spaces around <code>-></code>, sometimes aren't.</p></li>\n<li><p>You could use a <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">guard clause</a> to make the code flatten:</p>\n\n<pre><code>$user_id = $this->session->userdata('user_id');\nif ($user_id != TRUE)\n{\n return;\n}\nif (is_numeric($user_id) && strlen($user_id) < 5)\n{\n $this->session->unset_userdata('user_id');\n $this->session->sess_destroy();\n current_url();\n}\nelse\n{\n redirect('dashboard', 'refresh'); \n} \n</code></pre>\n\n<p>It would help a lot to make it easier to read the <code>process</code> function. (You should extract a few functions there too.)</p></li>\n<li><blockquote>\n<pre><code>current_url();\n</code></pre>\n</blockquote>\n\n<p>It's not clear what does this function do. Does it get the current url? Log it? Modify it? Its name should contain an action, like <code>doSomething</code>.</p></li>\n<li><p>Instead of magic numbers like <code>0</code>, <code>900</code>, <code>901</code> etc. you should use named constants which describe their purpose. It would be easier to read.</p></li>\n<li><blockquote>\n<pre><code>$this -> general_functions -> publish_output($output_array['status'], $output_array['data_array'], NULL, NULL, 'json', TRUE);\n</code></pre>\n</blockquote>\n\n<p>I would create local variables for the two <code>NULL</code> values and the <code>TRUE</code> value too to explain their intent. It would make the code readable and don't force readers to check the parameters of the <code>publish_output</code> function.</p>\n\n<p>(<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G19: Use Explanatory Variables</em>; <em>Refactoring: Improving the Design of Existing Code by Martin Fowler</em>, <em>Introduce Explaining Variable</em>)</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T21:31:07.433",
"Id": "44618",
"ParentId": "41127",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T03:34:05.230",
"Id": "41127",
"Score": "5",
"Tags": [
"php",
"codeigniter",
"authentication"
],
"Title": "Codeigniter Login Controller"
}
|
41127
|
<ol>
<li><p>I saw somewhere on here that it helps reduce spam by adding a dummy input field that you hide with <code>display: none</code>, and like if it's filled out, then it's obviously a bot sending the message. Well, I did something kind of like that but initially set it to <code>= 0</code>. So if it's not <code>0</code> then it doesn't send the form, since a bot would have changed the value to something else. I don't know if that will really work effectively or not. If you have a better way to do something like that, please share.</p></li>
<li><p>I don't know if my token validation stuff is anywhere close to how it should be. Please let me know if what I'm doing with that is even adding any security or not. </p></li>
<li><p>After the user submits the form, I put some echo's in so that what they entered is still shown in the form fields, in case there was an error so they don't lose what they typed. Is my use of <code>htmlspecialcharacters</code> needed there?</p></li>
</ol>
<p>Please share any other comments, recommendations, improvements, etc, etc that you see with my code, because I really want to get better at this and your answers almost always help me understand things better. You know, the manual can be kind of confusing at times when your new so having a master coder review your code and explain things helps so much for me.</p>
<pre><code><?php
session_start();
function getIp() {
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
if($_POST['yourlastname'] === '0') {
if ($_SESSION['token1'] == $_POST['token']) {
echo "<p>checker: " . $_SESSION['token1'] . " and the post token " . $_POST['token'] ."</p>";
if(filter_var($_POST['youremail'], FILTER_VALIDATE_EMAIL)) {
$name = htmlspecialchars($_POST['yourname']);
$email = htmlspecialchars($_POST['youremail']);
$from = $name . ' - ' . $email;
$ip = getIp();
$message = htmlspecialchars($_POST['yourmessage']) . "\r\n" .
'Name : ' . $name . "\r\n" .
'Email : ' . $email . "\r\n" .
'User IP: ' . htmlspecialchars($ip);
$message = wordwrap($message, 60, "\r\n");
$headers = 'From: ' . $from . "\r\n" .
'Reply-To: ' . $email;
mail('email@example.com', 'Static Subject', $message, $headers);
}
}
}
$token1 = md5(microtime(true));
$_SESSION['token1'] = $token1;
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tittle</title>
</head>
<body>
<?php $token2 = md5(microtime(true)); ?>
<form method="post" name="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<input name="token" type="hidden" value="<?php echo htmlspecialchars($token2); ?>">
<label for="yourname">Your Name:</label>
<input class="required" id="yourname" name="yourname" type="text" value="<?php if(isset($_POST['yourname'])) { echo htmlspecialchars($_POST['yourname']); } ?>">
<label for="yourlastname" style="display: none;">Your Last Name:</label>
<input class="required" id="yourlastname" name="yourlastname" type="text" style="display: none;" value="0">
<label for="youremail">Your Email:</label>
<input class="required" id="youremail" name="youremail" type="text" value="<?php if(isset($_POST['youremail'])) { echo htmlspecialchars($_POST['youremail']); } ?>">
<label for="yourmessage">Your Message:</label>
<textarea class="required" id="yourmessage" name="yourmessage" cols="30" rows="8"><?php if(isset($_POST['yourmessage'])) { echo htmlspecialchars($_POST['yourmessage']); } ?></textarea>
<input type="submit" id="send" value="Send">
</form>
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T14:14:33.617",
"Id": "70612",
"Score": "0",
"body": "1. I don't think this will be particularly effective security. I wouldn't be surprised if automated tools simply recognize hidden fields and not touch them. You might want to look into hooking up to the Akismet API, which is the system used in Wordpress to filter comment spam."
}
] |
[
{
"body": "<p>Right, I'll be adding to this answer later on, but for a kick-off, here's a few quick remarks/considerations:</p>\n\n<p><strong>On the hidden input fields</strong><br>\nAs Martijn said in his comment: most bots will probably parse the DOM, and filter out those fields that are marked as required (looking for labels with a <code>*</code> text node in them), and they'll simply ignore hidden fields. You've created regular input fields that are not displayed. That might work on <em>some</em> bots, but like I said, they'll probably parse the DOM and see that they have a <code>style</code> attribute that sets the display to none.<br>\nIt's not hard to deal with that, and if I were to write a bot, it wouldn't take me 5 minutes to add the code to deal with those input fields, too.</p>\n\n<p>You can keep those hidden input fields as a means of security (they don't do any harm, after all), but don't set their style attributes in the markup, use CSS classes, or better still: use JavaScript to set class/attributes on the load event. That way, the DOM doesn't reflect what the page will actually look like as much as it does now.<br>\nThis may help a little, but all in all, this will only protect you from script-kiddies and amateurish attacks.</p>\n\n<p><strong>The token stuff</strong><Br>\nThat's fine. Session tokens that should be posted back are basic security steps that everybody <em>should</em> take. How you get those tokens is up to you, but an <code>md5</code> of the timestamp? A hash doesn't make your token more secure. Don't go thinking that <code>md5</code> does anything else than add overhead, however minor it may be.<br>\nOf course I get that a hash string just makes the token look more important, and in a way less random than it actually is, but why not hash some of the clients data in that case, like the remote address or referrer or whatever... though far from reliable, it <em>can</em> give you something extra to check, and log, and compare to the access logs of your server. It may also give you a clue as to what tools are being used when your page is targeted.</p>\n\n<p>However, you should add checks along the lines of <code>if (isset($_POST['yourlastname']))</code> and <code>isset($_SESSION['token1'])</code>, to ensure that you <em>can</em> actually validate the form submission. But that's as an asside.</p>\n\n<p><strong>htmlspecialchars</strong><Br>\nIs it needed? <strong><em>NO</em></strong>. In fact, they're capable of doing more harm than good in some cases. Particularly when they're applied to the email address, as you seem to be doing. You're using <code>filter_var($email, FILTER_VALIDATE_EMAIL)</code>, which is great, because that filter can handle the complex and wacky email addresses <em>can contain htmlspecial chars, including: <code><</code></em>. Here's what I'd do:</p>\n\n<pre><code>$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);//sanitize\nif (filter_var($email, FILTER_VALIDATE_EMAIL))\n //continue\n</code></pre>\n\n<p>As far as the sanitation of the other data that'll make-up your email message is concerned: set the MIME type to text,because it would appear that that's all you need, and take measures against email injection.<br>\nA subject I've already discussed <a href=\"https://codereview.stackexchange.com/questions/36330/critique-sanitized-user-email-php-script/36354#36354\">in my answer here</a></p>\n\n<p><strong><em>Code issues</em></strong><br>\nJust a quick update of my answer. On second glance, I may have spotted an issue with your code that could sometimes result in your script treating a valid form submission as an invalid one:</p>\n\n<pre><code>$token1 = md5(microtime(true));\n$_SESSION['token1'] = $token1;//set token, then:\n?>\n<!DOCTYPE html>\n<html>\n<!-- setting HTML... -->\n<?php $token2 = md5(microtime(true)); ?>\n<form method=\"post\" name=\"form\" action=\"<?php echo htmlspecialchars($_SERVER[\"PHP_SELF\"]); ?>\">\n\n<input name=\"token\" type=\"hidden\" value=\"<?php echo htmlspecialchars($token2); ?>\">\n</code></pre>\n\n<p>The token value set in your form is a different variable than the one you've assigned to <code>$_SESSION['token']</code>! Why? The chances that the values of <code>$token1</code> and <code>$token2</code> are different are really quite high.<br>\nWhy aren't you simply using <code>$token1</code> in the form, too?</p>\n\n<p>Next: <code>htmlspecialchars</code>? What's the point? <code>$token1</code> and <code>$token2</code> both are hash strings, which are all <code>[a-z0-9]</code> chars, to put it in regex terms. They don't need escaping, so this function call (which adds overhead) can, and should be dropped.</p>\n\n<p>Also note that you don't have to specify the <code>action</code> attribute for the form, if the target is <code>$_SERVER['PHP_SELF']</code>. Leaving it blank triggers a form submissions default behaviour, which is to submit to <em>self</em></p>\n\n<pre><code><form method=\"post\" name=\"form\"> <!-- will do the trick -->\n</code></pre>\n\n<p>As an aside, also check my addition to the recommendations bit below on how you can make the mix-ins of your php in the markup, IMO at least, a bit more easy to read.</p>\n\n<p><strong>Recommendations</strong><br>\nGiven the fact you are looking into ways to ensure bots/spammers can't abuse your form, why not use <a href=\"http://en.wikipedia.org/wiki/CAPTCHA\" rel=\"nofollow noreferrer\">a simple <strong><em>Captcha</em></strong></a>? It's proven technology, and rather effective anyway...</p>\n\n<p>There are various scripts readily available, <a href=\"http://www.phpcaptcha.org/\" rel=\"nofollow noreferrer\">phpcaptcha</a> is a free script you can download. It's easy, fairly well documented, actively maintained, there's a lot of plugins readily available for all major CMS/blog type of things and it's already been extensively tested.<Br>\nI've just looked into the source of phpcaptcha now. I must say, there's a couple of things I don't much care for in there, but on the whole, it's not bad. I've even gone through the trouble of forking the repo, and I've started writing a little extra feature (which I'll call <em>\"mangler\"</em>). It'll transform words like <code>transform</code> into <code>tr@nsf0rm</code>, in such a way that both <code>transform</code> and <code>tr@nsf0rm</code> are accepted.<br>\nThough still work in progress, <a href=\"https://github.com/EVODelavega/securimage/compare/dapphp:master...master\" rel=\"nofollow noreferrer\">feel free to contribute</a> ;-P</p>\n\n<p>When echo-ing PHP variables inside HTML, you may find your code easier to read when using the short <code>echo</code> tag. This is <em>not</em> the same as the short open tag (<code><?</code>) in that it <strong>does not require specific ini settings</strong>. In other words, it's always going to be available.<br>\nIf nothing else, it at least requires less typing/code-chars</p>\n\n<pre><code><input name=\"token\" type=\"hidden\" value=\"<?php echo htmlspecialchars($token2); ?>\">\n<!-- can be written as (I'm applying my critiques, too) -->\n<input name=\"token\" type=\"hidden\" value=\"<?= $token1; ?>\">\n</code></pre>\n\n<p>Not even the <code>;</code> at the end of the line is required, but I prefer to have it there... it's a good habit.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-17T00:55:34.453",
"Id": "246810",
"Score": "0",
"body": "Can anyone explain how does writing the token in a hidden form field and in $_SESSION, and later comparing the two and rejecting mis-matches protect against bots (the stated intent)? Wouldn't any bot who makes this request and then submit the form pass this test?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-20T14:05:40.470",
"Id": "247381",
"Score": "1",
"body": "@Patrick: a great deal of spam-bots won't actually submit the form itself, they'll simply parse the DOM, build the request and send it to the form action. These bots often ignore non-required fields (like hidden fields), and simply do not include hidden field data in the requests they'll send. Others might use proxies so as to not seem too suspicious, and they'll send the same requests over various proxies (and therefore various sessions). If they submit a single token value for all requests, irrespective of the proxy/session they use, a hidden field will stop most bogus requests"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-20T14:11:28.833",
"Id": "247383",
"Score": "1",
"body": "Of course, this catches out only some of the bots, but even so, you can change the token for each request, which means a bot that repeatedly sends the same request will only be able to send its spam once. Then you have people adding another layer of bot defences to this simple token approach by adding dummy token fields (containing gibberish or partial token values), and use JS to set the actual values after the DOM is loaded. If a bot merely parses the DOM, it will almost certainly generate invalid requests, or incomplete tokens. TL;DR: a token alone is not enough, but it does help"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-20T14:17:20.867",
"Id": "247384",
"Score": "0",
"body": "@Patrick: A more sophisticated bot would actually use a webdriver, and populate the fields and submit the form in the exact same way a human user would. Those kinds of bots would not be detected through hidden fields and tokens like this. You can defend against those requests in many different ways (IP tracking, either in your application, or at server level), timing between page request and form submission < 10 sec -> captcha (something similar to what SO does) or just add a captcha to all of your forms to begin with..."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T10:31:27.840",
"Id": "41318",
"ParentId": "41129",
"Score": "13"
}
}
] |
{
"AcceptedAnswerId": "41318",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T03:45:18.013",
"Id": "41129",
"Score": "12",
"Tags": [
"php",
"beginner",
"security",
"form",
"session"
],
"Title": "PHP form with bot deterrent"
}
|
41129
|
<p>I have created an MS Excel type of grid in jQuery. I want to learn best practices and I need your comments for more optimized code.</p>
<p>Please review the code and offer your suggestions.</p>
<p><a href="http://jsfiddle.net/ananddeepsingh/pdfrN/" rel="nofollow">Demo</a></p>
<p><strong>jQuery:</strong></p>
<pre class="lang-js prettyprint-override"><code>var JS = JS || {};
JS.training = JS.training || {};
JS.training.tableData = JS.training.tableData || {};
JS.training.tableData = {
defaults: {
$table: $('#myTable'),
addTableRowBtn: $('#addRowBtn'),
addTableColBtn: $('#addColBtn')
},
createTable: function () {
var _this = this,
table = "";
table += "<thead>";
for (i = 0; i < 5; i++) {
var tableHeader = (i == 0) ? "<th style='border:1px solid #E5E5E5; background:#F1F1F1'></th>" : "<th style='border:1px solid #E5E5E5; background:#F1F1F1'>A" + i + "</th>";
table += tableHeader;
}
table += "</thead>";
table += "<tbody>";
for (i = 0; i < 5; i++) {
table += "<tr id='row" + i + "'>";
for (var j = 0; j < 5; j++) {
var tableDataCells = (j == 0) ? "<td width='3%' style='border:1px solid #E5E5E5;'>" + (i + 1) + "</td>" : "<td width=100px style='border:1px solid #E5E5E5' id='td" + j + "' contenteditable=true> </td>";
table += tableDataCells;
}
table += '</tr>';
}
table += "</tbody>";
//APPEND TABLE MARKUP
$(_this.defaults.$table).append(table);
//BIND EVENTS
_this.bindEvents();
},
addTableRow: function () {
var _this = this,
colLen = $("#myTable tr:nth-child(1) td").length,
colVal = parseInt($("#myTable tr:last-child td:first").text()) + 1;
for (i = 0; i < 1; i++) {
var table = "<tr id=row" + colVal + "'>";
for (var j = 0; j < colLen; j++) {
if (j == 0) {
table += '<td width="3%" style="border:1px solid #E5E5E5; background:#F1F1F1">' + colVal + ' </td>';
} else {
table += "<td width=100px style='border:1px solid #E5E5E5;' contenteditable=true id='td" + j + "'> </td>";
}
}
table += '</tr>';
}
$(_this.defaults.$table).append(table);
},
addTableColumn: function () {
var _this = this,
colVal = $("#myTable tr th:last-child").text(),
colNum = parseInt(colVal.charAt(1)) + 1;
console.log(colNum);
$("#myTable thead tr:last-child").append("<th style='border:1px solid #E5E5E5; background:#F1F1F1'>A" + colNum + "</th>");
$("#myTable tbody tr").each(function () {
$(this).append("<td width=100px style='border:1px solid #E5E5E5;' contenteditable=true id='td" + colNum + "'></td>")
});
},
bindEvents: function () {
var _this = this;
//CAPTURE ADD ROW BUTTON CLICK
_this.defaults.addTableRowBtn.on('click', function () {
_this.addTableRow();
});
//CAPTURE ADD COLUMN BUTTON CLICK
_this.defaults.addTableColBtn.on('click', function () {
_this.addTableColumn();
});
},
init: function () {
var _this = this;
_this.createTable();
}
};
//INIT CALL
JS.training.tableData.init();
</code></pre>
<p><strong>HTML:</strong></p>
<pre class="lang-html prettyprint-override"><code><div id="wrapper">
<button id="addRowBtn" name="addRowBtn" value="Add Row">Add Row</button>
<button id="addColBtn" name="addColBtn" value="Add Col">Add Column</button>
<div id="table">
<table id="myTable" cellpadding="0" cellspacing="0" border="0" style="border:1px solid #E5E5E5"></table>
</div>
</div>
</code></pre>
<p><strong>CSS:</strong></p>
<pre class="lang-css prettyprint-override"><code>body {
font:normal 14px/16px Arial, Helvetica, sans-serif
}
#wrapper {
margin:100px auto 0;
width:80%;
}
#myTable {
width:100%;
margin:20px auto 0
}
#myTable th, #myTable td {
padding:5px;
}
#myTable tr td.first {
background:#F1F1F1;
border:1px solid #E5E5E5;
}
</code></pre>
|
[] |
[
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li>The column and row count should be a parameter/variable/default</li>\n<li>The namespace <code>JS.training</code> seems like overkill, I doubt anybody would ever use 2 libraries for showing datagrids ;)</li>\n<li><p>The following could use extraction of the pattern, also you should look into a templating library I am using my personal template function here as an example:</p>\n\n<pre><code> for (i = 0; i < 5; i++) {\n var tableHeader = (i == 0) ? \n \"<th style='border:1px solid #E5E5E5; background:#F1F1F1'></th>\" : \n \"<th style='border:1px solid #E5E5E5; background:#F1F1F1'>A\" + i + \"</th>\";\n table += tableHeader;\n }\n</code></pre>\n\n<p>could be</p>\n\n<pre><code>function fillTemplate( s )\n{ //Replace ~ with further provided arguments\n for( var i = 1, a = s.split('~'), s = '' ; i < arguments.length ; i++ )\n s = s + a.shift() + arguments[i];\n return s + a.join(\"\");\n} \n\nvar headerTemplate = `<th style='border:1px solid #E5E5E5; background:#F1F1F1'>~</th>` \nfor (i = 0; i < 5; i++) {\n var header = (i == 0) ? \"\" : i;\n table += fillTemplate( headerTemplate, header );\n}\n</code></pre></li>\n<li><p>I would split up the creation of header and items HTML into 2 separate functions</p></li>\n<li><code>var _this = this</code> is really only useful for closures, and you are not using those in <code>createTable</code>.</li>\n<li>You should extract <code><td width=\"3%\" style=\"border:1px solid #E5E5E5; background:#F1F1F1\"></code> into a template as well, you use it both in <code>createTable</code> and <code>addTableRow</code>.</li>\n<li>Same goes for the header template which you use as well in <code>addTableColumn</code></li>\n<li><p>These comments can be filed under Captain Obvious and removed:</p>\n\n<pre><code>//CAPTURE ADD ROW BUTTON CLICK\n_this.defaults.addTableRowBtn.on('click', function () {\n _this.addTableRow();\n});\n\n//CAPTURE ADD COLUMN BUTTON CLICK\n_this.defaults.addTableColBtn.on('click', function () {\n _this.addTableColumn();\n});\n</code></pre></li>\n</ul>\n\n<p>All in all I really like your code, I will leave it to @kleinfreund to review your CSS.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T14:18:12.017",
"Id": "41150",
"ParentId": "41130",
"Score": "7"
}
},
{
"body": "<p>Only some quick notes on your HTML/CSS.</p>\n\n<p><strong>HTML:</strong></p>\n\n<ol>\n<li>You're repeating ID's in your generated markup. ID's must only occur once. If you need them in multiple locations, use classes instead.</li>\n</ol>\n\n<p><strong>CSS:</strong></p>\n\n<ol>\n<li><p>You declare a line-height of 16 pixels. I'd advice you using a unit-less relative value for line-height like this: <code>font: 14px/1.2 Arial, Helvetica, sans-serif;</code></p>\n\n<p>Otherwise you would need to redefine the line-height on all elements with a higher font-size, because they currently have a line-height of 16 pixels as well. With a relative value you do this only once.</p>\n\n<p>I also ommited <code>normal</code> in your declaration, because the default values for <code>font-style</code>, <code>font-weight</code> and <code>font-variation</code> are <code>normal</code> anyway.</p></li>\n<li><p>Although it's possible to ommit the last <code>;</code> in a rule declaration, it's not a good practise. You will run into troubles while editing CSS. By always including it, you don't need to worry about issues like moving the declaration further to the top, etc.</p></li>\n<li><p>You add some CSS rules as inline styles to all your generated <code>td</code>'s. You can move these rules to your CSS to reduce this unnecessary repetition.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T14:28:53.650",
"Id": "41152",
"ParentId": "41130",
"Score": "7"
}
},
{
"body": "<p>Some further points...</p>\n\n<ul>\n<li><p>You have inline CSS in your <code>td</code>s, this could easily be extracted into your stylesheet.</p></li>\n<li><p>I much prefer creating HTML using jQuery, rather than ugly concatenated strings:</p>\n\n<pre><code>var $table = $('<tbody>')\n\nfor (i = 0; i < 5; i++) {\n var $row = $('<tr>');\n for (var j = 0; j < 5; j++) {\n var $cell = (j == 0)\n ? $('<td>').text(i + 1) \n : $('<td>').attr('contenteditable', true);\n $cell.appendTo($row);\n }\n $row.appendTo($table);\n}\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T01:05:50.713",
"Id": "41303",
"ParentId": "41130",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T04:44:32.557",
"Id": "41130",
"Score": "10",
"Tags": [
"javascript",
"jquery",
"css",
"excel"
],
"Title": "MS Excel type of grid in jQuery"
}
|
41130
|
<p>This maze has multiple entry points, and quite obviously multiple exits. The entry or exit is not provided at input. Of the multiple sources and destinations, any single path from any source to any destination should be returned. The path need not be the optimal or shortest path.</p>
<p>I'm looking for code optimization, good practices etc. Please ignore the numeric prefixes (i.e. Coordinate3 etc.)</p>
<p>Two questions:</p>
<ol>
<li><p>Please verify complexity: O(nm)</p></li>
<li><p>The enum <code>Direction</code> is <code>so called nested</code>. I mean not a separate Java file but internal to the Maze class and it is also <code>static</code>. Is this the right way to do for enum? I have followed the prototype of Node class in Sun's linkedlist.java.</p></li>
</ol>
<p></p>
<pre><code>final class Coordinate3 {
private final int row;
private final int col;
public Coordinate3(int row, int col) {
this.row = row;
this.col = col;
}
public int getX() {
return row;
}
public int getY() {
return col;
}
public boolean equals(Object o) {
/**
* http://stackoverflow.com/questions/6364258/override-equals-method
* NOTE: order of this check is designed for efficiency
*/
/**
* easiest. if this results in true then we prevented a lot of hassles. comparisons can be made without any fear
* NPE or classcast
*/
if (this == o)
return true;
/**
* Mechanisms to prevent popping up exceptions. Ideally such checks better be performed at higher level.
*/
if (o == null)
return false;
if (getClass() != o.getClass())
return false;
// now to the check.
final Coordinate3 coordinate = (Coordinate3) o;
return coordinate.row == row && coordinate.col == col;
}
public int hashCode() {
return row + col;
}
@Override
public String toString() {
return row + " : " + col;
}
}
public class Maze3 {
private final int[][] maze;
public Maze3(int[][] maze) {
if (maze.length == 0) throw new IllegalArgumentException("The maze is empty.");
this.maze = maze;
}
/**
* Returns the solution to the maze. Of the multiple sources and destinations, any single path from any source to
* any destination should be returned. The path need not be optimal / shortest.
*
* @return the set which is the solution to the maze.
*/
public Set<Coordinate3> solve() {
/* trying to find entry point in the first and last row. */
final Set<Coordinate3> mazeSolution = new LinkedHashSet<Coordinate3>();
for (int i = 0; i < maze[0].length; i++) {
if (maze[0][i] == 1) {
if (solvedMaze(0, i, mazeSolution)) {
return mazeSolution;
}
}
if (maze[maze.length - 1][i] == 1) {
if (solvedMaze(0, i, mazeSolution)) {
return mazeSolution;
}
}
}
/* trying to find entry point in the first and last column */
for (int i = 0; i < maze.length; i++) {
if (maze[i][0] == 1) {
if (solvedMaze(i, 0, mazeSolution)) {
System.out.println("case 3");
return mazeSolution;
}
}
if (maze[i][maze[0].length - 1] == 1) {
if (solvedMaze(i, maze[0].length - 1, mazeSolution)) {
return mazeSolution;
}
}
}
return Collections.emptySet();
}
private boolean solvedMaze(int row, int col, Set<Coordinate3> visitedSet) {
boolean gotMaze = false;
Coordinate3 coor = new Coordinate3(row, col);
if (visitedSet.contains(coor)) {
return false;
}
if (isExit(row, col, visitedSet)) {
visitedSet.add(coor);
return true;
}
visitedSet.add(coor);
for (Direction dir : Direction.values()) {
int newRow = row + dir.getY();
int newCol = col + dir.getX();
if (!gotMaze && isInBounds(newRow, newCol) && maze[newRow][newCol] == 1) {
gotMaze = solvedMaze(newRow, newCol, visitedSet);
}
}
if (!gotMaze) {
visitedSet.remove(coor);
}
return gotMaze;
}
boolean isExit(int row, int col, Set<Coordinate3> visitedSet) {
return ((row == 0) || (row == maze.length - 1) || ((col == maze[0].length - 1) || col == 0))
&& !visitedSet.isEmpty();
}
boolean isInBounds(int row, int col) {
return row >= 0 && col >= 0 && row < maze.length && col < maze[0].length;
}
private static enum Direction {
NORTH(0, -1), EAST(1, 0), SOUTH(0, 1), WEST(-1, 0);
int dx;
int dy;
private Direction(int dx, int dy) {
this.dx = dx;
this.dy = dy;
}
public int getX() {
return dx;
}
public int getY() {
return dy;
}
}
public static void main(String[] args) {
int[][] m1 = { { 0, 1, 0 },
{ 1, 1, 0 },
{ 0, 0, 0 } };
for (Coordinate3 coord : new Maze3(m1).solve()) {
System.out.println(coord);
}
System.out.println("-------------------------------------");
int[][] m2 = { { 0, 0, 0, 0 },
{ 0, 0, 1, 1 },
{ 0, 1, 1, 0 },
{ 0, 0, 1, 0 },
{ 1, 1, 1, 0 },
{ 0, 0, 0, 0 } };
for (Coordinate3 coord : new Maze3(m2).solve()) {
System.out.println(coord);
}
System.out.println("-------------------------------------");
int[][] m3 = { { 0, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 1 },
{ 0, 1, 1, 1, 0 },
{ 0, 1, 0, 1, 0 },
{ 0, 1, 1, 1, 1 },
{ 0, 0, 0, 0, 0 } };
for (Coordinate3 coord : new Maze3(m3).solve()) {
System.out.println(coord);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Here are a few comments about the style. You'll find comments about the algorithm itself at the end.</p>\n\n<p><strong>Naming</strong></p>\n\n<p>The <code>3</code> at the end of the class names is a bit awkward.</p>\n\n<p>The same kind of things are sometimes called <code>x</code>, <code>dx</code> or <code>row</code>.</p>\n\n<p>(<code>Coordinate</code> and <code>Direction</code> look pretty similar too but trying to merge them showed me they were actually different in the spirit.)</p>\n\n<p><strong>Getters</strong></p>\n\n<p>In <code>Coordinate</code> and <code>Direction</code>, the members are constant (either explicitly with <code>final</code> or just because no method changes them). Though, you don't need to bother defining getters, just make them public and that will be it. (I am quite aware that this is not the way most Java developpers see things but at least you get a different point of view).</p>\n\n<p><strong>Early stop</strong></p>\n\n<p>It seems like the loop in </p>\n\n<pre><code> for (Direction dir : Direction.values()) {\n int newRow = x + dir.y;\n int newCol = y + dir.x;\n if (!gotMaze && isInBounds(newRow, newCol) && maze[newRow][newCol] == 1) {\n gotMaze = solvedMaze(newRow, newCol, visitedSet);\n }\n }\n\n if (!gotMaze) {\n visitedSet.remove(coor);\n }\n\n return gotMaze;\n</code></pre>\n\n<p>will not do anything once <code>gotMaze</code> is <code>true</code>. Thus, this might as well just be :</p>\n\n<pre><code> for (Direction dir : Direction.values()) {\n int newRow = x + dir.y;\n int newCol = y + dir.x;\n if (isInBounds(newRow, newCol) && maze[newRow][newCol] == 1 && solvedMaze(newRow, newCol, visitedSet))\n return true;\n }\n\n visitedSet.remove(coor);\n return false;\n</code></pre>\n\n<p><strong>Types</strong></p>\n\n<p>It's a bit weird to compare the content of the maze to <code>1</code> every time. It would probably be easier to define the type of the content as a boolean.\nAs a drawback, it does make the definition of mazes more tedious.</p>\n\n<p>The method you've defined that takes <code>x</code> and <code>y</code> as parameters should/could take coordinates.</p>\n\n<p>At the end, here's what my code is like :</p>\n\n<pre><code>import java.util.*;\n\nfinal class Coordinate {\n\n public final int x;\n public final int y;\n\n public Coordinate(int x, int y) {\n this.x = x;\n this.y = y;\n }\n\n public boolean equals(Object o) {\n /**\n * http://stackoverflow.com/questions/6364258/override-equals-method\n * NOTE: order of this check is designed for efficiency\n */\n\n /**\n * easiest. if this results in true then we prevented a lot of hassles. comparisons can be made without any fear\n * NPE or classcast\n */\n if (this == o)\n return true;\n\n /**\n * Mechanisms to prevent popping up exceptions. Ideally such checks better be performed at higher level.\n */\n if (o == null)\n return false;\n if (getClass() != o.getClass())\n return false;\n\n // now to the check.\n final Coordinate coordinate = (Coordinate) o;\n return coordinate.x == x && coordinate.y == y;\n }\n\n public int hashCode() {\n return x + y;\n }\n\n @Override\n public String toString() {\n return x + \" : \" + y;\n }\n}\n\npublic class Maze {\n\n private final boolean[][] maze;\n\n public Maze(boolean[][] maze) {\n if (maze.length == 0) throw new IllegalArgumentException(\"The maze is empty.\");\n this.maze = maze;\n }\n\n /**\n * Returns the solution to the maze. Of the multiple sources and destinations, any single path from any source to\n * any destination should be returned. The path need not be optimal / shortest.\n * \n * @return the set which is the solution to the maze.\n */\n public Set<Coordinate> solve() {\n\n /* trying to find entry point in the first and last row. */\n final Set<Coordinate> mazeSolution = new LinkedHashSet<Coordinate>();\n\n for (int i = 0; i < maze[0].length; i++) {\n if (maze[0][i]) {\n if (solvedMaze(0, i, mazeSolution)) {\n return mazeSolution;\n }\n }\n\n if (maze[maze.length - 1][i]) {\n if (solvedMaze(0, i, mazeSolution)) {\n return mazeSolution;\n }\n }\n\n }\n\n /* trying to find entry point in the first and last column */\n for (int i = 0; i < maze.length; i++) {\n if (maze[i][0]) {\n if (solvedMaze(i, 0, mazeSolution)) {\n System.out.println(\"case 3\");\n return mazeSolution;\n }\n }\n\n if (maze[i][maze[0].length - 1]) {\n if (solvedMaze(i, maze[0].length - 1, mazeSolution)) {\n return mazeSolution;\n }\n }\n }\n\n return Collections.emptySet();\n }\n\n private boolean solvedMaze(int x, int y, Set<Coordinate> visitedSet) {\n Coordinate coor = new Coordinate(x, y);\n\n if (visitedSet.contains(coor)) {\n return false;\n }\n\n if (isExit(x, y, visitedSet)) {\n visitedSet.add(coor);\n return true;\n }\n\n visitedSet.add(coor);\n\n for (Direction dir : Direction.values()) {\n int newRow = x + dir.y;\n int newCol = y + dir.x;\n if (isInBounds(newRow, newCol) && maze[newRow][newCol] && solvedMaze(newRow, newCol, visitedSet))\n return true;\n }\n\n visitedSet.remove(coor);\n return false;\n }\n\n boolean isExit(int x, int y, Set<Coordinate> visitedSet) {\n return ((x == 0) || (x == maze.length - 1) || ((y == maze[0].length - 1) || y == 0))\n && !visitedSet.isEmpty();\n }\n\n boolean isInBounds(int x, int y) {\n return x >= 0 && y >= 0 && x < maze.length && y < maze[0].length;\n }\n\n private static enum Direction {\n NORTH(0, -1), EAST(1, 0), SOUTH(0, 1), WEST(-1, 0);\n\n public final int x;\n public final int y;\n\n private Direction(int x, int y) {\n this.x = x;\n this.y = y;\n }\n\n }\n\n public static void main(String[] args) {\n boolean[][] m1 = { { false, true, false }, \n { true, true, false }, \n { false, false, false } };\n\n for (Coordinate coord : new Maze(m1).solve()) {\n System.out.println(coord);\n }\n\n System.out.println(\"-------------------------------------\");\n\n boolean[][] m2 = { { false, false, false, false },\n { false, false, true, true },\n { false, true, true, false },\n { false, false, true, false },\n { true, true, true, false },\n { false, false, false, false } };\n\n for (Coordinate coord : new Maze(m2).solve()) {\n System.out.println(coord);\n }\n\n System.out.println(\"-------------------------------------\");\n\n boolean[][] m3 = { { false, false, false, false, false },\n { false, false, false, true, true },\n { false, true, true, true, false },\n { false, true, false, true, false },\n { false, true, true, true, true },\n { false, false, false, false, false } };\n\n for (Coordinate coord : new Maze(m3).solve()) {\n System.out.println(coord);\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Algorithm</strong></p>\n\n<p>Let's work on the following example to see what you've done and what you could do.</p>\n\n<p>Assuming I've understood everything, you basically bruteforce by trying to go down then right if you cannot go down then up if you cannot go right and left if you cannot go up.</p>\n\n<p>What you could do is a slightly smarter algorithm which would actually tell you not only how to go to an exit but also the best way to do so. On can find a few examples <a href=\"http://en.wikipedia.org/wiki/Pathfinding#Dijkstra.27s_Algorithm\">on Wikipedia</a>. The Sample Algorithm is pretty close to what are are trying to achieve.</p>\n\n<p>I cannot tell whether it would be more efficient than yours but it would have a few advantages such as :</p>\n\n<ul>\n<li><p>having the same solution no matter how your maze is oriented (at the moment, a problem can be easily solved but the same maze turned or reversed could be much harder)</p></li>\n<li><p>knowing that the algorithm won't \"get stuck\" in some \"useless\" parts of the maze (it is quite easy to design an problem that would make your solution go pretty crazy)</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T21:54:50.833",
"Id": "70690",
"Score": "0",
"body": "Thanks for review, can someone help verify complexity ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T09:32:50.333",
"Id": "70713",
"Score": "0",
"body": "I cannot a proper analysis right now but I'd be willing to very that the worst case is much worse than what you have found. It probably correspond to the number of path in a n*m angle and this is likely to be a lot."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T09:36:37.400",
"Id": "41140",
"ParentId": "41133",
"Score": "13"
}
},
{
"body": "<p>Josay's answer is perfect for improving your logic and coding style. But you are also looking for <em>best-practice</em>. Now in your code you override the <code>hashcode</code> method as</p>\n\n<pre><code>return row + col;\n</code></pre>\n\n<p>This is very bad cause for two CoOrdinates like <code>(2,3)</code> and <code>(3,2)</code> will return same hash. This is pure evil if you use your <code>Coordinate</code> class in <code>Map</code>. Now if you are using any modern IDE like Eclipse/NetBeans you can auto-generate the <code>hashcode</code> method.</p>\n\n<p>From NetBeans I get</p>\n\n<pre><code>public int hashCode() {\n int hash = 7;\n hash = 43 * hash + this.row;\n hash = 43 * hash + this.col;\n return hash;\n}\n</code></pre>\n\n<hr>\n\n<p>Since JDK 1.7 there is an <code>Objects</code> class with helper methods to override the method from <code>Object</code> class. You can take help of <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html#hashCode%28java.lang.Object%29\" rel=\"nofollow\"><code>Objects.hashcode</code></a> also. How? simple like this</p>\n\n<pre><code>public int hashCode() {\n return Objects.hash(this.row, this.col);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T09:43:46.593",
"Id": "70916",
"Score": "0",
"body": "`Objects.hashCode` calls `Object.hashCode`. So `public int hashCode() {return Objects.hashCode(this);}` is a `StackOverflowError`. You meant [`Objects.hash`](http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html#hash%28java.lang.Object...%29) I assume."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T13:04:02.670",
"Id": "70935",
"Score": "0",
"body": "I'm not supplying a single reference here:`Objects.hash(this.row, this.col);` though, am I? Also a class containing a single field **need not** have the same hash code as the hash code of the field. Also see the example [right above the warning](http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html#hash%28java.lang.Object...%29), and compare with my edit."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T11:36:10.500",
"Id": "41283",
"ParentId": "41133",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "41140",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T06:31:18.770",
"Id": "41133",
"Score": "10",
"Tags": [
"java",
"pathfinding"
],
"Title": "Find a path through a maze"
}
|
41133
|
<p>Please review the following code:</p>
<pre><code>static int md5_encode(const char * input_md5 , char * output , int size)
{
// checking pre-requisits //
if( output == NULL || input_md5 == NULL || size == 0)
{
printf( "main.cpp:md5_encode() error check for the prerequisites. \n");
exit(0);
}
int input_length = strlen(input_md5);
// null terminate the output first //
output[0] = 0;
char * buffer [10];
for (int i=0; i<input_length,i++)
{
char current_char = input_md5 [i];
// encode it //
strcat(output,"uc");
sprintf(buffer,"%d",current_char);
strcat(output,buffer);
}
// check for the buffer overflow condtions //
// if something goes out of the buffer then assert //
if(size < strlen(output) )
{
printf("Warning: Possible buffer-overflow\n");
return 0;
}
// return on success //
return 1;
}
</code></pre>
<p>As you can see, what this does is to encode an md5 string into ucuc format. The output buffer is allocated by the caller and its size and address are passed as parameters. </p>
<p>The function just writes to the output buffer with 'strcat()' without any checking. Then afterwards it checks whether 'size' is less than the amount that was written. If it exceeds the limit, then the function gives an error message.</p>
<p>Any more suggestions than just a warning message? How could I improve this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T21:10:48.440",
"Id": "70682",
"Score": "0",
"body": "You tagged your question as [tag:c], and the code is written in C style. Yet, curiously, the code mentions `main.cpp`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T22:56:31.380",
"Id": "70692",
"Score": "0",
"body": "What is \"ucuc\" format?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T03:45:07.520",
"Id": "70699",
"Score": "0",
"body": "uc%duc%d format is the format that I taught. Because I have to store MD5 in a text .ini file. Google does not show any results."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T03:45:25.990",
"Id": "70700",
"Score": "0",
"body": "I'd use a state machine to decode it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T03:52:41.053",
"Id": "70702",
"Score": "0",
"body": "Why not store a 16-character string of hexadecimal digits, the same way everyone else represents MD5 hashes?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T05:18:49.453",
"Id": "70705",
"Score": "0",
"body": "because sir,the ini parser that I've implemented does not support those meta and escape characters. \nSo I need to encode it. 'uc' there means an unsigned char."
}
] |
[
{
"body": "<p>I'm not familiar with the \"ucuc format\", or what such an output format could be useful for. A <a href=\"https://www.google.com/search?q=md5+ucuc+format\" rel=\"nofollow noreferrer\">Google search for <code>md5 ucuc format</code></a> shows this question itself as the only relevant hit.</p>\n\n<p>What are the expected inputs? A 32-character string of hexadecimal digits? If so, the longest possible output should be 32 repetitions of <code>uc102</code>, corresponding to an input of <code>ffffffffffffffff</code>. (If the input can contain <em>arbitrary</em> characters, then allow for 6 bytes of output per byte of input, since there might be a negative sign.) Why not just document the requirement for the caller to pass you an output buffer capable of storing 161 bytes? Then do away with the <code>size</code> parameter. You could return the number of bytes of output (excluding the <code>\\0</code> terminator).</p>\n\n<p>Printing the error messages is not advised; it contaminates the output, and side effects limit the ability to reuse your code. If you <em>must</em> print diagnostics, print to <code>stderr</code> instead. You can use the <code>__FILE__</code> and <a href=\"https://stackoverflow.com/a/733074/1157100\"><code>__FUNCTION__</code></a> macros for the error message.</p>\n\n<p>A more common way to handle null inputs is to either let it crash, or use assertions. An assertion failure message typically already includes the line number. If you use assertions, use three separate assertions, not a combined one. Calling <code>exit()</code> is unusual; calling <code>exit(0)</code> to exit <em>successfully</em> is even weirder.</p>\n\n<p>Checking for possible buffer overflow at the end of the function is useless. The damage would already be done, and your program could very well have crashed before reaching the check.</p>\n\n<p>Your use of <code>strlen()</code> and <code>strcat()</code> is inefficient, especially when done in a loop. Each of those calls is an O(<em>n</em>) operation, as it scans the buffer for the <code>\\0</code> terminator. You already know exactly where those terminators are, since you composed the output string yourself.</p>\n\n<pre><code>/**\n * Encodes the input_md5 in ucuc format, whatever that means.\n * The caller must provide an output capable of holding 5 bytes\n * per byte of input, plus 1 byte for a null terminator.\n *\n * Returns the length of the output in bytes, excluding the null\n * terminator.\n */\nstatic int md5_encode(const char *input_md5, char *output)\n{\n // Check preconditions\n assert(input_md5);\n assert(output);\n\n int out_offset = 0;\n for (const char *in = input_md5; *in; in++)\n {\n // Encode it. sprintf() already adds a \\0 terminator.\n out_offset += sprintf(output + out_offset, \"uc%d\", *in);\n }\n\n return out_offset;\n}\n</code></pre>\n\n<p>In my opinion, two spaces of indentation per level is too stingy for readability, and also encourages inappropriately deep nesting.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T21:04:42.543",
"Id": "41181",
"ParentId": "41134",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T06:35:54.400",
"Id": "41134",
"Score": "5",
"Tags": [
"c",
"memory-management"
],
"Title": "Input memory buffer exceeding situation handling"
}
|
41134
|
<p>I am working on a micro project: a Haskell DSL for describing circuits.
(You can find the code <a href="https://github.com/j-rock/hCircuit/blob/master/src/Alu.hs" rel="nofollow">here</a>)</p>
<p>I'm pretty happy with everything so far, but there is an ugly function <code>alu32</code>:</p>
<pre><code> alu32 c0 c1 c2 a b =
let aluc = alu1 c0 c1 c2
(out0, cout0) = aluc (a !! 0) (b !! 0) c0
(out1, cout1) = aluc (a !! 1) (b !! 1) cout0
(out2, cout2) = aluc (a !! 2) (b !! 2) cout1
(out3, cout3) = aluc (a !! 3) (b !! 3) cout2
...
</code></pre>
<p>Can anyone suggest a more idiomatic way of representing this? Also, if you feel like browsing the repository, feel free to make any suggestions. I have a bunch of things that I would still like to implement.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T10:03:02.753",
"Id": "70590",
"Score": "0",
"body": "You could do something like `results = (aluc (head a) (head b) c0) :: zipWith3 (\\x y z -> aluc x y (snd z)) (tail a) (tail b) results` then `map fst results` I haven't tried this, but you should be able to make it work on repl with few changes."
}
] |
[
{
"body": "<blockquote>\n <p>Can anyone suggest a more idiomatic way of representing this? </p>\n</blockquote>\n\n<p>The equations for the ALU have the form</p>\n\n<pre><code>(out !! i, cout !! i) = aluc (a !! i) (b !! i) (cout !! (i - 1))\n</code></pre>\n\n<p>so we should be able to express all of the equations with a single equation that manipulates lists. If only <code>cout !! (i - 1)</code> would be <code>something !! i</code>, this would be easier because all the indexes would be uniform. We can make the indexes more uniform by defining <code>cin = c0 : cout</code>, and then the equations become:</p>\n\n<pre><code>(out !! i, cout !! i) = aluc (a !! i) (b !! i) (cin !! i)\n</code></pre>\n\n<p>Now we can make a loop over i to implement alu32 as follows:</p>\n\n<pre><code>alu32 c0 c1 c2 a b =\n let (out, cout) = unzip [alu1 c0 c1 c2 (a !! i) (b !! i) (cin !! i) | i <- [0 .. 31]]\n cin = c0 : cout\n ...\n in ...\n</code></pre>\n\n<p>This should solve the main question: How to implement alu32 without repeating all these equations. On the way, I also replaced the translate with an unzip.</p>\n\n<p>However, we can do even better if we avoid the index computations. There are two problems with the indices: Index lookup is slow and awkward compared to just looping over the elements of a list. And the loop over the indices forces us to choose a fixed upper bound in the <code>[0 .. 31]</code> expression.</p>\n\n<p>To avoid the indices, we note that the list comprehension</p>\n\n<pre><code>[alu1 c0 c1 c2 (a !! i) (b !! i) (cin !! i) | i <- [0 .. 31]]\n</code></pre>\n\n<p>just loops over three lists in parallel, <code>a</code>, <code>b</code> and <code>cin</code>. This parallel loop over three lists can be expressed with zipWith3 as follows:</p>\n\n<pre><code>unzip (zipWith3 (alu1 c0 c1 c2) a b cin)\n</code></pre>\n\n<p>Or you activate GHC's extension for parallel list comprehensions by putting <code>{-# LANGUAGE ParallelListComp #-}</code> near the top of the file, and then use:</p>\n\n<pre><code>unzip [alu1 c0 c1 c2 ai bi ci | ai <- a | bi <- b | ci <- cin]\n</code></pre>\n\n<p>The latter will desugar to the former. Clearly, this variant of the code doesn't use any indices anymore. This also means that it works for arbitrary bitvectors, not just 32bit ones. We only have to adapt the rest of the alu32 implementation to avoid indices, too. For example:</p>\n\n<pre><code>alu :: Wire -- Control Bit 0\n -> Wire -- Control Bit 1\n -> Wire -- Control Bit 2\n -> ByteWire -- n Bit Wire addend\n -> ByteWire -- n Bit Wire addend\n -> (ByteWire, Wire, Wire, Wire)\nalu c0 c1 c2 a b =\n let (out, cout) = unzip (zipWith3 (alu1 c0 c1 c2) a b cin)\n cin = c0 : cout\n overflow = xorGate (take 2 (reverse cout))\n isZero = map (all (==False)) out\n negative = last out\n in (out, overflow, isZero, negative)\n</code></pre>\n\n<p>This version of alu is concise and works for bitvectors of arbitrary length.</p>\n\n<p>I'm not really sure about <code>map (all (== False)) out</code> to compute that all bits are zero. Maybe I would use something like <code>map (all not) out</code> or <code>map (not . or) out</code>. Note sure. Or maybe I would define a gate for deciding that something is all zeros and then use that one.</p>\n\n<blockquote>\n <p>Also, if you feel like browsing the repository, feel free to make any suggestions.</p>\n</blockquote>\n\n<ol>\n<li><p>Consider adding a cabal file. When I cloned your repo in order to test the above suggestion, I was confused that <code>cabal sandbox init && cabal build</code> didn't work. You can just run <code>cabal init</code> in the repository and it should ask you questions to help you make the cabal file.</p></li>\n<li><p>Consider making the <code>Wire</code> type more abstract.</p>\n\n<p>Currently, you have:</p>\n\n<pre><code>type Wire = [Binary] -- A list of discrete states\n</code></pre>\n\n<p>Instead, you could use:</p>\n\n<pre><code>newtype Wire = Secret [Binary]\n</code></pre>\n\n<p>The benefit of this definition is that it becomes harder to \"cheat\" and use list operations instead of gates. Later, when you are finished defining the basic gates, you can make a module that exports the <code>Wire</code> type and the gates, but not the <code>Secret</code> constructors. This way, you force the users of that module to use the gates and only the gates to compose wires.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T07:35:26.960",
"Id": "41540",
"ParentId": "41135",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T06:56:30.200",
"Id": "41135",
"Score": "3",
"Tags": [
"haskell",
"dsl"
],
"Title": "DSL for describing circuits"
}
|
41135
|
<p>In <code>JUnit 3</code>, I cannot tell <code>JUnit</code> what type of exception is expected. In <code>JUnit 4</code>, the declaration <code>@Test(expected=NullPointerException.class)</code> does it.</p>
<p>But, unfortunately in <code>Android development</code>, I can use only <code>JUnit 3</code>. So I wrote this simple method:</p>
<pre><code>public class TestingUtils {
public static void assertExpectedException(
Class<? extends Exception> exceptionClass, Runnable runnable) {
try {
runnable.run();
throw new AssertionFailedError(
"Expected exception: <" + exceptionClass.getName() + ">");
} catch (Exception e) {
if (!exceptionClass.equals(e.getClass())) {
throw new AssertionFailedError(
"Expected exception: <" + exceptionClass.getName() + "> " +
"but was: <" + e.getClass().getName() + ">"
);
}
}
}
}
</code></pre>
<p>Using:</p>
<pre><code>public void testConstructorThrowsExceptionIfArgumentIsNull() {
TestingUtils.assertExpectedException(IllegalArgumentException.class, new Runnable() {
@Override
public void run() {
new SomeTestedClass(null);
}
});
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T10:12:13.933",
"Id": "70591",
"Score": "2",
"body": "The message for the case if it is was *not* thrown should be clearer, including something like \"Expected exception X, but was not thrown\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T11:23:45.073",
"Id": "70599",
"Score": "2",
"body": "FYI, I have done [something similar in JDOM](https://github.com/hunterhacker/jdom/blob/master/test/src/java/org/jdom2/test/util/UnitTestUtil.java#L305) and [I use it like this](https://github.com/hunterhacker/jdom/blob/master/test/src/java/org/jdom2/test/cases/TestElement.java#L3281)."
}
] |
[
{
"body": "<p>I have <a href=\"https://github.com/hunterhacker/jdom/blob/master/test/src/java/org/jdom2/test/util/UnitTestUtil.java#L305\" rel=\"nofollow\">been though this loop before</a>. I chose to do things in a slightly different way to you, in that instead of creating a Runnable, I instead add a try/catch block to the actual test.</p>\n\n<p>Each system has pros/cons, but the differences are really cosmetic. Using a <code>Runnable</code> does make the JUnit logic better contained in the utility code.... but makes calling the utility test code a little bit more complicated. I am not sure which one I prefer.</p>\n\n<p>I have a suggestion regarding this line here:</p>\n\n<pre><code>if (!exceptionClass.equals(e.getClass())) { ....\n</code></pre>\n\n<p>It is useful to be able to expect a super-type of an exception. For example, you want to trap an <code>SQLException</code> when you run a query, or you want to trap an <code>IOException</code> when you do something on a Stream..... you have the code:</p>\n\n<pre><code>TestingUtils.assertExpectedException(SQLException.class, ....);\n</code></pre>\n\n<p>but, the actual exception may be <code>com.ibm.db2.jdbc.xxx.PicnicException</code>, which is a subclass of SQLException.</p>\n\n<p>Using <code>equals()</code> to match the exceptions is a problem.... you should use:</p>\n\n<pre><code>if (!exceptionClass.isInstance(e)) {....\n</code></pre>\n\n<p>One other thing, which is android specific.....</p>\n\n<p>I found a <a href=\"http://code.google.com/p/android/issues/detail?id=29378\" rel=\"nofollow\">bug in the Android Dalvik implementation/SDK</a> relating to this problem... you <strong>should</strong> be setting the 'cause' for your AssertionError so that it is logged correctly. Unfortunately, the bug (which is fixed in Jelly-Bean) makes this impossible.</p>\n\n<p>If you are sure you will be testing on Jelly-Bean or newer (the bug <em>was fixed</em> a while ago), you should also be initializing the cause on your AssertionError:</p>\n\n<pre><code> AssertionFailedError tothrow = new AssertionFailedError(\n \"Expected exception: <\" + exceptionClass.getName() + \"> \" +\n \"but was: <\" + e.getClass().getName() + \">\"\n );\n tothrow.initCause(e);\n throw tothrow;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T12:38:30.163",
"Id": "41145",
"ParentId": "41141",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "41145",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T10:06:45.047",
"Id": "41141",
"Score": "4",
"Tags": [
"java",
"android",
"exception-handling"
],
"Title": "Simple helper method for JUnit3 tests"
}
|
41141
|
<p>I'm trying to develop code to filter my e-mail with <code>JavaMail</code>, but I doubt it's the best way of doing this. And I want to collect all messages without attachment.</p>
<pre><code>package service.forkinjoin;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RecursiveAction;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.internet.MimeBodyPart;
import service.FileUtil;
public class ForkSortMessages extends RecursiveAction {
private static final long serialVersionUID = -1092415796824205832L;
private List<Message> listMessages;
private List<Message> listMessagesToDelete;
public ForkSortMessages(List<Message> listMessages, List<Message> listMessagesToDelete) {
this.listMessages = listMessages;
this.listMessagesToDelete = listMessagesToDelete;
}
@Override
protected void compute() {
List<RecursiveAction> actions = new ArrayList<>();
if (this.listMessages.size() <= Runtime.getRuntime().availableProcessors()) {
try {
this.separateMessages();
} catch (MessagingException | IOException e) {
e.printStackTrace();
}
} else {
int end = this.listMessages.size() / 2;
actions.add(new ForkSortMessages(this.listMessages.subList(0, end), this.listMessagesToDelete));
end += this.listMessages.size() % 2 == 0 ? 0 : 1;
actions.add(new ForkSortMessages(this.listMessages.subList(end, this.listMessages.size()), this.listMessagesToDelete));
invokeAll(actions);
}
}
private void separateMessages() throws MessagingException, IOException {
for (Message message : this.listMessages) {
if ((this.hasNoAttachment(message.getContentType()) || (this.hasNoXmlAttachment(message)))) {
listMessagesToDelete.add(message);
}
}
}
private boolean hasNoAttachment(String content) {
return !content.contains("multipart/MIXED");
}
private boolean hasNoXmlAttachment(Message message) throws IOException, MessagingException {
Multipart multipart = (Multipart) message.getContent();
for (int i = 0; i < multipart.getCount(); i++) {
MimeBodyPart mimeBodyPart = (MimeBodyPart) multipart.getBodyPart(i);
if (Part.ATTACHMENT.equalsIgnoreCase(mimeBodyPart.getDisposition())) {
if (FileUtil.isXmlFile(mimeBodyPart.getFileName())) {
return false;
}
}
}
return true;
}
}
</code></pre>
<p>So what can I do to improve my code? I've tried to do like <a href="http://www.oracle.com/technetwork/articles/java/fork-join-422606.html" rel="nofollow">Oracle</a> tutorial but I can't.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T12:15:22.847",
"Id": "70604",
"Score": "0",
"body": "There is no fork/join, or even Executor code in here... nothing multi-threaded at all.... except a call to `invokeAll(...)`, but there is no `invokeAll` method here. Where is your code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T12:19:42.843",
"Id": "70605",
"Score": "0",
"body": "@rolfl my code is following a example found in `Google`, if my code isn´t any kind of multi-threaded. Show me a example"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T10:15:07.780",
"Id": "70721",
"Score": "0",
"body": "@rolfl problably I told wrong things, but I created my code using tutorial found in `Google`, now I recreated my code, following tutorial of `Oracle`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T11:23:34.623",
"Id": "70725",
"Score": "0",
"body": "@rolfl: It's in the superclass."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T19:17:58.440",
"Id": "70760",
"Score": "1",
"body": "Do you need this code to be multi-process? It seems that the actual work is simply to check if it has no attachments - hardly a reason to fork the work..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T19:29:12.520",
"Id": "70762",
"Score": "0",
"body": "@UriAgassi I want to process much faster my code, so I decided to use parallel, but I don´t know if it´s the best way because I have one source of data, and this need to be processed and return one result. Other ways can be suggested to me, like simple thread or other things."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T19:37:11.487",
"Id": "70763",
"Score": "0",
"body": "Have you done benchmarks? How long is your list? Using forks and multi-processes has overhead and caveats, and should be used _only_ when needed. When the work is trivial, it might be faster to simply do it rather than splitting the input, copying the state, starting another process, then merging the result..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T19:40:56.017",
"Id": "70764",
"Score": "0",
"body": "@UriAgassi I did sometime a benchmark, my list in the begin will be big but later not. I wanted to use because I thougth would be faster. I used simple thread, but I found fork in join and thougth would be faster. But I´m having problem that some data are being lost or mixed."
}
] |
[
{
"body": "<p>In order to correctly work in parallel, you must follow the <a href=\"http://en.wikipedia.org/wiki/Actor_model\" rel=\"nofollow noreferrer\">Actor Model</a>, which basically says that each iteration should not share memory when doing their work. In your code, you pass a <code>List<Message></code> to the child processes, which they are expected to fill. Each child process changes his own copy of the list, which makes the final result unexpected.</p>\n\n<p>To build your actors correctly, each should create its own solution vector, and later its parent process should merge the result of the children, and pass them on (you can see <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/RecursiveAction.html\" rel=\"nofollow noreferrer\">samples here</a>).</p>\n\n<p>If the order of the messages is important to you, even this is not enough, since you don't know which child process will finish first, so the messages in the resulting list will not be in the same order as in the input list.</p>\n\n<p>After all being said and done - you might find out that you do not get better performance, and sometimes even <a href=\"https://stackoverflow.com/questions/14131467/java-fork-join-performance\">worse performance</a>.</p>\n\n<p>My suggestion is to keep it simple - the actual work you are doing on the array is simple enough - do a straight forward iteration. By they way you describe your use-case - at most you will have to wait a couple of minutes (tens of minutes?) for the initial bulk to be computed, but at least you'll be confident that you have the correct result. I assure you it would take less time to run it synchronously than to develop and debug a fork/join solution...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T21:06:49.523",
"Id": "70781",
"Score": "0",
"body": "Ok, you won, I´m going to keep it simple. Later I´m going to read your document, I just wanted to process things much faster. But I need to learn more about Java Parallel"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T11:58:39.817",
"Id": "70828",
"Score": "0",
"body": "I have one doubt, operation with I/O, are not good to use threads or parallel operations?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T12:15:58.890",
"Id": "70831",
"Score": "0",
"body": "There is no I/O in your filtering - you simply look at the content of the message you received..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T20:54:49.300",
"Id": "41252",
"ParentId": "41143",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "41252",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T11:15:18.910",
"Id": "41143",
"Score": "2",
"Tags": [
"java",
"multithreading",
"email"
],
"Title": "Filter email with JavaMail"
}
|
41143
|
<p>I'm working on a small command line application in c# where data is read from a CSV file along with a query and KNN is calculated for the query based on the data.</p>
<p>My problem isn't the algorithm at all, I understand it. Im having difficulty working with my code though. I think it's down to bad planning.</p>
<p>Here's my object for holding a "row" of data. the data is based on weather data and if something was played that day or not.</p>
<pre><code>class dataRow
{
public double sun {get; set;}
public double temp {get; set;}
public double humidity {get; set;}
public double wind {get; set;}
public bool play {get; set;}
public override string ToString()
{
return string.Format("\n\tSun: {0}\n\tTemp: {1}\n\tHumidity: {2}\n\tWind: {3}\n\tPlay: {4}", sun, temp, humidity, wind, play);
}
public double[] toArray()
{
return new double[] { sun, temp, humidity, wind };
}
}
</code></pre>
<p>I'm trying to Znormalize the data and the query before I work out euclidean distance between points but I'm stuck in a rut of annoying nested loops and I have a hunch there's a better way to code what I'm doing</p>
<pre><code>class KNN
{
public int numK;
List<dataRow> dataSet;
dataRow QueryRow;
dataRow stdDev;
dataRow avg;
public KNN(String[] input)
{
numK = Int32.Parse(input[0]);
dataSet = dataImport.import(input[1]);
//inputRow = dataImport.import(input[2])[0];
avg = getAverage(toDoubleList(dataSet));
}
public List<double[]> toDoubleList(List<dataRow> input)
{
var doubleList = new List<double[]>();
for(int i =0; i<input.Count; i++)
{
doubleList[i] = input[i].toArray();
}
return doubleList;
}
public dataRow getAverage(List<double[]> input)
{
var avgTotals = new double[4];
var avgRow = new dataRow();
for (int y = 0; y < 3; y++)
{
double avg = 0;
for (int x = 0; x < input.Count; x++)
{
avg += input[x][y];
}
avgTotals[y] = avg / input.Count;
}
avgRow.sun = avgTotals[0];
avgRow.temp = avgTotals[1];
avgRow.sun = avgTotals[2];
avgRow.wind = avgTotals[3];
return avgRow;
}
public dataRow getStdDev(List<double[]> input)
{
var stdDevTotals = new double[4];
var stdDevRow = new dataRow();
for (int y = 0; y < 3; y++)
{
double stdDev = 0;
for (int x = 0; x < input.Count; x++)
{
stdDev += Math.Pow(input[x][y] - this.avg.toArray()[y], 2);
}
stdDev = Math.Sqrt(stdDev/input.Count);
stdDevTotals[y] = stdDev / input.Count;
}
stdDevRow.sun = stdDevTotals[0];
stdDevRow.temp = stdDevTotals[1];
stdDevRow.sun = stdDevTotals[2];
stdDevRow.wind = stdDevTotals[3];
return stdDevRow;
}
}
</code></pre>
<p>Any advice or ideas? (All harsh criticism welcome!)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T14:02:12.997",
"Id": "70611",
"Score": "1",
"body": "To get you right, your code is basically working?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T14:40:05.550",
"Id": "70614",
"Score": "0",
"body": "sounds to me like it works @kleinfreund. the first set of wording was weird. but it sounds like it works when read all the way through"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T17:44:32.117",
"Id": "70641",
"Score": "2",
"body": "Method, Property, and Class names should be PascalCase in C#."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T18:40:18.363",
"Id": "70659",
"Score": "0",
"body": "Yes, I'm basically pulling in CSV data, creating a list of the datRow objects then having to pull data from each objects and insert them into arrays so I can loop through them and do calculations (trying to get avg, stdDev and then the Znormalization) \n\nPardon the poor phrasing on the question. What I want to know is if there's a better or easier way to do what I'm doing?\n\n\n@Magus I originally learned Java, old habits die hard. Noted though, thank you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T18:43:49.983",
"Id": "70661",
"Score": "0",
"body": "That's no excuse on `DataRow` - even *Java* does PascalCase class names."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T14:58:03.560",
"Id": "72299",
"Score": "1",
"body": "As pointed out the class names are not too good. Public members (including properties) stay PascalCase. Methods are PascalCase at all times (no excuses). Avoid abusing the var keyword, it's mainly handy for extremely long names. Your for loop variables should be named i, j, k, l ... rather than x and y. Also don't bother giving your variables short names, as with lots of similar short names it becomes unreadable. Why is `numK` public? Also what is KNN??? Try and use good/sensible names if you are unsure, put a comment saying `//Need to think of good name here`. My rant is over."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T19:27:54.140",
"Id": "72359",
"Score": "0",
"body": "Thank you for this, will help me write better code in future."
}
] |
[
{
"body": "<ol>\n<li><p>As others mentioned in comments, you should follow <a href=\"http://msdn.microsoft.com/en-us/library/ms229043\" rel=\"nofollow\">the .Net naming guidelines</a>. It will make your code consistent with all other .Net code.</p></li>\n<li><p>Try to avoid abbreviated names like <code>KNN</code>, because they can be confusing. And if that's supposed to mean <a href=\"https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm\" rel=\"nofollow\">k-nearest neighbors</a>, then I don't see how does your class compute that.</p>\n\n<p>This applies also to names like <code>numK</code>.</p></li>\n<li><p>Computing some statistics on your data should be separate from parsing inputs. So the constructor of <code>KNN</code> should take directly <code>numK</code> and <code>dataSet</code> and it should be the job of its caller to parse the inputs.</p></li>\n<li><p>If the common approach is to create a <code>DataRow</code> once and then never change it again, consider making it immutable: make the property setters <code>private</code> and create a constructor that can be used to set them.</p>\n\n<p>You could also add a constructor from an array of <code>double</code>s, as an counterpart of <code>ToArray()</code>.</p></li>\n<li><p>Both your <code>GetAverage()</code> and <code>GetStdDev()</code> follow the same pattern. I would try to abstract away this pattern into a separate method, to avoid repetition:</p>\n\n<pre><code>public static DataRow AggregateRows(\n this IList<DataRow> rows, Func<IEnumerable<double>, double> func)\n{\n return new DataRow\n {\n Sun = func(rows.Select(row => row.Sun)),\n Temp = func(rows.Select(row => row.Temp)),\n Humidity = func(rows.Select(row => row.Humidity)),\n Wind = func(rows.Select(row => row.Wind))\n };\n}\n</code></pre>\n\n<p>With this, both methods can be significantly simplified using the LINQ method <a href=\"http://msdn.microsoft.com/en-us/library/system.linq.enumerable.average\" rel=\"nofollow\"><code>Average()</code></a>:</p>\n\n<pre><code>public DataRow Average()\n{\n return dataSet.AggregateRows(values => values.Average());\n}\n\npublic DataRow StdDev()\n{\n return dataSet.AggregateRows(\n values =>\n {\n var average = values.Average();\n var variance = values.Average(value => Math.Pow(value - average, 2));\n return Math.Sqrt(variance);\n });\n}\n</code></pre>\n\n<p>Note that the structure of the expression for computing variance is very similar to the way it's normally written: E[(X - E[X])<sup>2</sup>].</p>\n\n<p>Also, if you do it this way, you won't need the <code>ToArray()</code> method anymore.</p></li>\n<li><p>If you have many types whose <code>ToString()</code> follows the same pattern, you could implement it just once using reflection and then use that implementation everywhere.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T16:00:43.877",
"Id": "41973",
"ParentId": "41146",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T13:30:28.137",
"Id": "41146",
"Score": "4",
"Tags": [
"c#",
"csv",
"statistics"
],
"Title": "Averages and standard deviations for a Knn application"
}
|
41146
|
<pre><code>#include <stdio.h>
#include <stdint.h>
#include <assert.h>
typedef uint8_t byte;
typedef struct
{
byte i, j;
byte S[256];
} Rc4State;
void swap(byte *a, byte *b)
{
byte temp = *a;
*a = *b;
*b = temp;
}
/*Initialization & initial permutation
also initialize i&j counters in state for stream generation*/
void initState(const byte K[256], int keylen, Rc4State *state)
{
byte T[256];
assert(keylen>=1 && keylen<=256);
int i;
for(i = 0; i < 256; i++) {
state-> S[i] = i;
T[i] = K[i % keylen];
}
//Initial permutation of S
byte *S = state->S;
int j = 0;
for(i = 0; i < 256; i++) {
j = (j + S[i] + T[i]) % 256;
swap(&S[i], &S[j]);
}
//Initialize counters in state
state->i = state->j = 0;
}
/*Encrypt/Decrypt text by XORing with next byte of keystream*/
byte crypt(byte text, Rc4State *state)
{
byte t, k;
byte *i = &(state->i), *j = &(state->j);
byte *S = state->S;
*i = (*i+1) % 256;
*j = (*j+S[*i]) % 256;
swap(&S[*i], &S[*j]);
t = (S[*i] + S[*j]) % 256;
k = S[t];
return text ^ k;
}
</code></pre>
<p>I considered removing the <code>%256</code> since it's implied in unsigned 8 bit arithmetic but left it in for clarity.</p>
<p><a href="https://stackoverflow.com/questions/21611184/is-arithmetic-overflow-equivalent-to-modulo-operation">I asked this on SO</a>.</p>
<p>Any comments would be appreciated.</p>
|
[] |
[
{
"body": "<p>From top to bottom…</p>\n\n<ul>\n<li><code>#include <stdio.h></code> appears to be left over from development, and can be removed.</li>\n<li><code>swap()</code> is not part of your library's interface, and should be declared <code>static</code>.</li>\n<li>To give your library a sense of unity, I'd rename <code>initState()</code> → <code>rc4InitState()</code> and <code>crypt()</code> → <code>rc4Crypt()</code>. The latter renaming is also important so as not to clash with the traditional Unix <a href=\"http://en.wikipedia.org/wiki/Crypt_(Unix)\"><code>crypt(3)</code></a> function. Also for consistency, I'd make <code>Rc4State *state</code> the first parameter of each function.</li>\n<li><p>Assertions are not really an appropriate mechanism for parameter validation. The use of <code>assert()</code> in <code>initState()</code> is marginal. You should assert conditions that you <em>know</em> to be true, rather than conditions that you <em>hope</em> to be true. Alternatively stated, assertion failures should arise from programmer errors, not user errors.</p>\n\n<p>Change <code>int keylen</code> to <code>uint8_t keylen</code>, and most of the validation problem goes away anyway. (In C, <code>i % 0</code> has undefined behaviour.)</p></li>\n<li>On the other hand, you <em>could</em> add an <code>assert((byte)(S[i] + 256) == S[i])</code> to put to rest your concerns about overflow.</li>\n<li>Calling <code>crypt()</code> to encrypt a byte at a time is inefficient. The function should accept a byte array and length. A compiler might inline a function, but if you're writing this as a library, the linker can't optimize away a function call.</li>\n<li><p><code>*i</code> and <code>*j</code> are a bit unconventional for my taste. Here's how I would express it:</p>\n\n<pre><code>static byte rc4CryptByte(Rc4State *state, byte plainText)\n{\n byte *S = state->S;\n byte i = ++(state->i);\n byte j = (state->j += S[i]);\n\n swap(&S[i], &S[j]);\n byte t = S[i] + S[j];\n byte k = S[t];\n\n return plainText ^ k;\n}\n\nvoid rc4Crypt(Rc4State *state, byte text[], size_t len)\n{\n for (size_t i = 0; i < len; i++)\n {\n text[i] = rc4CryptByte(state, text[i]);\n }\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T20:23:36.027",
"Id": "70677",
"Score": "0",
"body": "Actually, I wasn't implementing a library and I just copy pasted everything except the `main()` from my program."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T20:28:36.480",
"Id": "70678",
"Score": "0",
"body": "It would still be a good habit to write your code as if you were designing a library. The best practices I suggested cost you nothing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T20:35:03.580",
"Id": "70679",
"Score": "1",
"body": "Of course, I was simply clarifying. The main motive in posting to CR was to make a habit of following best practices.Thanks for the part on assert & static esp.\nAlso, I don't think I can make `keylen` as `uint8_t` as it won't be able to take the value 256."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T17:34:26.000",
"Id": "41169",
"ParentId": "41148",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "41169",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T14:05:46.077",
"Id": "41148",
"Score": "8",
"Tags": [
"c",
"cryptography"
],
"Title": "RC4 implementation in C"
}
|
41148
|
<p>Suppose I have the array:</p>
<pre><code>double[] arrayToCut = new double[100];
for(int i = 0 ; i < 100 ; ++i) {
arrayToCut[i] = Math.random();
}
</code></pre>
<p>My objective is to end up with two arrays, <code>firstArray</code> and <code>secondArray</code>. <code>firstArray</code> is equal to (for example);</p>
<pre><code>double[] firstArray = new double[50];
for(int i = 0 ; i < 50 ; ++i) {
firstArray[i] = arrayToCut[i];
}
</code></pre>
<p>and <code>secondArray</code> is defined analogously (taking values from <code>arrayToCut</code> from <code>50</code> to <code>99</code> index).</p>
<p>However, this is linear time complexity and I want to cut gigantic arrays over 1 million in length. How can I speed up the above code (reduce computational overhead in any way for large arrays, whether by time complexity reduction or some other approach)?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T15:49:33.233",
"Id": "70621",
"Score": "1",
"body": "see: http://stackoverflow.com/questions/1100371/grabbing-a-segment-of-an-array-in-java"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T17:54:29.047",
"Id": "70647",
"Score": "4",
"body": "And here I was hoping it was C and would be a simple pointer question..."
}
] |
[
{
"body": "<p>I am pretty sure you can use <code>copyOfRange(double[] original, int from, int to)</code> from <code>java.util.Arrays</code>. @Rolfl said, and I quote : <em>It is recommended practice to use Arrays.copyOf instead of System.arraycopy().</em></p>\n\n<p>If you need to cut up the million+ array for parallel processing, then I would suggest you chunk the data while reading it, this should save you a processing step.</p>\n\n<hr>\n\n<p>Edit: Internally, <code>Arrays.copyOf()</code> uses <code>System.arraycopy()</code> to do the hard work of duplicating the Array data in the new copy, and it will make your code look like this simple 1-liner:</p>\n\n<pre><code>double[] firstArray = Arrays.copyOf(arrayToCut, 50);\ndouble[] secondArray = Arrays.copyOfRange(arrayToCut, 50, 100);\n</code></pre>\n\n<p>While using <code>System.arraycopy()</code> may seem like the fastest alternative, whenever you copy an array you have to:</p>\n\n<ul>\n<li>first create the destination for the data to be copied to. This step requires initializing all the destination array points to their initialization values, which is a linear operation, but done in native code, so is fast.</li>\n<li>then call the System.arraycopy() for the actual data re-write.</li>\n</ul>\n\n<p>There are many ways that people may want to do this operation, and the various <code>Arrays.copy*()</code> methods are designed to make the relatively mundane, yet still rather complicated and bug-prone process a lot simpler, and less buggy.</p>\n\n<p><a href=\"http://www.developer.com/java/data/article.php/3680241/Copying-Arrays-in-Java-6.htm\" rel=\"nofollow noreferrer\">Whenever you have a use case where you are copying data from one array to a <strong>new</strong> array, you should by default use the <code>Arrays.copy*()</code> methods.</a> Only when you have a use case where you are overwriting data in to an existing array (or relocating data inside an array) should you use <code>System.arraycopy()</code>. As for the performance aspect, it appears that the <a href=\"https://stackoverflow.com/a/12157504/1305253\">performance of most native mechanisms are similar</a>.</p>\n\n<p>Arrays.copy* methods lead to better, more maintainable, and less buggy code, and, there is essentially no performance penalty because it is just doing the work you were going to do anyway.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T14:44:01.937",
"Id": "70616",
"Score": "0",
"body": "This will actually call System.arrayCopy, as can be seen [in the source](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Arrays.java#Arrays.copyOfRange%28double%5B%5D%2Cint%2Cint%29)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T14:52:29.770",
"Id": "70617",
"Score": "0",
"body": "Right your are!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T03:23:57.447",
"Id": "71044",
"Score": "1",
"body": "+1 because 10 is so much nicer than 9, and 11 silver / 77 bronze is so much better than 11 silver / 76 bronze ;)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T14:36:58.993",
"Id": "41154",
"ParentId": "41151",
"Score": "10"
}
},
{
"body": "<p>The method <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#arraycopy(java.lang.Object,%20int,%20java.lang.Object,%20int,%20int)\" rel=\"nofollow noreferrer\">System.arrayCopy(...)</a> invokes the native JIT implementation code for copying arrays and <a href=\"https://stackoverflow.com/questions/8526907/is-javas-system-arraycopy-efficient-for-small-arrays\">is the fastest alternative for large arrays</a>.</p>\n\n<p>In the end though, <code>Arrays.copyOfRange</code> is actually calling <code>System.arrayCopy</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T14:39:26.337",
"Id": "41155",
"ParentId": "41151",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "41154",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T14:25:23.427",
"Id": "41151",
"Score": "8",
"Tags": [
"java",
"performance",
"array"
],
"Title": "Fastest way to cut an array into two arrays at a particular index"
}
|
41151
|
<p>I have 2 tables as below:</p>
<p>Downtime</p>
<p><img src="https://i.stack.imgur.com/7YdFT.jpg" alt="enter image description here"></p>
<p>DowntimeCode</p>
<p><img src="https://i.stack.imgur.com/27LDb.jpg" alt="enter image description here"></p>
<p>I am then doing this to get the Description field from the DowntimeCode table for the DowntimeCode with the sum highest value in the Downtime table for the current date and a specified line:</p>
<pre><code>public string TopCodeForToday(string line)
{
var date = DateTime.Now;
using (var db = new PillowContext())
{
var qry = (from d in db.DownTimes
where DbFunctions.TruncateTime(d.DateTime) == DbFunctions.TruncateTime(date) && d.Line == line
group d by new { d.Code }
into g
let total = g.Sum(x=>x.Amount)
orderby total descending
select new { g.Key.Code, Total = total }).ToList();
for (int i = 0; i <= 1; i++)
{
foreach (var item in qry)
{
int x = item.Code;
var result = from r in db.DownTimeCodes
where r.Code == x
select r.Description;
return result.FirstOrDefault();
}
}
}
return "Fail";
}
</code></pre>
<p>Now this is working OK but I can't help but think there is a simpler way of doing it. I'm also not too hot on error handling (hence there not being any). Can anyone make any recommendations on how to improve and streamline the above?</p>
|
[] |
[
{
"body": "<p>I don't understand your <code>for</code> and <code>foreach</code> loops - you always return from the first iteration!</p>\n\n<p>What's wrong with this code?:</p>\n\n<pre><code>public string TopCodeForToday(string line)\n{\n var date = DateTime.Now;\n\n using (var db = new PillowContext())\n {\n var qry = from d in db.DownTimes\n where DbFunctions.TruncateTime(d.DateTime) == DbFunctions.TruncateTime(date) && d.Line == line\n group d by new { d.Code }\n into g\n let total = g.Sum(x=>x.Amount)\n orderby total descending \n select new { g.Key.Code, Total = total };\n\n var item = qry.FirstOrDefault();\n if (item == null) {\n return \"Fail\";\n }\n int x = item.Code;\n var result = from r in db.DownTimeCodes\n where r.Code == x\n select r.Description;\n\n return result.FirstOrDefault(); \n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T17:10:28.593",
"Id": "70628",
"Score": "0",
"body": "instead of creating the `x` variable you could just say `where r.Code == item.Code`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T17:41:56.153",
"Id": "70640",
"Score": "0",
"body": "Sorry, totally agree with you. I had a brain fart and forgot about FirstOrDefault so originally I was trying to do it with result.ToString (hence the need for the loops to narrow it down to 1 result). I then realised that this will return the actual query string so amended it but forgot to take the loops out."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T15:58:05.153",
"Id": "41159",
"ParentId": "41156",
"Score": "6"
}
},
{
"body": "<p>Not having any error handling in your <code>TopCodeForToday()</code> method, means <em>if anything goes wrong</em>, you're putting the burden of catching any exceptions onto the caller.</p>\n\n<p><strong>And this isn't necessarily a bad thing</strong>. It depends on what the client code is expecting.</p>\n\n<p>We don't know what class this method is a member of. The problem is that the <em>naming</em> of the method doesn't convey any information about <em>what's going on</em>, and <em>whether the calling code should wrap it with a <code>try/catch</code> block</em>. If the class is <strong>clearly</strong> an object that accesses a database <strong>and only does <code>SELECT</code> operations</strong>, then it's probably fine. Otherwise the method's name should say what it's doing - <code>SelectTopCodeForToday()</code> would be a better name regardless of all of the above, be it only because <em>it starts with a verb</em>.</p>\n\n<hr>\n\n<p>I don't think returning a string that says \"Fail\" is a good idea. Replace <code>FirstOrDefault()</code> with <code>First()</code> and let it throw an exception, and then your client code will know that something is wrong with the data.</p>\n\n<p>The problem with returning a \"Fail\" string, is that <strong>it's a valid string</strong>. And then the client code needs to verify whether the function returned \"Fail\" or not. By throwing, you only handle the \"happy\" path, making your code more focused; and you handle exceptional situations with ...exceptions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T17:48:56.593",
"Id": "70643",
"Score": "0",
"body": "Thank you for the explanation. Makes sense. This class is just performing select statements but now you come to mention it the naming convention isn't ideal. The \"Fail\" string was just a placeholder I put there for now until I could work out how to error handle the method properly."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T16:56:30.550",
"Id": "41164",
"ParentId": "41156",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "41164",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T14:40:32.340",
"Id": "41156",
"Score": "6",
"Tags": [
"c#",
"linq",
"error-handling"
],
"Title": "Optimising and error handling Linq query"
}
|
41156
|
<p>I am brand new to C++ and am working with the Arduino micro controller. The project I've been working on for my university requires me to write code to do the following:</p>
<blockquote>
<ul>
<li><p>If the ultrasonic sensor detects a distance within a certain range, output HIGH to activate an electric motor</p></li>
<li><p>If the sensor detects distance outside this range, outputs LOW to deactivate the motor</p></li>
</ul>
</blockquote>
<ul>
<li><p>I hope to create an array that will average the readings from the ultrasonic sensor over a .5 sec - 1 second interval and then output that average.</p></li>
<li><p>I started with a rangefinder script that went along with a tutorial provided on Arduino's website, so my goal is to modify that script to fit into my goals to output HIGH or LOW based on the code that I've tested and already works well to test for distance.</p></li>
</ul>
<p>I am looking for any tips to create an array to average the distance from the sensor, then using a <code>for</code> loop to test whether it is in the interval and output HIGH or LOW.</p>
<p>Any help and direction would be appreciated!</p>
<pre><code>const int TriggerPin = 8; //sensor trigger pin
const int EchoPin = 9; //sensor echo pin
const int MotorPin = 7; //motor out pin
long Duration = 0;
void setup(){
pinMode(TriggerPin,OUTPUT); //sets trigger as output
pinMode(EchoPin,INPUT); //sets echo as input
pinMode(MotorPin,OUTPUT); //sets motor as output
Serial.begin(9600); //displays to serial monitor
}
void loop(){
digitalWrite(TriggerPin,LOW); //trigger pin to 0V
delayMicroseconds(2); //waits 2 us
digitalWrite(TriggerPin,HIGH); //trigger pin to 5V
delayMicroseconds(10); //10 us delay to recieve ping
digitalWrite(TriggerPin,LOW);
Duration = pulseIn(EchoPin,HIGH); //waits for echo pin to get high
//pulseIn returns the Duration in microseconds
long Distance_mm = Distance(Duration); //uses function to calc. distance
delay(100); //delay half second, do next measurement
}
long Distance(long time);
{
long DistanceCalc; //calculation variable
DistanceCalc = ((time /2.9) / 2);
//want to average this DistanceCalc reading over 10 readings, then use this value to compare to the desired range
void loop(){
if (dist_avg < 600 && dist_avg > 400);
digitalWrite(MotorPin,HIGH);
else
digitalWrite(MotorPin,LOW);
}
//if average distance is within .4-.6 meter range, output HIGH; turns motor on
//if avergae distance is outside .4-.6 meter range, outut LOW; turns motor off
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T17:14:35.180",
"Id": "70629",
"Score": "0",
"body": "what kind of average do you want? there is the running average: this reading + next reading / 2, or it's the framed average: sum of last x readings / x - these will prbably be the most reasonable as you want to adopt to change, not actually find the total average of all readings"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T17:49:12.507",
"Id": "70644",
"Score": "0",
"body": "The framed average: Like you said I would like to respond and adopt to the average reading. It was suggested to me that taking the average of a few readings would help reduce the risk of a outlier value to be taken into account and causing the response when it wasn't desired. I'm writing this to control a greenhouse harvest cart, and desire the cart to react to the presence of a harvester: if he is in the correct range, the cart will move continuously as he picks fruit, and if he is outside the range, the motor turns off."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T17:54:28.523",
"Id": "70646",
"Score": "0",
"body": "right I see, you should first refactor your loop that genereates the duration and your Distance function into one function. Then you can call that x times in a row and store the values in an array, before you then get an average.\nBeware that you have a bug here 'if (dist_avg < 600 && dist_avg > 400);' the if will never trigger the following code block, becuase you terminate the statement with ;"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T18:16:17.953",
"Id": "70655",
"Score": "0",
"body": "I'm very novice with coding so I am confused as to how I would combine the duration and Distance into one function. To clarify, you suggest letting the distance function run x times in a row, store these values in an array, and then average that set. I removed the ; to allow the code to continue to run if the condition isn't met on the first 'if'. If you could provide an example of how to combine the function and also to create the array to be averaged, that would be enormously helpful! And thank you in the first place for the help so far"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T22:06:26.523",
"Id": "70788",
"Score": "0",
"body": "How exactly are `HIGH` and `LOW` defined? With the way they're named, I assume they're macros."
}
] |
[
{
"body": "<ul>\n<li><p>As per C++ naming convention, only user-defined types and macros in C++ are capitalized. Your constants, global variable, and functions should start with a lowercase letter.</p></li>\n<li><p>Since your constants are similar, you can group them into an <a href=\"http://www.cprogramming.com/tutorial/enum.html\" rel=\"nofollow\"><code>enum</code></a> instead:</p>\n\n<pre><code>enum Pin { Motor=7, Trigger, Echo };\n</code></pre>\n\n<p>With the first one set to 7, the following ones will be set to 8 and 9 respectively.</p>\n\n<p>This could also help with code maintenance. If you ever need to add another <code>Pin</code>, you just need to insert it into the <code>enum</code> appropriately, as opposed to creating another constant.</p></li>\n<li><p><code>Duration</code> is only used in <code>loop()</code>, so just initialize and use it there. Having it as a global variable could invite bugs, and is otherwise bad practice. This applies to global variables in general because they're accessible throughout the entire program, meaning they can be changed <em>anywhere</em>.</p></li>\n<li><p>You're using \"magic numbers\" (hard-coded numbers) in places. You should either make them variables or constants, or provide comments to specify their meaning.</p></li>\n<li><p>Your indentation is quite inconsistent. You indent a different number of spaces in different functions, but you should stick to one (most common is four spaces). You especially should have indentation within functions, otherwise it may appear that the code isn't contained within that function.</p></li>\n<li><p>This isn't syntactically correct:</p>\n\n<pre><code>if (dist_avg < 600 && dist_avg > 400);\ndigitalWrite(MotorPin,HIGH);\nelse\ndigitalWrite(MotorPin,LOW);\n</code></pre>\n\n<p>There shouldn't be a semicolon after the <code>if</code> condition, otherwise the following statements won't work with it. The second and fourth lines should also be indented.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T20:19:04.067",
"Id": "41250",
"ParentId": "41160",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T16:08:02.490",
"Id": "41160",
"Score": "4",
"Tags": [
"c++",
"beginner",
"arduino"
],
"Title": "Arduino based ultrasonic sensor program, output HIGH to control electric motor"
}
|
41160
|
<p>Aim: To have only one of each character on the Return string:</p>
<pre><code>Public Shared Function CheckForDuplicates(ByVal vCharCheck As String) As String
Dim vDeDuplicated As String = ""
Dim i As Integer
For i = 1 To vCharCheck.Length ' Count length of string
'vDeDuplicate is blank to start so will always capture first character
'vDeDuplicate is then checked against each character in the incoming string to see if it contains this character already
'thus deduplicting the string
If vDeDuplicated.Contains(Mid(vCharCheck, i, 1)) Then
'Check the new string to see if it exists, if it does it is not allowed
Else
'The character is not found so we add it
vDeDuplicated += Mid(vCharCheck, i, 1)
End If
Next
Return vDeDuplicated
End Function
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T17:41:48.340",
"Id": "70639",
"Score": "1",
"body": "I think we are missing some code, some of this doesn't make sense, how is `vCharCheck` determined/populated? where do you assign a value to `vDeDuplicated`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T21:01:06.890",
"Id": "70681",
"Score": "0",
"body": "Added a note. A string input to a function"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T21:17:06.147",
"Id": "70683",
"Score": "0",
"body": "@indofraiser It would be easier if you added the function definition to the code."
}
] |
[
{
"body": "<p>you should change the code around a little bit so that if the string is empty it will exit the code before hitting the loop. and you should use a <code>foreach</code> instead of a <code>for</code>\nand get rid of all the Mid stuff</p>\n\n<pre><code>For Each Character As Char In vCharCheck\n If Not vDeDuplicated.Contains(Character) Then\n vDeDuplicated += Character\n End If\nNext\n</code></pre>\n\n<hr>\n\n<p><strike>the loop won't run if the Length of <code>vCharCheck</code> is less than 1 so you don't really have to check that it contains a first letter.</p>\n\n<p>I am sorry it will run, infinitely I think, because it will start at <code>1</code> and loop until it reaches <code>0</code> and nothing will happen inside the loop</strike></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T17:47:58.127",
"Id": "70642",
"Score": "3",
"body": "Loop will not run infinitely ... [. Before the statement block runs, Visual Basic compares counter to end. If counter is already larger than the end value (or smaller if step is negative), the For loop ends and control passes to the statement that follows the Next statement](http://msdn.microsoft.com/en-us/library/5z06z1kb.aspx)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T17:50:32.683",
"Id": "70645",
"Score": "0",
"body": "@rolfl, that makes sense. but shouldn't. *VB*"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T18:07:32.943",
"Id": "70649",
"Score": "0",
"body": "I think checking the string length before the `foreach` loop adds complexity. The `foreach` inherently checks for an empty string because if the string is empty, it will not execute. By removing the `If`, you have reduced nesting, made the code flow, and made it less confusing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T18:11:45.670",
"Id": "70652",
"Score": "0",
"body": "@JeffVanzella the whole point of checking it outside is to keep the stuff inside of it from trying to run if it doesn't have to."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T18:14:54.160",
"Id": "70653",
"Score": "0",
"body": "It won't run if the string is empty period. The `if` is implied in the `foreach`. `For Each Character As Char in \"\"' will result in 0 loops, and it takes as much time as the `If` statement therefore, the `If` statement is just adding extra code to figure out at a later date."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T18:18:41.507",
"Id": "70656",
"Score": "1",
"body": "@JeffVanzella, that makes sense and I agree with you. plus I had the wrong variable in that if statement as well"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T17:30:04.337",
"Id": "41168",
"ParentId": "41165",
"Score": "5"
}
},
{
"body": "<p>Of course you can eliminate the loop by using the Distinct method of the string, which won't care if the string is empty or not. Assuming vCharCheck is the input string, it would look something like this:</p>\n\n<pre><code>Return New String(vCharCheck.Distinct.ToArray)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T21:20:36.840",
"Id": "71012",
"Score": "2",
"body": "In a similar vein: `String.Concat(vCharCheck.Distinct)`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T03:40:18.567",
"Id": "41265",
"ParentId": "41165",
"Score": "7"
}
},
{
"body": "<p>There are also two minor improvements that could increase the performance of your function - although they do add a little bit of complexity to the final code. </p>\n\n<ol>\n<li><p>Decrease complexity using a structure that allows constant time character lookup.</p>\n\n<p>Your implementation uses the result string (<code>vDeDuplicated</code>) as a placeholder for the unique characters. Therefore, for every character c read from the input string, there is a call to <code>vDeDuplicated.Contains(c)</code> - which executes a linear search on <code>vDeDuplicated</code>. That could be avoided if we used a hashtable or an array, indexed by the character code itself. We can now check for repeated characters in constant time:</p>\n\n<pre><code>'if the string is encoded in ASCII, we only need 128 elements \n'to store every existing character. \n'For unicode strings, you can change it to 65536\nDim vDeDuplicated(128) As Boolean \nDim result As String = \"\"\n\nFor Each Character As Char In vCharCheck\n 'using the character numeric code as an index - constant time lookup\n If Not vDeDuplicated(AscW(Character)) Then\n result += Character\n vDeDuplicated(AscW(Character)) = True\n End If\nNext\n\nReturn result\n</code></pre></li>\n<li><p>Use a StringBuilder to generate your result.</p>\n\n<p>Since strings are immutable in VB.NET, using the string concatenation operator (+) will always generate new strings, leading to a significant performance penalty. As a rule of thumb, you should always try to use StringBuilder when the number of concatenations you need to perform is not known at compile time. These are some nice articles on that matter:</p>\n\n<ul>\n<li><p><a href=\"http://yoda.arachsys.com/csharp/stringbuilder.html\" rel=\"nofollow\">Concatenating Strings Efficiently - Jon Skeet</a></p></li>\n<li><p><a href=\"http://www.codinghorror.com/blog/2009/01/the-sad-tragedy-of-micro-optimization-theater.html\" rel=\"nofollow\">The Sad Tragedy of Micro-Optimization Theater - Jeff Atwood</a></p></li>\n</ul></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T16:52:01.357",
"Id": "71126",
"Score": "1",
"body": "I agree with your second point that we should be using a StriungBuilder, but the first point looks like we are adding complexity that isn't needed here. the other two answers cover this situation much better than adding a new variable array into the mix, it just doesn't seem logical to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T17:18:10.830",
"Id": "71129",
"Score": "1",
"body": "Yes, I agree! At least from the point of view of code quality/maintainability - and that's why I added the remark that \"they do add a little bit of complexity to the final code.\". However, one cannot ignore the fact that we are decreasing complexity from O(n^2) to O(n) by adding a couple of lines (this is actually a pretty well known technique for implementing character lookup efficiently). The OP was not concerned with performance/complexity, but nonetheless I think this is an aspect that could/should be addressed in code review. Accepted answer is definitely much simpler, though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T17:27:32.230",
"Id": "71134",
"Score": "0",
"body": "I will give it the UpVote, I was on the fence and you pushed me off of it onto the upvote side"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T18:09:39.510",
"Id": "41352",
"ParentId": "41165",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "41265",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T17:01:26.243",
"Id": "41165",
"Score": "6",
"Tags": [
"strings",
"vb.net"
],
"Title": "Creating new string with only distinct letters"
}
|
41165
|
<p>So I developed some code as part of a larger project. I came upon a problem with how to match paragraphs, and wasn't sure how to proceed, so I asked on Stack Overflow <a href="https://stackoverflow.com/questions/21466890/paragraph-matching-python">here</a>. You can find an in-depth description of my problem there if you're curious.</p>
<p>Just to be clear, <strong>I am not reposting the same question here to get an answer.</strong></p>
<p>I came up with a solution to my own problem, but I'm unsure of limits/pitfalls, and here seems like the perfect place for that. </p>
<p><strong>The short version on the explanation is this:</strong> I have two strings, one is the revised version of the other. I want to generate markups and preserve the paragraph spacing, thus, I need to correlate the list of paragraphs in each, match them, and then mark the remaining as either new or deleted.</p>
<p>So I have a function (<code>paraMatcher()</code>) which matches paragraphs and returns a list of tuples as follows:</p>
<ul>
<li><p><code>(num1, num2)</code> means that the best match for revised paragraph <code>num1</code> is original paragraph <code>num2</code></p></li>
<li><p><code>(num, '+')</code> means that there is no match for revised paragraph <code>num</code>, so it must be new (designated by the <code>'+'</code>)</p></li>
<li><p><code>(num, '-')</code> means that no revised paragraph was matched to original paragraph <code>num</code> so it must have been deleted (designated by the <code>'-'</code>)</p></li>
</ul>
<p>So without further adiue, here is my function:</p>
<pre><code>def paraMatcher(orParas, revParas):
THRESHOLD = 0.75
matchSet = []
shifter = 0
for revPara in revParas:
print "Checking revPara ", revParas.index(revPara)
matchTuples = [(difflib.SequenceMatcher(a=orPara,b=revPara).ratio(), orParas.index(orPara)) for orPara in orParas]
print "MatchTuples: ", matchTuples
if matchTuples:
bestMatch = sorted(matchTuples, key = lambda tup: tup[0])[-1]
print "Best Match: ", bestMatch
if bestMatch[0] > THRESHOLD:
orParas.pop(bestMatch[1])
print orParas
matchSet.append((revParas.index(revPara), bestMatch[1] + shifter))
shifter += 1
else:
matchSet.append((revParas.index(revPara), "+"))
print ""
print "---------------"
print ""
if orParas:
print "++++++++++++++dealing with extra paragraphs++++++++++++++"
print orParas
for orPara in orParas:
matchSet.insert(orParas.index(orPara) + shifter, (orParas.index(orPara) + shifter, "-"))
return matchSet
</code></pre>
<p>While I definitely want review of general coding style, etc, here are a few issues that I'm really interested in getting feedback on:</p>
<ul>
<li>The function needs to be called with copies of the lists (<code>paraMatcher(lst1[:], lst2[:])</code>)</li>
<li>How might this fail?</li>
<li>How do I determine an appropriate value for <code>THRESHOLD</code></li>
</ul>
<p><strong>Some Extra Notes:</strong></p>
<ul>
<li>I've left the diagnostic printing in there in case any of you want to test it</li>
<li>Due to other parts of the code, its more convenient that this function take lists of paragraphs as arguments, rather than the strings</li>
<li>I don't think it matters, but this is 32-bit Python 2.7.6 running on 64-bit Windows 7</li>
</ul>
|
[] |
[
{
"body": "<p>A few tips for leaner code:</p>\n\n<ul>\n<li><p>Use <code>enumerate</code> while iterating when you need the index, to avoid the sequential search and extra verbosity of <code>orParas.index(orPara)</code>. For example the last loop becomes</p>\n\n<pre><code>for orIndex, orPara in enumerate(orParas):\n matchSet.insert(orIndex + shifter, (orIndex + shifter, \"-\"))\n</code></pre></li>\n<li><p><code>max(matchTuples)</code> achieves the same as <code>sorted(matchTuples, key = lambda tup: tup[0])[-1]</code> and avoids sorting. You could even give a <code>key</code> argument to <code>max</code>, but tuples are sorted item by item anyway, and here the second item is an ascending integer, so including it in the sort key does not change the order.</p></li>\n<li>Unpacking <code>bestRatio, bestIndex = max(matchTuples)</code> improves readability as you can use <code>bestRatio</code> instead of <code>bestMatch[0]</code> in the code that follows.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T11:47:20.747",
"Id": "41221",
"ParentId": "41167",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T17:16:16.023",
"Id": "41167",
"Score": "4",
"Tags": [
"python",
"python-2.x"
],
"Title": "Paragraph Matching in Python"
}
|
41167
|
<p>One of the books I'm currently reading to learn C# asked me to write a method that takes an integer between 1 and 99999 and displays each number in that integer in a sequence, separating each digit by 2 spaces.</p>
<p>For example: the int <code>87564</code> would be written to the console as <code>8 7 5 6 4</code>.</p>
<p>This is simple enough to do using the input as a string, converting it to a char array, or looping over the string with a <code>foreach</code> and printing out a formatted string for each character.</p>
<p>For fun though and mostly to challenge myself, I like to work out the problems as they are intended for someone just learning the concepts for the first time. The chapter was about methods and briefly introduced recursion. It's clearly the author's intent that you solve this using division and modulus operations to pick off each digit and then write them out.</p>
<p>So there really were limited options in terms of solving this with the material you have learned to this point in the book. You could pick off each digit and store it as it's own variable, then later write them out in order since you know the range of integers.</p>
<p>I decided to make the method more useful by really allowing any non-negative integer and my approach involved recursion. I'm not really experienced using recursion so I'd like to get some feedback on my implementation to see what I could have done better.</p>
<pre><code>public class Program
{
static void Main()
{
// Get User Input From Console
// Validate and parse as int input
DisplayDigits(input);
}
static void DisplayDigits(int value)
{
if (value < 10)
{
Console.Write("{0} ", value);
return;
}
DisplayDigits(value / 10);
Console.Write("{0} ", value % 10);
}
}
</code></pre>
<p>Obviously, this is not meant to be production level code, I'm solving the problem in the textbook and then throwing the code away.
It appears to be working for all non-negative numbers I've tried. I even wrote an overload that takes a <code>ulong</code> and passed it <code>UInt64.MaxValue</code> and it printed everything fine. I can't help but feel like maybe it could be better in some way. Any criticism, suggestions, links to more reading material would be appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T18:30:34.740",
"Id": "70658",
"Score": "1",
"body": "Welcome to CR! This small snippet makes your post very focused on the specific problem you're trying to solve (which isn't *bad* in itself). You'd probably get a more thorough review if you included the entire code (I presume `DisplayDigits` is `static` because it's called from `static void Main()`?)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T13:54:35.143",
"Id": "70733",
"Score": "1",
"body": "Your code displays the digits in reverse order. Not in the same order as they appera in your example."
}
] |
[
{
"body": "<p>Your method is lying. Not only it's <em>displaying the digits</em>, performing every <code>Console.Write</code> operation that needs to happen, it's also performing the \"digit-splitting\" logic.</p>\n\n<p>It's more work than what its name says. For a simple coding exercise it's without consequences, but in larger projects if this is a coding habit you have, it can mean much bigger problems.</p>\n\n<p><strong>Separation of Concerns</strong></p>\n\n<p>Let's see what needs to happen here.</p>\n\n<ul>\n<li>Get a valid user input.</li>\n<li>Determine what the digits are.</li>\n<li>Come up with a <code>string</code> to output.</li>\n</ul>\n\n<p>You haven't included how you're addressing the first concern, so I won't cover it here.</p>\n\n<p>Ideally, the result of <em>determining what the digits are</em> should be just that: some <code>IEnumerable<int></code> that contains all the digits you want to display. I would make it so that the recursive function that contains the logic for that, works with an <code>IList<int></code> and adds each digit it finds (instead of outputting it directly to the console).</p>\n\n<p>Then, when your recursive logic completes, you have an <code>IEnumerable<int></code> to iterate through. Right? Maybe not. <code>string</code> has methods, such as <code>Join()</code> that can make your \"digit separator\" string very explicit - if you're using .net 4+ you can use the <a href=\"http://msdn.microsoft.com/en-us/library/dd992421%28v=vs.110%29.aspx\"><code>Join<T>(string, IEnumerable<T>)</code> overload</a>:</p>\n\n<pre><code>var input = GetValidUserInput();\nif (string.IsNullOrEmpty(input))\n{\n return;\n}\n\nvar digits = SeparateTheDigits(input);\n\nvar separator = \" \";\nvar result = string.Join(separator, digits);\n\nConsole.WriteLine(result);\n</code></pre>\n\n<p>As a result of separating the concerns, you now only write to the console once... and you haven't hard-coded your digit separator into a format string.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T19:08:55.237",
"Id": "70663",
"Score": "1",
"body": "Perhaps `GetValidUserInput()` is going to validate that the input is a valid number - in that case you'll probably want the method to return an `int`, so `SeparateTheDigits` can work off an `int` instead of directly with the user's input."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T19:14:56.113",
"Id": "70665",
"Score": "0",
"body": "I like to keep my logic on the same level of complexity and if you want to do that you would move the separator/result/write into a separate method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T19:29:13.653",
"Id": "70672",
"Score": "3",
"body": "I guess this question is more about maximizing and working within the restrictions of the textbook. At this point, the author hasn't talked about `arrays` or working with the `String` class. At the end of the day it's throwaway code from a textbook exercise, but for the sake of mastering the simple things, I thought I'd see what else could be done without using arrays or treating it as a string. The author assumes you will get the input from `Console.ReadLine` and use `Convert.ToInt32`. I think for this particular case, all I could really do is have `GetDigits` return a string instead."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T18:57:57.760",
"Id": "41176",
"ParentId": "41174",
"Score": "20"
}
},
{
"body": "<p>I strongly agree with lol.upvote answer, regarding the separation of concerns. I Think you should have a method to get the chars and then present them to the user, because you may need know what chars of a number are later. And so I made all the major approaches that you may have when implementing a GetDigits. A iterative, recursive and a straightforward way:</p>\n\n<pre><code>public static char[] GetDigitsRecursive(int value){\n int length = value.ToString().Length;\n return GetDigitsRecursiveAux(value, new char[length], length-1);\n}\n\nprivate static char[] GetDigitsRecursiveAux(int value, char[] digits, int idx){\n digits[idx] = (char)(value % 10 + '0');\n if(value <= 9){\n return digits;\n }\n return GetDigitsRecursiveAux(value/10, digits, idx-1);\n}\n\npublic static char[] GetDigitsIterative(int value){\n char[] digits = new char[value.ToString().Length];\n for(int i = digits.Length-1; i >= 0; --i){\n digits[i] = (char)(value %10 + '0');\n value = value / 10;\n }\n return digits;\n}\n\npublic static char[] GetDigitsSimplistic(int value){\n return value.ToString().ToCharArray();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T19:18:03.033",
"Id": "70668",
"Score": "2",
"body": "Nice! lol.upvoted!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T16:17:49.940",
"Id": "72324",
"Score": "2",
"body": "It feels weird to call `ToString()`, which almost does what is needed here and then throw away its result except for the length."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T17:01:41.330",
"Id": "72328",
"Score": "0",
"body": "It is quite true, that's why I pointed out the third way (and that's the one I would use). The other ones are exercises only. But if you would rather do a function to count the digits then it's your call..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T19:14:12.660",
"Id": "41177",
"ParentId": "41174",
"Score": "8"
}
},
{
"body": "<p>I'm not too worried about separation of concerns for such a simple problem. You should try to eliminate a <code>Console.Write()</code> repetitive call, though.</p>\n\n<pre><code>static void DisplayDigits(int value)\n{\n if (value >= 10)\n {\n DisplayDigits(value / 10);\n }\n Console.Write(\"{0} \", value % 10);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T03:29:51.333",
"Id": "70809",
"Score": "0",
"body": "This is pretty much the type of feedback I was looking for. I understand the usefulness of separation of concerns and why writing code that way is important, this was more about picking out little details (too many `Console.Write` calls)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T22:52:19.307",
"Id": "41186",
"ParentId": "41174",
"Score": "8"
}
},
{
"body": "<p>Here is a more functional approach using recursion and returns back the formatted string rather than writing to Console.</p>\n\n<pre><code>static \nstring\nFormatDigits(\n int value)\n{\n return\n value < 10\n ? value.ToString()\n : String.Format(\n \"{0} {1}\",\n FormatDigits(value / 10),\n value % 10);\n\n}\n</code></pre>\n\n<p>Update: \nSome explanation for those unfamiliar with recursion or find this code difficult to digest. Recursion provides a way to reduce the problem into a set of smaller problems and simpler solutions.</p>\n\n<p>There are 2 cases here. </p>\n\n<ol>\n<li>If the value < 10 (exactly one digit)<br>\nSimply convert the digit to a string, (value.ToString()) and return it </li>\n<li>If the value >= 10 (more than one digit)<br>\nThe value % 10 will give the last digit, use this value as the last character of the result (with a space prefix) the \" {1}\" part of the string format.<br>\n The problem is now reduced to doing the same thing all over again, this time with a value without the last digit (value / 10) and placing the result in the \"{0}\" part of the format string. </li>\n</ol>\n\n<p>Update 2:\nDon't like the string format or find it difficult to understand? Here is another refactor.</p>\n\n<pre><code>static string FormatDigits(int value)\n{\n return value < 10\n ? value.ToString()\n : FormatDigits(value / 10) + \" \" + FormatDigits(value % 10);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T01:07:47.440",
"Id": "41197",
"ParentId": "41174",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41186",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T18:21:07.157",
"Id": "41174",
"Score": "19",
"Tags": [
"c#",
"recursion",
"integer"
],
"Title": "Displaying each number of an integer in a sequence"
}
|
41174
|
<p>I want to draw the table like this:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>6³ = 3³ + 4³ + 5³
9³ = 1³ + 6³ + 8³
12³ = 6³ + 8³ + 10³
18³ = 2³ + 12³ + 16³
18³ = 9³ + 12³ + 15³
19³ = 3³ + 10³ + 18³
20³ = 7³ + 14³ + 17³
.....
100³ = 35³ + 70³ + 85³
</code></pre>
</blockquote>
<p>I've tried this: </p>
<pre class="lang-php prettyprint-override"><code>$start = microtime(true);
funcC(100);
echo microtime(true) - $start;
function funcC($n){
$tnum = 3;
$s = '³';
$testmax = $n-$tnum;
$p3a = array();
$numlist = array_fill(0, 10, array());
for ($i = 0; $i <= $n; $i++) {
$j = pow($i,3);
$p3a[] = $j;
$numlist[$j%10][$j] = $i;
}
for ($i = $tnum; $i <= $n; $i++) {
$ipow = $p3a[$i];
for ($j = 1; $j <= $i; $j++) {
for ($k = $j+1; $k <= $testmax+2; $k++) {
if($p3a[$j]+$p3a[$k] > $ipow){break;}
$diff = $ipow - ($p3a[$j]+$p3a[$k]);
$diff_t = $diff%10;
if(isset($numlist[$diff_t][$diff]) && $numlist[$diff_t][$diff]>$k ){
echo " $i$s = $j$s + $k$s + ".$numlist[$diff_t][$diff].$s.'<br>'.PHP_EOL;
break;
}
}
}
}
}
</code></pre>
<p>It is ok, but I want to know a faster way of doing this.</p>
<p>This code uses 0.59064292907715 as test code <a href="http://codepad.org/gWy9ptQ0" rel="nofollow">here</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T22:14:54.543",
"Id": "70691",
"Score": "0",
"body": "Have you tried *not* using precalculated values?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T16:33:52.430",
"Id": "70743",
"Score": "2",
"body": "@JOELEE pardon my ignorance, but what is the name of the mathematical formula/principle for finding out the numbers on the right hand side?"
}
] |
[
{
"body": "<p>I would make a few changes for readability:</p>\n\n<ul>\n<li>Rename:\n<ul>\n<li><code>$p3a</code> → <code>$cubes</code></li>\n<li><code>$numlist</code> → <code>$cubeRoots</code></li>\n</ul></li>\n<li>Hard-code <code>$tnum</code>. It's not going to vary anyway, since it wasn't a parameter.</li>\n<li>Eliminate <code>$testmax</code>. It's not worth the effort to save a few loop iterations.</li>\n<li>More generous horizontal spacing. (You use lots of newlines in your source code, but need more spaces.)</li>\n</ul>\n\n<p>Changing <code>$numlist</code> from a two-level array to a 1-dimensional array results in better readability as well as a performance improvement.</p>\n\n<p><code>$i * $i * $i</code> is simpler and faster than <code>pow($i, 3)</code>.</p>\n\n<p>Changing the termination condition of your inner loop results in an even more dramatic performance improvement.</p>\n\n<p>Overall, this completes in about 1/3 of the time of the original code:</p>\n\n<pre><code>function funcC($n) {\n $exp = '³';\n\n $cubes = array();\n $cubeRoots = array();\n\n for ($i = 0; $i <= $n; $i++) {\n $j = $i * $i * $i;\n $cubes[$i] = $j;\n $cubeRoots[$j] = $i;\n }\n\n for ($i = 3; $i <= $n; $i++) {\n\n for ($j = 1; $j <= $i; $j++) {\n for ($k = $j; ($diff = $cubes[$i] - $cubes[$j] - $cubes[$k]) >= $cubes[$k]; $k++) {\n if (isset($cubeRoots[$diff])) {\n echo \" $i$exp = $j$exp + $k$exp + \" . $cubeRoots[$diff] . $exp . '<br>' . PHP_EOL;\n break;\n }\n }\n }\n\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T07:10:25.813",
"Id": "70706",
"Score": "0",
"body": "http://codepad.org/FXTw5ENn this code just return 15 line.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T07:46:54.570",
"Id": "70707",
"Score": "0",
"body": "Silly mistake — reversed an inequality. Fixed in [Rev 2](http://codereview.stackexchange.com/revisions/41185/2)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T22:39:40.843",
"Id": "41185",
"ParentId": "41179",
"Score": "7"
}
},
{
"body": "<ul>\n<li><p><a href=\"http://codepad.org/gWy9ptQ0\" rel=\"nofollow\">My old code</a>:</p>\n\n<p>0.59064292907715 seconds<br>\nloop count = 100 + (100*100*100)</p></li>\n<li><p><a href=\"http://codepad.org/asX8Wakc\" rel=\"nofollow\">200_success' code</a>:</p>\n\n<p>0.13945198059082 seconds<br>\nloop count = 100 + (100*100*100)</p></li>\n<li><p>I find the new way <a href=\"http://codepad.org/Hvr5pKLh\" rel=\"nofollow\">here</a>:</p>\n\n<p>0.090393781661987 seconds<br>\nloop count = 100*100 + 100*100</p>\n\n<p>then </p>\n\n<pre><code>$cubeRoots[$a][$i] = $i.$exp.'+'.$k.$exp; => $cubeRoots[$a][$i] = $k;\n</code></pre>\n\n<p>0.085232019424438 seconds</p></li>\n</ul>\n\n<p></p>\n\n<pre><code><?php\n$start = microtime(true);\nfuncC(100);\necho microtime(true) - $start; \nfunction funcC($n) {\n $exp = '³';\n\n $cubes = array();\n $cubeRoots = array();\n\n for ($i = 2; $i <= $n; $i++) {\n $j = $i * $i * $i;\n $cubes[$i] = $j;\n\n for ($k = $i+1; $k <= $n; $k++) {\n $a=$j+($k*$k*$k);\n if(!isset($cubeRoots[$a])){\n $cubeRoots[$a] = array(); \n }\n //$cubeRoots[$a][$i] = $i.$exp.'+'.$k.$exp;\n $cubeRoots[$a][$i] = $k;\n }\n\n }\n\n for ($i = 3; $i <= $n; $i++) {\n\n for ($j = 1; $j <= $i; $j++) {\n\n $diff = $cubes[$i] - $cubes[$j];\n if (isset($cubeRoots[$diff])) {\n foreach($cubeRoots[$diff] AS $key => $v){\n if($j< $key){\n //echo \" $i$exp = $j$exp + \" . $v . '<br>' . PHP_EOL;\n\necho \" $i$exp = $j$exp + $key$exp+ $v$exp <br>\" . PHP_EOL;\n }\n }\n\n }\n\n }\n\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T10:09:47.560",
"Id": "70719",
"Score": "0",
"body": "`$cubeRoots` is no longer an accurate name. Try changing `$cubeRoots[$a][$i] = $i.$exp.'+'.$k.$exp` to `$cubePartitions[$a][$i] = $k`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T10:30:23.903",
"Id": "70724",
"Score": "0",
"body": "You are right .. 0.085232019424438 very good.."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T09:49:09.340",
"Id": "41213",
"ParentId": "41179",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T20:38:02.057",
"Id": "41179",
"Score": "9",
"Tags": [
"php",
"algorithm",
"performance",
"mathematics"
],
"Title": "Draw the table like 6³ = 3³ + 4³ + 5³ to 100³ = 35³ + 70³ + 85³"
}
|
41179
|
<p>If one does not know tilt maze then the game looks like <a href="http://www.mathsisfun.com/games/tilt-maze.html" rel="nofollow">this</a>. Basically one can travel in 4 directions North, East, South and West, but this travel's endpoint is the furthest <em>non-obstructed</em> block. If solution has multiple routes, then the any single solution is returned which need not be optimal.</p>
<p>Please verify complexity: O(row * col). I'm looking for code review, good practices, optimizations etc.</p>
<pre><code>final class CoordinateTiltMaze {
private final int row;
private final int col;
CoordinateTiltMaze(int row, int col) {
this.row = row;
this.col = col;
}
public int getRow() {
return row;
}
public int getCol() {
return col;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
if (getClass() != o.getClass()) return false;
final CoordinateTiltMaze coordinateTiltMaze = (CoordinateTiltMaze)o;
return row == coordinateTiltMaze.row && col == coordinateTiltMaze.col;
}
@Override
public int hashCode() {
return row + col;
}
@Override
public String toString() {
return row + " : " + col;
}
}
public final class TiltMaze {
private boolean[][] maze;
static int ctr = 0;
public TiltMaze(boolean[][] maze) {
if (maze.length == 0) throw new IllegalArgumentException("The maze should have length.");
this.maze = maze;
}
/**
*
* Returns the path from source to destination.
* If solution has multiple routes, then the any single solution is returned which need not be optimal. Please
* verify complexity - O (row * col) Looking for code review, good practices, optimizations etc.
*
*
* @param startRow
* The row index of the start position.
* @param startCol
* The col index of the start position
* @param endRow
* The row index of the end position
* @param endCol
* The column index of end positin
* @return The path from source to destination, empty set if non exists
* @throws IllegalArgumentException
* on invalid input.
*/
public Set<CoordinateTiltMaze> getPath (int startRow, int startCol, int endRow, int endCol) {
verify(startRow, startCol, endRow, endCol);
final Set<CoordinateTiltMaze> coordinateSet = new LinkedHashSet<CoordinateTiltMaze>();
if (processPoint(startRow, startCol, endRow, endCol, coordinateSet)) return coordinateSet;
return Collections.EMPTY_SET;
}
private void verify(int startRow, int startCol, int endRow, int endCol) {
if (rowOutOfBound(startRow)) throw new IllegalArgumentException("The startRow: " + startRow + " is out of bounds.");
if (columnOutOfBound(startCol)) throw new IllegalArgumentException("The startCol: " + startCol + " is out of bounds");
if (rowOutOfBound(endRow)) throw new IllegalArgumentException("The endRow: " + endRow + " is out of bounds.");
if (columnOutOfBound(endCol)) throw new IllegalArgumentException("The endCol: " + endCol + " is out of bounds");
}
private boolean rowOutOfBound(int startRow) {
return startRow < 0 || startRow >= maze.length;
}
private boolean columnOutOfBound(int startCol) {
return startCol < 0 || startCol >= maze[0].length;
}
private boolean processPoint (int row, int col, int endRow, int endCol, Set<CoordinateTiltMaze> coordinateSet) {
final CoordinateTiltMaze coord = new CoordinateTiltMaze(row, col);
if (row == endRow && col == endCol) {
coordinateSet.add(coord);
return true;
}
if (coordinateSet.contains(coord)) {
return false;
}
coordinateSet.add(coord);
for (CoordinateTiltMaze neighbor : getNeighbors(row, col)) {
if (processPoint (neighbor.getRow(), neighbor.getCol(), endRow, endCol, coordinateSet)) return true;
}
coordinateSet.remove(coord);
return false;
}
private List<CoordinateTiltMaze> getNeighbors(int row, int col) {
final List<CoordinateTiltMaze> nodes = new ArrayList<CoordinateTiltMaze>();
// north.
for (int i = row - 1; i >= -1; i--) {
if (isObstacle(i, col)) {
nodes.add(new CoordinateTiltMaze(i + 1, col));
break;
}
}
// east.
for (int i = col + 1; i <= maze[0].length; i++) {
if (isObstacle(row, i)) {
nodes.add(new CoordinateTiltMaze(row, i - 1));
break;
}
}
// south
for (int i = row + 1; i <= maze.length; i++) {
if (isObstacle(i, col)) {
nodes.add(new CoordinateTiltMaze(i - 1, col));
break;
}
}
// west
for (int i = col - 1; i >= -1; i--) {
if (isObstacle(row, i)) {
nodes.add(new CoordinateTiltMaze(row, i + 1));
break;
}
}
return nodes;
}
private boolean isObstacle(int newRow, int newCol) {
// in bounds of board.
if (newRow < 0 || newCol < 0 || newRow >= maze.length || newCol >= maze[0].length) {
return true;
}
// 1's in a matrix represent obstacles.
if (!maze[newRow][newCol]) {
return true;
}
return false;
}
public static void main(String[] args) {
boolean[][] m = {
{true, true, false, false},
{true, true, true, true},
{true, false, false, true}
};
TiltMaze tiltMaze = new TiltMaze(m);
for (CoordinateTiltMaze coordTiltMaze : tiltMaze.getPath(0, 0, 2, 3)) {
System.out.println(coordTiltMaze);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<h1>hashCode implementation</h1>\n<p>Your <code>hashCode</code> method leaves some things to be desired.</p>\n<p>The more often a hashCode is unique, the better. Even though your <code>CoordinateTiltMaze</code> class fulfills the equals & hashCode contract, your if an object has the hashCode <code>9</code> it could mean that it is (5, 4), (4, 5), (3, 6), (1, 8) and so on...</p>\n<p>A better implementation would be:</p>\n<pre><code>@Override\npublic int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + row;\n result = prime * result + col;\n return result;\n}\n</code></pre>\n<p>This will make the resulting hashCode a lot more unique. In fact, none of the previous objects that had the same hashCode will now have a unique hashCode. And you will still fulfill the hashCode & equals contract.</p>\n<p><em>(Hint: Your IDE almost certainly provides a way to automatically generate a good hashCode implementation, I used Eclipse to generate the above one)</em></p>\n<h1>Code duplication in <code>getNeighbors</code></h1>\n<p>You have four sets of code in your <code>getNeighbors</code> method, one for each direction. I believe that you can get rid of some of this code duplication by using an <a href=\"https://codereview.stackexchange.com/questions/34054/random-walk-on-a-2d-grid/34056#34056\">Direction4 enum</a>.</p>\n<h1>Naming</h1>\n<p>Your naming of <code>CoordinateTiltMaze</code> was a bit confusing for me for a moment. Is it a Maze for a CoordinateTilt? No! It's a Coordinate for a TiltMaze! I think <code>TiltMazeCoordinate</code>, <code>MazeCoordinate</code>, or simply <code>Coordinate</code> would be a better name. Or even <code>Point</code>. Because this class is not coupled to your <code>TiltMaze</code> at all, and this is good. It is totally re-usable in all of your projects where you are working with 2d coordinates.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T23:49:03.213",
"Id": "41190",
"ParentId": "41187",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "41190",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T23:34:00.470",
"Id": "41187",
"Score": "4",
"Tags": [
"java",
"algorithm",
"pathfinding"
],
"Title": "Tilt maze solution"
}
|
41187
|
<p>In order to complete one of my assignment I needed to include a quicksort so I was wondering if this is correct and acceptable. </p>
<p>The code: </p>
<pre><code> private ArrayList<String> sort(ArrayList<String> ar, int lo, int hi){
if (lo < hi){
int splitPoint = partition(ar, lo, hi);
sort(ar, lo, splitPoint);
sort(ar, splitPoint +1, hi);
}
return ar;
}
private int partition(ArrayList<String> ar, int lo, int hi){
String pivot = ar.get(lo);
lo--;
hi++;
while (true){
lo++;
while (lo<hi && ar.get(lo).compareTo(pivot) < 0){
lo++;
}
hi--;
while (hi>lo && ar.get(hi).compareTo(pivot) >= 0){
hi--;
}
if (lo<hi){
swap(ar, lo, hi);
}else {
return hi;
}
}
}
</code></pre>
<p>The additional swap method: </p>
<pre><code> private ArrayList<String> swap(ArrayList<String> ar, int a, int b){
String temp = ar.get(a);
ar.set(a, ar.get(b));
ar.set(b, temp);
return ar;
}
</code></pre>
<p>If this is incorrectly done can you please give me some pointers and tell me why. Otherwise I would gladly accept any suggestions you have. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T00:00:32.407",
"Id": "70694",
"Score": "1",
"body": "Have you tested your code anything?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T00:38:21.827",
"Id": "70696",
"Score": "0",
"body": "@SimonAndréForsberg yes I did and it seems to work."
}
] |
[
{
"body": "<p>Those are pure functions that don't access any instance variables. You can therefore make them <code>static</code>.</p>\n\n<p>You could use generics more generically. Your code should work with any <code>List</code>, as long as it supports an <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/RandomAccess.html\" rel=\"nofollow\">efficient <code>.get(i)</code> for arbitrary <em>i</em></a>. The elements of the list can be any kind of <code>Comparable</code> object.</p>\n\n<p>The <code>.sort()</code> function should have a <code>void</code> return type to avoid giving the false impression that it returns a copy of the original array.</p>\n\n<pre><code>private static <E extends Comparable<E>, L extends List<E> & RandomAccess>\nvoid sort(L ar, int lo, int hi) {\n if (lo < hi) {\n int splitPoint = partition(ar, lo, hi);\n sort(ar, lo, splitPoint);\n sort(ar, splitPoint +1, hi);\n }\n}\n\nprivate static <E extends Comparable<E>, L extends List<E> & RandomAccess>\nint partition(L ar, int lo, int hi){\n E pivot = ar.get(lo);\n lo--;\n hi++;\n while (true){\n lo++;\n while (lo<hi && ar.get(lo).compareTo(pivot) < 0){\n lo++;\n }\n hi--;\n while (hi>lo && ar.get(hi).compareTo(pivot) >= 0){\n hi--;\n }\n if (lo<hi){\n swap(ar, lo, hi);\n }else {\n return hi;\n }\n }\n}\n\nprivate static <E extends Comparable<E>, L extends List<E> & RandomAccess>\nvoid swap(L ar, int a, int b){\n E temp = ar.get(a);\n ar.set(a, ar.get(b));\n ar.set(b, temp);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T01:50:42.393",
"Id": "70697",
"Score": "0",
"body": "I am not a fan of exposing the RandomAccess interface in the generics. In this case, as example code, it sort of makes sense, but, in a real implementation, the signature should just be `private static <E extends Comparable<E>> void sort(List<E> ar, int lo, int hi) {...` and then, inside the sort method, it should choose between two alternative algorithms depending on whether the input list is `RandomAccess` or not. The `RandomAccess` interface leads to confusion for most Java programmers (who have never heard of it)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T03:48:54.320",
"Id": "70701",
"Score": "0",
"body": "@rolfl True, but then you would be getting into creeping expansion of feature scope. My point was that you could get that flexibility for free just by changing the method signatures."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T13:56:13.273",
"Id": "70734",
"Score": "0",
"body": "It all seems reasonable points to me, but as of now I can't relate to what you said as I am still to learn 'generics' in my AP class."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T01:02:45.980",
"Id": "41196",
"ParentId": "41189",
"Score": "4"
}
},
{
"body": "<p>I agree with the handy generics use from previous answer and I would like to add something more that I noticed. </p>\n\n<p>In your partition method I thin you can remove the following code</p>\n\n<pre><code>private int partition(ArrayList<String> ar, int lo, int hi){\n String pivot = ar.get(lo);\n lo--;//remove\n hi++;//remove\n while (true){\n lo++;//remove\n while (lo<hi && ar.get(lo).compareTo(pivot) < 0){\n lo++;\n }\n hi--;//remove\n while (hi>lo && ar.get(hi).compareTo(pivot) >= 0){\n hi--;\n }\n if (lo<hi){\n swap(ar, lo, hi);\n }else {\n return hi;\n }\n }\n}\n</code></pre>\n\n<p>I the l-- and l++ right after you can get rid of because this path always happens. regarding the h++ and h-- I had to look into it longer but if you think line by line what the code does I am pretty sure those two can be removed as well.</p>\n\n<p><strong>Efficiency:</strong></p>\n\n<p>Another important point regarding the efficiency (since you asked that as well) is the selection of the pivot. Quick sort has complexity from O(n.logn) to O(n^2). And that depends on the selection of the pivot. Lets say you try to sort the array that is sorted other way around. Your pivot selection would result in O(n^2) complexity because in every level of recursion one half is of a size of 1 and other is n - 1. The best complexity would be if both the half are the same at each level, which you cannot achieve for any array. </p>\n\n<p><strong>Statistically</strong> speaking if you select the pivot randomly every time you end up with asymptotic time complexity O(nlogn) in most of the cases. That is why Quicksort is said to have <strong>average</strong> time complexity O(nlogn).</p>\n\n<p>Last addition about the static method. That was a good point in the previous answer but just bear in mind that static methods cannot be overriden and are hard to mock in testing. So if you would like to do some general design of your classes to let's say have one super class \"Sort\" with method sort and underneath having QuickSort, Buble, Merge Sort... you would probably like to stay with non-static sorting method. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T21:43:57.717",
"Id": "41255",
"ParentId": "41189",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "41196",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T23:46:57.257",
"Id": "41189",
"Score": "7",
"Tags": [
"java",
"algorithm",
"sorting",
"quick-sort"
],
"Title": "Is this quicksort efficient and acceptable?"
}
|
41189
|
<p>I am trying to create simple registration form with Backbone. I need to validate fields on blur, and whole form on submit.</p>
<p><strong>HTML:</strong></p>
<pre><code><form>
<div><input name="name" type="text" placeholder="Name"/></div>
<div><input name="surname" type="text" placeholder="Surname"/></div>
<div><input name="email" type="text" placeholder="Your mail"/></div>
<div><input name="password" type="password" placeholder="Password"/></div>
<div><input name="pagename" type="text" placeholder="Page name"/></div>
<input type="submit" value="Go"></input>
</form>
</code></pre>
<p><strong>Model:</strong></p>
<pre><code>app.__definitions.models.Signup = Backbone.Model.extend({
url: '/app/signup',
defaults: {
name: '',
surname: '',
email: '',
password: '',
pagename: ''
},
validateOne: validator.validateOne,
validate: function(fields) {
var result = validator.validateAll(fields);
if (result !== true) return result;
}
});
</code></pre>
<p><strong>View:</strong></p>
<pre><code>app.__definitions.views.Signup = Backbone.View.extend({
el: $('form'),
events: {
'submit': 'onFormSubmit',
'change input[type!="submit"]': 'onInputChange',
'blur input[type!="submit"]': 'onInputChange',
'focus input': function(e) {
this.resetInputErrors(e.target);
}
},
templates: {
'error': _.template('<span class="error"><%=error%></span>')
},
initialize: function() {
this.model = new app.__definitions.models.Signup();
this.model.on('invalid', this.onModelInvalid, this);
},
getInput: function(name) {
return this.$el.find('[name="' + name + '"]');
},
onModelInvalid: function(model, errors) {
var _this = this;
_.each(errors, function(error, name) {
_this.showInputErrors(_this.getInput(name), error);
})
},
onFormSubmit: function(e) {
e.preventDefault();
var model = this.model;
this.$el.find('input[name]').each(function() {
model.set(this.name, this.value);
})
this.model.save();
},
onInputChange: function(e) {
this.model.set(e.target.name, e.target.value);
var result = this.model.validateOne(e.target.name, e.target.value);
if (result !== true) this.showInputErrors(e.target, result)
},
resetInputErrors: function(target) {
var $target = $(target);
$target.removeClass('incorrect')
$target.parent().find('.error').remove();
},
showInputErrors: function(target, errors) {
var $target = $(target);
var errorsHTML = '';
this.resetInputErrors(target);
for (var i = 0; i < errors.length; i++) {
errorsHTML += this.templates.error({error: se.errors.get(errors[i])});
}
$target.addClass('incorrect');
$target.parent().append(errorsHTML);
}
});
</code></pre>
<p><strong>Init:</strong></p>
<pre><code> app.views.Signup = new app.__definitions.views.Signup();
app.routers.Router = new app.__definitions.routers.Main({hashChange: true});
</code></pre>
<p>Questions:</p>
<ol>
<li>Do I understand right how to make Backbone application?</li>
<li>Where is the mistakes? What can I do better or clearer? </li>
<li>Is there a better way to connect model with inputs on my form, or my getInput is ok? </li>
<li>In my case I don't need to use the collection? Am I right?</li>
</ol>
|
[] |
[
{
"body": "<p>I don't know too much about backbone, but here are my tips, i don't like, why?</p>\n\n<p>1 - This is ugly: app.__definitions.models.Signup, i don't like to use globals, you should avoid it, and \"Signup\" what? your app i suppose but if you've another \"sign up\" in your app what you would call it? Ok, maybe you just have one, but try to explain more what you want in your variables.</p>\n\n<p>2 - You're manipulating too much DOM elements in your methods, avoiding then to reuse them.</p>\n\n<p>3 - Use more dependency injection, you're using unknown objects inside your methods, do you know about <a href=\"http://en.wikipedia.org/wiki/Law_of_Demeter\" rel=\"nofollow\">Law of Demeter (LoD) or principle of least knowledge </a>?</p>\n\n<p>4 - One function one thing, you're doing too much inside of your functions. </p>\n\n<p>like i said before, i don't know too much about backbone, but if this framework doesn't encourages you to modularize your code, run to another framework.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T21:39:25.190",
"Id": "41193",
"ParentId": "41192",
"Score": "-1"
}
},
{
"body": "<p>Generally it looks like your know what your doing, maybe you could be more efficient by removing the <code>blur</code> event since you wouldn't need to save/validate if the input is already populated or left empty, this will also save you calling <code>onInputChange</code> twice when an input is changed.</p>\n\n<p>Backbone will automatically create <code>this.$el</code> from the <code>el</code> property so you can just do.</p>\n\n<p><code>el: 'form'</code> and then <code>this.$el</code> would be created for you.</p>\n\n<p>Finally i would use <code>listenTo</code> rather than <code>on</code> for example.</p>\n\n<p><code>this.model.on('invalid', this.onModelInvalid, this);</code></p>\n\n<p>would be done like this using <code>listenTo</code>.</p>\n\n<p><code>this.listenTo(this.model, 'invalid', this.onModelInvalid);</code></p>\n\n<p>This allows you to keep track of events on the object and then remove them all at once later on.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T21:42:14.467",
"Id": "41194",
"ParentId": "41192",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-07T21:13:00.383",
"Id": "41192",
"Score": "5",
"Tags": [
"javascript",
"jquery",
"backbone.js"
],
"Title": "Simple registration form with Backbone"
}
|
41192
|
<p>I have been working for weeks on a "BookViewer" AngularJS directive. I would like to write some blog posts on the lessons I learned in writing the directive. Before doing this I would like to ask for some feedback on how I wrote the directive. I ran into a lot trouble, learned a lot, but in the end I am quite happy with the result. I used AngularJS+Typescript+Angular-UI Bootstrap. This is my first attempt to implement a large directive.</p>
<p>The code can be found on <a href="https://github.com/svdoever/AngularJS-bookviewer" rel="nofollow noreferrer">GitHub</a>. A live version can be found <a href="http://svdoever.github.io/AngularJS-bookviewer" rel="nofollow noreferrer">here</a>.</p>
<p>The visual result of using the directive is as follows:</p>
<p><img src="https://i.stack.imgur.com/BnfJ0.png" alt="Sample chapter">
<img src="https://i.stack.imgur.com/ROEu9.png" alt="Sample index"></p>
<p>It is possible to switch between a text and index view by setting the <code>indexmode</code> attribute on the directive which I control from a button in the navigation bar, external from the directive. </p>
<p>I made some decisions where I don't know if these are the best decisions:</p>
<p><strong>Using Typescript in the directive</strong></p>
<p>I could not get the directive working with a Typescript class for the controller and the link function. So I use anonymous functions, and use Typescript only for interface definitions and type-checking. In my link function I need to process the DOM, I do this in an anonymous function in the <code>timeout</code> otherwise the DOM is not ready yet. In the anonymous function I need to call other functions. I could not find another way than defining this function on the scope in the controller function. Is it possible to use functions and variables in an instance of a Typescript class?</p>
<pre><code>directive.link = ($scope: IBookViewerScope, $element, $attrs) : void => {
$timeout(() => {
$scope.processDom();
:
}, 0);
};
</code></pre>
<p>The controller function creates a lot of variables and functions in the scope, this was the only way I found to have access to the variables and functions in <code>$timeout</code> callbacks like above. Is this the best approach?</p>
<pre><code>angular.module('directive.bookviewer', [])
.constant('bookviewerConfig', {
})
.controller('bookviewerController',
['$scope', '$element', '$attrs', '$sce', '$location', '$anchorScroll', '$timeout', '$log',
function($scope:IBookViewerScope, $element, $attrs, $sce, \
$location:ng.ILocationService, $anchorScroll, $timeout, $log) : void {
$scope.savedElement = $element; // keep track of element for usage in later code
$scope.savedAttrs = $attrs; // keep track of attributes for usage in later code
$scope.trustAsHtml = (html:string) : any => {
return $sce.trustAsHtml(html);
};
$scope.indexOpenChapterIndex = (chapterIndexId:string) => { ... }
:
}]);
</code></pre>
<p><strong>Handling fixed bar at top of page</strong></p>
<p>I use a fixed bar at the top. To compensate for this in jumping around in the book I added anchor tags <code><a class="anchor" id="..."></a></code>, and in my directive link function I put on each "anchor" element the following code:</p>
<pre><code>$element.css({
display: "block",
position: "relative",
top: offset
});
</code></pre>
<p>where <code>offset</code> is <code>-heightOfFixedBar</code>. Problem is that the top of the chapter was still at the wrong offset, so I added a div with the same height as the fixed bar at the top:</p>
<pre><code><div style="margin: 51px 0 0 0;"/>
<bookviewer booktoc="vm.toc" chaptercontent="vm.chapter"
indexmode="vm.indexmode" offset-element-id="'topnavbar'"
anchorid="vm.anchorid" on-navigate="vm.navigate(chapterid, anchorid)"
on-select="vm.select(text)"/>
</div>
</code></pre>
<p><strong>All navigation is done by watching</strong></p>
<p>Initially I started with explicit navigation. I had callback functions connected to links in the html and in those functions I did the scrolling to anchors or callbacks to the function to load the contents of another chapter. I got into a lot of trouble with this, because I also had to respond to changes in the bound parameters of the directive. I ended up with a set of watch functions defined on the scope:</p>
<pre><code>// toggle between text/index view
$scope.$watch('indexmode', (newValue, oldValue) => { ... }
// respond to click on links
$scope.$watch(() => { return $location.hash(); }, () => { ... }
// respond to content changes (new chapter content) and anchor changes
$scope.$watch('[chaptercontent.Id, anchorid]', function (newValues, oldValues) { ...}
</code></pre>
<p>Although I am intending to use only a single instance of the bookviewer per page, it is a bit of a pity to depend on <code>$location.hash()</code> within a directive. Problem is: I could not find another way while keeping the next/prev button of the browser working.</p>
<p><strong>Rendering with dynamic templates</strong></p>
<p>I do all the rendering with templates defined in the <strong>directive.templateUrl</strong>.</p>
<pre><code><script id="curChapterIndexTmpl.html" type="text/ng-template">
<li><a ng-click="navigate(paragraph.Id)" href="javascript:void(0)">{{paragraph.Title}}</a></li>
<ng-include ng-repeat="paragraph in paragraph.Paragraphs" src="'curChapterIndexTmpl.html'"></ng-include>
</script>
<script id="otherChapterIndexTmpl.html" type="text/ng-template">
<li><a ng-click="navigate(paragraph.Id)" href="javascript:void(0)">{{paragraph.Title}}</a></li>
</script>
<script id="paragraphTmpl.html" type="text/ng-template">
<a class="anchor" id="{{paragraph.Id}}"></a>
<h4>{{paragraph.Title}}</h4>
<div class="paragraph-text" ng-bind-html="trustAsHtml(paragraph.Content)"></div>
<ng-include ng-repeat="paragraph in paragraph.Paragraphs" src="'paragraphTmpl.html'"></ng-include>
</script>
<div class="bookchapter" ng-hide="indexmode">
<a class="anchor" id="{{chaptercontent.Id}}"></a>
<h3>{{chaptercontent.Title}}</h3>
<div class="chapter-text" ng-bind-html="trustAsHtml(chaptercontent.Content)"></div>
<ng-include ng-repeat="paragraph in chaptercontent.Paragraphs" src="'paragraphTmpl.html'"></ng-include>
</div>
<div id="bookindex" ng-show="indexmode">
<h1>Book index</h1>
<accordion close-others="true">
<accordion-group ng-repeat="tocChapter in booktoc.Chapters" is-open="indexOpenChapterIndex('i-' + tocChapter.Id)">
<a class="anchor" id="i-{{tocChapter.Id}}"></a>
<accordion-heading>
<a ng-click="navigate(tocChapter.Id)" href="javascript:void(0)">{{tocChapter.Title}}</a>
<i class="pull-right glyphicon" ng-class="{'glyphicon-chevron-down': isopen, 'glyphicon-chevron-right': !isopen}"></i>
</accordion-heading>
<ul ng-if="tocChapter.Id === $parent.chaptercontent.Id">
<ng-include ng-repeat="paragraph in $parent.chaptercontent.Paragraphs" src="'curChapterIndexTmpl.html'"></ng-include>
</ul>
<ul ng-if="tocChapter.Id !== $parent.chaptercontent.Id">
<ng-include ng-repeat="paragraph in tocChapter.Paragraphs" src="'otherChapterIndexTmpl.html'"></ng-include>
</ul>
</accordion-group>
</accordion>
</div>
</code></pre>
<p>I must say: I learned my lessons there. I initially worked with self-closing divs (<code><div ... /></code>). This worked when working with jQuery. When I removed jQuery and depended on the AngularJS JQLite implementation, a lot went wrong. So NEVER use self-closing divs. It isn't even supported in the html5 spec. See <a href="https://stackoverflow.com/questions/21552560/angularjs-bug-in-ng-include-when-not-using-jquery">this</a>.</p>
<p>I tried to get the code working in Plunker (see <a href="https://stackoverflow.com/questions/21555834/plunker-with-angularjs-and-typescript-possible">this</a>). The solution was to create a "gh-pages" branch of the git repository, so the example is now visible <a href="http://svdoever.github.io/AngularJS-bookviewer" rel="nofollow noreferrer">here</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T00:46:44.130",
"Id": "41195",
"Score": "1",
"Tags": [
"angular.js",
"typescript"
],
"Title": "AngularJS bookviewer directive written with Typescript and Angular-ui bootstrap"
}
|
41195
|
<p>To download the tool and for usage instructions, see <a href="https://codereview.stackexchange.com/questions/41225/follow-up-to-tool-for-posting-code-review-questions">the follow up to this question</a></p>
<hr>
<h1>Description</h1>
<p>I have realized that there's a whole bunch of code I want to have reviewed, but copying file by file, selecting the code and pressing Ctrl + K is a slow process, and I want to remember which other parts to include in my question, so I decided to make a tool for it. I thought it could be useful, especially since <a href="https://codereview.stackexchange.com/users/31562/simon-andre-forsberg?tab=questions&sort=votes">most of my questions</a> are structured in very similar ways already...</p>
<p>This code is for inputting a couple of files, and outputting a CR question stub, ready to be filled in with details. The code automatically formats the input files to match StackExchange formatting, with four spaces added in front of each line (No more <kbd>Ctrl</kbd> + <kbd>K</kbd> !!)</p>
<p>It is very likely that you will see more questions from me structured in the same way as this question is. And if you want to use it yourself, feel free to do so.</p>
<p>Related previously existing tools:</p>
<ul>
<li><a href="https://codereview.stackexchange.com/questions/40422/tool-for-automatically-correcting-indentation-and-formatting-of-cr-so-code">Tool for automatically correcting indentation and formatting of CR & SO code</a></li>
<li><a href="https://codereview.stackexchange.com/questions/38336/bookmarklet-for-selecting-code-snippets-on-code-review">Bookmarklet for selecting code snippets on Code Review</a></li>
</ul>
<h1>Code download</h1>
<p>For your convenience, this code can be found on <a href="https://github.com/Zomis/ReviewPrepare" rel="noreferrer">GitHub</a> (Many thanks to @amon who taught me a lot more about <a href="http://chat.stackexchange.com/rooms/12699/cr-community-git-support">how to use git</a>)</p>
<h3>Class Summary (10079 bytes in 342 lines in 4 files)</h3>
<ul>
<li>CountingStream: OutputStream that keeps track on the number of written bytes to it</li>
<li>ReviewPrepareFrame: JFrame for letting user select files that should be up for review</li>
<li>ReviewPreparer: The most important class, takes care of most of the work. Expects a List of files in the constructor and an OutputStream when called.</li>
<li>TextAreaOutputStream: OutputStream for outputting to a <code>JTextArea</code>.</li>
</ul>
<h1>Code</h1>
<p><strong>CountingStream:</strong> (approximately 679 bytes in 27 lines)</p>
<pre><code>/**
* An output stream that keeps track of how many bytes that has been written to it.
*/
public class CountingStream extends FilterOutputStream {
private final AtomicInteger bytesWritten;
public CountingStream(OutputStream out) {
super(out);
this.bytesWritten = new AtomicInteger();
}
@Override
public void write(int b) throws IOException {
bytesWritten.incrementAndGet();
super.write(b);
}
public int getBytesWritten() {
return bytesWritten.get();
}
}
</code></pre>
<p><strong>ReviewPrepareFrame:</strong> (approximately 3178 bytes in 109 lines)</p>
<pre><code>public class ReviewPrepareFrame extends JFrame {
private static final long serialVersionUID = 2050188992596669693L;
private JPanel contentPane;
private final JTextArea result = new JTextArea();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new ReviewPrepareFrame().setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ReviewPrepareFrame() {
setTitle("Prepare code for Code Review");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.NORTH);
final DefaultListModel<File> model = new DefaultListModel<>();
final JList<File> list = new JList<File>();
panel.add(list);
list.setModel(model);
JButton btnAddFiles = new JButton("Add files");
btnAddFiles.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser dialog = new JFileChooser();
dialog.setMultiSelectionEnabled(true);
if (dialog.showOpenDialog(ReviewPrepareFrame.this) == JFileChooser.APPROVE_OPTION) {
for (File file : dialog.getSelectedFiles()) {
model.addElement(file);
}
}
}
});
panel.add(btnAddFiles);
JButton btnRemoveFiles = new JButton("Remove files");
btnRemoveFiles.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (File file : new ArrayList<>(list.getSelectedValuesList())) {
model.removeElement(file);
}
}
});
panel.add(btnRemoveFiles);
JButton performButton = new JButton("Create Question stub with code included");
performButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
result.setText("");
ReviewPreparer preparer = new ReviewPreparer(filesToList(model));
TextAreaOutputStream outputStream = new TextAreaOutputStream(result);
preparer.createFormattedQuestion(outputStream);
}
});
contentPane.add(performButton, BorderLayout.SOUTH);
contentPane.add(result, BorderLayout.CENTER);
}
public List<File> filesToList(DefaultListModel<File> model) {
List<File> files = new ArrayList<>();
for (int i = 0; i < model.getSize(); i++) {
files.add(model.get(i));
}
return files;
}
}
</code></pre>
<p><strong>ReviewPreparer:</strong> (approximately 5416 bytes in 165 lines)</p>
<pre><code>public class ReviewPreparer {
private final List<File> files;
public ReviewPreparer(List<File> files) {
this.files = new ArrayList<>();
for (File file : files) {
if (file.getName().lastIndexOf('.') == -1)
continue;
if (file.length() < 10)
continue;
this.files.add(file);
}
}
public int createFormattedQuestion(OutputStream out) {
CountingStream counter = new CountingStream(out);
PrintStream ps = new PrintStream(counter);
outputHeader(ps);
outputFileNames(ps);
outputFileContents(ps);
outputDependencies(ps);
outputFooter(ps);
ps.print("Question Length: ");
ps.println(counter.getBytesWritten());
return counter.getBytesWritten();
}
private void outputFooter(PrintStream ps) {
ps.println("#Usage / Test");
ps.println();
ps.println();
ps.println("#Questions");
ps.println();
ps.println();
ps.println();
}
private void outputDependencies(PrintStream ps) {
List<String> dependencies = new ArrayList<>();
for (File file : files) {
try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
String line;
while ((line = in.readLine()) != null) {
if (!line.startsWith("import ")) continue;
if (line.startsWith("import java.")) continue;
if (line.startsWith("import javax.")) continue;
String importStatement = line.substring("import ".length());
importStatement = importStatement.substring(0, importStatement.length() - 1); // cut the semicolon
dependencies.add(importStatement);
}
}
catch (IOException e) {
ps.println("Could not read " + file.getAbsolutePath());
ps.println();
// this will be handled by another function
}
}
if (!dependencies.isEmpty()) {
ps.println("#Dependencies");
ps.println();
for (String str : dependencies)
ps.println("- " + str + ": ");
}
ps.println();
}
private int countLines(File file) throws IOException {
return Files.readAllLines(file.toPath(), StandardCharsets.UTF_8).size();
}
private void outputFileContents(PrintStream ps) {
ps.println();
for (File file : files) {
try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
ps.printf("**%s:** (approximately %d bytes in %d lines)", className(file), file.length(), countLines(file));
ps.println();
ps.println();
String line;
int importStatementsFinished = 0;
while ((line = in.readLine()) != null) {
// skip package and import declarations
if (line.startsWith("package ")) continue;
if (line.startsWith("import ")) {
importStatementsFinished = 1;
continue;
}
if (importStatementsFinished >= 0) importStatementsFinished = -1;
if (importStatementsFinished == -1 && line.trim().isEmpty()) continue;
importStatementsFinished = -2;
line = line.replaceAll(" ", "\t"); // replace four spaces with tabs, since that takes less space
ps.print(" "); // format as code for StackExchange, this needs to be spaces.
ps.println(line);
}
}
catch (IOException e) {
ps.print("> ");
e.printStackTrace(ps);
}
ps.println();
}
}
private void outputFileNames(PrintStream ps) {
int totalLength = 0;
int totalLines = 0;
for (File file : files) {
totalLength += file.length();
try {
totalLines += countLines(file);
}
catch (IOException e) {
ps.println("Unable to determine line count for " + file.getAbsolutePath());
}
}
ps.printf("###Class Summary (%d bytes in %d lines in %d files)", totalLength, totalLines, files.size());
ps.println();
ps.println();
for (File file : files) {
ps.println("- " + className(file) + ": ");
}
}
private String className(File file) {
String str = file.getName();
return str.substring(0, str.lastIndexOf('.'));
}
private void outputHeader(PrintStream ps) {
ps.println("#Description");
ps.println();
ps.println("- Add some [description for what the code does](http://meta.codereview.stackexchange.com/questions/1226/code-should-include-a-description-of-what-the-code-does)");
ps.println("- Is this a follow-up question? Answer [What has changed, Which question was the previous one, and why you are looking for another review](http://meta.codereview.stackexchange.com/questions/1065/how-to-post-a-follow-up-question)");
ps.println();
ps.println("#Code download");
ps.println();
ps.println("For convenience, this code can be downloaded from [somewhere](http://github.com repository perhaps?)");
ps.println();
}
public static void main(String[] args) throws IOException {
// List<File> fileList = Arrays.asList(new File("C:/_zomisnet/_reviewtest").listFiles());
List<File> fileList = Arrays.asList(new File("./src/net/zomis/reviewprep").listFiles());
new ReviewPreparer(fileList).createFormattedQuestion(System.out);
}
}
</code></pre>
<p><strong>TextAreaOutputStream:</strong> (approximately 806 bytes in 41 lines)</p>
<pre><code>public class TextAreaOutputStream extends OutputStream {
private final JTextArea textArea;
private final StringBuilder sb = new StringBuilder();
public TextAreaOutputStream(final JTextArea textArea) {
this.textArea = textArea;
}
@Override
public void flush() {
}
@Override
public void close() {
}
@Override
public void write(int b) throws IOException {
if (b == '\n') {
final String text = sb.toString() + "\n";
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(text);
}
});
sb.setLength(0);
return;
}
sb.append((char) b);
}
}
</code></pre>
<h1>Usage / Test</h1>
<p>Input: Run the JFrame, select files that should be reviewed, click the button.</p>
<p>Output: The stub to this question I am currently writing :)</p>
<h1>Questions</h1>
<p>Looking for general comments on my code. The code is Open-Source in case you want to continue the work I have started. I am currently only treating Java specially since that's what I code the most in, but I believe better support for other languages can be added later (I am <strong>not asking</strong> for how to do it, or for you to do it, I'm just saying that with some modifications, I believe it is possible).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T13:06:00.740",
"Id": "70729",
"Score": "0",
"body": "This question now has a follow-up: http://codereview.stackexchange.com/questions/41225/follow-up-to-tool-for-posting-code-review-questions"
}
] |
[
{
"body": "<p>I would encourage you to produce more explicit output, particularly with the filenames. If I wanted to reverse the process and scrape the code into files on my machine, using a Python script such as the following…</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>import json\nfrom lxml import html\nimport re\nimport requests\n\nFILENAME_HINT_XPATH = \"../preceding-sibling::p[1]/strong/text()\"\n\ndef code_for_post(site, post):\n r = requests.get('https://api.stackexchange.com/2.1/posts/{1}?site={0}&filter=withbody'.format(site, post))\n j = json.loads(r.text)\n body = j['items'][0]['body']\n tree = html.fromstring(body)\n\n code_elements = tree.xpath(\"//pre/code[%s]\" % (FILENAME_HINT_XPATH))\n return dict((c.xpath(FILENAME_HINT_XPATH)[0], c.findtext(\".\")) for c in code_elements)\n\ndef write_files(code):\n extension = '.java' # <-- Yuck, due to @Simon.\n for filename_hint, content in code.iteritems():\n filename = re.sub(r'[^A-Za-z0-9]', '', filename_hint) + extension\n with open(filename, 'w') as f:\n print >>f, content\n\nwrite_files(code_for_post('codereview', 41198))\n</code></pre>\n\n<p>… then I would have to make assumptions about the filename extension.</p>\n\n<hr>\n\n<p>The invocation method could be improved. Instead of hard-coding a particular directory to look in for the source files, I would suggest…</p>\n\n<ul>\n<li>If files are explicitly passed to the program as command-line arguments, use those files.</li>\n<li>If a directory is specified, then use all files contained therein, excluding files with significant non-ASCII content.</li>\n<li>If no command-line arguments are used, then operate on the current directory.</li>\n</ul>\n\n<p>It would be nice to be able to say <code>java ReviewPreparer *.java |</code><a href=\"https://developer.apple.com/library/mac/documentation/darwin/reference/manpages/man1/pbcopy.1.html\"><code>pbcopy</code></a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T09:20:02.887",
"Id": "70708",
"Score": "1",
"body": "You mean that I should print out that it's `.java` files?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T09:25:44.077",
"Id": "70710",
"Score": "1",
"body": "Yes, that would let me remove the `# Yuck` line."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T09:16:34.210",
"Id": "41210",
"ParentId": "41198",
"Score": "17"
}
},
{
"body": "<p>It's much more important to convey the code faithfully than to save a few bytes of output by replacing spaces with tabs:</p>\n\n<pre><code>line = line.replaceAll(\" \", \"\\t\"); // replace four spaces with tabs, since that takes less space\n</code></pre>\n\n<p>In fact, since you used your program to produce this question itself, I suspect that your tool is responsible for introducing the bug in the immediately following line:</p>\n\n<pre><code>ps.print(\" \"); // format as code for StackExchange, this needs to be spaces.\n</code></pre>\n\n<p>Markdown requires four leading spaces to create a code block, not two.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T09:58:05.373",
"Id": "70718",
"Score": "0",
"body": "Ouch! Indeed correct. I'm also considering if perhaps replacing tabs with spaces would be better instead? (The only problem is that the code I want to have review tends to be quite big :) )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T10:13:38.467",
"Id": "70720",
"Score": "3",
"body": "In my opinion, no good can come out of mucking with the content any more than necessary to convey the code faithfully."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T10:19:59.110",
"Id": "70722",
"Score": "0",
"body": "You have a good point there. It's probably best to simply add four spaces in the beginning of each line and just leave it at that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T12:47:18.623",
"Id": "70728",
"Score": "1",
"body": "@SimonAndréForsberg +1 to 200_success for bug find, and another +1 for 'don't muck around ...'. (capped at +1 though). Also, you should ***only muck with whitespace at the beginning/end of lines, unless it is Python, in which case, the only safe modification is adding 4 spaces at front***."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T09:53:51.523",
"Id": "41214",
"ParentId": "41198",
"Score": "14"
}
}
] |
{
"AcceptedAnswerId": "41210",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T01:42:26.610",
"Id": "41198",
"Score": "45",
"Tags": [
"java",
"swing",
"formatting",
"stackexchange"
],
"Title": "Tool for creating CodeReview questions"
}
|
41198
|
<p>I looking over some old code, I had written the function below with a C-style for-loop iterating over a count variable. I then fixed it up with new knowledge, but still am suspicious that there is even a better way to do this.</p>
<p>The function should behave like so:</p>
<pre><code>>>> join_list(['a'])
'a'
>>> join_list(['a', 'b'])
'a or b'
>>> join_list(['a', 'b', 'c'])
'a, b, or c'
</code></pre>
<p>The function I have currently:</p>
<pre><code>def join_list(my_list):
length = len(my_list)
if length == 1:
return my_list[0]
elif length == 2:
return ' or '.join(my_list)
else:
head = ', '.join(my_list[:-1])
return head + ', or ' + my_list[-1]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T10:28:01.173",
"Id": "70723",
"Score": "0",
"body": "There's no docstring!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T17:34:58.543",
"Id": "70751",
"Score": "0",
"body": "To be fair I defined this function within my `if __name__ == '__main__'` conditional, but I digress I think the code speaks for itself :)."
}
] |
[
{
"body": "<p>Looks pretty good. The only problem I can see is that you're not doing a check to make sure the list is not empty: if it is, then you'll try to access <code>my_list[-1]</code> in the final <code>else</code> clause, which will raise an <code>IndexError</code>.</p>\n\n<p>Hence, I'd simply add a check up front for <code>length == 0</code> and <code>return ''</code> in that case. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T17:41:06.320",
"Id": "70752",
"Score": "1",
"body": "if you handle 2 and 3 item cases first you can fall through to `''.join(my_list)` which covers both 0 and 1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T18:06:23.120",
"Id": "70755",
"Score": "0",
"body": "I like that a lot, but I want to test for least first. All I need to change is the first clause to `if length <= 1: ''.join(my_list)`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T02:31:55.103",
"Id": "41200",
"ParentId": "41199",
"Score": "8"
}
},
{
"body": "<p>You could also write, a bit shorter:</p>\n\n<pre><code>def join_list(items):\n if not items:\n return ''\n *init, last = map(str, items)\n return (', '.join(init) + ' or '*bool(init) + last)\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>>>> join_list(range(5))\n'0, 1, 2, 3 or 4'\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T04:49:48.430",
"Id": "70813",
"Score": "0",
"body": "I tested that on Python 2.7.6 and Python 3.3. Looks like the asterisk in `*init, last = map(str, items)` raises a `SyntaxError` on Python 2.7.6. Do you know what that feature of Python 3.3 is called?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T09:09:32.467",
"Id": "70915",
"Score": "1",
"body": "@Winny Sorry, forgot to mention its python3 code. Its called extended unpacking (pep 3132)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T01:10:50.500",
"Id": "41262",
"ParentId": "41199",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "41200",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T02:21:48.463",
"Id": "41199",
"Score": "11",
"Tags": [
"python",
"strings"
],
"Title": "Is there a simpler way to make an English-readable list from strings in a tuple?"
}
|
41199
|
<p><strong>What I'm doing?</strong></p>
<p>I'm creating a member-list where initially only the names are visible. Clicking the names reveals the member information. This is done with jQuery by adding/removing classes.</p>
<p>I left out the CSS with the transitions for this review. </p>
<p><strong>HTML:</strong></p>
<pre><code><ul class="block-list member-list">
<li>
<a href="#" class="block-list__link">member name</a>
<div class="block-list__content">
<!-- member information -->
</div>
</li>
<li>
<a href="#" class="block-list__link">member name</a>
<div class="block-list__content">
<!-- member information -->
</div>
</li>
<li>
<a href="#" class="block-list__link">member name</a>
<div class="block-list__content">
<!-- member information -->
</div>
</li>
</ul>
</code></pre>
<p><strong>jQuery:</strong></p>
<pre><code><script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>if (!window.jQuery) { document.write('<script src="/jquery/jquery-1.10.2.min.js"><\/script>'); }</script>
<script type="text/javascript">
$(document).ready(function(){
var blContent = $(".block-list__content");
// If JS is disabled, the member information is visible by default
$(blContent).addClass("hidden");
$(".block-list__link").click(function(e) {
// Prevent fragment identifier being added to the URL
e.preventDefault();
// Save the `block-list__content` which is a sibling of the clicked `block-list__link`
var blCurrentContent = $(this).siblings(".block-list__content");
if ($(blCurrentContent).hasClass("hidden")) {
// Remove `visible` class from all `block-list__content`'s and add `hidden` class
$(blContent).removeClass("visible").addClass("hidden");
// Remove the `hidden` class from the current `block-list__content` and add `visible` class
$(blCurrentContent).removeClass("hidden").addClass("visible");
} else {
// If `block-list__link` is clicked again, add `hidden` class
$(blCurrentContent).removeClass("visible").addClass("hidden");
}
});
});
</script>
</code></pre>
|
[] |
[
{
"body": "<p>You're double-wrapping elements in jQuery. <code>blContent</code> and <code>blCurrentContent</code> are already jQuery objects, so doing <code>$(blContent)</code> isn't necessary. It's common practice to prefix jQuery collections with a dollar sign <code>$</code>.</p>\n\n<p>Other than that your code looks fine, but you could use <code>toggleClass</code> and exclude the current sibling element from the previous collection:</p>\n\n<pre><code>var $blContent = $('.block-list__content').addClass('hidden');\n\n$('.block-list__link').click(function(e) {\n e.preventDefault();\n var $content = $(this)\n .siblings('.block-list__content')\n .toggleClass('hidden visible');\n $blContent\n .not($content)\n .removeClass('visible')\n .addClass('hidden');\n});\n</code></pre>\n\n<ul>\n<li>Your code: <a href=\"http://jsbin.com/duqeb/1/edit\">http://jsbin.com/duqeb/1/edit</a> </li>\n<li>Updated code: <a href=\"http://jsbin.com/geboq/4/edit\">http://jsbin.com/geboq/4/edit</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T09:25:13.383",
"Id": "70709",
"Score": "0",
"body": "I'm a jQuery beginner. Wouldn't clicking a link for an already expanded div 1.) Remove `visible` and add `hidden` and then 2.) toggle it, which will remove `hidden` again and add `visible`. Therefor I won't be able to hide the divs anymore, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T09:29:19.847",
"Id": "70711",
"Score": "0",
"body": "It works the same as your code, I'm not sure I understand the question..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T09:31:15.147",
"Id": "70712",
"Score": "0",
"body": "No, it doesn't. Clicking a `block-list__link` with an already visible `block-list__content` won't hide it again. I _believe_ it adds `hidden` while removing all `visible` classes and right away toggles it back to `visible`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T09:37:05.317",
"Id": "70714",
"Score": "0",
"body": "Oh I didn't notice that. Well it's because the line above add the class, you'd have to exclude the current sibling, see if this works as expected http://jsbin.com/geboq/2/edit and I'll update the answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T09:42:09.040",
"Id": "70716",
"Score": "0",
"body": "I updated the question with slightly better code, that should do."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T08:54:08.353",
"Id": "41208",
"ParentId": "41207",
"Score": "6"
}
},
{
"body": "<p>I massively don't like your class name convention, but I guess that's personal preference. I understand that you're using the <code>__</code> to denote subcomponents, but if you follow the principles below then that shouldn't be necessary. Just change your content to <code>.content</code> and your links to <code>.link</code>.</p>\n\n<ul>\n<li><p>Something that your code does that you might not be aware of is bind a click event to each <code>.block-list__link</code> individually. While this is not a big issue when there are only three links, it's better practice to use event delegation:</p>\n\n<pre><code>$('.block-list').on('click', '.link', function () {\n\n});\n</code></pre>\n\n<p>This will only bind the event once (to the parent <code>.block-list</code>), but it will only fire when one of the delegates (<code>.link</code>) is clicked.</p></li>\n<li><p>You should never be adding a class <code>onload</code>, that doesn't make sense and may cause flickering as the DOM loads before the JavaScript. Have the class added already in your HTML or better still, set the elements default in your CSS. If the <code>.content</code> elements are invisible by default then you need only have one add/remove class in your JavaScript. Let's use <code>.visible</code> for this.</p></li>\n<li><p>Regarding the hiding/showing, what <code>elclanrs</code> posted is valid, but I still don't think it's very easy to read. I'd prefer something like this, remember the <code>.content</code> blocks are invisible by default;</p>\n\n<pre><code>var $blockList = $('.block-list'),\n $content = $('.content', $blockList);\n\n$blockList.on('click', '.link', function () {\n // hide the visible one\n var $justHidden = $content.filter('.visible')\n .removeClass('visible');\n // show the closest one, unless it's the one we just hid\n $(this).next('.content').not($justHidden)\n .addClass('visible');\n});\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T17:15:03.473",
"Id": "41237",
"ParentId": "41207",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "41237",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T08:37:21.943",
"Id": "41207",
"Score": "10",
"Tags": [
"javascript",
"jquery",
"beginner",
"html"
],
"Title": "Member list reveals member information on click (#1)"
}
|
41207
|
<p>This is a comment system that I wrote, is it secure?</p>
<pre><code><!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<?PHP
//Turn off error reporting (Not Necessary)
error_reporting(E_ALL ^ E_NOTICE);
//Connect to the database
if (!@mysql_connect('localhost', 'user', '') or !@mysql_select_db('comments')) {
die('Could not connect, please check back later.');
}
//Variables
$guest_name = htmlentities(str_replace(' ', '',$_POST['guest_name']));
$comment = htmlentities($_POST['comment']);
$time = date('g:i A', time());
$date = date('n/j/Y');
$query = "INSERT INTO `user_comments` VALUES(
'".mysql_real_escape_string('')."',
'".mysql_real_escape_string($guest_name)."',
'".mysql_real_escape_string($comment)."',
'".mysql_real_escape_string($date)."',
'".mysql_real_escape_string($time)."'
)";
$array_query = mysql_query("SELECT * FROM `comments` ORDER BY `ID` DESC");
//Insert comment into the database
if (isset($_POST['submit_comment']) && !empty($comment) && !empty($guest_name)) {
if(mysql_query($query)) {
header('Location: index.php');
}
}
//Check if user has filled in all fields
if (isset($_POST['submit_comment']) && empty($guest_name)) {
echo '<span style="color:red">*Please enter a Guest Name*</span><br>';
}
if (isset($_POST['submit_comment']) && empty($comment)) {
echo '<span style="color:red">*Please enter a Comment*</span>';
}
//List comments
function list_comments () {
$query = "SELECT * FROM `user_comments` ORDER BY `ID` DESC";
$query_run = mysql_query($query);
while ($result = mysql_fetch_array($query_run)) {
echo '<div id="comment_border">' . $result['Guest Name'] . ' - ' . $result['Date'] . ' - ' . $result['Time'] . '<br>' . $result['Comment'] . '<br></div><br>';
}
};
?>
<title>Main_Page</title>
</head>
<body>
<!-- \/ COMMENT FORM \/ -->
<form method="post" action="index.php">
<input type="text" name="guest_name" maxlength="15" placeholder="Guest Name"><br>
<textarea cols="70" rows="5" name="comment" maxlength="512" placeholder="Comment"></textarea>
<input type="submit" name="submit_comment">
</form>
<!-- /\ COMMENT FORM /\ -->
<hr><h1>Comments</h1><br>
<!-- Comments will list below here -->
<?PHP
list_comments();
?>
</body>
</html>
</code></pre>
|
[] |
[
{
"body": "<p>One of the most common mistakes for PHP programmers is that they don't seem to have been looking at the big red box in the documentation for <a href=\"http://www.php.net/mysql_query\" rel=\"nofollow noreferrer\">mysql_query</a>, neither have they seen one of the many comments on Stack Overflow pointing to <a href=\"https://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php\">this question</a>, and they have also missed the <a href=\"http://php.net/manual/en/mysqlinfo.api.choosing.php\" rel=\"nofollow noreferrer\">guide to choosing a database API</a> in the PHP documentation.</p>\n\n<p>Summary: (can't be emphasized enough, really...)</p>\n\n<p><img src=\"https://i.stack.imgur.com/Lz7PG.gif\" alt=\"#DON'T USE THE MYSQL_* FUNCTIONS! THEY ARE DEPRECATED!\"></p>\n\n<p>Instead, use <a href=\"http://www.php.net/manual/en/ref.pdo-mysql.php\" rel=\"nofollow noreferrer\">PDO</a> or <a href=\"http://www.php.net/manual/en/book.mysqli.php\" rel=\"nofollow noreferrer\">mysqli</a>. Also use <strong>prepared statements</strong> and you won't have to call as many functions to try and protect yourself from SQL injection attacks, the prepared statements will do a lot for you in preventing such attacks.</p>\n\n<p>Another potential problem I see in your code is that you're not protecting yourself from spam-bots in any way. Once automatic bots find your form, they will use it. A lot. Use some <a href=\"http://www.phpcaptcha.org/\" rel=\"nofollow noreferrer\">PHP Captcha</a> script to prevent bots from spamming you to oblivion.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T19:42:12.353",
"Id": "70765",
"Score": "3",
"body": "I think your summary could be a bit bigger, just to make sure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T19:45:38.087",
"Id": "70766",
"Score": "0",
"body": "@Bobby I would make it bigger if I could."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T20:10:56.630",
"Id": "70768",
"Score": "3",
"body": "Where is the blink tag if, for once, there's a legit usage for it?!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T20:24:51.923",
"Id": "70771",
"Score": "1",
"body": "@Bobby In the future, we could use [this link](http://altreus.github.io/qi-klaxon/?don%27t%20use%20the%20deprecated%20mysql_*%20functions)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T20:40:06.833",
"Id": "70775",
"Score": "1",
"body": "I think the OP got the message for now..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T20:54:27.733",
"Id": "70777",
"Score": "0",
"body": "How about [something like this](http://jsfiddle.net/XZWDX/)? On second thought, we could ask in the SO PHP chat room if they already have such a site. on third thought, [this SO question](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) does already a very decent job. We should link to that one from now on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T21:00:11.553",
"Id": "70779",
"Score": "0",
"body": "On fourth thought, you already know about that question, so scratch all that..."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T09:31:55.160",
"Id": "41211",
"ParentId": "41209",
"Score": "11"
}
},
{
"body": "<pre><code><?PHP\n</code></pre>\n\n<p>Normally it's all lower case, just saying.</p>\n\n<hr>\n\n<pre><code>//Turn off error reporting (Not Necessary)\nerror_reporting(E_ALL ^ E_NOTICE);\n</code></pre>\n\n<p>This is one prime example of confusing and not helpful commenting. If this call is not necessary, why is it there at all?</p>\n\n<hr>\n\n<pre><code>if (!@mysql_connect('localhost', 'user', '') or !@mysql_select_db('comments')) {\n</code></pre>\n\n<p>Stop using the <code>mysql_*</code> functions, seriously.</p>\n\n<hr>\n\n<pre><code>$guest_name = htmlentities(str_replace(' ', '',$_POST['guest_name']));\n</code></pre>\n\n<p>Why are you replacing entities here? You should not replace stuff when saving it into your database. Ideally the data in your database would be as unbiased as possible. Only replace entities if you need to, f.e. you display it on a webpage.</p>\n\n<hr>\n\n<pre><code>$time = date('g:i A', time());\n$date = date('n/j/Y');\n$query = \"INSERT INTO `user_comments` VALUES(\n '\".mysql_real_escape_string('').\"',\n '\".mysql_real_escape_string($guest_name).\"',\n '\".mysql_real_escape_string($comment).\"',\n '\".mysql_real_escape_string($date).\"',\n '\".mysql_real_escape_string($time).\"'\n )\";\n</code></pre>\n\n<p>From this query I can tell you a few things:</p>\n\n<ol>\n<li>Your database layout is sub-optimal, it uses <code>VARCHAR</code> fields if it should use a <code>DATETIME</code> field.</li>\n<li>You like to copy and paste code, that's bad.</li>\n<li>You don't do things explicitly, consider adding a fields list to your queries.</li>\n</ol>\n\n<p>First, you should be using a <code>DATETIME</code> type if you're gonna save date and time. MySQL supports also a 'pure' <code>DATE</code> and <code>TIME</code> format, there's absolutely no reason and no excuse to use use a <code>VARCHAR</code> field for that.</p>\n\n<p>And then there's your missing fields list, I made a habit out of adding a fields list to my queries for two reasons:</p>\n\n<ol>\n<li>It let's the reader know <em>exactly</em> what is getting set to where.</li>\n<li>It makes your code more robust, the query will not fail if you add a field. Removing a field is also easier, as a simple grep for the field will yield all queries that use it.</li>\n</ol>\n\n<p>So, your query should look like this:</p>\n\n<pre><code>$query = \"\n INSERT INTO \n user_comments\n SET\n name = :name,\n comment = :comment;\n\";\n</code></pre>\n\n<p>It's easy to read and you know exactly what ends where. Additionally the date/time stuff is here completely missing, because I changed the database layout:</p>\n\n<pre><code>CREATE TABLE user_comments\n name VARCHAR,\n comment VARCHAR,\n timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP;\n</code></pre>\n\n<p>The <code>TIMESTAMP</code> type is <em>optimal</em> for this kind of operation, as it is able to save automatically the time when the row is created.</p>\n\n<hr>\n\n<pre><code>$array_query = mysql_query(\"SELECT * FROM `comments` ORDER BY `ID` DESC\");\n</code></pre>\n\n<p>Same here, your usage of the <code>*</code> makes it easily broken by adding new fields. Additionally you don't know what fields are fetched until you look at the table declaration.</p>\n\n<hr>\n\n<pre><code>header('Location: index.php');\n</code></pre>\n\n<p>I'm 99% sure that this should not work. Headers can not be changed after data was send, you set the header in the middle of the file, but your php script should be moved to the top of the file. Additionally if you want to redirect people, it would be good to <code>die()</code> afterwards to make sure that your script stops executing at this point:</p>\n\n<pre><code><?php\n if (condition) {\n header(\"Location: othersite.php\");\n die(\"Redirect: <full address here>\");\n }\n?>\n<html>\n <head>\n ...\n</code></pre>\n\n<p>This will also allow everyone who is not automatically redirected to see where to go to now.</p>\n\n<hr>\n\n<pre><code>echo '<span style=\"color:red\">*Please enter a Guest Name*</span><br>';\n</code></pre>\n\n<p>You're outputting stuff while inside the <code><head></code>, that's bad practice, content should go into the <code><body></code>.</p>\n\n<hr>\n\n<pre><code><!-- \\/ COMMENT FORM \\/ -->\n</code></pre>\n\n<p>What is this?!</p>\n\n<hr>\n\n<p>And just to make sure:</p>\n\n<h1><a href=\"https://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php\">Stop using the <code>mysql_*</code> functions and start using prepared queries!</a></h1>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T20:10:39.923",
"Id": "41249",
"ParentId": "41209",
"Score": "13"
}
}
] |
{
"AcceptedAnswerId": "41249",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T09:11:43.057",
"Id": "41209",
"Score": "8",
"Tags": [
"php",
"html",
"security"
],
"Title": "Simple comment system"
}
|
41209
|
<p>I have this function in this <a href="http://jsfiddle.net/saadshahd/3smGz/">fiddle</a></p>
<p><strong>JavaScript:</strong></p>
<pre><code>var newsTicker = function (ele) {
var eles = ele.find('ul li'),
indexEle = 0,
dataEle = ele.find('.ticker-post'),
rotateChars = function (title) {
dataEle.text('');
indexCut = 0;
rotateCharsTimer = setInterval(function () {
if (dataEle.text().length == title.length) {
clearInterval(rotateCharsTimer);
} else if (dataEle.text().length < title.length) {
text = dataEle.text().concat(title.substr(indexCut, 1));
dataEle.text(text);
};
if (title.length - 1 > indexCut) indexCut++;
else indexCut = 0;
}, 90);
},
loopLs = function () {
loopEle = eles.get(indexEle);
eleHref = $(loopEle).data('href');
eleTitle = $(loopEle).data('title');
dataEle.attr('href', eleHref);
if (typeof rotateCharsTimer != 'undefined') {
dataEle.fadeOut();
clearInterval(rotateCharsTimer);
}
dataEle.fadeIn();
rotateChars(eleTitle);
if (eles.length - 1 > indexEle) indexEle++;
else indexEle = 0;
}
loopLs();
setInterval(function (){loopLs()},9400);
}
</code></pre>
<p><strong>HTML:</strong></p>
<pre><code><div id="news-ticker">
<div class="ticker-title">Breaking News:</div>
<ul>
<li data-href="#1" data-title="No 10 armed police arrested over hardcore pornography"></li>
<li data-href="#2" data-title="EDF extends life of UK nuclear plants"></li>
<li data-href="#3" data-title="Superwoman Stephanie Flanders on how to do it all"></li>
<li data-href="#4" data-title="Will Liverpool deliver for Suárez? Can Arsenal last?"></li>
</ul>
<a class="ticker-post"></a>
</div>
</code></pre>
<p>Is this the best way to do this?</p>
|
[] |
[
{
"body": "<p>The HTML markup should be semantic, such that it degrades gracefully in the absence of JavaScript:</p>\n\n<pre><code><ul>\n <li><a href=\"#1\">No 10 armed police arrested over hardcore pornography</a></li>\n <li><a href=\"#2\">EDF extends life of UK nuclear plants</a></li>\n <li><a href=\"#3\">Superwoman Stephanie Flanders on how to do it all</a></li>\n <li><a href=\"#4\">Will Liverpool deliver for Suárez? Can Arsenal last?</a></li>\n</ul>\n</code></pre>\n\n<p>To make that work, the CSS should not contain a <code>ul { display: none }</code> rule. Instead, the JavaScript code should be responsible for suppressing the normal display.</p>\n\n<hr>\n\n<p>You have a bug in the timing that causes each ticker item to briefly fade out and fade in again, causing an undesirable flashing effect. The problem is that you don't wait for the fade-out to complete before proceeding. The fix is to use the <code>complete</code> callback of <a href=\"http://api.jquery.com/fadeOut/\"><code>.fadeOut()</code></a>. In order to fade out the correct element, it's easier to hang on to a <code>$current</code> jQuery object, advancing it only after the fade-out has completed.</p>\n\n<hr>\n\n<p>You forgot to localize the variables in your inner functions using <code>var</code>. In <code>rotateCharsTimer</code>, the substring operation could be simplified. For readability, I prefer to write the <code>newsTicker()</code>, <code>rotateChars()</code>, and <code>loopLs()</code> functions \"normally\" rather than as anonymous functions assigned to a variable. Also for readability, I suggest passing parameters to the helper functions explicitly.</p>\n\n<pre><code>function newsTicker($ele) {\n var $eles = $ele.find('ul > li'),\n $current = $eles.hide().first(),\n rotateCharsTimer;\n\n function rotateChars($ele) {\n var indexCut = 0;\n var title = $ele.data('title');\n rotateCharsTimer = setInterval(function () {\n if ($ele.text().length >= title.length) {\n clearInterval(rotateCharsTimer);\n } else {\n $ele.text(title.substr(0, indexCut++));\n }\n }, 90);\n }\n\n function loopLs($eles) {\n if (typeof rotateCharsTimer != 'undefined'){\n clearInterval(rotateCharsTimer);\n }\n $current.find('a').fadeOut('slow', function() {\n $eles.hide(); \n $current = $current.next().length ? $current.next()\n : $eles.first();\n rotateChars($current.show()\n .find('a')\n .text('')\n .fadeIn());\n });\n }\n\n // Transfer the text into a data-title attribute\n $eles.find('a').each(function() {\n $(this).data('title', $(this).text());\n });\n loopLs($eles);\n setInterval(function(){loopLs($eles);}, 9400);\n}\n\n$ = jQuery;\nnewsTicker($('#news-ticker'));\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/8gSqU/\">jsFiddle with the recommendations</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T12:55:18.423",
"Id": "41224",
"ParentId": "41215",
"Score": "5"
}
},
{
"body": "<p>Your jQuery function was okay, but it's common practice now to put your animations into CSS wherever possible. </p>\n\n<p>I've rewritten your code, moving as much as possible into CSS. I'll explain how and why below, or you can skip to the <a href=\"http://jsfiddle.net/3smGz/3/\">final solution here</a>.</p>\n\n<p>Semantically your links shouldn't be <code>data-attributes</code> as they control page navigation and need to be visible and identifiable as such.</p>\n\n<pre><code><div id=\"news-ticker\">\n <div class=\"ticker-title\">Breaking News: </div>\n <ul>\n <li>\n <a href=\"http://www.thetimes.co.uk/tto/news/uk/crime/article3999682.ece\">No 10 armed police arrested over hardcore pornography</a>\n </li>\n <li>\n <a href=\"http://www.thetimes.co.uk/tto/environment/article3999530.ece\">EDF extends life of UK nuclear plants</a>\n </li>\n </ul>\n</div>\n</code></pre>\n\n<p>You shouldn't use <code>float: left</code> for this, these components are <code>inline</code>, not floating.</p>\n\n<pre><code>#news-ticker .ticker-title {\n display: inline-block;\n margin-right: 12px;\n}\n\n#news-ticker ul { \n display: inline-block;\n position: relative;\n}\n</code></pre>\n\n<p>Next we want to make each news item invisible when not active, and we want them to all appear in the same place. A simple way to do this is to make their position <code>absolute</code>.</p>\n\n<pre><code>#news-ticker li {\n position: absolute;\n left: 0;\n width: 0;\n overflow: hidden;\n height: 1em;\n word-wrap: break-word; \n opacity: 0\n}\n</code></pre>\n\n<p>There are a few more things I've added here as well...</p>\n\n<ol>\n<li><code>width: 0</code>: By making the width of the elements 0 they are invisible, and we can extend the width to show them a letter at a time.</li>\n<li><code>word-wrap: break-word</code>: This helps us get the <code>tick</code> each letter at a time effect.</li>\n<li><code>overflow: hidden</code>: stops us from seeing the rest of the sentence when the container isn't wide enough.</li>\n</ol>\n\n<p>Next we make the animation. There's a good guide <a href=\"https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_animations\">here about how they work</a>.</p>\n\n<pre><code>#news-ticker li.tick {\n -webkit-animation: tick 5s linear;\n\n}\n\n@-webkit-keyframes tick {\n 0% {\n width: 0;\n }\n 5% {\n opacity: 1;\n } \n 90% {\n width: 550px;\n opacity: 1;\n }\n 100% {\n opacity: 0\n }\n}\n</code></pre>\n\n<p>This means that when we add the class <code>.tick</code> to one of our list elements it will animate from <code>0</code> width to <code>550px</code>.</p>\n\n<p>Now for our small amount of JavaScript to switch the classes and make the wrap work on letters instead of words.</p>\n\n<pre><code>$(function () {\n var $ticker = $('#news-ticker'),\n $first = $('li:first-child', $ticker);\n</code></pre>\n\n<p>Unfortunately there's no <code>letter-wrap</code> CSS attribute, so we have to <em>cheat</em> a little. Here I insert a blank space inbetween each letter, essentially making it a word.</p>\n\n<pre><code> $('a', $ticker).each(function () {\n var $this = $(this),\n text = $this.text();\n $this.html(text.split('').join('&#8203;'));\n });\n</code></pre>\n\n<p>And then start the ticker. Every time an animation ends, it grabs the next (or first) element and continues:</p>\n\n<pre><code> function tick($el) {\n $el.addClass('tick')\n .one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function () {\n\n $el.removeClass('tick');\n var $next = $el.next('li');\n $next = $next.length > 0 ? $next : $first;\n tick($next);\n });\n }\n\n tick($first);\n\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T18:48:20.913",
"Id": "70758",
"Score": "0",
"body": "@SaadShahd Also it's much more performant to keep animations in your CSS."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T13:02:30.170",
"Id": "41226",
"ParentId": "41215",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "41224",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T10:01:02.700",
"Id": "41215",
"Score": "10",
"Tags": [
"javascript",
"jquery"
],
"Title": "Create news ticker animation"
}
|
41215
|
<p>This is my code to check if a string C is an interleaving of Strings A and B. Please suggests optimizations, and where I can improve.</p>
<pre><code>#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include<string.h>
using namespace std;
int isInterleaved(char a[100],char b[100],char c[200],int i, int j, int k)
{
if(i==0&&j==0)
return true;
if(i>=0&&j>=0)
{
if(c[k]==a[i]&&c[k]!=b[j])
return isInterleaved(a,b,c,i-1,j,k-1);
else if(c[k]==b[j]&&c[k]!=a[i])
return isInterleaved(a,b,c,i,j-1,k-1);
else if(c[k]==a[i]&&c[k]==b[j])
return isInterleaved(a,b,c,i-1,j,k-1)||isInterleaved(a,b,c,i,j-1,k-1);
else
return false;
}
else
{
if(i<0&&j>=0)
{
if(c[k]==b[j])
return isInterleaved(a,b,c,i,j-1,k-1);
else
return false;
}
if(j<0&&i>=0)
{
if(c[k]==a[i])
return isInterleaved(a,b,c,i-1,j,k-1);
else
return false;
}
}
}
int main()
{
char a[100],b[100],c[200];
cin>>a;
cin>>b;
cin>>c;
int l1=strlen(a),l2=strlen(b),l3=strlen(c);
if(l3>l1+l2)
{
printf("C is not an interleaving of A and B\n");
return 0;
}
int ans=isInterleaved(a,b,c,l1-1,l2-1,l3-1);
printf("%d\n",ans);
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>I would rewrite this part of code</p>\n\n<pre><code>if(c[k]==a[i]&&c[k]!=b[j])\n return isInterleaved(a,b,c,i-1,j,k-1);\nelse if(c[k]==b[j]&&c[k]!=a[i])\n return isInterleaved(a,b,c,i,j-1,k-1);\nelse if(c[k]==a[i]&&c[k]==b[j])\n return isInterleaved(a,b,c,i-1,j,k-1)||isInterleaved(a,b,c,i,j-1,k-1);\nelse\n return false;\n}\n</code></pre>\n\n<p>where you are, at the end, testing 2 posible ways to go on, as this</p>\n\n<pre><code>if(c[k]==a[i]) {\n if (isInterleaved(a,b,c,i-1,j,k-1)) return true;\n}\nif(c[k]==b[j]) {\n if (isInterleaved(a,b,c,i,j-1,k-1)) return true;\n}\nreturn false;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T11:54:58.983",
"Id": "41222",
"ParentId": "41217",
"Score": "5"
}
},
{
"body": "<p>Just about every <code>#include</code> in this code is unneeded. You use <code>cin</code>, <code>strlen</code> and <code>printf</code>. That requires just <code><cstring></code>, <code><cstdio></code>, and <code><iostream></code>. In fact, if you're using C++, you should just use <code>cout</code> as an output stream instead of using <code>printf</code>, which would cut the imports down to <code><cstring></code> and <code><iostream></code>. The rest should be completely removed.</p>\n\n<p>Why hardcode the array lengths as arguments?</p>\n\n<pre><code>int isInterleaved(char a[100],char b[100],char c[200],int i, int j, int k)\n</code></pre>\n\n<p>This should be:</p>\n\n<pre><code>int isInterleaved(char *a, char *b, char *c, int i, int j, int k)\n</code></pre>\n\n<p>Preferably, if you're using C++ and not C, you should instead use <code>std::string</code> (which would need an <code>#include <string></code>.)</p>\n\n<p>You're using a fairly strange (and inconsistent) brace style:</p>\n\n<pre><code>if(l3>l1+l2)\n {\n printf(\"C is not an interleaving of A and B\\n\");\n return 0;\n }\n</code></pre>\n\n<p>Or no indentation:</p>\n\n<pre><code>if(i>=0&&j>=0)\n{\n\nif(c[k]==a[i]&&c[k]!=b[j])\n return isInterleaved(a,b,c,i-1,j,k-1);\nelse if(c[k]==b[j]&&c[k]!=a[i])\n return isInterleaved(a,b,c,i,j-1,k-1);\nelse if(c[k]==a[i]&&c[k]==b[j])\n return isInterleaved(a,b,c,i-1,j,k-1)||isInterleaved(a,b,c,i,j-1,k-1);\nelse\n return false;\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>if(c[k]==b[j])\nreturn isInterleaved(a,b,c,i,j-1,k-1);\n</code></pre>\n\n<p>This makes the code harder to read.</p>\n\n<p>Your code could probably do with some commenting, at least explaining the different cases.</p>\n\n<p>In the end, using some C++ features, I'd do it something like this:</p>\n\n<pre><code>#include <iostream>\n#include <string>\n#include <iterator>\n\ntemplate <typename Iterator>\nbool is_interleaved_impl(Iterator a_begin, Iterator a_end, Iterator b_begin, \n Iterator b_end, Iterator c_begin, Iterator c_end)\n{\n // Case 1: We've exhausted a, so all we can do is draw the rest of the characters\n // from b, in order.\n if(a_begin == a_end) {\n if(std::distance(b_begin, b_end) != std::distance(c_begin, c_end)) {\n return false;\n }\n return std::string(c_begin, c_end) == std::string(b_begin, b_end);\n }\n // Case 2: We've exhausted b, so all we can do is draw the rest of the\n // characters from a, in order.\n else if(b_begin == b_end) {\n if(std::distance(a_begin, a_end) != std::distance(c_begin, c_end)) {\n return false;\n }\n return std::string(c_begin, c_end) == std::string(a_begin, a_end);\n }\n // Case 3: Characters can be chosen from either a OR b. In this case, we split into\n // 2 possibilities == 2 recurive calls.\n else if(*a_begin == *c_begin && *b_begin == *c_begin) {\n return is_interleaved_impl(a_begin + 1, a_end, b_begin, b_end, c_begin + 1, c_end) ||\n is_interleaved_impl(a_begin, a_end, b_begin + 1, b_end, c_begin + 1, c_end);\n }\n // Case 4: Only the next character from a matches.\n else if(*a_begin == *c_begin) {\n return is_interleaved_impl(++a_begin, a_end, b_begin, b_end, ++c_begin, c_end);\n }\n // Case 5: Only the next character from b matches.\n else if(*b_begin == *c_begin) {\n return is_interleaved_impl(a_begin, a_end, ++b_begin, b_end, ++c_begin, c_end);\n }\n // Nothing matches, so they aren't interleaved.\n return false;\n}\n\nbool is_interleaved(const std::string& a, const std::string& b, const std::string& c)\n{\n if(a.size() + b.size() != c.size()) {\n return false;\n }\n return is_interleaved_impl(a.begin(), a.end(), b.begin(), b.end(), c.begin(), c.end());\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T01:21:54.137",
"Id": "70804",
"Score": "1",
"body": "The two subcalls in case 3 seem like they would pass the wrong values for the begin iterators due to how they use preincrement. I would suggest passing `a_begin + 1`, `b_begin + 1` and `c_begin + 1` (or precalculating them) instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T06:19:10.913",
"Id": "70816",
"Score": "0",
"body": "@MichaelUrman Good catch. Fixed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T13:04:18.233",
"Id": "41227",
"ParentId": "41217",
"Score": "7"
}
},
{
"body": "<p>You include a ton of headers you don't use. This is distracting and hurts both reading and compilation time.</p>\n\n<p>The early check for matching size seems like an optimization, but since it's checked every time through the recursion, it's probably harmful. It turns what should be an linear algorithm into a quadratic algorithm as it scans every remaining letter for each letter.</p>\n\n<p>I would probably use character pointers instead of character arrays, and try to use more meaningful names. If you really want to stick with indices instead of character pointers, I would suggest wrapping this in a class that can track the three strings, allowing you to pass only the indices to the recursive call. Here's an untested attempt to implement this with pointers.</p>\n\n<pre><code>// A string is considered interleaved if for each character along `interleaved` you can\n// find its character at the front of the remainder of one of the source strings.\n// All strings must be c-style zero-terminated strings.\nbool isInterleaved(char const *interleaved, char const *source1, char const *source2)\n{\n // must terminate at end of `interleaved`\n if (!*interleaved)\n return !*source1 && !*source2\n\n // check whether front characters of `interleaved` and either source string match\n // and remainders are an interleaved string\n return (*interleaved == *source1 && isInterleaved(interleaved + 1, source1 + 1, source2))\n || (*interleaved == *source2 && isInterleaved(interleaved + 1, source1, source2 + 1));\n}\n</code></pre>\n\n<p>The worst case running time of this approach would be for a call that looks like <code>isInterleaved(\"aaaaaa...aaaa\", \"aaaaa...aaaa\", \"aaaaa...aaab\")</code> where it has to check both options in both strings until it finally finds at the end that it never matches. In some cases the early length-based termination could catch this, but in others it cannot.</p>\n\n<p>If you are working with particularly long strings, you may need to use the heap rather than the stack to track the recursive step of the algorithm. This is often done by storing the tuple of three character pointers in a <code>std::stack</code> or <code>std::queue</code> and iterating through that until a match is confirmed or the collection is empty.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T08:09:17.950",
"Id": "70822",
"Score": "0",
"body": "Took me a while to realize that partially overlapping sources requires the recursion. Tnx for pointing that out in my flawed attempt."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T13:04:50.680",
"Id": "41228",
"ParentId": "41217",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "41222",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T10:24:32.193",
"Id": "41217",
"Score": "2",
"Tags": [
"c++",
"c",
"algorithm",
"strings",
"recursion"
],
"Title": "To check if a string C is an interleaving of A and B Code"
}
|
41217
|
<p>This is my adapter class, to create a custom <code>listView</code> with three <code>radiobuttons</code>:</p>
<pre><code>public class Attendancelist_customadapter extends ArrayAdapter {
///needs two arraylists - one for the peopledetails, and one for the attendance status. read from file. passed to this.
///then assemble into a ListView with customview - in this.
///three radio buttons per item. invited, not attending, attending.
///
Context context;
int layoutResourceId;
ArrayList<People_Attendance> people_attendance = null;
String[] attendance_status;
String ATTENDING ="ATTENDING";
String NOT_ATTENDING = "NOT ATTENDING";
String INVITED = "INVITED";
public Attendancelist_customadapter(Context context, int layoutResourceId, ArrayList<People_Attendance> people_attendance){
super(context, layoutResourceId, people_attendance);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.people_attendance = people_attendance;
this.attendance_status = new String[this.people_attendance.size()];
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
attendance_holder holder = null;
People_Attendance people_array[] = people_attendance.toArray(new People_Attendance[people_attendance.size()]);
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new attendance_holder();
holder.txtName = (TextView)row.findViewById(R.id.name_txt);
holder.txtNumber = (TextView)row.findViewById(R.id.number_txt);
holder.attendance_group = row.findViewById(R.id.Attendance_Group);
holder.not_attending = (RadioButton) holder.attendance_group.findViewById(R.id.not_attending_radio);
holder.attending = (RadioButton) holder.attendance_group.findViewById(R.id.attending_radio);
holder.invited = (RadioButton) holder.attendance_group.findViewById(R.id.invited_radio);
row.setTag(holder);
}
else
{
holder = (attendance_holder)row.getTag();
}
holder.txtName.setText(people_array[position].name);
holder.txtNumber.setText(people_array[position].number);
holder.invited.setChecked(people_array[position].attendance_status.equals(INVITED));
holder.attending.setChecked(people_array[position].attendance_status.equals(ATTENDING));
holder.not_attending.setChecked(people_array[position].attendance_status.equals(NOT_ATTENDING));
holder.attending.setTag(position);
holder.not_attending.setTag(position);
holder.invited.setTag(position);
holder.invited.setOnCheckedChangeListener((new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int position = (Integer) buttonView.getTag();
if (isChecked == true){
attendance_status[position] = INVITED;
}
}
}));
holder.attending.setOnCheckedChangeListener((new CompoundButton.OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
int position = (Integer) buttonView.getTag();
if (isChecked == true){
attendance_status[position] = ATTENDING;
}
}
}));
holder.not_attending.setOnCheckedChangeListener((new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
int position = (Integer) buttonView.getTag();
if (isChecked == true){
attendance_status[position] = NOT_ATTENDING;
}
}
}));
return row;
}
People_Attendance getPerson(int position){
return ((People_Attendance) getItem(position));
}
static class attendance_holder{
TextView txtName;
TextView txtNumber;
RadioButton invited;
RadioButton attending;
RadioButton not_attending;
View attendance_group;
public String getChecked(){
String return_string = "";
if(invited.isChecked()){
return_string = "INVITED";
return return_string;
}else if(attending.isChecked()){
return_string = "ATTENDING";
return return_string;
}else if(not_attending.isChecked()){
return_string = "NOT ATTENDING";
return return_string;
}else{
invited.setChecked(true);///checks the Invited checkbox, if none others are checked.
/// as only people who have been invited will be passed to this, therefore set to invited if nothing else.
return_string = "INVITED";
return return_string;
}
}
}
}
</code></pre>
<ol>
<li>Is there a shorter way of writing the code for the Listeners for each of the <code>RadioButtons</code>?</li>
<li>Is there a suitable method that could be implemented from the <code>RadioGroup</code>, that would shorten the code?</li>
</ol>
<p>In my main activity I will get the <code>string[] attendance_status</code>, and then use that to write to a file. My question is whether there is a shorter, more efficient code that I could use, instead of having three <code>onCheckedChangeListners</code>?</p>
|
[] |
[
{
"body": "<p>This is your lucky day, there is an \"easier\" way to do this. First, we create a custom <strong>inner</strong> class: (put this code inside your current class, just like you would do with a method)</p>\n\n<pre><code>private class MyCheckedChange implements CompoundButton.OnCheckedChangeListener {\n private final String status;\n public MyCheckedChange(String status) {\n this.status = status;\n }\n @Override\n public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){\n int position = (Integer) buttonView.getTag();\n if (isChecked == true){\n attendance_status[position] = status;\n }\n }\n}\n</code></pre>\n\n<p>Then you can instantiate this class with a corresponding status value.</p>\n\n<pre><code>holder.attending.setOnCheckedChangeListener(new MyCheckedChange(ATTENDING));\nholder.not_attending.setOnCheckedChangeListener(new MyCheckedChange(NOT_ATTENDING));\nholder.invited.setOnCheckedChangeListener(new MyCheckedChange(INVITED));\n</code></pre>\n\n<h3>Further suggestions: (use them if you like them)</h3>\n\n<p><strong>Use an enum for attendance status:</strong></p>\n\n<pre><code>public enum AttendingStatus {\n NOT_ATTENDING, ATTENDING, INVITED;\n}\n</code></pre>\n\n<p>And use <code>AttendingStatus[] attendance_status;</code> instead of your string array.</p>\n\n<p>This will open up the possibility of many things, if you would like:</p>\n\n<p>You can match up your radiobuttons to an attendingstatus, by using a <code>Map<RadioButton, AttendingStatus></code> for example, which could reduce code duplication in the <code>getChecked()</code> method by grabbing a RadioButtons corresponding AttendingStatus by using <code>AttendingStatus status = map.get(radioButton);</code> and using <code>status.toString().replaceAll(\"_\", \" \");</code> to get it's string version.</p>\n\n<p>I don't know your skill level so this might be a bit advanced for you, but if you are willing to learn, I really suggest that you start playing around with enums. You will love them :)</p>\n\n<p><strong>Spacing</strong></p>\n\n<pre><code>`}else if(attending.isChecked()){`\n</code></pre>\n\n<p>is a bit tightly written, you can increase readability a bit by using more spaces, like this:</p>\n\n<pre><code>`} else if (attending.isChecked()) {`\n</code></pre>\n\n<p><strong>Private, final, and constants</strong></p>\n\n<p>There are plenty of instance variables in your code that could be private, final, and possibly static.</p>\n\n<pre><code>String ATTENDING = \"ATTENDING\";\nString NOT_ATTENDING = \"NOT ATTENDING\";\nString INVITED = \"INVITED\";\n</code></pre>\n\n<p>All these are constants, they should never change, and should therefore be declared <code>private static final</code></p>\n\n<pre><code>private static final String ATTENDING = \"ATTENDING\";\nprivate static final String NOT_ATTENDING = \"NOT ATTENDING\";\nprivate static final String INVITED = \"INVITED\";\n</code></pre>\n\n<p>I believe that all of your variable declarations above your constructor can be marked private, and I also believe that all them can be final:</p>\n\n<pre><code>private final Context context; \nprivate final int layoutResourceId; \nprivate final ArrayList<People_Attendance> people_attendance = null;\nprivate final String[] attendance_status;\n</code></pre>\n\n<p>Making them private will let the compiler tell you if any of them are not used, and making them final will ensure you that once initialized in the constructor, their value / object-reference cannot change.</p>\n\n<p><strong>Naming</strong></p>\n\n<p>Using class names with <code>_</code> in Java is unusual and not convention, <code>PeopleAttendance</code> would be a better name. Also, class names should start with an upper-case letter and use CamelCasing, making <code>attendance_holder</code> --> <code>AttendanceHolder</code>.</p>\n\n<p>Overall though, I get the impression that you seem to know what you are doing coding-wise, good work :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T11:22:38.883",
"Id": "41219",
"ParentId": "41218",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "41219",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T10:53:09.637",
"Id": "41218",
"Score": "4",
"Tags": [
"java",
"android"
],
"Title": "Radio ListView onCheckedChangeListener?"
}
|
41218
|
<p>I am using building REST services for file upload on the server. Here is some code of that</p>
<pre><code>[OprationContract]
[WebInvoke(Method = "POST", UriTemplate = "UploadFile/{fileName}")]
public string UploadFile(string fileName, Stream fileStream)
{
string filePath = serverDirectory + "\\" + fileName;
using (var output = File.Open(filePath, FileMode.Create))
{
fileStream.CopyTo(output);
}
return "success";
}
</code></pre>
<p>However this method works fine when file size is small. but when the file size is large say 30-40 Mb then the performance become low. </p>
<p>So I want to know what are the best practices to upload the files on the server with speed.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T15:01:40.867",
"Id": "70735",
"Score": "0",
"body": "This code won't compile, your method isn't returning anything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T15:07:12.180",
"Id": "70736",
"Score": "0",
"body": "@svick ohh I forgot to add that. Actaully I am returning my customer `ServiceResponse` object but for simplicity I didn't included that."
}
] |
[
{
"body": "<p>The lines of code inside your UploadFile method look optimal to me.</p>\n\n<p>Perhaps the problem is that your Stream contents are being fully buffered before they're being delivered.</p>\n\n<p>I've no experience with this myself, but\n<a href=\"http://msdn.microsoft.com/en-us/library/ms789010.aspx\" rel=\"nofollow\">How to: Enable Streaming</a> suggests you may need to change your configured <code>TransferMode</code>, and change your API so that it has a method whose only parameter is <code>Stream</code> (perhaps pass the filename in one method and the Stream in the next method).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T11:59:35.877",
"Id": "41223",
"ParentId": "41220",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T11:23:58.763",
"Id": "41220",
"Score": "1",
"Tags": [
"c#",
"file",
"web-services"
],
"Title": "Best practice to upload files on server using Rest Service"
}
|
41220
|
<h1>Description</h1>
<p>This is a follow-up question to <a href="https://codereview.stackexchange.com/questions/41198/tool-for-creating-code-review-questions">Tool for creating CodeReview questions</a>.</p>
<p>Things that has changed include:</p>
<ul>
<li>Removed replacing four spaces with one tab, all tabs and all spaces in the code itself is now left as-is.</li>
<li>Added file extensions to the output.</li>
<li>Switched order of lines and bytes as I feel that the number of lines of code is more interesting than the number of bytes.</li>
<li>Support for command-line parameters to directly process a directory or a bunch of files, with the support for wildcards. If a directory or wildcard is used, files that don't pass an ASCII-content check gets skipped. If you have specified a file that has a lot of non-ASCII content it is processed anyway.</li>
</ul>
<p>I am asking for another review because of the things that I have added mostly, see the questions below.</p>
<h3>Class Summary (413 lines in 4 files, making a total of 12134 bytes)</h3>
<ul>
<li>CountingStream.java: OutputStream that keeps track on the number of written bytes to it</li>
<li>ReviewPrepareFrame.java: JFrame for letting user select files that should be up for review</li>
<li>ReviewPreparer.java: The most important class, takes care of most of the work. Expects a List of files in the constructor and an OutputStream when called.</li>
<li>TextAreaOutputStream.java: OutputStream for outputting to a JTextArea.</li>
</ul>
<h1>Code</h1>
<p>The code can also be found on <a href="https://github.com/Zomis/ReviewPrepare" rel="nofollow noreferrer">GitHub</a></p>
<p><strong>CountingStream.java:</strong> (27 lines, 679 bytes)</p>
<pre><code>/**
* An output stream that keeps track of how many bytes that has been written to it.
*/
public class CountingStream extends FilterOutputStream {
private final AtomicInteger bytesWritten;
public CountingStream(OutputStream out) {
super(out);
this.bytesWritten = new AtomicInteger();
}
@Override
public void write(int b) throws IOException {
bytesWritten.incrementAndGet();
super.write(b);
}
public int getBytesWritten() {
return bytesWritten.get();
}
}
</code></pre>
<p><strong>ReviewPrepareFrame.java:</strong> (112 lines, 3255 bytes)</p>
<pre><code>public class ReviewPrepareFrame extends JFrame {
private static final long serialVersionUID = 2050188992596669693L;
private JPanel contentPane;
private final JTextArea result = new JTextArea();
/**
* Launch the application.
*/
public static void main(String[] args) {
if (args.length == 0) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new ReviewPrepareFrame().setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
else ReviewPreparer.main(args);
}
/**
* Create the frame.
*/
public ReviewPrepareFrame() {
setTitle("Prepare code for Code Review");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.NORTH);
final DefaultListModel<File> model = new DefaultListModel<>();
final JList<File> list = new JList<File>();
panel.add(list);
list.setModel(model);
JButton btnAddFiles = new JButton("Add files");
btnAddFiles.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser dialog = new JFileChooser();
dialog.setMultiSelectionEnabled(true);
if (dialog.showOpenDialog(ReviewPrepareFrame.this) == JFileChooser.APPROVE_OPTION) {
for (File file : dialog.getSelectedFiles()) {
model.addElement(file);
}
}
}
});
panel.add(btnAddFiles);
JButton btnRemoveFiles = new JButton("Remove files");
btnRemoveFiles.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (File file : new ArrayList<>(list.getSelectedValuesList())) {
model.removeElement(file);
}
}
});
panel.add(btnRemoveFiles);
JButton performButton = new JButton("Create Question stub with code included");
performButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
result.setText("");
ReviewPreparer preparer = new ReviewPreparer(filesToList(model));
TextAreaOutputStream outputStream = new TextAreaOutputStream(result);
preparer.createFormattedQuestion(outputStream);
}
});
contentPane.add(performButton, BorderLayout.SOUTH);
contentPane.add(result, BorderLayout.CENTER);
}
public List<File> filesToList(DefaultListModel<File> model) {
List<File> files = new ArrayList<>();
for (int i = 0; i < model.getSize(); i++) {
files.add(model.get(i));
}
return files;
}
}
</code></pre>
<p><strong>ReviewPreparer.java:</strong> (233 lines, 7394 bytes)</p>
<pre><code>public class ReviewPreparer {
public static double detectAsciiness(File input) throws IOException {
if (input.length() == 0)
return 0;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(input)))) {
int read;
long asciis = 0;
char[] cbuf = new char[1024];
while ((read = reader.read(cbuf)) != -1) {
for (int i = 0; i < read; i++) {
char c = cbuf[i];
if (c <= 0x7f)
asciis++;
}
}
return asciis / (double) input.length();
}
}
private final List<File> files;
public ReviewPreparer(List<File> files) {
this.files = new ArrayList<>();
for (File file : files) {
if (file.getName().lastIndexOf('.') == -1)
continue;
if (file.length() < 10)
continue;
this.files.add(file);
}
}
public int createFormattedQuestion(OutputStream out) {
CountingStream counter = new CountingStream(out);
PrintStream ps = new PrintStream(counter);
outputHeader(ps);
outputFileNames(ps);
outputFileContents(ps);
outputDependencies(ps);
outputFooter(ps);
ps.print("Question Length: ");
ps.println(counter.getBytesWritten());
return counter.getBytesWritten();
}
private void outputFooter(PrintStream ps) {
ps.println("#Usage / Test");
ps.println();
ps.println();
ps.println("#Questions");
ps.println();
ps.println();
ps.println();
}
private void outputDependencies(PrintStream ps) {
List<String> dependencies = new ArrayList<>();
for (File file : files) {
try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
String line;
while ((line = in.readLine()) != null) {
if (!line.startsWith("import ")) continue;
if (line.startsWith("import java.")) continue;
if (line.startsWith("import javax.")) continue;
String importStatement = line.substring("import ".length());
importStatement = importStatement.substring(0, importStatement.length() - 1); // cut the semicolon
dependencies.add(importStatement);
}
}
catch (IOException e) {
ps.println("Could not read " + file.getAbsolutePath());
ps.println();
// more detailed handling of this exception will be handled by another function
}
}
if (!dependencies.isEmpty()) {
ps.println("#Dependencies");
ps.println();
for (String str : dependencies)
ps.println("- " + str + ": ");
}
ps.println();
}
private int countLines(File file) throws IOException {
return Files.readAllLines(file.toPath(), StandardCharsets.UTF_8).size();
}
private void outputFileContents(PrintStream ps) {
ps.println("#Code");
ps.println();
ps.println("This code can also be downloaded from [somewhere](http://github.com repository perhaps?)");
ps.println();
for (File file : files) {
try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
int lines = -1;
try {
lines = countLines(file);
}
catch (IOException e) {
}
ps.printf("**%s:** (%d lines, %d bytes)", file.getName(), lines, file.length());
ps.println();
ps.println();
String line;
int importStatementsFinished = 0;
while ((line = in.readLine()) != null) {
// skip package and import declarations
if (line.startsWith("package "))
continue;
if (line.startsWith("import ")) {
importStatementsFinished = 1;
continue;
}
if (importStatementsFinished >= 0) importStatementsFinished = -1;
if (importStatementsFinished == -1 && line.trim().isEmpty()) // skip empty lines directly after import statements
continue;
importStatementsFinished = -2;
ps.print(" "); // format as code for StackExchange, this needs to be four spaces.
ps.println(line);
}
}
catch (IOException e) {
ps.print("> Unable to read " + file + ": "); // use a block-quote for exceptions
e.printStackTrace(ps);
}
ps.println();
}
}
private void outputFileNames(PrintStream ps) {
int totalLength = 0;
int totalLines = 0;
for (File file : files) {
totalLength += file.length();
try {
totalLines += countLines(file);
}
catch (IOException e) {
ps.println("Unable to determine line count for " + file.getAbsolutePath());
}
}
ps.printf("###Class Summary (%d lines in %d files, making a total of %d bytes)", totalLines, files.size(), totalLength);
ps.println();
ps.println();
for (File file : files) {
ps.println("- " + file.getName() + ": ");
}
ps.println();
}
private void outputHeader(PrintStream ps) {
ps.println("#Description");
ps.println();
ps.println("- Add some [description for what the code does](http://meta.codereview.stackexchange.com/questions/1226/code-should-include-a-description-of-what-the-code-does)");
ps.println("- Is this a follow-up question? Answer [What has changed, Which question was the previous one, and why you are looking for another review](http://meta.codereview.stackexchange.com/questions/1065/how-to-post-a-follow-up-question)");
ps.println();
}
public static boolean isAsciiFile(File file) {
try {
return detectAsciiness(file) >= 0.99;
}
catch (IOException e) {
return true; // if an error occoured, we want it to be added to a list and the error shown in the output
}
}
public static void main(String[] args) {
List<File> files = new ArrayList<>();
if (args.length == 0)
files.addAll(fileList("."));
for (String arg : args) {
files.addAll(fileList(arg));
}
new ReviewPreparer(files).createFormattedQuestion(System.out);
}
public static List<File> fileList(String pattern) {
List<File> files = new ArrayList<>();
File file = new File(pattern);
if (file.exists()) {
if (file.isDirectory()) {
for (File f : file.listFiles())
if (!f.isDirectory() && isAsciiFile(f))
files.add(f);
}
else files.add(file);
}
else {
// extract path
int lastSeparator = pattern.lastIndexOf('\\');
lastSeparator = Math.max(lastSeparator, pattern.lastIndexOf('/'));
String path = lastSeparator < 0 ? "." : pattern.substring(0, lastSeparator);
file = new File(path);
// path has been extracted, check if path exists
if (file.exists()) {
// create a regex for searching for files, such as *.java, Test*.java
String regex = lastSeparator < 0 ? pattern : pattern.substring(lastSeparator + 1);
regex = regex.replaceAll("\\.", "\\.").replaceAll("\\?", ".?").replaceAll("\\*", ".*");
for (File f : file.listFiles()) {
// loop through directory, skip directories and filenames that don't match the pattern
if (!f.isDirectory() && f.getName().matches(regex) && isAsciiFile(f)) {
files.add(f);
}
}
}
else System.out.println("Unable to find path " + file);
}
return files;
}
}
</code></pre>
<p><strong>TextAreaOutputStream.java:</strong> (41 lines, 806 bytes)</p>
<pre><code>public class TextAreaOutputStream extends OutputStream {
private final JTextArea textArea;
private final StringBuilder sb = new StringBuilder();
public TextAreaOutputStream(final JTextArea textArea) {
this.textArea = textArea;
}
@Override
public void flush() {
}
@Override
public void close() {
}
@Override
public void write(int b) throws IOException {
if (b == '\n') {
final String text = sb.toString() + "\n";
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(text);
}
});
sb.setLength(0);
return;
}
sb.append((char) b);
}
}
</code></pre>
<h1>Usage / Test</h1>
<p>You can now use the tool directly by downloading <a href="https://github.com/Zomis/ReviewPrepare/releases" rel="nofollow noreferrer">the jar-file from GitHub</a> and running it with one of the following options:</p>
<ul>
<li><code>java -jar ReviewPrepare.jar</code> runs the Swing form to let you choose files using a GUI.</li>
<li><code>java -jar ReviewPrepare.jar .</code> runs the program in the current working directory and outputting to stdout.</li>
<li><code>java -jar ReviewPrepare.jar . > out.txt</code> runs the program in the current working directory and outputting to the file <code>out.txt</code> (I used this to create this question)</li>
<li><code>java -jar ReviewPrepare.jar C:/some/path/*.java > out.txt</code> runs the program in the specified directory, matching all *.java files and outputting to the file <code>out.txt</code></li>
</ul>
<h1>Questions</h1>
<p>My main concern currently is with the way I implemented the command line parameters, could it be done easier? (Preferably without using an external library as I would like my code to be independent if possible, although library suggestions for this is also welcome) Is there any common file-pattern-argument that I missed?</p>
<p>I'm also a bit concerned with the extensibility of this, right now it feels not extensible at all. What if someone would want to add custom features for the way Python/C#/C++/etc. files are formatted? Then hard-coding the "scan for imports" in the way I have done it doesn't feel quite optimal.</p>
<p>General reviews are also of course welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-26T17:06:45.663",
"Id": "427315",
"Score": "0",
"body": "Are there templates on StackExchange how to structure questions/answers?"
}
] |
[
{
"body": "<h2>General</h2>\n\n<p>Now that you have such neat postings, the answers are going to need to be neater too.</p>\n\n<h2>GUI Bugs</h2>\n\n<p>When I run the GUI, it does not let me select directories from the File Browser. It also starts in the 'Documents' directory, and it would be better to do one of two things:</p>\n\n<ul>\n<li>start in the current directory</li>\n<li>start in the last directory used (use java.util.pefs.Preferences ?)</li>\n</ul>\n\n<p>You should add:</p>\n\n<pre><code> JFileChooser dialog = new JFileChooser();\n dialog.setCurrentDirectory(\".\");\n dialog.setMultiSelectionEnabled(true);\n dialog.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);\n</code></pre>\n\n<p>Then you should also support expanding any directory results from the chooser. This will make the behaviour in the GUI match the commandline more closely.</p>\n\n<p>A second problem is in the JTextArea display. It should have scroll-bars so that you can inspect the results before copying/pasting them. While looking at those changes, I discovered that you were doing all your File IO on the event-dispatch thread... this is bad practice....</p>\n\n<p>I had to do the following:</p>\n\n<pre><code>// add a scrollPane....\nprivate final JScrollPane scrollPane = new JScrollPane(result);\n\n......\n\n// Inside the constructor:\n\n final Runnable viewupdater = new Runnable() {\n public void run() {\n result.setText(\"\");\n ReviewPreparer preparer = new ReviewPreparer(filesToList(model));\n TextAreaOutputStream outputStream = new TextAreaOutputStream(result);\n preparer.createFormattedQuestion(outputStream);\n outputStream.flush();\n result.setCaretPosition(0);\n }\n };\n\n JButton performButton = new JButton(\"Create Question stub with code included\");\n performButton.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent arg0) {\n Thread worker = new Thread(viewupdater);\n worker.setDaemon(true);\n worker.start();\n }\n });\n\n scrollPane.setAutoscrolls(true);\n scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);\n scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);\n contentPane.add(scrollPane, BorderLayout.CENTER);\n contentPane.add(performButton, BorderLayout.SOUTH);\n</code></pre>\n\n<p>As I was doing this change I noticed that you are not doing any best-practice closing of the TextAreaOutputStream instance, and, I looked in to the TextAreaOutputStream code, and, it's not the right solution. It is creating a new thread for every line from every file.... and it is horrible overkill. That whole class should be removed, and replaced with:</p>\n\n<pre><code> final Runnable viewupdater = new Runnable() {\n public void run() {\n ReviewPreparer preparer = new ReviewPreparer(filesToList(model));\n try (final StringWriter sw = new StringWriter()) {\n preparer.createFormattedQuestion(sw);\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n result.setText(sw.toString());\n result.setCaretPosition(0);\n }\n });\n }\n }\n };\n</code></pre>\n\n<p>Note how the above is changed to use a Writer instead of an OutputStream..... Using an OutputStream for text data is a broken model.... Readers and Writers for text, and Streams for binary.</p>\n\n<p>That's a good segway in to the non-gui code....</p>\n\n<h2>The Core engine</h2>\n\n<p>The TextareaOutputStream made me realize that <strong>all</strong> of your methods are stream based, except for some parts that are buried in the ReviewPreparer.</p>\n\n<p>The PrintStream code should all be replaced with a StringBuilder..... you are limited to the size of a CR post anyway, and you are accumulating the data in to a TextArea... it's not like you will run out of memory.</p>\n\n<p>This is also an interesting segway to the CountingOutputStream. There is no need for that either.... you are not using it to count the file sizes, but the actual post length. This should be measured in characters, not bytes.... so, it's a broken class. Get rid of it.</p>\n\n<p>So, get rid of the PrintStream as well. PrintStream is a synchronized class, and is much, much slower than StringBuilder. Appending the data to StringBuilder also means you can get the character-length from the StringBuilder instead of the byte-length from the CountingOutputStream.</p>\n\n<p>One final observation....... inside the <code>outputFileContents(PrintStream ps)</code> method you do:</p>\n\n<pre><code> try (BufferedReader in = new BufferedReader(new InputStreamReader(\n new FileInputStream(file)))) {\n int lines = -1;\n try {\n lines = countLines(file);\n } catch (IOException e) {\n }\n ps.printf(\"**%s:** (%d lines, %d bytes)\", file.getName(),\n lines, file.length());\n\n ps.println();\n ps.println();\n String line;\n int importStatementsFinished = 0;\n while ((line = in.readLine()) != null) {\n</code></pre>\n\n<p>This is broken for a few reasons....</p>\n\n<p>Firstly, you should not be using a FileInputStream, but a FileReader.</p>\n\n<p>Secondly, you have the support method <code>countLines(File)</code>:</p>\n\n<pre><code>private int countLines(File file) throws IOException {\n return Files.readAllLines(file.toPath(), StandardCharsets.UTF_8).size();\n}\n</code></pre>\n\n<p>This method fully-reads the file.... <strong>again</strong> .... Why don't you replace all the big code above with:</p>\n\n<pre><code> try {\n List<String> filelines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);\n sb.append(String.format(\"**%s:** (%d lines, %d bytes)\", file.getName(),\n filelines.size(), file.length()));\n\n sb.append(\"\\n\\n\");\n int importStatementsFinished = 0;\n for (String line : filelines) {\n // skip package and import declarations\n</code></pre>\n\n<p>This saves having to read each file twice.....</p>\n\n<p>Anway, that's enough for now.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T19:10:07.730",
"Id": "41246",
"ParentId": "41225",
"Score": "17"
}
}
] |
{
"AcceptedAnswerId": "41246",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T13:01:54.403",
"Id": "41225",
"Score": "25",
"Tags": [
"java",
"swing",
"file-system",
"formatting",
"stackexchange"
],
"Title": "Follow-up to tool for posting CodeReview questions"
}
|
41225
|
<p><a href="http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm" rel="nofollow">KMP algorithm</a> is for searching and matching string with a given pattern. The most important part is to build a table for the pattern then move a proper step rather than just one step increment. </p>
<p>In my code I created the table correctly but something is wrong for moving steps.
It stuck in the for loop as variable was always equal to 2.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KMP
{
class Program
{
const string pattern = "abcdabd";
const string s = "aadabcdabedxdfabcdabddsa";
static int[] x = new int[7];
static void Main(string[] args)
{
x = BuildTable(pattern);
var y = Match(x, s);
Console.WriteLine(y);
Console.Read();
}
private static int Match(int[] x, string s)
{
int n = s.Length;
int l = x.Length;
int find = 0;
Char[] charPattern = pattern.ToCharArray();
for (int i = 0; i < n; )
{
string a = s.Substring(i, l);
if (a.CompareTo(pattern).Equals(0))
{
return i; // Found match, return match position of the first letter
}
// move position by BuildTable
Char[] charSubstring = a.ToCharArray();
int count = 0;
for (int j = 0; j < l; j++)
{
if (charPattern[j] == charSubstring[j])
{
count++;// count of matched chars
continue;
}
else
{
i += count - x[j]; // move forward steps = matched count - table value
break;
}
}
}
return -999; // not found
}
public static int[] BuildTable(string p)
{
int[] result = new int[p.Length];
result[0] = 0;
for (int i = 1; i < p.Length - 1; i++)
{
// The substring from p[1] to p[i]
string s = p.Substring(0, i + 1);
var prefixes = Enumerable.Range(1, s.Length - 1)
.Select(a => s.Substring(0, a)).ToList();
var suffixes = Enumerable.Range(1, s.Length - 1)
.Select(a => s.Substring(a, s.Length - a)).ToList();
var common = prefixes.Intersect(suffixes).FirstOrDefault();
result[i] = (common == null) ? 0 : common.Length;
}
return result;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T17:03:24.527",
"Id": "70747",
"Score": "0",
"body": "If `if (charPattern[j] == charSubstring[j])` is true, you never advance the `i`..... and loop infinitely. Closing off-topic."
}
] |
[
{
"body": "<p>It is very hard to read your code, since you use single letter variables (<code>x</code>, <code>s</code>, <code>l</code>... etc.).</p>\n\n<p>Some more general concerns: <code>x</code> is a class member, initialized in its declaration, overriden in the <code>Main</code> method (without the initial value ever being used), and then passed as an argument to the <code>Match</code> method.</p>\n\n<p>As for why the value is stuck on 2, my guess is that the line <code>i += count - x[j];</code> leaves the <code>i</code> value the same - <code>count - x[j] == 0</code> perhaps you meant to write <code>count + x[j]</code>?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T16:09:48.317",
"Id": "70737",
"Score": "0",
"body": "What is the correct writing of a variable in C#? CamelCase?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T16:11:37.703",
"Id": "70738",
"Score": "0",
"body": "Yes, see http://stackoverflow.com/a/1618325/1120015"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T15:54:42.960",
"Id": "41232",
"ParentId": "41229",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T15:09:32.230",
"Id": "41229",
"Score": "0",
"Tags": [
"c#",
"algorithm"
],
"Title": "Moving steps in KMP algorithm"
}
|
41229
|
<p>One of my classes regularly triggers one of two asynchronous operations: a "turn on" and a "turn off" that each take about a second. I'm using this method below to make sure that they don't run simultaneously. It doesn't seem very elegant to me. Is there some better way to do this? I'm using .NET 4.0, but I would like to know if there are any .NET 4.5 methods that make this easier.</p>
<pre><code>private Task _changingControl;
private void RunControlTask(Task newTask)
{
var cc = _changingControl;
if (cc == null || cc.IsCompleted)
{
_changingControl = newTask;
newTask.Start();
}
else
{
_changingControl = cc.ContinueWith(old =>
{
newTask.RunSynchronously();
newTask.Dispose(); // only needed if we manually wait for it to finish
});
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T16:31:51.073",
"Id": "70741",
"Score": "0",
"body": "If you submit new tasks faster than they can be executed, is it necessary that they execute in the order they were submitted in?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T16:46:56.183",
"Id": "70745",
"Score": "0",
"body": "Yes, the ordering is important."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T16:51:49.760",
"Id": "70746",
"Score": "0",
"body": "At some point I would like to change it such that if I'm currently \"turning off\", and I have both an on and an off task waiting, I skip the following two because my current action will take me to the appropriate state."
}
] |
[
{
"body": "<p>First, some notes about your code:</p>\n\n<ul>\n<li>Using <code>Task</code>s that are first created and later started usually doesn't make much sense. To represent some work to be done, just use a delegate.</li>\n<li><a href=\"http://blogs.msdn.com/b/pfxteam/archive/2012/03/25/10287435.aspx\" rel=\"nofollow\"><code>Task</code>s almost never need to be <code>Dispose</code>d.</a></li>\n</ul>\n\n<p>Now, I think that what you want to do would be easiest to achieve using <code>ActionBlock</code> from TPL Dataflow. When you want to perform the operation, you would send a message to the block and the action in the block would execute it. <code>ActionBlock</code> already performs all synchronization necessary to make sure only one operation executes at a time.</p>\n\n<pre><code>ActionBlock<bool> _changeControlBlock = new ActionBlock<bool>(ChangeControl);\n\nprivate void ChangeControl(bool on)\n{\n if (on)\n {\n // turn on\n }\n else\n {\n // turn off\n }\n}\n\npublic void TurnOn()\n{\n _changeControlBlock.Post(true);\n}\n\npublic void TurnOn()\n{\n _changeControlBlock.Post(false);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T18:59:17.670",
"Id": "72353",
"Score": "0",
"body": "I think this sufficiently answers the question of alternative methods. I make a different post for the question of skipping tasks in the middle."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T16:31:00.587",
"Id": "41233",
"ParentId": "41230",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "41233",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T15:25:04.503",
"Id": "41230",
"Score": "3",
"Tags": [
"c#",
".net",
"task-parallel-library"
],
"Title": "Run control tasks asynchronously using TPL"
}
|
41230
|
<p>This script scrapes recent articles on bitcoin, does sentiment analysis, and does some mock trading based on the sentiment of the articles. I'm looking for advice on code style, and I would love to learn how to write beautiful Ruby.</p>
<pre><code>require 'coinbase'
require 'sanitize'
require 'cgi'
require 'htmlentities'
require 'sentimental'
require 'simple-rss'
require 'open-uri'
require 'sqlite3'
require 'date'
@db = SQLite3::Database.open('instructions.db')
@db.execute("CREATE TABLE IF NOT EXISTS instructions2(Id INTEGER PRIMARY KEY AUTOINCREMENT, Date TEXT, Do_now TEXT, Do_later TEXT, Buy_price TEXT, Sell_price TEXT)")
@rss = SimpleRSS.parse(open('http://fulltextrssfeed.com/news.google.com/news?pz=1&cf=all&ned=us&hl=en&q=Bitcoin&output=rss'))
@coinbase = Coinbase::Client.new(ENV['COINBASEKEY'])
@coder = HTMLEntities.new
Sentimental.load_defaults
@analyzer = Sentimental.new
@ran_today = false
@scores_today = []
@log = File.open('log.txt', 'w')
def write_log(me)
@log << DateTime.now.to_s + " : " + me.to_s
end
def check_sentiment
@ran_today = true
@rss.items.each do |item|
@scores_today.push(@analyzer.get_score(clean(item.description)))
end
react_sentiment
end
def react_sentiment
avg = @scores_today.reduce(:+).to_f / @scores_today.size
do_now = :nothing
do_later = :nothing
#if negative, sell now, buy when low
if avg > 3.0
do_now = :buy
do_later = :sell
elsif avg < -2.0
do_now = :sell
do_later = :buy
end
write_log("day's sentiment score : " + avg.to_s)
method(do_now).call
write_log(@db.execute("INSERT INTO instructions2(Date, Do_now, Do_later, Buy_price, Sell_price) VALUES (?, ?, ?, ?, ?)", (Date.today+2).to_s, do_now.to_s, do_later.to_s, check_buy.to_s, check_sell.to_s))
end
def read_instructions
@db.execute("SELECT Id, Date, Do_now, Do_later, Buy_price, Sell_price FROM instructions2;").each do |id, date, do_now, do_later, buy_price, sell_price|
if Date.today.to_s == date
if do_now == "buy"
if check_buy < sell_price.to_f
buy
else
puts "want to buy, buy " + buy_price + " > sell " + sell_price
end
elsif do_now == "sell"
if check_sell > buy_price.to_f
sell
else
puts "want to sell, sell " + sell_price + " > buy " + buy_price
end
end
@db.execute("DELETE * FROM instructions2 WHERE Date=?", Date.today.to_s)
end
end
end
def buy
write_log("would buy at " + check_buy.to_s + " at " + Date.today.to_s)
end
def sell
write_log("would sell at " + check_sell.to_s + " at " + Date.today.to_s)
end
def nothing
write_log("would do nothing at " + Date.today.to_s)
end
def check_sell
@coinbase.sell_price(1)
end
def check_buy
@coinbase.buy_price(1)
end
def clean(stuff)
Sanitize.clean(CGI.unescapeHTML(stuff).to_s.force_encoding('UTF-8'))
end
check_sentiment
read_instructions
@ran_today = true
while true
if Time.now.hour == 23 and not @ran_today
check_sentiment
elsif Time.now.hour == 1
read_instructions
elsif Time.now.hour == 24
@ran_today = false
@scores_today = []
end
sleep(60000)
end
</code></pre>
|
[] |
[
{
"body": "<p>The <code>@</code> variable prefix should only be used inside a class to denote instance variables. That said, for a script like this, you might like to wrap all the logic in a class (or rather a module since you don't need multiple instances).</p>\n\n<p>Use string interpolation. So instead of</p>\n\n<pre><code>DateTime.now.to_s + \" : \" + me.to_s\n</code></pre>\n\n<p>you can write</p>\n\n<pre><code>\"#{DateTime.now} : #{me}\"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T19:48:51.410",
"Id": "41247",
"ParentId": "41234",
"Score": "5"
}
},
{
"body": "<p>A few observations:</p>\n\n<ol>\n<li>It seems that you fill <code>@rss</code> only when the program starts, and never again, which means that each time you run <code>check_sentiment</code> you read the same (stale) data.</li>\n<li>When you <code>react_sentiment</code> you call <code>method(do_now).call</code>, and when you <code>read_instructions</code> you also call <code>do_now</code>. You never use <code>do_later</code> though...</li>\n<li>In your main loop you <code>sleep(60000)</code>, between iterations, which means you sleep 60,000 seconds - about 17 hours. This means you will miss some of the check points you intended to run. Generally speaking, maybe running this indefinitely for a couple of check points a day is not recommended, and better way would be to use <a href=\"http://www.unixgeeks.org/security/newbie/unix/cron-1.html\" rel=\"nofollow\"><code>cron</code> jobs</a> to run at 0100 and at 2300.</li>\n<li><p>Encapsulation - you seem to have a lot of instance members in your code, some of which need to be maintained manually (like <code>@scores_today</code>), some maintenance is neglected (like <code>@rss</code>), and some are forgotten (like <code>@coder</code>, which is never used). To prevent this, you need to think which members are actually part of your <em>state</em>, and which are not. If there is no good reason to keep them - don't:</p>\n\n<pre><code>def check_sentiment\n @ran_today = true\n rss = SimpleRSS.parse(open('http://fulltextrssfeed.com/news.google.com/news?pz=1&cf=all&ned=us&hl=en&q=Bitcoin&output=rss'))\n analyzer = Sentimental.new\n scores_today = rss.items.map do |item|\n analyzer.get_score(clean(item.description)))\n end\n react_sentiment(scores_today)\nend\n\ndef react_sentiment\n avg = scores_today.reduce(:+).to_f / scores_today.size\n\n # ... etc\nend\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T08:33:31.420",
"Id": "41629",
"ParentId": "41234",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T16:32:59.923",
"Id": "41234",
"Score": "5",
"Tags": [
"ruby",
"datetime",
"web-scraping"
],
"Title": "Scraping and analyzing recent articles on bitcoin"
}
|
41234
|
<p>For the past four years I've attended a private school which requires its students to wear ties. I've found that it's far easier to figure out what combination of shirt, pants, and tie that go together the night before, as it can sometimes be a tedious process. To make this process simpler, I had the idea to create a script to automatically generate new combinations of matching clothes.</p>
<p>As of now, I input all of my clothes into a <code>JSON</code> file, separated into arrays representing categories (shirts, pants, ties). The first element of each array is a another array, filled with all available colors/patterns in that category (red, blue, etc). For each color, there is an array ID'd by its color, consisting of an object describing what color/pattern pants/ties/sweaters go with that shirt color. Finally there is an array with the names of each type of clothing item that falls under that color. In case you didn't follow any of that, here's a section of my <code>JSON</code> file (<a href="http://pastebin.com/raw.php?i=LC5zDLas">full here</a>):</p>
<pre><code>"shirts": [{
"colors": [
"red"
],
"red": [{
"pants": [
"navy",
"khaki"
],
"sweaters": [
"navy",
"grey"
],
"ties": [
"all"
]
},
[
"Red Flannel",
"That Other Red Flannel"
]
]
}],
...
</code></pre>
<p>It's a pretty tedious structure (IMO), but I can't think of a better implementation since there are multiple criteria that the matching clothes need to match. My method of creating a random combination is equally tedious:</p>
<pre><code>$.getJSON("clothes.json", function (clothes) {
window.clothes = clothes;
var colors = clothes["shirts"][0]["colors"];
$(colors).each(function (i) {
$("#color").append("<option>" + colors[i] + "</option>");
});
});
function randomArrayValue(array) {
var array = eval(array);
return array[Math.floor(Math.random() * array.length)];
}
function randomClothes(times, color, sweater, tie) {
$("#output").html("");
// Objects for everything
var shirts = clothes["shirts"][0];
pants = clothes["pants"][0];
sweaters = clothes["sweaters"][0];
ties = clothes["ties"][0];
shoes = clothes["shoes"][0];
for (var x = 0; x < times; x++) {
if (color) {
startShirt = shirts[color];
} else {
startShirt = shirts[randomArrayValue(shirts["colors"])]
}
shirt_optionsPants = startShirt[0]["pants"];
shirt_optionsSweaters = startShirt[0]["sweaters"];
shirt_optionsTies = startShirt[0]["ties"];
// Array to hold random combinations
combination = new Array();
for (var i = 0; i < shirt_optionsPants.length; i++) {
var currentPantColor = shirt_optionsPants[i];
var pant_optionsSweaters = pants[currentPantColor][0]["sweaters"];
if (tie) {
var pant_optionsTies = pants[currentPantColor][0]["ties"];
} else {
var pant_optionsTies = new Array("all");
}
// Availible ties between pants and shirt, tie color has to be both present in shirt and pant or it wont be added
var availableShirtPantTies = new Array();
$(shirt_optionsTies).each(function (i) {
var currentShirtTie = shirt_optionsTies[i];
if (pant_optionsTies[0] === "all") {
availableShirtPantTies.push(currentShirtTie);
} else {
$(pant_optionsTies).each(function (i) {
if (pant_optionsTies[i] === currentShirtTie) {
availableShirtPantTies.push(currentShirtTie);
} else if (currentShirtTie === "all") {
availableShirtPantTies.push(pant_optionsTies[i]);
}
});
}
});
for (var k = 0; k < pant_optionsSweaters.length; k++) {
var currentSweaterColor = pant_optionsSweaters[k];
var sweater_optionsTies = sweaters[currentSweaterColor][0]["ties"];
// Check if there are any ties that matches both the pants and shirt
if (availableShirtPantTies.length > 0) {
if (sweater) {
var availableShirtPantSweaterTies = new Array();
$(sweater_optionsTies).each(function (i) {
var currentSweaterTie = sweater_optionsTies[i];
if ($.inArray(currentSweaterTie, availableShirtPantTies) >= 0) {
availableShirtPantSweaterTies.push(currentSweaterTie)
} else if (currentSweaterTie === "all") {
$(availableShirtPantTies).each(function (i) {
availableShirtPantSweaterTies.push(availableShirtPantTies[i]);
});
} else {
if (sweater_optionsTies[i] === sweater_optionsTies[i]) {
availableShirtPantSweaterTies.push(sweater_optionsTies[i]);
}
}
});
} else {
availableShirtPantSweaterTies = availableShirtPantTies;
}
$(availableShirtPantSweaterTies).each(function (i) {
// Assign any tie to a color
if (tie) {
if (availableShirtPantSweaterTies[i] === "all") {
currentTieColor = randomArrayValue(ties["colors"]);
} else {
currentTieColor = availableShirtPantSweaterTies[i];
}
} else {
currentTieColor = ties["colors"][0];
}
//Result object
var result = new Object();
result.shoes = randomArrayValue(pants[currentPantColor][0]["shoes"]);
result.pants = currentPantColor;
result.sweater = currentSweaterColor;
result.tie = currentTieColor;
combination.push(result);
});
}
}
}
var randomCombination = randomArrayValue(combination);
pantsColor = randomCombination["pants"];
sweaterColor = randomCombination["sweater"];
tieColor = randomCombination["tie"];
shoesColor = randomCombination["shoes"];
var randomShirt = randomArrayValue(startShirt[1]);
randomPants = randomArrayValue(pants[pantsColor][1]);
randomSweater = randomArrayValue(sweaters[sweaterColor][1]);
randomTie = randomArrayValue(ties[tieColor][0]);
randomShoes = randomArrayValue(shoes[shoesColor][0]);
//Debugging
//console.log(randomShirt, randomPants, randomSweater, randomTie, randomShoes);
if (sweater) {
var sweaterContent = "Sweater: " + randomSweater + "<br />";
} else {
var sweaterContent = "";
}
if (tie) {
var tieContent = "Tie: " + randomTie + "<br />";
} else {
var tieContent = "";
}
var content = "Shirt: " + randomShirt + "<br />Pants: " + randomPants + "<br />" + sweaterContent + tieContent + "Shoes: " + randomShoes + "<br /><br />";
$("#output").append(content);
}
}
$("#random").click(function () {
randomClothes(1, "", true, true);
});
</code></pre>
<p>This isn't like anything I've really coded before, and I'm not the best when it comes to visualizing randomness. My original method of coding this did not take into account that certain shirts could go with certain ties, but those shirts might go with sweaters that the ties or pants do not. Consequently, the code is rather large. I have to believe, however, that there is a much better solution to what I'm trying to achieve. <strong>Also</strong>, I would like to add in implementations for regular T-Shirts or anything for that matter, but as it stands now, the structure is much too strict to allow for much modification.</p>
<p>Oh yes, if it wasn't clear, the code hinges off of the shirt. So it picks a random shirt, then sees what matches it. If the code wasn't as strict, it would be nice to be able to start with any article of clothing, such as pants.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T23:09:01.237",
"Id": "70795",
"Score": "0",
"body": "Could you post a jsfiddle demo to test?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T00:34:23.297",
"Id": "70801",
"Score": "0",
"body": "@elclanrs [Sure thing](http://jsfiddle.net/charlescarver/Ecr62/)!"
}
] |
[
{
"body": "<p>Nice idea. I really like what you've done, but some of your implementation can definitely be improved. Let's start with the JSON.</p>\n\n<ul>\n<li><p>Some of those arrays are not needed. You wrap each <code>clothes</code> item in <code>[]</code>, there's no need for this as there's just one item in the array! In fact you should only be using arrays to group <code>like</code> items. I'm also going to get rid of your colour array since it seems redundant (more on this later). Consider this redesign;</p>\n\n<pre><code>\"shirts\": {\n \"red\": {\n \"items\": [ \n \"Red Flannel\",\n \"That Other Red Flannel\"\n ],\n \"matches\": {\n \"pants\": [\n \"navy\",\n \"khaki\"\n ],\n \"sweaters\": [\n \"navy\",\n \"grey\"\n ],\n \"ties\": [\n \"all\"\n ]\n }\n }\n}\n</code></pre>\n\n<p>Do you see how that instantly makes it easier for us to look items up and iterate over matches?</p>\n\n<p>Now you can remove all the <code>[0]</code> accessors:</p>\n\n<p>Now you can select colours with: <code>shirts[color]</code>, and iterate over matches with;</p>\n\n<pre><code> for (var match in shirts[color].matches) { \n\n }\n</code></pre>\n\n<p>Which brings me to my next point.</p></li>\n<li><p>You seem to be using bracket notation a lot to access the items in your object. When the accessor isn't a variable then you can use dot notation.</p>\n\n<pre><code>shirts[color]['matches'] === shirts[color].matches\n</code></pre>\n\n<p>The distinction helps us to distinguish how we're accessing the property at a glance.</p></li>\n<li><p>The function <code>randomArrayValue</code> is using an unnecessary <code>eval</code>. Eval is not needed most of the time, and is often misused by new JavaScript devs. You could just do;</p>\n\n<pre><code>function randomArrayValue(arr) {\n return arr[Math.floor(Math.random() * arr.length)];\n}\n</code></pre>\n\n<p>As an aside you can also use <code>~~</code> instead of <code>Math.floor</code>, and it's slightly faster.</p></li>\n<li><p>You're missing a <strong>lot</strong> of <code>var</code> statements. This is generally bad as variables declared without <code>var</code> are set as globals, accessible from anywhere. There's nothing as annoying as global variable bugs. You can get notiofied of issues like this by including the string <code>'use strict';</code> at the top of the program. This tells the browser to be stricter with compilation.</p></li>\n<li><p>Consider literals instead of new Objects. For example:</p>\n\n<pre><code>combination = new Array(); // okay\ncombination = []; // better\n\nresult = new Object(); // not great\nresult = {}; // awesome\n</code></pre></li>\n<li><p>For your result object, you'll be much better off creating an Object literal;</p>\n\n<pre><code>var result = {\n shoes: randomArrayValue(pants[currentPantColor].shoes),\n pants: currentPantColor,\n sweater: currentSweaterColor,\n tie: currentTieColor\n};\ncombination.push(result);\n</code></pre></li>\n<li><p>Back to that colour object... You can get the keys of an Object using <code>Object.keys(obj)</code>. So if you want to know all the colours that your shirts come in you can call <code>Object.keys(clothes.shirts)</code>. If you want to iterate over all the colours then you can <code>for...in</code>:</p>\n\n<pre><code>for (var colour in clothes.shirts) {\n var items = clothes.shirts[colour].items,\n matches = clothes.shirts[colour].matches;\n}\n</code></pre></li>\n</ul>\n\n<p>That's enough to start with, let me know if you'd like me to point out how you can take advantage of some of these designs within your solution.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T15:15:52.167",
"Id": "70843",
"Score": "1",
"body": "I'm going to read this in depth, but 2 quick things: 1.) I wrote this code a few months ago and after rediscovering it yesterday, I saw I used `eval` and I had absolutely no idea why. I think it was left over from an earlier version 2.) I also only recently started using dot notation"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T16:23:57.197",
"Id": "70854",
"Score": "1",
"body": "My main concern with my code is about the addition of other clothing items. Do you see any solution where it's easier to add in more functionality? I see it as different functions, each being able to sort from the list, and then all I have to do is pipe in the data and it gives me corresponding items."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T20:29:48.617",
"Id": "70870",
"Score": "0",
"body": "I ended up [making the changes](http://jsfiddle.net/charlescarver/Ecr62/3/), and it looks a bit cleaner. The logic, however, still seems redundant in places."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-11T05:10:35.670",
"Id": "101011",
"Score": "0",
"body": "@Jivings Any word on improving the logic?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T13:56:07.027",
"Id": "41285",
"ParentId": "41238",
"Score": "22"
}
},
{
"body": "<p>To accomplish what you're asking for you need to switch your approach to a functional approach and significantly rewrite your code. What you're looking for is best solved by the concept of folding. </p>\n\n<p>Check it!</p>\n\n<p>You call a function that finds a match for the shirt you picked. You say \"hey, here's a shirt, find me some matching pants!\" It then returns not just some matching pants but an object containing both the shirt and pants it just found for you, and here's why--you then turn around and pass that object into the same function, saying \"yo, here's what I've picked out so far, now find me a matching sweater!\" Your function adds a random match to what you have so far and returns your whole outfit so far, which is then passed in to the next function.</p>\n\n<p>Check out the array reduce method. \n<a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce</a></p>\n\n<p>If you use this you could create an array that holds a list of items you want to retrieve, and then call reduce on it, e.g. <code>[\"shirt\", \"tie\", \"sweater\"].reduce(findMatches);</code> where findMatches is your callback function.</p>\n\n<p>This also has the added bonus of keeping all of your logic in one place. And, as long as your data is updated correctly, adding new articles of clothing is as simple as adding a string to the array!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-24T20:26:22.857",
"Id": "74802",
"ParentId": "41238",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T17:17:17.660",
"Id": "41238",
"Score": "36",
"Tags": [
"javascript",
"jquery",
"json",
"random"
],
"Title": "Random clothes generator"
}
|
41238
|
<p>Using Rails 3.2, I have the following:</p>
<pre><code>g = Geocoder.search(address)
# if no address found, geocode with latitude and longitude
if g.empty?
g = Geocoder.search(latitude, longitude)
if g.empty?
log.info "Geocode failed for #{latitude}, #{longitude}"
end
else
---save---
end
</code></pre>
<p>If the first geocoding with address fails, it will try latitude and longitude. If still fails, then it logs error, else it will save.</p>
<p>Is this a good way to write this code?</p>
|
[] |
[
{
"body": "<p>Nesting your <code>if</code>s is unnecessary, and flatting them will look better:</p>\n\n<pre><code>g = Geocoder.search(address)\n\n# if no address found, geocode with latitude and longitude\nif g.empty?\n g = Geocoder.search(latitude, longitude)\nend\n\nif g.empty?\n log.info \"Geocode failed for #{latitude}, #{longitude}\"\n end\nelse\n ---save---\nend\n</code></pre>\n\n<p>You can even go one-liners to make the code look more succinct:</p>\n\n<pre><code>g = Geocoder.search(address)\n\n# if no address found, geocode with latitude and longitude\ng = Geocoder.search(latitude, longitude) if g.empty?\n\nlog.info \"Geocode failed for #{latitude}, #{longitude}\" && return if g.empty?\n\n---save---\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T18:33:36.307",
"Id": "70756",
"Score": "0",
"body": "Ha! Your first answer was what I had before refactoring!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T19:10:20.093",
"Id": "70759",
"Score": "0",
"body": "Nested ifs are considered [a smell](http://c2.com/cgi/wiki?ArrowAntiPattern), just imagine how your code look if had two more fallbacks - each fallback will nest another if, and it would be hard to read the flow of the code - does it save? does it log?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T18:26:13.440",
"Id": "41245",
"ParentId": "41241",
"Score": "4"
}
},
{
"body": "<p>Some notes:</p>\n\n<ul>\n<li><code>g</code>: use meaningful names.</li>\n<li>Don't mix code with parentheses and without.</li>\n<li>Check the pattern <a href=\"http://api.rubyonrails.org/classes/Object.html#method-i-presence\" rel=\"nofollow\">Object#presence</a>.</li>\n<li><code># if no address found, ...</code>: declarative code makes this kind of comments unnecessary.</li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>results = Geocoder.search(address).presence || Geocoder.search(latitude, longitude)\nif results.present?\n # save\nelse\n log.info(\"Geocode failed for addr='#{search}' and coords=#{latitude}/#{longitude}\")\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T20:22:53.553",
"Id": "41251",
"ParentId": "41241",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "41251",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T17:55:01.163",
"Id": "41241",
"Score": "6",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Nested trial and error in if-else condition"
}
|
41241
|
<p>This is in preparation for a competition that only allows C++03.</p>
<pre><code>// Neighbor index plus weight of edge connecting this vertex with neighbor
struct NeighborWeight
{
Index neighbor;
Distance weight;
};
// Represents adjacency information for a single vertex (contains all
// neighbors and weights of edges connecting them)
typedef std::list<NeighborWeight> AdjVertex;
// Represents adjacency information for all vertices (thus representing
// a complete directed/undirected graph)
typedef std::vector<AdjVertex> AdjList;
// Dijkstra's algorithm: computes SHORTEST PATH to all vertices from a starting
// vertex for a DIRECTED/UNDIRECTED graph with NONNEGATIVE edge weights.
// result.dist[v] = shortest distance from source to v.
// result.prev[v] = predecessor of v in shortest path from source to v.
// If v is not connected to start_vertex, dist[v] = max value of Distance, and
// prev[v] = -1.
// If v = start_vertex, prev[v] = -1.
// Prim's algorithm (call with do_prim = true): computes MINIMUM SPANNING TREE
// starting from a seed vertex for an UNDIRECTED graph with ANY edge weights.
// result.dist[v] should be ignored.
// result.prev[v] = parent of v in minimal spanning tree.
// If v is not connected to start_vertex, prev[v] = -1.
// If v = start_vertex, prev[v] = -1;
struct DijkstraResult
{
std::vector<Distance> dist;
std::vector<Index> prev;
};
DijkstraResult dijkstra(AdjList al, Index start_vertex, bool do_prim = false)
{
typedef std::pair<Distance, Index> DistAndIndex;
const Distance infinity = std::numeric_limits<Distance>::max();
const Index undefined_index = -1;
const Index num_vertices = al.size();
std::vector<Distance> dist(num_vertices, infinity); // tentative distances
std::vector<Index> prev(num_vertices, undefined_index); // predecessors
std::vector<uint8_t> is_visited(num_vertices, false);
std::set<DistAndIndex> unvisited_queue;
dist[start_vertex] = 0;
// Populate unvisited_queue in order with (Distance, Index) pairs
unvisited_queue.insert(std::make_pair(0, start_vertex));
for (Index v = 0; v < num_vertices; ++v)
if (v != start_vertex)
unvisited_queue.insert(unvisited_queue.end(),
std::make_pair(infinity, v));
while (!unvisited_queue.empty())
{
// u = index of unvisited vertex with least distance
Index u = unvisited_queue.begin()->second;
// If this least distance is infinity, break (no more connected verts)
if (unvisited_queue.begin()->first == infinity) break;
// Visit this vertex
unvisited_queue.erase(unvisited_queue.begin());
is_visited[u] = true;
// In Prim's, distances are computed from the MST. Adding a vertex
// to the MST makes the distance 0.
if (do_prim) dist[u] = 0;
// vert = vertex corresponding to u
AdjVertex &vert = al[u];
// Iterate through neighbors of u
for (AdjVertex::iterator it = vert.begin(); it != vert.end(); ++it)
{
// v = it->neighbor is the index of the neighbor; it->weight is the
// edge weight between u and v
Index v = it->neighbor;
// Skip if v is visited
if (is_visited[v]) continue;
// Now compute new dist for v
Distance alt = dist[u] + it->weight;
// And compare with previous
if (alt < dist[v])
{
unvisited_queue.erase(std::make_pair(dist[v], v));
unvisited_queue.insert(std::make_pair(alt, v));
dist[v] = alt;
prev[v] = u;
}
}
}
DijkstraResult res = { dist, prev };
return res;
}
</code></pre>
<p>There's another set of <code>typedef</code>s and functions that duplicates a list of undirected edges into an <code>AdjList</code> structure.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T18:19:46.367",
"Id": "70867",
"Score": "0",
"body": "*competition that only allows C++03* you should have entered this before 2011. By now the language standard has moved on."
}
] |
[
{
"body": "<p>I'll address some minor things (unrelated to efficiency, at least):</p>\n\n<ul>\n<li><p>The comments describing the <em>algorithm</em> could be at the very top so that the code in between isn't missed. Any comments describing the <em>functions</em> or the <code>typedef</code>s can stay above them.</p></li>\n<li><p>These <code>struct</code>s are in global scope, so they should be contained by something (such as a function) to put them into local scope, preventing unknown modifications.</p>\n\n<p>For instance, <code>DijkstraResult</code> could probably be defined in the calling code, which I assume is <code>main()</code> (not shown here). Wherever the result of <code>dijkstra()</code> is received, that <code>struct</code> should be contained there. This will also help with keeping code lower in scope, which eases maintenance and prevents bugs associated with this.</p></li>\n<li><p>If you still want a <code>typedef</code> for the <code>std::pair</code>, at least consider a less-obvious (and possibly more accurate) name. The name <code>DistAndIndex</code> can still be read from the <code>std::pair</code>, so it doesn't help much. It also doesn't save very many keystrokes, if that's even a concern.</p></li>\n<li><p>The name <code>infinity</code> doesn't make sense here as you're not assigning it to anything considered infinite (it's also not a number, but a concept). It is assigned to a <em>max</em> value, which is <em>finite</em>, also according to the <a href=\"http://en.cppreference.com/w/cpp/types/numeric_limits/max\" rel=\"nofollow\">documentation</a>.</p>\n\n<p>Bearing that in mind, a more appropriate name may be something like <code>maxDistance</code>.</p></li>\n<li><p>Curly braces should be used here:</p>\n\n<pre><code>for (Index v = 0; v < num_vertices; ++v)\n if (v != start_vertex)\n unvisited_queue.insert(unvisited_queue.end(),\n std::make_pair(infinity, v));\n</code></pre>\n\n<p>From a readability standpoint, it's not entirely clear what is contained in what. It can also hurt maintainability as adding or removing code from here can break something.</p>\n\n<p>Regarding the code within the <code>if</code> block, the second line should be indented so that it is not read as a separate statement.</p>\n\n<pre><code>for (Index v = 0; v < num_vertices; ++v)\n{\n if (v != start_vertex)\n {\n unvisited_queue.insert(unvisited_queue.end(),\n std::make_pair(infinity, v));\n }\n}\n</code></pre></li>\n<li><p><code>uint8_t</code> should be <code>std::uint8_t</code> in C++.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T01:53:59.637",
"Id": "48535",
"ParentId": "41254",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T21:12:56.297",
"Id": "41254",
"Score": "5",
"Tags": [
"c++",
"graph",
"contest-problem",
"c++03"
],
"Title": "Dijkstra's and Prim's algorithms: correctness/efficiency"
}
|
41254
|
<p>iMacros is a program that is used for writing scripts for Internet macros, which automatically perform tasks. </p>
<p>Javascript is mainly affiliated with this in writing scripts with iMacros.</p>
<p>For a full guide <a href="http://wiki.imacros.net/Main_Page" rel="nofollow">go here</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T22:36:56.570",
"Id": "41257",
"Score": "0",
"Tags": null,
"Title": null
}
|
41257
|
iMacros is a Firefox Add-On that is used for making web macros.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-08T22:36:56.570",
"Id": "41258",
"Score": "0",
"Tags": null,
"Title": null
}
|
41258
|
<p>Given a set of 2 dimensional points, it returns the two nearest points. If more pairs have the same min-distance between them, then an arbitrary choice is made. This program expects the points to be sorted on the x-axis. If not, input is unpredictable.</p>
<p>I'm looking for code review, optimizations and best practices.</p>
<pre><code>final class PointPair {
private final Point point1;
private final Point point2;
private final double distance;
PointPair (Point point1, Point point2, double distance) {
this.point1 = point1;
this.point2 = point2;
this.distance = distance;
}
public Point getPoint1() {
return point1;
}
public Point getPoint2() {
return point2;
}
public double getDistance() {
return distance;
}
}
final class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
public final class ClosestPair {
private static final int BRUTEFORCE_INDEX = 3;
private ClosestPair() {}
/**
* Given a set of 2 dimensional points it returns the the two nearest points.
* If more pairs have the same min-distance between then then arbitrary choice is made.
* This program expects the points to be sorted on x-axis. If not input is unpredictable.
*
*
* @param points the array of points sorted by x-axis
* @return the pair of points which are nearest to each other.
*/
public static PointPair minPointPair (Point[] points) {
return calcPointPair(points, 0, points.length);
}
private static PointPair calcPointPair(Point[] points, int low, int high) {
assert points != null;
if ((high - low) <= BRUTEFORCE_INDEX) {
return bruteForce(points, low, high);
}
int mid = (low + high) / 2;
final PointPair leftPair = calcPointPair(points, low, mid);
final PointPair rightPair = calcPointPair(points, mid + 1, high);
final PointPair minPair = getMin (leftPair, rightPair);
final PointPair pointPair = zoneSearch(points, mid, minPair.getDistance());
return getMin(minPair, pointPair);
}
private static PointPair getMin (PointPair pointPair1, PointPair pointPair2) {
assert pointPair1 != null;
assert pointPair2 != null;
if (pointPair1.getDistance() < pointPair2.getDistance()) {
return pointPair1;
} else {
return pointPair2;
}
}
private static PointPair bruteForce(Point[] points, int low, int high) {
double minDistance = Double.MAX_VALUE;
Point firstPoint = null;
Point secondPoint = null;
for (int i = low; i < high - 1; i++) {
for (int j = i + 1; j < high; j++) {
double distance = calcDistance(points[i], points[j]);
if (distance < minDistance) {
firstPoint = points[i];
secondPoint = points[j];
minDistance = distance;
}
}
}
return new PointPair(firstPoint, secondPoint, minDistance);
}
private static double calcDistance(Point point1, Point point2) {
int diffX = point1.getX() - point2.getY();
int diffY = point1.getY() - point2.getY();
return Math.sqrt(Math.pow(diffX, 2) + Math.pow(diffY, 2));
}
private static PointPair zoneSearch(Point[] points, int mid, double distance) {
// contains all the nodes which are in horizontal x axis proximity of mid.
final List<Point> pointList = new ArrayList<Point>();
for (int i = 0; i < points.length; i++) {
if (i != mid) {
if (Math.abs(points[i].getX() - points[mid].getX()) <= distance) {
pointList.add(points[i]);
}
}
}
// sorted by y axis
Collections.sort(pointList, new Comparator<Point>() {
@Override
public int compare(Point point1, Point point2) {
return point2.getY() - point1.getY(); // sorting from top down
}
});
double minDistance = Double.MAX_VALUE;
Point firstPoint = null;
Point secondPoint = null;
// for each point, starting from the point on the top.
for (int i = 0; i < pointList.size() - 1; i++) {
for (int j = i + 1; j < pointList.size(); j++) {
double yDistance = pointList.get(i).getY() - pointList.get(j).getY();
if (yDistance > minDistance) { break; }
double candidateDistance = calcDistance(pointList.get(i), pointList.get(j));
if (calcDistance(pointList.get(i), pointList.get(j)) < minDistance) {
minDistance = candidateDistance;
firstPoint = pointList.get(i);
secondPoint = pointList.get(j);
}
}
}
return new PointPair(firstPoint, secondPoint, minDistance);
}
public static void main(String[] args) {
Point p1 = new Point(1, 1);
Point p2 = new Point(2, 2);
Point p3 = new Point(4, 4);
Point p4 = new Point(7, 7);
Point[] point1 = new Point[4];
point1[0] = p1;
point1[1] = p2;
point1[2] = p3;
point1[3] = p4;
System.out.print("Expected 1,1 : 2, 2 Actual: ");
PointPair pp = ClosestPair.minPointPair(point1);
System.out.print(pp.getPoint1().getX() + "," + pp.getPoint1().getY() + " : ");
System.out.println(pp.getPoint2().getX() + "," + pp.getPoint2().getY());
Point p5 = new Point(1, 1);
Point p6 = new Point(20, 20);
Point p7 = new Point(40, 40);
Point p8 = new Point(70, 70);
Point p9 = new Point(100, 100);
Point p10 = new Point(150, 150);
Point p11 = new Point(400, 400);
Point p12 = new Point(7, 7);
Point[] point2 = new Point[8];
point2[0] = p5;
point2[1] = p6;
point2[2] = p7;
point2[3] = p8;
point2[4] = p9;
point2[5] = p10;
point2[6] = p11;
point2[7] = p12;
System.out.print("Expected 1,1 : 7,7 Actual: ");
pp = ClosestPair.minPointPair(point2);
System.out.print(pp.getPoint1().getX() + "," + pp.getPoint1().getY() + " : ");
System.out.println(pp.getPoint2().getX() + "," + pp.getPoint2().getY());
Point p13 = new Point(1, 1);
Point p14 = new Point(20, 20);
Point p15 = new Point(40, 40);
Point p16 = new Point(70, 70);
Point p17 = new Point(100, 100);
Point p18 = new Point(150, 150);
Point p19 = new Point(5, 5);
Point p20 = new Point(7, 7);
Point[] point3 = new Point[8];
point3[0] = p13;
point3[1] = p14;
point3[2] = p15;
point3[3] = p16;
point3[4] = p17;
point3[5] = p18;
point3[6] = p19;
point3[7] = p20;
System.out.print("Expected 5,5 : 7,7, Actual: ");
pp = ClosestPair.minPointPair(point3);
System.out.print(pp.getPoint1().getX() + "," + pp.getPoint1().getY() + " : ");
System.out.println(pp.getPoint2().getX() + "," + pp.getPoint2().getY());
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T00:32:40.947",
"Id": "70800",
"Score": "3",
"body": "Quick tip: You don't need the *actual* distances A-B and A-C to determine whether B or C is closer to A--just the *relative* distances. Drop the call to `sqrt` to shave off a few CPU cycles."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T01:58:14.823",
"Id": "70806",
"Score": "1",
"body": "You could explicitly save off the `Comparator<Point>` you're using for sorting on y-location, although the JITter may be doing that for you anyways. You said that your method required data to be sorted on the x-axis, but the examples you give _aren't_, what's up with that? You should probably add `.equals()`, `.hashcode()`, and `.toString()` methods for your value types. Some methods should probably be broken up further."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T18:19:33.273",
"Id": "71154",
"Score": "1",
"body": "in `zoneSearch` you go over the _whole_ array every time, instead of only from `low` to `high`, which means you make too many calculations, and you may return a result which is not in the range expected..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T23:28:27.270",
"Id": "71356",
"Score": "0",
"body": "@Clockwork-Muse good point, i realized this does not need a sorted array as input"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T10:02:42.673",
"Id": "71407",
"Score": "1",
"body": "Um, if you're trying for the [planar case optimization](http://en.wikipedia.org/wiki/Closest_pair_of_points_problem#Planar_case) (which it looks like), you _do_ need them sorted on the x-axis. I have a feeling you're currently getting correct results only because of a small data-set, and/or the use of `bruteForce(...)`. What happens if you pump the number of points up to 100 or further? Also, your current code has a weakness to integer overflow... why aren't the x/y coordinates `double`s to begin with?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T19:33:32.070",
"Id": "71487",
"Score": "0",
"body": "i think i agree with you"
}
] |
[
{
"body": "<p>The <code>main()</code> method could be replaced with automatized JUnit tests to avoid <a href=\"http://xunitpatterns.com/Manual%20Intervention.html#Manual%20Result%20Verification\" rel=\"nofollow\">manual result verification</a>. You could also have more test methods which help <a href=\"http://xunitpatterns.com/Goals%20of%20Test%20Automation.html#Defect%20Localization\" rel=\"nofollow\">defect localization</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T04:58:55.470",
"Id": "41268",
"ParentId": "41259",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "41268",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T00:16:47.707",
"Id": "41259",
"Score": "4",
"Tags": [
"java",
"algorithm",
"clustering"
],
"Title": "Nearest pair of points"
}
|
41259
|
<p>I decided to work on putting together an Arena-style (very basic) text-based RPG as a way to help myself learn Python. Unfortunately, after about 1,000 lines of pieced-together code, I realize that I've been doing myself a *dis*service by reenforcing poor practices, and by going line-by-line, my inefficiency is multiplying exponentially.</p>
<p>I don't honestly know where to start. I'm sure there are libraries, shortcuts, and greatly more efficient methods than what I'm using. I'm okay with starting over (there are errors not worth finding, anyway), but I would hugely appreciate anyone knowledgeable looking over my code, giving me a few of the bigger pointers for how to clean up my current methods, and where to look for new ones. A quick skim, I'm sure, would suffice. I also want to keep it mostly text and basic, so I'm not looking for something like PyGame, just straightforward stuff. (For extra, I plan on utilizing my final code to create a "leaderboard" of randomly-generated characters that fight each other, so pointers in that direction help). I had to cut out many of the very long lists for post length, but it gives you an idea.</p>
<pre><code>import random
import math
class character:
def __init__(self):
# There are hundreds of these... cut down for post length
self.STR = 75
self.DEX = 75
self.CON = 75
self.AGI = 75
self.INT = 75
self.WIS = 75
self.statPoints = 75
self.AP = 0
self.XP = 0
self.LVL = 1
self.name = ''
self.xpToLVL = 500
self.fightsWon = 0
self.XPSinceLVL = 0
self.dmgmitPercent = 0
self.mindmg = 0
self.maxdmg = 0
self.mindmgmit = 0
self.maxdmgmit = 0
self.minrobeSP = 0
self.maxrobeSP = 0
self.WarBuff = 0
self.poisonCounter = 0
self.dmg = 0
self.armorType = 0
self.shieldEquipped = 0
self.visitedPTrainer = 0
self.visitedCTrainer = 0
self.visitedArena = 0
def fightRound(hero, enemy, skillPick):
heavyB = 0
defS = 0
flank = 0
poison = 0
heal = 0
shock = 0
fireB = 0
counterA = 0
resil = 0
shockstun = 0
monkstun = 0
rejuv = 0
if hero.curClass == 1 and skillPick == 1:
heavyB = 1
elif hero.curClass == 1 and skillPick == 2:
defS = 1
elif hero.curClass == 1 and skillPick == 3:
hero.WarBuff += 1
# ETC, cut for post length
EheavyB = 0
EdefS = 0
Eflank = 0
Epoison = 0
Eheal = 0
Eshock = 0
EfireB = 0
EcounterA = 0
Eresil = 0
Eshockstun = 0
Emonkstun = 0
Erejuv = 0
EskillPick = 0
if enemy.curClass == 1:
if hero.HP < ((enemy.CON * 5 * enemy.LVL) / 10):
EskillPick = 1
elif enemy.HP > (enemy.CON * 5 * enemy.LVL) / 2 and hero.HP > (hero.CON * 5 * hero.LVL) / 2:
if random.randint(1, 100) < 66:
EskillPick = 2
elif random.randint(1, 100) < 51:
EskillPick = 2
else:
EskillPick = 1
if enemy.curClass == 2:
if hero.HP > (hero.CON * 5 * hero.LVL) / 2 and enemy.HP > (enemy.HP * 5 * enemy.LVL) / 2:
if random.randint(1, 100) < 80:
EskillPick = 1
elif random.randint(1, 100) < 40:
EskillPick = 2
else:
EskillPick = 1
#ETC, cut down for post length
if enemy.curClass == 1 and EskillPick == 1:
EheavyB = 1
print 'Your enemy lunges forward...'
elif enemy.curClass == 1 and EskillPick == 2:
EdefS = 1
print 'Your enemy pulls back...'
elif enemy.curClass == 1 and EskillPick == 3:
enemy.WarBuff += 1
elif enemy.curClass == 2 and EskillPick == 1:
Eflank = 1
print 'Your enemy tries to flank you...'
elif enemy.curClass == 2 and EskillPick == 2:
Epoison = 1
print 'Your enemy coats his daggers...'
# ETC, cut for post length
hero.STR = float(hero.STR)
hero.DEX = float(hero.DEX)
hero.CON = float(hero.CON)
hero.INT = float(hero.INT)
hero.WIS = float(hero.WIS)
#hero.DEX = float(hero.DEX)
heroMissed = 0
enemyMissed = 0
enemy.STR = float(enemy.STR)
enemy.DEX = float(enemy.DEX)
enemy.CON = float(enemy.CON)
enemy.INT = float(enemy.INT)
enemy.WIS = float(enemy.WIS)
hero.dodge = float(hero.dodge)
hero.block = float(hero.block)
enemy.dodge = float(enemy.dodge)
enemy.block = float(enemy.block)
hero.crit = float(hero.crit)
enemy.crit = float(enemy.crit)
if hero.weaponType == 0:
hero.swing = hero.AGI * 3
elif hero.weaponType == 1:
hero.swing = hero.AGI * 2
elif hero.weaponType > 1:
hero.swing = hero.AGI
heroAttacks = int(math.floor(hero.swing / 100))
heroExtraAttack = hero.swing - (heroAttacks * 100)
if random.randint(1, 100) <= heroExtraAttack:
heroAttacks += 1
if heroAttacks < 1:
heroMissed = 1
if enemy.weaponType == 0:
enemy.swing = enemy.AGI * 3
elif enemy.weaponType == 1:
enemy.swing = enemy.AGI * 2
elif enemy.weaponType > 1:
enemy.swing = enemy.AGI
enemyAttacks = int(math.floor(enemy.swing / 100))
enemyExtraAttack = enemy.swing - (enemyAttacks * 100)
if random.randint(1, 100) <= enemyExtraAttack:
enemyAttacks += 1
if enemyAttacks < 1:
enemyMissed = 1
# print '*DEBUG*: \# of hero attacks:',heroAttacks
# print '*DEBUG*: \# of enemy attacks:',enemyAttacks
# Just until I get items in...
if hero.weaponType == 0:
hero.mindmg = hero.LVL * 10
hero.maxdmg = hero.LVL * 10
elif hero.weaponType == 1:
hero.mindmg = hero.LVL * 5
hero.maxdmg = hero.LVL * 25
#ETC, cut...
hero.dodge = hero.AGI / 20 + hero.MonP * 0.4
if hero.armorType == 2:
hero.dodge = hero.dodge / 4
elif hero.armorType == 1:
hero.dodge = hero.dodge / 2
hero.dodge = float(hero.dodge)
hero.crit = hero.AGI / 20 + hero.RogP * 0.4
hero.crit = float(hero.crit)
hero.dmgmitPercent = float(hero.STR / 20 / 100)
if hero.armorType == 2:
hero.mindmgmit = hero.LVL * 10
hero.maxdmgmit = hero.LVL * 15
elif hero.armorType == 1:
hero.mindmgmit = hero.LVL * 3
hero.maxdmgmit = hero.LVL * 6
elif hero.armorType == 3:
hero.minrobeSP = hero.LVL * 1
hero.maxrobeSP = hero.LVL * 10
enemy.dodge = enemy.AGI / 20 + enemy.MonP * 0.4
if enemy.armorType == 2:
enemy.dodge = enemy.dodge / 4
elif enemy.armorType == 1:
enemy.dodge = enemy.dodge / 2
enemy.dodge = float(enemy.dodge)
enemy.crit = enemy.AGI / 20 + enemy.RogP * 0.4
enemy.crit = float(enemy.crit)
enemy.dmgmitPercent = float(enemy.STR / 20 / 100)
# haven't done this yet
if hero.shieldEquipped == 1:
hero.block = hero.STR / 20
else:
hero.block = 0
if hero.weaponType == 4:
hero.SP = random.randint(hero.mindmg, hero.maxdmg)
elif hero.weaponType != 4:
hero.SP = hero.LVL * 10
if hero.armorType == 3:
hero.SP += random.randint(hero.minrobeSP, hero.maxrobeSP)
hero.SP *= hero.INT / 100
if enemy.weaponType == 4:
enemy.SP = random.randint(enemy.mindmg, enemy.maxdmg)
elif enemy.weaponType != 4:
enemy.SP = enemy.LVL * 10
if enemy.armorType == 3:
enemy.SP += random.randint(enemy.minrobeSP, enemy.maxrobeSP)
enemy.SP *= enemy.INT / 100
if enemy.curClass == 3 or enemy.curClass == 4:
enemyMissed = 0
enemyAttacks = 1
if enemy.curClass == 3 or enemy.curClass == 4:
enemyMissed = 0
enemyAttacks = 1
if heroMissed == 1:
print 'You missed!'
while heroAttacks > 0:
herodmg = float(random.randint(hero.mindmg, hero.maxdmg))
enemymit = float(random.randint(enemy.mindmgmit, enemy.maxdmgmit))
heroagility = float(hero.AGI)
if hero.weaponType == 0:
herodmg *= hero.CON / 100
enemymit = enemymit / (heroagility / 33)
elif hero.weaponType == 1:
herodmg *= hero.DEX / 100
enemymit = enemymit / (heroagility / 50)
elif hero.weaponType == 2:
herodmg *= hero.STR / 100
enemymit = enemymit / (heroagility / 100)
elif hero.weaponType == 3:
herodmg *= hero.STR / 67
enemymit = enemymit / (heroagility / 100)
elif hero.weaponType == 4:
herodmg *= hero.INT / 100
enemymit = 0
if enemymit < 0:
enemymit = 0
enemydodgeroll = enemy.dodge * 100
enemyblockroll = enemy.block * 100
herocritroll = hero.crit * 100
enemydodged = 0
enemyblocked = 0
herocritted = 0
if shock == 1:
herocritroll = 0
enemydodgeroll = 0
enemyblockroll = 0
enemymit = 0
herodmg = hero.SP
shockroll = (500 + hero.WizA1 * 5)
if random.randint(1, 10000) <= shockroll:
enemy.paralyzed = 1
shockstun = 1
# ETC, cut...
if defS == 1:
herodmg = float(herodmg)
herodmg *= (0.75 - (enemy.WarA2 * .0025))
herodmg = int(herodmg)
herodmg = int(herodmg)
if rejuv == 1:
herodmg = 0
heroAttacks = 0
print 'You close your eyes and inhale deeply.'
elif heal == 1:
herodmg = 0
heroAttacks = 0
heroheal = float(hero.SP * (1.1 + (hero.HeaA1 * 0.009)))
heroheal = int(math.ceil(heroheal))
print 'You heal', heroheal, 'damage!'
hero.HP += heroheal
elif hero.paralyzed == 1:
print 'You struggle but can\'t move!'
herodmg = 0
hero.paralyzed = 0
# ETC, cut down for post length
elif herocritted == 1:
print 'You crit for', herodmg, 'damage!'
else:
print 'You strike your enemy for', herodmg, 'damage.'
enemy.HP -= herodmg
heroAttacks -= 1
if enemyMissed == 1:
print 'Your enemy missed!'
while enemyAttacks > 0:
# print 'average enemy dmg is',float((enemy.mindmg+enemy.maxdmg)/2)
enemydmg = float(random.randint(enemy.mindmg, enemy.maxdmg))
heromit = float(random.randint(hero.mindmgmit, hero.maxdmgmit))
enemyagility = float(enemy.AGI)
if enemy.weaponType == 0:
enemydmg *= enemy.CON / 100
heromit = heromit / (enemyagility / 33)
elif enemy.weaponType == 1:
enemydmg *= enemy.DEX / 100
heromit = heromit / (enemyagility / 50)
elif enemy.weaponType == 2:
enemydmg *= enemy.STR / 100
heromit = heromit / (enemyagility / 100)
elif enemy.weaponType == 3:
enemydmg *= enemy.STR / 67
heromit = heromit / (enemyagility / 100)
elif enemy.weaponType == 4:
enemydmg *= enemy.INT / 100
heromit = 0
if heromit < 0:
heromit = 0
# print 'Your mitigation is',heromit
herododgeroll = hero.dodge * 100
heroblockroll = hero.block * 100
enemycritroll = enemy.crit * 100
enemycritted = 0
herododged = 0
heroblocked = 0
if Eshock == 1:
herododgeroll = 0
heroblockroll = 0
enemycritroll = 0
heromit = 0
enemydmg = enemy.SP
Eshockroll = (500 + enemy.WizA1 * 5)
if random.randint(1, 10000) <= Eshockroll:
hero.paralyzed = 1
Eshockstun = 1
if EfireB == 1:
enemycritroll = 0
heromit = 0
enemydmg = enemy.SP
fireBburn = int(
float(math.ceil(enemydmg * (0.1 + enemy.WizA2 * 0.004))))
if fireBburn > hero.fireBburn:
hero.fireBburn = fireBburn
hero.fireBCount = 5
if Eresil == 1:
herododgeroll = 0
hero.dmgmitPercent += (
hero.dodge / 100) * (0.5 + .005 * hero.MonA2)
if random.randint(1, 10000) <= enemycritroll:
enemydmg *= enemy.DEX / 50
enemycritted = 1
if flank == 1:
heromit *= (0.9 - (hero.RogA1 * 0.009))
herododgeroll *= (0.9 - (hero.RogA1 * 0.009))
heroblockroll *= (0.9 - (hero.RogA1 * 0.009))
if Eflank == 1:
heromit *= (0.9 - (enemy.RogA1 * 0.009))
herododgeroll *= (0.9 - (enemy.RogA1 * 0.009))
heroblockroll *= (0.9 - (enemy.RogA1 * 0.009))
# ETC
if enemy.stunned == 1:
if enemydmg - enemy.stunvalue >= 1:
enemydmg = enemydmg - enemy.stunvalue
enemy.stunvalue = 0
enemy.stunned = 0
print 'He stammers a bit, then',
elif enemydmg - enemy.stunvalue < 1:
enemy.stunvalue = enemy.stunvalue - enemydmg
enemydmg = 0
enemydmg = int(enemydmg)
if Erejuv == 1:
enemydmg = 0
enemyAttacks = 0
Erejuv = 0
elif Eheal == 1:
enemydmg = 0
enemyAttacks = 0
enemyheal = float(enemy.SP * (1.1 + (enemy.HeaA1 * 0.009)))
enemyheal = int(math.ceil(enemyheal))
print 'Your enemy heals', enemyheal, 'damage!'
enemy.HP += enemyheal
elif enemy.paralyzed == 1:
print 'Your enemy only twitches.'
enemydmg = 0
enemy.paralyzed = 0
# ETC...
elif enemycritted == 1:
print 'Your enemy crits you for', enemydmg, 'damage!'
else:
print 'Your enemy strikes you for', enemydmg, 'damage.'
hero.HP -= enemydmg
enemyAttacks -= 1
hero = character()
def fight(hero, enemy):
createEnemy(enemy)
hero.HP = hero.CON * 5 * hero.LVL
enemy.HP = enemy.CON * 5 * enemy.LVL
hero.WarBuff = 0
hero.RogBuff = 0
hero.HeaBuff = 0
hero.WizBuff = 0
hero.MonBuff = 0
hero.rejuvCounter = 0
hero.poisonCounter = 0
hero.stunned = 0
hero.fireBburn = 0
hero.fireBCount = 0
hero.stunvalue = 0
hero.paralyzed = 0
while hero.HP > 0 and enemy.HP > 0:
errorcheckFight = 1
while errorcheckFight == 1:
print('What would you like to do?'),
if hero.curClass == 1:
skillPick = input(
' [0] Attack | [1] Heavy Blow | [2] Defensive Strike | [3] Buff: Training')
elif hero.curClass == 2:
skillPick = input(
' [0] Attack | [1] Flank | [2] Poison | [3] Buff: Feinting')
# ETC...
if skillPick > 3:
print
print 'Please select a proper response, from inside the [brackets].'
print
else:
errorcheckFight = 0
print
fightRound(hero, enemy, skillPick)
if enemy.poisonCounter > 0:
print 'Your enemy was Poisoned for', enemy.poisonCounter * hero.RogA2 * 5, 'damage.'
enemy.HP -= enemy.poisonCounter * hero.RogA2 * 5
if hero.rejuvCounter > 0:
herorejuv = int(
float(math.ceil((hero.SP) * (.3 + (hero.HeaA2 * .003)))))
print 'You rejuvenated', herorejuv, 'damage.'
hero.HP += herorejuv
hero.rejuvCounter -= 1
if enemy.fireBCount > 0:
print 'Your enemy burns for', enemy.fireBburn, 'damage.'
enemy.HP -= enemy.fireBburn
enemy.fireBCount -= 0
if enemy.fireBCount < 1:
enemy.fireBburn = 0
if hero.poisonCounter > 0:
print 'You were Poisoned for', hero.poisonCounter * enemy.RogA2 * 5, 'damage.'
hero.HP -= hero.poisonCounter * enemy.RogA2 * 5
if enemy.rejuvCounter > 0:
enemyrejuv = int(
float(math.ceil((enemy.SP) * (.3 + (enemy.HeaA2 * .003)))))
print 'Your enemy rejuvenated', enemyrejuv, 'damage.'
enemy.HP += enemyrejuv
enemy.rejuvCounter -= 1
if hero.fireBCount > 0:
print 'You burn for', hero.fireBburn, 'damage.'
hero.HP -= hero.fireBburn
hero.fireBCount -= 0
if hero.fireBCount < 1:
hero.fireBburn = 0
print
print 'HERO HP:', hero.HP, ' |------| ENEMY HP:', enemy.HP
print
if enemy.HP <= 0:
hero.fightsWon += 1
print 'You Won!'
print 'You gain 100 XP and', int(float(hero.WIS / 75) * 100), 'AP.'
hero.XP += 100
hero.XPSinceLVL += 100
hero.AP += int(float(hero.WIS / 75) * 100)
hero.APSinceLVL += int(float(hero.WIS / 75) * 100)
elif hero.HP <= 0:
hero.fightsLost += 1
print 'You Lost...'
hero.xpToLVL = (hero.LVL * 100 + 500) - hero.XPSinceLVL
if hero.xpToLVL <= 0:
hero.LVL += 1
hero.XPSinceLVL = 0
hero.statPoints += 5
print
print 'You have gained a level! You are now level,', str(hero.LVL) + '!'
classList = ['', 'Warrior', 'Rogue', 'Healer', 'Wizard', 'Monk']
classLevels = [0, hero.WarLVL, hero.RogLVL,
hero.HeaLVL, hero.WizLVL, hero.MonLVL]
if (classLevels[hero.curClass] * 100 + 500) - (hero.APSinceLVL) <= 0:
hero.APSinceLVL = 0
classLevels[hero.curClass] += 1
print 'You have gained a class level! You are now a level', classLevels[hero.curClass], classList[hero.curClass] + '!'
print
print hero.xpToLVL, 'experience left for level', (hero.LVL + 1), 'and', int((classLevels[hero.curClass] * 100 + 500) - (hero.APSinceLVL)), 'left for', classList[hero.curClass], 'level', str(classLevels[hero.curClass]) + '.'
# print '*DEBUG*: Fights Won:',hero.fightsWon,' Fights
# Lost:',hero.fightsLost,' Level:',hero.LVL
main()
def createEnemy(enemy):
#enemy = character()
enemy.LVL = hero.LVL
enemyClass = random.randint(1, 5)
enemy.curClass = enemyClass
enemy.statPoints += (enemy.LVL - 1) * 3
if enemy.curClass == 1:
enemy.STR += int(enemy.statPoints * 0.50)
enemy.CON += int(enemy.statPoints * 0.30)
enemy.AGI += int(enemy.statPoints * 0.20)
enemy.WarP += int(enemy.LVL * 0.70)
enemy.WarA1 += int(enemy.LVL * 0.60)
enemy.WarA2 += int(enemy.LVL * 0.60)
enemy.mindmgmit = enemy.LVL * 5
enemy.maxdmgmit = enemy.LVL * 10
enemy.mindmg = enemy.LVL * 10
enemy.maxdmg = enemy.LVL * 50
wartype = random.randint(1, 2)
if wartype == 1:
enemy.weaponType = 2
enemy.shieldEquipped = 1
enemy.mindmgmit += enemy.LVL * 2
enemy.maxdmgmit += enemy.LVL * 5
else:
enemy.weaponType = 3
enemy.shieldEquipped = 0
elif enemy.curClass == 2:
enemy.DEX += int(enemy.statPoints * 0.50)
enemy.AGI += int(enemy.statPoints * 0.30)
enemy.CON += int(enemy.statPoints * 0.20)
enemy.RogP += int(enemy.LVL * 0.60)
enemy.RogA1 += int(enemy.LVL * 0.50)
enemy.RogA2 += int(enemy.LVL * 0.50)
enemy.mindmgmit = enemy.LVL * 3
enemy.maxdmgmit = enemy.LVL * 6
enemy.mindmg = enemy.LVL * 5
enemy.maxdmg = enemy.LVL * 25
enemy.weaponType = 1
enemy.armorType = 1
# ETC, cut for post length
def classPick(hero):
classList = ['Warrior', 'Rogue', 'Healer', 'Wizard', 'Monk']
classLevels = [hero.WarLVL, hero.RogLVL,
hero.HeaLVL, hero.WizLVL, hero.MonLVL]
print ' -------'
print '---------------------------| ARENA |----------------------------'
print ' -------'
print
charname = raw_input('Please enter your hero\'s name:')
hero.name = charname
print
print 'Please pick a starting class:'
classAnswered = 0
while classAnswered == 0:
classNumcounter = 0
print
while classNumcounter < 5:
print '[' + str(classNumcounter + 1) + ']:', classList[classNumcounter]
classNumcounter += 1
print '[H]elp for more information.'
classAnswer = raw_input('Please enter [1-5] or [H]')
if classAnswer == 'H':
# HAVE FUN HERE -- DON'T FORGET!!
print
print '----------------------------------------------------------------'
print 'THE WARRIOR:'
print 'The warrior is a heavily armored fighter using a sword,'
print 'Versed in offensive and defensive tactics.'
print 'This class is straightforward and harty, suited for beginners.'
# ETC cut for post length
print '----------------------------------------------------------------'
print
else:
classAnswer = int(classAnswer)
if classAnswer == 1:
hero.WarLVL += 1
hero.WarA1 += 1
hero.WarA2 += 1
hero.WarB += 1
hero.WarP += 1
hero.WarE += 1
hero.weaponType = 3
hero.armorType = 2
hero.curClass = 1
elif classAnswer == 2:
hero.RogLVL += 1
hero.RogA1 += 1
hero.RogA2 += 1
hero.RogB += 1
hero.RogP += 1
hero.RogE += 1
hero.weaponType = 1
hero.armorType = 1
hero.curClass = 2
# ETC, cut for post length
classAnswered = 1
classAnswer -= 1
classList = ['Warrior', 'Rogue', 'Healer', 'Wizard', 'Monk']
classLevels = [hero.WarLVL, hero.RogLVL,
hero.HeaLVL, hero.WizLVL, hero.MonLVL]
print
print 'Welcome to the Arena,', hero.name + ', the level', classLevels[classAnswer], classList[classAnswer] + '!'
print
print 'Please visit your [P]ersonal trainer before stepping into'
print 'The Arena itself.'
def personalTrainer(hero):
statCounter = 0
while hero.visitedPTrainer == 0:
print
print 'Ah,', hero.name + ', come in, come in!'
#ETC, cut for post length
print
hero.visitedPTrainer = 1
statsList = ['STR', 'DEX', 'CON', 'AGI', 'INT', 'WIS']
statsValues = [hero.STR, hero.DEX, hero.CON, hero.AGI, hero.INT, hero.WIS]
print '------------------------'
print 'Your current Stats:'
while statCounter < 6:
print '[' + str(statCounter + 1) + ']', statsList[statCounter] + ':', int(statsValues[statCounter])
statCounter += 1
print 'You have', hero.statPoints, 'points left.'
print '------------------------'
statPick = raw_input(
'Train [1]-[6]; [V]iew detailed stats; [L]eave; [H]elp')
if str.upper(statPick) == 'L':
main()
elif str.upper(statPick) == 'V':
print '(Definitely not yet implemented...)'
personalTrainer(hero)
elif str.upper(statPick) == 'H':
# more tedium
print
print '----------------------------------------------------------------'
print 'STRENGTH:'
print 'Strength determines your damage with swords and staves: (STR)%'
print 'And your raw damage mitigation. ((STR-100)/10)%: 200STR = -10%'
print 'It is especially important for Warriors and Healers.'
print
print 'DEXTERITY:'
# ETC, cut for post length
print '----------------------------------------------------------------'
print
personalTrainer(hero)
else:
if hero.statPoints <= 0:
print 'You need more experience to train further.'
personalTrainer(hero)
statPick = int(statPick)
if statPick == 1:
STRadd = input(
'How many points would you like to add to Strength? [0]-[' + str(hero.statPoints) + ']')
if STRadd > hero.statPoints:
STRadd = 0
print 'You haven\'t gained enough experience to train so much!'
hero.STR += STRadd
hero.statPoints -= STRadd
personalTrainer(hero)
elif statPick == 2:
DEXadd = input(
'How many points would you like to add to Dexterity? [0]-[' + str(hero.statPoints) + ']')
if DEXadd > hero.statPoints:
DEXadd = 0
print 'You haven\'t gained enough experience to train so much!'
hero.DEX += DEXadd
hero.statPoints -= DEXadd
personalTrainer(hero)
# Etc - cut for post length
else:
print 'Please pick something from inside the [brackets].'
personalTrainer(hero)
def main():
if hero.WarLVL == 0 and hero.RogLVL == 0 and hero.HeaLVL == 0 and hero.WizLVL == 0 and hero.MonLVL == 0:
classPick(hero)
print
print 'What would you like to do?:'
locationPick = raw_input(
'[F]ight in the Arena; [C]lass Trainer; [P]ersonal Trainer; [H]elp')
if str.upper(locationPick) == 'F':
enemy = character()
fight(hero, enemy)
# ETC...
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T02:45:04.843",
"Id": "70807",
"Score": "0",
"body": "If someone wants to point me to the proper location to use, I would be happy to post the uncut version and link it. The post here limits me to 30k characters, despite the scrollbar."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T23:03:36.810",
"Id": "70882",
"Score": "0",
"body": "You might want to edit your *off-site* code based on the answer[s] you receive, then post the new code as [a follow-up question](http://meta.codereview.stackexchange.com/a/1066/34757). If there's something in a specific answer you don't understand (e.g. 'refactoring' or 'classes'), then ask about that answer by posting a comment to the answer."
}
] |
[
{
"body": "<p>The primary problem I see is that your functions try to do everything from start to finish. For example <code>fightRound</code> knows all about the different kinds of weapons and armor and chances of critical hits and what effect these all have on the damage. It would benefit greatly being separated into multiple items that handle individual aspects of this. Consider a conductor of an orchestra: he doesn't tell violinist to pull the bow or the trumpet player when to breathe; the conductor just decides when the notes must be played.</p>\n\n<p>You can make <code>fightRound</code> more like a conductor through something called refactoring. It's a process of finding similar code, turning it into reusable blocks, and using that new block without changing the meaning of your code. By giving that reusable block a name, it can become the master of its primary purpose (playing a trumpet note), and let the caller focus on conducting.</p>\n\n<p>In your code you can find many good candidates for refactoring by looking for <code>if/elif</code> trees. Since I'm not seeing all of your code, I may guess the wrong pattern to simplify. But on the whole this approach should help reduce the amount of code, and increase the focus within each block. But watch out for any cases where my advice is wrong because I didn't have the full picture, and see if you can figure out how to tweak it into something that helps.</p>\n\n<p><strong>Refactoring into functions</strong></p>\n\n<p>Let's start with a simple refactoring. Here's some code from early on in <code>fightRound</code>:</p>\n\n<pre><code>if hero.weaponType == 0:\n hero.swing = hero.AGI * 3\nelif hero.weaponType == 1:\n hero.swing = hero.AGI * 2\nelif hero.weaponType > 1:\n hero.swing = hero.AGI\n\n[...]\n\nif enemy.weaponType == 0:\n enemy.swing = enemy.AGI * 3\nelif enemy.weaponType == 1:\n enemy.swing = enemy.AGI * 2\nelif enemy.weaponType > 1:\n enemy.swing = enemy.AGI\n</code></pre>\n\n<p>These two blocks are the same, except the first one references <code>hero</code> everywhere and the second references <code>enemy</code>. As a first step, I would like to see this become something like:</p>\n\n<pre><code>hero.swing = getWeaponSwing(hero)\nenemy.swing = getWeaponSwing(enemy)\n</code></pre>\n\n<p>where <code>getWeaponSwing(char)</code> was a simple implementation of that common code.</p>\n\n<p>Similarly the interleaved code that calculates attacks and misses is also repeated. This could become its own function, or perhaps merged with the suggested <code>getWeaponSwing</code> and given a more inclusive name.</p>\n\n<p><strong>Refactoring into data</strong></p>\n\n<p>A little further down, just past the comment <code># Just until I get items in...</code>, there is an abbreviated <code>if/elif</code> tree that sets <code>mindmg</code> and <code>maxdmg</code> per the type of weapon. Let's consider what refactoring can do here. If the overall structure looks the same for all the omitted <code>weaponType</code> values, consider a data-driven refactoring:</p>\n\n<pre><code># up above, probably globally:\nWeaponDamageCoef = [\n (10, 10), # level 0\n (5, 25), # level 1\n ... ]\n\n# back in fightRound\ncoef = WeaponDamageCoef[hero.weaponType]\nhero.mindmg = coef[0] * hero.LVL\nhero.maxdmg = coef[1] * hero.LVL\n\n# or, a more advanced way\nhero.mindmg, hero.maxdmg = [coef * hero.LVL for coef in WeaponDamageCoef[hero.weaponType]]\n</code></pre>\n\n<p><strong>Refactoring into classes</strong></p>\n\n<p>It's possible that the above scenario was simplified. Maybe it's not always a coefficient you can look up by weapon type, or it's not always multiplied by the level. If you need further customization, you can make multiple weapon classes that offer the same interface. Then store an instance of the weapon on your hero and enemy, and let the weapon figure out its thing. Here's a roughed out example of that:</p>\n\n<pre><code>class Weapon(object):\n def getDamageRange(self, char):\n return 10 * char.LVL, 10 * char.LVL\n\nclass MagicWeapon(object): # or perhaps inherit from Weapon, or some shared base\n def getDamageRange(self, char):\n return 5 * char.LVL + 3 * char.INT, 7 * char.LVL + 8 * char.INT\n...\nhero.weapon = MagicWeapon()\n...\nhero.mindmg, hero.maxdmg = hero.weapon.getDamageRange(hero)\n</code></pre>\n\n<p><strong>Next steps</strong></p>\n\n<p>Look for as many instances of repeating code as you can find, and try to refactor them into helpers. After you do this, the code should become smaller and easier to manage. You may find that after the first level of refactoring, other similarities start to become apparent and you can do further higher level refactorings.</p>\n\n<p>There are a lot of other opportunities to improve this code. Refactoring won't fix them all. My hope is that once you reduce the quantity of code through good factoring, it will be easier to address the opportunities that remain.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T07:13:53.723",
"Id": "77751",
"Score": "0",
"body": "I've seen mentions of \"refactoring libraries\" or modules for python. Is there anything that suggests or hints at refactoring in a proper or pythonian way? It seems like the kind of thing, oddly enough, that a python script could chew up (un-refactored) and spit out (refactored), at least as a starting point. It seems daunting to me at this point, even if I am starting over."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T16:31:23.640",
"Id": "77856",
"Score": "1",
"body": "Proper refactoring seems enough of an art that seems like asking for a \"proper\" cubist rendition of a photograph. Refactoring is daunting, as it's work that really only pays off if it easier to review and reveal defects or easier to add more functionality. Doing it well takes a lot of practice; try it in small pieces, changing things in small steps as you constantly verify the program still does what you want after each step."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T21:08:21.860",
"Id": "41294",
"ParentId": "41264",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "41294",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T01:44:13.323",
"Id": "41264",
"Score": "10",
"Tags": [
"python",
"classes",
"library",
"python-2.x"
],
"Title": "Shortcuts and imports for large RPG basic code"
}
|
41264
|
<p>Is there anything that I could have done better in this code?</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Quotes</title>
<style>
body { color: #333; font: 20px georgia; }
em { color: #555; font-size: 90%; }
</style>
</head>
<body>
<article id="quotes"></article>
<script>
(function() {
"use strict";
var quotes = [
["Stay Hungry. Stay Foolish.", "Steve Jobs"],
["Good Artists Copy, Great Artists Steal.", "Pablo Picasso"],
["Argue with idiots, and you become an idiot.", "Paul Graham"],
["Be yourself; everyone else is already taken.", "Oscar Wilde"],
["Simplicity is the ultimate sophistication.", "Leonardo Da Vinci"]
].sort(function() {
return 0.5 - Math.random();
}),
quotesHTML = "";
for (var i = 0; i < quotes.length; i++) {
quotesHTML += "<p>&ldquo;" + quotes[i][0] + "&rdquo; &mdash; <em>" + quotes[i][1] + "</em></p>";
}
document.getElementById("quotes").innerHTML = quotesHTML;
}());
</script>
</body>
</html>
</code></pre>
|
[] |
[
{
"body": "<p>I think your code looks pretty good already. It follows conventions and your indentation and variable names are precise. There's not much to review.</p>\n\n<p>But if you're targeting modern browsers (IE9+) I would suggest a different approach using <code>map</code> and would separate the random logic into a function. I'd also declare the element up top so I know at first glance that the code is working with the DOM. It may seem like more code at first but it's good for code reuse, plus I think it reads better; the intent is more clear:</p>\n\n<pre><code>(function() {\n \"use strict\";\n\n var el = document.getElementById(\"quotes\");\n\n var quotes = [\n [\"Stay Hungry. Stay Foolish.\", \"Steve Jobs\"],\n [\"Good Artists Copy, Great Artists Steal.\", \"Pablo Picasso\"],\n [\"Argue with idiots, and you become an idiot.\", \"Paul Graham\"],\n [\"Be yourself; everyone else is already taken.\", \"Oscar Wilde\"],\n [\"Simplicity is the ultimate sophistication.\", \"Leonardo Da Vinci\"]\n ];\n\n function rand(xs) {\n return xs.slice(0).sort(function(){\n return .5 - Math.random();\n });\n }\n\n function quote(q) {\n return \"<p>&ldquo;\"+ q[0] +\"&rdquo; &mdash; <em>\"+ q[1] +\"</em></p>\";\n }\n\n el.innerHTML = rand(quotes).map(quote).join('');\n\n}());\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T05:24:25.580",
"Id": "41271",
"ParentId": "41269",
"Score": "8"
}
},
{
"body": "<p>The only thing I'd change is your data structure. I think it would work better as an array of objects, then you can access the quote and author without indexing an array.</p>\n\n<pre><code>var quotes = [\n { \n quote: \"Stay Hungry. Stay Foolish.\", \n author: \"Steve Jobs\"\n },\n [...]\n];\n\n[...]\n\n\"<blockquote>&ldquo;\"+ q.quote +\"&rdquo; <footer class=\"author\"> &mdash;\" \n + q.author +\"</footer></blockquote>\"\n</code></pre>\n\n<p>Also, maybe use a <code><blockquote></code> element instead of a <code><p></code> for the correct semantics.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T14:50:53.150",
"Id": "70841",
"Score": "0",
"body": "The source of a quotation should be wrapped with a `footer` element inside the `blockquote`. Also there should be no space between the em dash and the author."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T15:18:44.230",
"Id": "70845",
"Score": "0",
"body": "@kleinfreund Done."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T15:27:16.553",
"Id": "70846",
"Score": "0",
"body": "Plus what I was trying to say: `author` is inappropriate here. It's not an author, but the source of the quote."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T15:28:00.273",
"Id": "70847",
"Score": "0",
"body": "@kleinfreund What's the difference?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T15:31:02.883",
"Id": "70848",
"Score": "0",
"body": "Tried googling that, but apparantly there isn't even an `author` element.^^"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T15:32:11.903",
"Id": "70849",
"Score": "0",
"body": "@kleinfreund Oh yeah. Oops. http://stackoverflow.com/questions/7290504/which-html5-tag-should-i-use-to-mark-up-an-authors-name"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T14:37:47.687",
"Id": "41286",
"ParentId": "41269",
"Score": "7"
}
},
{
"body": "<p>Based upon Jiving's answer and his markup, I'd suggest moving the <em>quote signs</em> to the CSS. For this purpose I added <code>p</code> tags inside <code>blockquote</code>. I also changed the <code>author</code> class to <code>source</code>.</p>\n\n<pre><code>\"<blockquote class=\"random-quotes\"><p>\"+ q.quote +\"</p><footer class=\"source\"> &mdash;\"+ q.author +\"</footer></blockquote>\"\n</code></pre>\n\n<p><em>(/!\\ Note: Since the <code>p</code> tags are hard coded into my example, this would only work with single paragraph quotes. I don't know if this is enough. If not, you'll need to pass the <code>p</code> tags with the quotes.)</em></p>\n\n<p><strong>CSS:</strong></p>\n\n<pre><code>blockquote p:first-of-type:before {\n content: \"\\201C\";\n}\n\n/* Selecting only the last paragraph for when there are multiple paragraphs */\nblockquote p:last-of-type:after {\n content: \"\\201D\";\n}\n\nblockquote p:last-of-type {\n margin-bottom: 0;\n}\n\n.source {\n display: block;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T17:32:08.433",
"Id": "70858",
"Score": "0",
"body": "Why `:last-of-type` when there's only one `p`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T18:13:38.393",
"Id": "70865",
"Score": "0",
"body": "@Jivings That's for the edge case when there are multiple paragraphs. One usually wants the margin between the paragraphs, but not between paragraph and source. Also one only needs the quotation marks on the last paragraph. Ah, wait a sec... gonna need a `:first-of-type` for the open quote as well then. ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T18:40:23.180",
"Id": "70869",
"Score": "0",
"body": "That makes more sense :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T16:49:11.163",
"Id": "41289",
"ParentId": "41269",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T05:05:35.833",
"Id": "41269",
"Score": "11",
"Tags": [
"javascript",
"html",
"array"
],
"Title": "Displaying random quotes from an array"
}
|
41269
|
<p>I'm writing a parser for HTTP Authorization header (see <a href="https://www.rfc-editor.org/rfc/rfc2616#section-14.8" rel="nofollow noreferrer">RFC2616#14.8</a> and <a href="https://www.rfc-editor.org/rfc/rfc2617#section-1.2" rel="nofollow noreferrer">RFC2617#1.2</a>). <strong>Note that I explicitly don't care about the base64-encoded syntax used by HTTP Basic authentication</strong>. I'm only interested in the <code>auth-param</code> syntax used by Digest authentication (to be more specific, I'm implementing a custom Authorization header similar to <a href="https://stackoverflow.com/questions/7802116/custom-http-authorization-header">this question on SO</a>). Basically, it's just a list of <code>key=value</code> pairs separated by commas and <code>value</code> could be quoted or unquoted.</p>
<p>Here's my code, which seems to parse the examples from the RFC just fine:</p>
<pre><code>package com.example.sample;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AuthorizationHeaderParser {
private static final String SEPARATORS = "()<>@,;:\\\\\"/\\[\\]?={} \t";
private static final Pattern TOKEN_PATTERN = Pattern
.compile("[[\\p{ASCII}]&&[^" + SEPARATORS + "]&&[^\\p{Cntrl}]]+");
private static final Pattern EQ_PATTERN = Pattern.compile("=");
private static final Pattern TOKEN_QUOTED_PATTERN = Pattern
.compile("\"([^\"]|\\\\\\p{ASCII})*\"");
private static final Pattern COMMA_PATTERN = Pattern.compile(",");
private static final Pattern LWS_PATTERN = Pattern
.compile("(\r?\n)?[ \t]+");
private static class Tokenizer {
private String remaining;
public Tokenizer(String input) {
remaining = input;
}
private void skipSpaces() {
Matcher m = LWS_PATTERN.matcher(remaining);
if (!m.lookingAt()) {
return;
}
String match = m.group();
remaining = remaining.substring(match.length());
}
public String match(Pattern p) {
skipSpaces();
Matcher m = p.matcher(remaining);
if (!m.lookingAt()) {
return null;
}
String match = m.group();
remaining = remaining.substring(match.length());
return match;
}
public String mustMatch(Pattern p) {
String match = match(p);
if (match == null) {
throw new NoSuchElementException();
}
return match;
}
public boolean hasMore() {
skipSpaces();
return remaining.length() > 0;
}
}
public static Map<String, String> parse(String input) {
Tokenizer t = new Tokenizer(input);
Map<String, String> map = new HashMap<String, String>();
String authScheme = t.match(TOKEN_PATTERN);
map.put(":auth-scheme", authScheme);
while (true) {
while (t.match(COMMA_PATTERN) != null) {
// Skip null list elements
}
if (!t.hasMore()) {
break;
}
String key = t.mustMatch(TOKEN_PATTERN);
t.mustMatch(EQ_PATTERN);
String value = t.match(TOKEN_PATTERN);
if (value == null) {
value = t.mustMatch(TOKEN_QUOTED_PATTERN);
// trim quotes
value = value.substring(1, value.length() - 1);
}
map.put(key, value);
if (t.hasMore()) {
t.mustMatch(COMMA_PATTERN);
}
}
return map;
}
public static void main(String args[]) {
String test1 = "Digest\n"
+ " realm=\"testrealm@host.com\",\n"
+ " qop=\"auth,auth-int\",\n"
+ " nonce=\"dcd98b7102dd2f0e8b11d0f600bfb0c093\",\n"
+ " opaque=\"5ccc069c403ebaf9f0171e9517f40e41\"";
String test2 = "Digest username=\"Mufasa\",\n"
+ " realm=\"testrealm@host.com\",\n"
+ " nonce=\"dcd98b7102dd2f0e8b11d0f600bfb0c093\",\n"
+ " uri=\"/dir/index.html\",\n"
+ " qop=auth,\n"
+ " nc=00000001,\n"
+ " cnonce=\"0a4f113b\",\n"
+ " response=\"6629fae49393a05397450978507c4ef1\",\n"
+ " opaque=\"5ccc069c403ebaf9f0171e9517f40e41\"";
System.out.println(parse(test1));
System.out.println(parse(test2));
}
}
</code></pre>
<p>My questions:</p>
<ol>
<li>For something as simple as this, is my approach (using regex) good enough or should I write a "real" parser?</li>
<li>Is my translation from the RFC BNF to regex correct, or have I made any mistakes that fail on a valid header or pass an invalid header?</li>
<li>The regular expressions seem too complex, can they be simplified?</li>
<li>Any other suggestions?</li>
</ol>
|
[] |
[
{
"body": "<p>Going through your specific questions, I have the following suggestions:</p>\n\n<ol>\n<li><em>Should you write a 'real' parser?</em> - Depends. Parsers can be complicated, and they make assumptions. Regardless, you have <strong>already</strong> written your own parser, and it is 'real'.</li>\n<li>This is the <em>BIG</em> question... <em>is it right?</em> - With regexes it is often hard to tell, and it requires careful analysis of the regex and the data to find out. I have looked at your code, and inspected the regex, and, frankly, it was more complicated than I could easily understand in one sitting.... (and without 'playing' with the code). So, is it right? I don't know.</li>\n<li><em>Are the regexes too complicated (can they be simplified)?</em> - yes, I would say yes to being too complicated, and unsure about whether they can be simplified.</li>\n<li><em>Other suggestions?</em> - yes, a few.... which leads on to:</li>\n</ol>\n\n<p>OK, so what are the other suggestions.....</p>\n\n<ul>\n<li>since you have a class called <code>Tokenizer</code>, it is apparent you are breaking the code in to tokens.... why don't you just use the tools in Java to do the work for you?</li>\n<li>This problem is commonly solved with a State machine as well, which are sometimes much faster, and quite interesting.</li>\n</ul>\n\n<p>So, as an exercise, I took your code, and implemented both a state-machine and a Scanner implementation. I have used statemachines in the past to parse comma-separated value files, and the process was very fast... I figured it made sense here too. The Scanner is more complicated than I would have hoped, but you may find the implementation to be educational (I did).</p>\n\n<p>As for a review of your code.... I found it 'easier' to write it again myself, than to try to understand yours. In a sense, that says a lot.</p>\n\n<pre><code>import java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class AuthorizationHeaderParser {\n\n\n /* ****************************************\n * OP Mechanism\n * **************************************** */\n\n private static final String SEPARATORS = \"()<>@,;:\\\\\\\\\\\"/\\\\[\\\\]?={} \\t\";\n\n private static final Pattern TOKEN_PATTERN = Pattern\n .compile(\"[[\\\\p{ASCII}]&&[^\" + SEPARATORS + \"]&&[^\\\\p{Cntrl}]]+\");\n private static final Pattern EQ_PATTERN = Pattern.compile(\"=\");\n private static final Pattern TOKEN_QUOTED_PATTERN = Pattern\n .compile(\"\\\"([^\\\"]|\\\\\\\\\\\\p{ASCII})*\\\"\");\n private static final Pattern COMMA_PATTERN = Pattern.compile(\",\");\n private static final Pattern LWS_PATTERN = Pattern\n .compile(\"(\\r?\\n)?[ \\t]+\");\n\n private static class Tokenizer {\n private String remaining;\n\n public Tokenizer(String input) {\n remaining = input;\n }\n\n private void skipSpaces() {\n Matcher m = LWS_PATTERN.matcher(remaining);\n if (!m.lookingAt()) {\n return;\n }\n String match = m.group();\n remaining = remaining.substring(match.length());\n }\n\n public String match(Pattern p) {\n skipSpaces();\n Matcher m = p.matcher(remaining);\n if (!m.lookingAt()) {\n return null;\n }\n String match = m.group();\n remaining = remaining.substring(match.length());\n return match;\n }\n\n public String mustMatch(Pattern p) {\n String match = match(p);\n if (match == null) {\n throw new NoSuchElementException();\n }\n return match;\n }\n\n public boolean hasMore() {\n skipSpaces();\n return remaining.length() > 0;\n }\n\n }\n\n public static Map<String, String> parse(String input) {\n Tokenizer t = new Tokenizer(input);\n Map<String, String> map = new HashMap<String, String>();\n\n String authScheme = t.match(TOKEN_PATTERN);\n map.put(\":auth-scheme\", authScheme);\n\n while (true) {\n while (t.match(COMMA_PATTERN) != null) {\n // Skip null list elements\n }\n\n if (!t.hasMore()) {\n break;\n }\n\n String key = t.mustMatch(TOKEN_PATTERN);\n t.mustMatch(EQ_PATTERN);\n String value = t.match(TOKEN_PATTERN);\n if (value == null) {\n value = t.mustMatch(TOKEN_QUOTED_PATTERN);\n // trim quotes\n value = value.substring(1, value.length() - 1);\n }\n\n map.put(key, value);\n\n if (t.hasMore()) {\n t.mustMatch(COMMA_PATTERN);\n }\n\n }\n return map;\n }\n\n /* ****************************************\n * State Machine Mechanism\n * **************************************** */\n\n private static enum ParseState{\n PROLOGSPACE,\n PROLOGWORD,\n KEY,\n KEYVALGAP,\n VALUE,\n QUOTEDVALUE,\n SEPARATOR,\n COMPLETE;\n }\n\n private static final String WHITESPACE = new String(\" \\t\\r\\n\");\n\n public static Map<String,String> parseSM(String value) {\n Map<String,String> result = new HashMap<>();\n\n ParseState currentstate = ParseState.PROLOGSPACE;\n char[] valchars = value.toCharArray();\n // add a null character at the end.\n valchars = Arrays.copyOf(valchars, valchars.length + 1);\n int mark = 0;\n String key = null;\n for (int i = 0; i < valchars.length; i++) {\n final char ch = valchars[i];\n switch (currentstate) {\n case PROLOGSPACE: {\n // we are in any whitespace before the 'Digest' :auth-scheme \n if (WHITESPACE.indexOf(ch) < 0) {\n // no longer in white-space, mark the spot, and move on.\n mark = i;\n currentstate = ParseState.PROLOGWORD;\n }\n break;\n }\n case PROLOGWORD: {\n // we are in the 'Digest' :auth-scheme \n if (WHITESPACE.indexOf(ch) >= 0) {\n // no longer on the word, handle it....\n result.put(\":auth-scheme\", new String(valchars, mark, i - mark));\n currentstate = ParseState.SEPARATOR;\n }\n break;\n }\n case SEPARATOR: {\n // processing the gap before/between key=value pairs.\n if (ch == 0) {\n currentstate = ParseState.COMPLETE;\n } else if (ch != ',' && WHITESPACE.indexOf(ch) < 0) {\n mark = i;\n currentstate = ParseState.KEY;\n }\n break;\n }\n case KEY: {\n // processing a key=value key.\n if (ch == '=' /* || WHITESPACE.indexOf(ch) >= 0 */ ) {\n // no longer in key\n key = new String(valchars, mark, i-mark);\n currentstate = ParseState.KEYVALGAP;\n }\n break;\n }\n case KEYVALGAP: {\n if (ch != '=' /* && WHITESPACE.indexOf(ch) < 0 */) {\n mark = 0;\n if (ch == '\"') {\n currentstate = ParseState.QUOTEDVALUE;\n mark = i + 1;\n } else {\n currentstate = ParseState.VALUE;\n mark = i;\n }\n }\n break;\n }\n case VALUE: {\n if (ch == ',' || ch == 0 || WHITESPACE.indexOf(ch) >= 0) {\n result.put(key, new String(valchars, mark, i - mark));\n currentstate = ParseState.SEPARATOR;\n }\n break;\n }\n case QUOTEDVALUE: {\n if (ch == '\"') {\n result.put(key, new String(valchars, mark, i - mark));\n currentstate = ParseState.SEPARATOR;\n }\n break;\n }\n case COMPLETE: {\n throw new IllegalStateException(\"There should be no characters after COMPLETE\");\n }\n\n }\n }\n if (currentstate != ParseState.COMPLETE) {\n throw new IllegalStateException(\"Unexpected parse path ended before completion (ended at \" + currentstate + \").\");\n }\n return result;\n }\n\n /* ****************************************\n * Scanner Mechanism\n * **************************************** */\n\n private static final Pattern SCANWHITESPACE = Pattern.compile(\"\\\\s+\");\n private static final Pattern SCANEQUALS = Pattern.compile(\"=\");\n private static final Pattern SCANONECHAR = Pattern.compile(\"\\\\s*\");\n private static final Pattern SCANCOMMA = Pattern.compile(\"\\\\s*,\\\\s*\");\n private static final Pattern SCANQUOTEEND = Pattern.compile(\"\\\"\");\n\n public static Map<String,String> parseScanner(String value) {\n Map<String,String> result = new HashMap<>();\n try (Scanner scanner = new Scanner(value)) {\n scanner.useDelimiter(SCANWHITESPACE);\n if (scanner.hasNext(SCANWHITESPACE)) {\n scanner.skip(SCANWHITESPACE);\n }\n result.put(\":auth-scheme\", scanner.next());\n while (scanner.hasNext()) {\n scanner.skip(scanner.delimiter());\n scanner.useDelimiter(SCANEQUALS);\n String key = scanner.next();\n scanner.skip(scanner.delimiter());\n scanner.useDelimiter(SCANONECHAR);\n if (scanner.hasNext()) {\n String firstchar = scanner.next();\n if (\"\\\"\".equals(firstchar)) {\n scanner.useDelimiter(SCANQUOTEEND);\n String val = scanner.next();\n result.put(key, val);\n scanner.skip(scanner.delimiter());\n scanner.useDelimiter(SCANCOMMA);\n } else {\n scanner.useDelimiter(SCANCOMMA);\n result.put(key, firstchar + scanner.next());\n }\n }\n }\n }\n\n return result;\n }\n\n public static void main(String args[]) {\n String test1 = \"Digest\\n\"\n + \" realm=\\\"testrealm@host.com\\\",\\n\"\n + \" qop=\\\"auth,auth-int\\\",\\n\"\n + \" nonce=\\\"dcd98b7102dd2f0e8b11d0f600bfb0c093\\\",\\n\"\n + \" opaque=\\\"5ccc069c403ebaf9f0171e9517f40e41\\\"\";\n String test2 = \"Digest username=\\\"Mufasa\\\",\\n\"\n + \" realm=\\\"testrealm@host.com\\\",\\n\"\n + \" nonce=\\\"dcd98b7102dd2f0e8b11d0f600bfb0c093\\\",\\n\"\n + \" uri=\\\"/dir/index.html\\\",\\n\"\n + \" qop=auth,\\n\"\n + \" nc=00000001,\\n\"\n + \" cnonce=\\\"0a4f113b\\\",\\n\"\n + \" response=\\\"6629fae49393a05397450978507c4ef1\\\",\\n\"\n + \" opaque=\\\"5ccc069c403ebaf9f0171e9517f40e41\\\"\";\n\n System.out.println(parse(test1));\n System.out.println(parseSM(test1));\n System.out.println(parseScanner(test1));\n System.out.println(parse(test2));\n System.out.println(parseSM(test2));\n System.out.println(parseScanner(test2));\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T04:33:11.303",
"Id": "71048",
"Score": "0",
"body": "I was trying (perhaps too hard) to conform to the RFCs. I took a quick look at your code and your examples accept having no commas between pairs, and they don't accept backslash-escaped characters inside quoted strings. Nevertheless, I found them instructive."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T19:19:53.280",
"Id": "41293",
"ParentId": "41270",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "41293",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T05:20:34.973",
"Id": "41270",
"Score": "7",
"Tags": [
"java",
"parsing",
"regex",
"http"
],
"Title": "HTTP Authorization header parser"
}
|
41270
|
<p>My boss needs me to embed the MD5 digest in a file path, but the problem is MD5 contains escape characters.</p>
<p>I've already taught about a <code>uc%duc%d...</code> format, but it also makes lengthy file names. In Linux it's not a problem since the Linux kernel could handle them.</p>
<pre><code>char * uc_encode_md5(const char * password)
{
char digest_output[1024];
MD5_CTX md5_ctx ;
MD5_Init(&md5_ctx);
MD5_Update(&md5_ctx,password,strlen(password));
MD5_Final((unsigned char*) digest_output,&md5_ctx);
char* ret = (char*) malloc(500);
int len=0;
int i ;
for(i=0;i<16;i++)
{
len+= sprintf(&ret[len],"uc%d",(unsigned char)digest_output[i]);
}
return ret;
}
</code></pre>
<p>Any better way than this? Since my just boss shared what to do, but not how to do it: what's the best practice here?</p>
<p>How about <code>#ifdef</code>'s? I could suggest more formats on here and let him choose when I get back to him later tonight.</p>
<p>For example:</p>
<pre><code>char * uc_encode_md5(const char * password)
{
#ifdef _UC_PATH_ENCODE_
char digest_output[1024];
MD5_CTX md5_ctx ;
MD5_Init(&md5_ctx);
MD5_Update(&md5_ctx,password,strlen(password));
MD5_Final((unsigned char*) digest_output,&md5_ctx);
char* ret = (char*) malloc(500);
int len=0;
int i ;
for(i=0;i<16;i++)
{
len+= sprintf(&ret[len],"uc%d",(unsigned char)digest_output[i]);
}
#endif /* endif _UC_PATH_ENCODE_ */
return ret;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T18:09:23.043",
"Id": "70864",
"Score": "0",
"body": "MD5 is a number. Convert the number into a string that is the ASCII representation of the number. Note: Usually this is done as hex number. If you make sure it is 0 padded it should always be 32 characters long (for 128 bit MD5). As each 8 bits is converted into two hex digits."
}
] |
[
{
"body": "<p>MD5 is simply a 128 bit number.</p>\n\n<p>Convert the number into a string that is the ASCII representation of the number. Note: Usually this is done as hex number. If you make sure it is 0 padded it will be 32 characters long (as each 8 bits is converted into two hex digits). </p>\n\n<p>This is how I would do it:</p>\n\n<pre><code>static_assert(sizeof(int) == 4, \"Figure it out with other sizes\");\n\nint* data = reinterpret_cast<int*>(ret);\nint len = 128 / (sizeof(int) * 8);\n\nfor(int i=len-1; i >= 0; --i)\n{\n std::cout << std::setfill('0') << std::setw(8) << std::hex << data[i];\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T02:11:36.620",
"Id": "70885",
"Score": "1",
"body": "`static_assert` is a keyword, and isn't in `std`. Also, you probably meant `sizeof(int) == 4`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T14:38:26.440",
"Id": "70949",
"Score": "1",
"body": "I'd avoid this code since it's endian and int size dependent. I'd rather iterate byte wise."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T20:34:27.740",
"Id": "71004",
"Score": "1",
"body": "@CodesInChaos: Yes there is definitely an issue with endianess of the int. The reason I did not care in this situation was it was only being used to generate a filename. This suggests they are using the filename to distribute the data files evenly across a distributed filesystem. If it is not being used for validation the actual order is not that important. If it is being used for validation then you should be more careful. But you can also provide your own answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T18:22:01.863",
"Id": "41292",
"ParentId": "41272",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T05:52:24.470",
"Id": "41272",
"Score": "7",
"Tags": [
"c",
"cryptography"
],
"Title": "Embed MD5 digest in a directory path name"
}
|
41272
|
<p>I am new to linq to objects in C#. I have the following query which works adequately. Is there someway to reduce or rewrite this query using joins or something else? </p>
<pre><code>var query =
from container in containers
let items = container.GetItems()
from itemA in items
let tag = CreateTag(itemA)
where IsInteresting(tag)
from itemB in items
let derivedTag = CreateDerivedTag(tag)
where CreateTag(itemB) == derivedTag
select new { first = itemA, second = itemB };
</code></pre>
<p>To summarize, </p>
<ul>
<li>there are a set of item sequences</li>
<li><p>for each item sequench </p>
<ul>
<li>for each item <strong><em>A</em></strong> that is IsInteresting()
<ul>
<li>find an item B in the <strong>same sequence</strong> that matches based on the criteria derived from the item A</li>
<li>create a new item containing a reference to matching items <strong><em>A</em></strong> and <strong><em>B</em></strong></li>
</ul></li>
</ul></li>
<li><p>return a collection of all such matching items </p></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T00:01:09.170",
"Id": "70883",
"Score": "3",
"body": "It looks like [join](http://code.msdn.microsoft.com/LINQ-Join-Operators-dabef4e9) might be possible. It might be easier to answer this question if you posted a complete program: e.g. definitions of CreateTag, CreateDerivedTag, IsInteresting, GetItems, together with some sample data in containers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-10T16:24:23.783",
"Id": "70970",
"Score": "0",
"body": "I tried answering this in lambda syntax, but this query is awfully strange. The final select and where are really hard to convert, the way I was doing it. Someone else can probably do a far better job."
}
] |
[
{
"body": "<p>After a <em>lot</em> of setup, I arrived at this:</p>\n\n<pre><code>var extensionMethodQuery =\n from container in containers\n let items = container.GetItems()\n select items.GetItemDerivedTagItems\n (items.SelectInterestingItemTags()).FirstOrDefault();\n</code></pre>\n\n<p>Your original query looks pretty optimal, but it took a while to see why. I broke it down into its component parts, and concluded that I'd concentrate on making it more reusable and readable. Personally, I find lambda joins too verbose, so created two extension methods instead:</p>\n\n<pre><code>public static class Filters\n{\n public static IEnumerable<ItemTag> SelectInterestingItemTags\n (this IEnumerable<Item> items)\n {\n return\n from item in items\n let tag = Tag.CreateTag(item)\n where Tag.IsInteresting(tag)\n select new ItemTag(item, tag);\n }\n\n public static IEnumerable<ItemDerivedTagItem>\n GetItemDerivedTagItems\n (this IEnumerable<Item> items, IEnumerable<ItemTag> itemTags)\n {\n return\n from itemTag in itemTags\n from item in items\n let derivedTag = Tag.CreateDerivedTag(itemTag.tag)\n where Tag.CreateTag(item) == derivedTag\n select new ItemDerivedTagItem(itemTag.item, item);\n\n }\n}\n</code></pre>\n\n<p>You'll notice I needed to create two extra classes to enable this, <code>ItemTag</code> and <code>ItemDerivedTagItem</code>, that replace the anonymous classes. Those names are probably awful, but not knowing the context, I did the best I could. The <code>IsInteresting</code> and <code>CreateDerivedTag</code> methods were made static member methods of their classes, too. The results were compared successfully via unit tests, against my dummy classes and dummy data, so hopefully you can verify that with yours.</p>\n\n<p>As ever, the proof is in the profiling, and for me at least, the extension method query is 4 times faster. I can supply the dummy classes and data I used if needed, but as mentioned in the comments, I'd much prefer those supplied next time please!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-14T00:00:57.223",
"Id": "41600",
"ParentId": "41273",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "41600",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T06:14:39.107",
"Id": "41273",
"Score": "8",
"Tags": [
"c#",
"linq"
],
"Title": "Reduce or improve Linq query with nested from-where clauses"
}
|
41273
|
<p>Requesting code review, best practices, optimizations for this solution to the <a href="http://en.wikipedia.org/wiki/Tower_of_Hanoi" rel="nofollow">Tower of Hanoi problem</a>.</p>
<pre><code>final class PlatePair {
private final String source;
private final String destination;
public PlatePair (String source, String destination) {
this.source = source;
this.destination = destination;
}
public String getSource() {
return source;
}
public String getDestination() {
return destination;
}
}
public final class ToweOfHanoi {
private ToweOfHanoi () { }
/**
* Solves the problem of tower of hanoi
*
* @param n The number of plates
* @return The Set of sequential steps to take to solve the hanoi problem.
*/
public static Set<PlatePair> solve(int n) {
if (n <= 0) throw new IllegalArgumentException("The number of plates " + n + " should be greater than zero.");
final Set<PlatePair> platePair = new LinkedHashSet<PlatePair>();
moveTowers(n, "A", "B", "C", platePair);
return platePair;
}
public static void moveTowers(int n, String from, String using, String to, Set<PlatePair> platePair) {
assert platePair != null;
if (n == 0) return;
moveTowers(n - 1, from, to, using, platePair);
platePair.add(new PlatePair(from, to));
moveTowers(n - 1, using, from, to, platePair);
}
public static void main(String[] args) {
for (PlatePair getHanoi : solve(3)) {
System.out.println(getHanoi.getSource() + " : " + getHanoi.getDestination());
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T13:59:58.153",
"Id": "70838",
"Score": "0",
"body": "I love towers of Hanoi :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T15:07:12.687",
"Id": "70842",
"Score": "1",
"body": "Downvoting because of the lack of documentation of how your algorithm really works, which doesn't make it easy for the reviewers."
}
] |
[
{
"body": "<p>While your solution appears to work, and I cannot see any bugs, there are a number of best-practices that you are not employing in your solution. It is alsmost as if your code works by coincidence, rather than by design. There are a number of things that look like desperate attempts to make it work... and, like duct-tape, they work, but they are not pretty.</p>\n\n<h2>General</h2>\n\n<p>You have not described your algorithm in any detail. You have two recursive calls in your recursive method, and you have no documentation as to why. Recursion, in general, is relatively complex to understand, and can be unintuitive. You should help the person reading your code to understand.... and you do nothing. I had to debug the code to watch it happen to understand why you do things the way you do. This is not fair.</p>\n\n<h2>Naming conventions</h2>\n\n<p>Your <code>Set<PlatePair></code> is called <code>platePair</code>. At minimum the variable name should be a plural, because, as it stands, it makes sense that <code>platePair</code> is a single <code>PlatePair</code>, and not a <code>Set<PlatePair></code>. My preference would be 'moves' which indicates what the data represents</p>\n\n<p>Oh, your class is called <code>ToweOfHanoi</code>, but should contain an 'r' as in <code>TowerOfHanoi</code></p>\n\n<h2>Collections</h2>\n\n<p>Speaking of <code>Set<PlatePair></code> ... really? Your actual implementation of the <code>Set<PlatePair></code> is a <code>LinkedHashSet</code>. The LinkedHashSet will iterate the results in the same order they were inserted, which is why this solution actually works, but, you <strong>do not expose that property</strong> of the LinkedHashSet to the calling functions. There is nothing stopping a user from calling:</p>\n\n<pre><code>Set<PlatePair> result = new HashSet<>();\nmoveTowers(4, \"A\", \"B\", \"C\", result);\n</code></pre>\n\n<p>and this would produce crap results.</p>\n\n<p>Frankly, you should not be using a set at all. You should be using a List.... because that is what it is, a List of moves to make.</p>\n\n<p><em><strong>This is your duct tape</em></strong> <code>LinkedHashSet</code> is a desperate solution to trying to bring order to a data collection that is designed to maintain unique contents (a Set) rather than an ordered collection of non-unique data (a List). Your moves are not unique... you often move a tile from tower <code>A</code> to tower <code>C</code>.... but, you use the the HashSet with unique move instances (instead of the neater move-reuse mechanism).</p>\n\n<p>A more immediate solution is to change the <code>moveTower</code> from being a public method to being a private method, which you should do anyway. There is no need for it to be public. Making it private would also affect the <code>assert</code> in the method.... you assert that the platePair instance is not null, but you do not check the from/using/to instances. That is careless. If you are going to assert, then do it comprehensively. In this case, if the method is changed to be private, I would simply remove the asserts, and move on.... you do trust your own code, right?</p>\n\n<h2>PlatePair</h2>\n\n<p>Which comes down to the next problem, The PlatePair class. This class should have a number of differences. Firstly, the values should not be Strings, they should be an ENUM, one member for each tower.</p>\n\n<pre><code>public enum Tower {\n A, B, C;\n}\n\npublic class PlatePair {\n private final Tower source, destination;\n\n public PlatePair(Tower source, Tower destination) {\n this.source = source;\n this.destination = destination;\n }\n\n public Tower getSource() {...}\n public Tower getDestination() {...}\n\n}\n</code></pre>\n\n<p>I would also strongly encourage you to avoid creating so many <code>PlatePair</code> instances.... there are only 6 possible moves that can be made... each Tower can only be the source/destination of 2 possible moves. You should only have 6 PlatePair instances, and they should be immutable, and have good <code>hashCode()</code> and <code>equals()</code> methods.</p>\n\n<p>Also, I don't like the class name <code>PlatePair</code>. It is not a pair of Plates, it is an ordered pair of Towers... a source, and a destination. I would rename it something like <code>Transfer</code>.</p>\n\n<h2>Conclusion</h2>\n\n<p>The code works, and gets the right answers. It does not read very well, and there are a few <em>gotcha's</em> in the code which mean you have to dig in to the code and understand the 'tricks' you are playing. The documentation/comments are really poor, and this code would fail any formal review in any sane business.</p>\n\n<p>I have taken your code, and restructured it using the ideas I have shown above. This is closer to something that I would consider readable. Note, I have not changed the algorithm at all:</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.EnumMap;\nimport java.util.List;\n\nenum Tower {\n A, B, C;\n\n\n static {\n\n // make each tower know what moves are possible from that tower.\n // tower A can have a transfer to towers B, and C.\n // tower B can have a transfer to towers A, and C.\n // tower C can have a transfer to towers A, and B.\n // these 2 transfers per tower are available through the getMove(destination)\n // method for each tower.\n A.setupTransfers(B, C);\n B.setupTransfers(A, C);\n C.setupTransfers(A, B);\n\n }\n\n private EnumMap<Tower, Transfer> destinations = null;\n\n private void setupTransfers(Tower one, Tower two) {\n destinations = new EnumMap<Tower, Transfer>(Tower.class);\n destinations.put(one, new Transfer(this, one));\n destinations.put(two, new Transfer(this, two));\n }\n\n public Transfer getMove(Tower destination) {\n return destinations.get(destination);\n }\n}\n\nfinal class Transfer {\n\n private final Tower source;\n private final Tower destination;\n\n public Transfer(Tower source, Tower destination) {\n this.source = source;\n this.destination = destination;\n }\n\n public Tower getSource() {\n return source;\n }\n\n public Tower getDestination() {\n return destination;\n }\n\n @Override\n public int hashCode() {\n return (31 * source.hashCode()) ^ destination.hashCode();\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj == this) {\n return true;\n }\n if (obj instanceof Transfer) {\n return ((Transfer) obj).source == source\n && ((Transfer) obj).destination == destination;\n }\n return false;\n }\n}\n\npublic final class TowerOfHanoi {\n\n private TowerOfHanoi() {\n }\n\n /**\n * Solves the Tower of Hanoi problem\n * \n * @param n\n * The number of plates on the starting tower\n * @return The sequential steps required to solve the problem.\n */\n public static List<Transfer> solve(int n) {\n if (n <= 0)\n throw new IllegalArgumentException(\"The number of plates \" + n\n + \" should be greater than zero.\");\n\n final List<Transfer> moves = new ArrayList<Transfer>();\n moveTowers(n, Tower.A, Tower.B, Tower.C, moves);\n return moves;\n }\n\n private static void moveTowers(int n, Tower from, Tower using, Tower to,\n List<Transfer> moves) {\n\n if (n == 0) {\n return;\n }\n\n // algorithm is:\n // we want to move the 'bottom' tile from the 'from' tower to the 'to'\n // tower.\n // we move everything on top of it to the 'using' tower\n // then we move the tile to the to tower,\n // then we move the things from the using tower back on top of the tile\n // we moved.\n\n // temporarily move everything on top to the using tower.\n moveTowers(n - 1, from, to, using, moves);\n // move the actual tile.\n moves.add(from.getMove(to));\n // move the temp stuff back on to the tile we just moved.\n moveTowers(n - 1, using, from, to, moves);\n }\n\n public static void main(String[] args) {\n for (final Transfer getHanoi : solve(4)) {\n System.out.println(getHanoi.getSource() + \" : \"\n + getHanoi.getDestination());\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T17:04:21.957",
"Id": "70856",
"Score": "1",
"body": "What are you doing in `static` block of `Tower` enum, I couldn't understand. Specially *why* are you doing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T17:53:26.340",
"Id": "70861",
"Score": "0",
"body": "@tintinmj - I am making a data structure in each tower that allows the method `public Transfer getMove(Tower destination)` to work. - it should have comments. Will fix"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T18:19:07.003",
"Id": "70866",
"Score": "0",
"body": "Ok got it. Confusing yet interesting! :D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T06:39:25.653",
"Id": "71218",
"Score": "0",
"body": "@rolfl was there any reason you chose static block in enum over constructor ? thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-12T11:12:30.027",
"Id": "71253",
"Score": "0",
"body": "Yes, there is. In order to create an EnumMap, you need to supply it with an Enum class `Tower.class`. The `Tower.class` is not fully initialized when the enum members `A`, `B`, and `C` are constructed, and thus the code will fail to create the EnumMap if you put the code in the `A` constructor, etc."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T14:55:17.470",
"Id": "41287",
"ParentId": "41275",
"Score": "13"
}
}
] |
{
"AcceptedAnswerId": "41287",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-09T06:26:29.107",
"Id": "41275",
"Score": "7",
"Tags": [
"java",
"algorithm",
"game",
"recursion",
"tower-of-hanoi"
],
"Title": "Tower of Hanoi solver"
}
|
41275
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.