body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>Can you please review the following code and give any suggestions for improvment?</p> <p>Class ContactList.java</p> <pre><code>import java.io.*; import java.util.*; public class ContactList { public static void main(String args[]) throws IOException { Contact contact; contact = new Contact(); int action = 0; ArrayList&lt;Contact&gt; contacts = new ArrayList&lt;Contact&gt;(); while (action != 6) { System.out.println("\nWelcome to Contact List DB. " + "What would you like to do? \n"); System.out.println("1. Enter a new person" + "\n" + "2. Print the contact list" + "\n" + "3. Retrieve a person's information by last name" + "\n" + "4. Retrieve a person's information by email address" + "\n" + "5. Retrieve all people who live in a given zip code" + "\n" + "6. Exit"); Scanner reader = new Scanner(System.in); reader.useDelimiter("\n"); action = reader.nextInt(); if (action &lt;= 0 || action &gt; 6) { System.out.println("Invalid selection. "); } switch (action) { case 1: { System.out.println("\nEnter Contact Last Name:"); String lastname = reader.next(); if (lastname == null) { System.out.println("\nInvalid entry. "); break; } else { contact.setLastName(lastname.toLowerCase()); } System.out.println("Enter Contact First Name: "); String firstname = reader.next(); contact.setFirstName(firstname.toLowerCase()); System.out.println("Enter Contact Street Address: "); String address = reader.next(); contact.setHouseAddress(address.toLowerCase()); System.out.println("Enter Contact City: "); String city = reader.next(); contact.setCity(city.toLowerCase()); System.out.println("Enter Contact Zip Code: "); String zip = reader.next(); contact.setZip(zip.toLowerCase()); System.out.println("Enter Contact Email: "); String email = reader.next(); contact.setEmail(email.toLowerCase()); System.out.println("Enter Contact Phone Number: "); String phone = reader.next(); contact.setPhone(phone.toLowerCase()); System.out.println("Enter Contact Notes: "); String notes = reader.next(); contact.setNotes(notes.toLowerCase()); contacts.add(contact); try { Contact c = contact; File file = new File("contactlist.csv"); // If file doesn't exists, then create it. if (!file.exists()) { file.createNewFile(); } try (PrintWriter output = new PrintWriter(new FileWriter( "contactlist.csv", true))) { output.printf("%s\r\n", c); } catch (Exception e) { } System.out.println("Your contact has been saved."); } catch (IOException e) { e.printStackTrace(); } } break; case 2: { int counter = 0; String line = null; // Location of file to read File file = new File("contactlist.csv"); // Sort contacts and print to console try { Scanner scanner = new Scanner(file); // Before printing, add each line to a sorted set. by Seth // Copeland Set&lt;String&gt; lines = new TreeSet&lt;&gt;(); while (scanner.hasNextLine()) { line = scanner.nextLine(); lines.add(line); counter++; } // Print sorted contacts to console. for (String fileLine : lines) { String outlook = fileLine.substring(0, 1).toUpperCase() + fileLine.substring(1); System.out.println(outlook); } scanner.close(); } catch (FileNotFoundException e) { } System.out.println("\n" + counter + " contacts in records."); } break; case 3: try { System.out.println("\nEnter the last" + "name to search for: "); String searchterm = reader.next(); // Open the file as a buffered reader BufferedReader bf = new BufferedReader(new FileReader( "contactlist.csv")); // Start a line count and declare a string to hold our // current line. int linecount = 0; String line; // Let the user know what we are searching for System.out.println("Searching for " + searchterm + " in file..."); // Loop through each line, putting the line into our line // variable. boolean noMatches = true; while ((line = bf.readLine()) != null) { // Increment the count and find the index of the word. linecount++; int indexfound = line.indexOf(searchterm.toLowerCase()); // If greater than -1, means we found a match. if (indexfound &gt; -1) { System.out.println("\nContact was FOUND\n" + "\nContact " + linecount + ": " + line); noMatches = false; } } // Close the file after done searching bf.close(); if (noMatches) { System.out.println("\nNO MATCH FOUND.\n"); } } catch (IOException e) { System.out.println("IO Error Occurred: " + e.toString()); } break; case 4: try { System.out.println("\nEnter the email " + "address to search for: "); String searchterm = reader.next(); // Open the file as a buffered reader BufferedReader bf = new BufferedReader(new FileReader( "contactlist.csv")); // Start a line count and declare a string to hold our // current line. int linecount = 0; String line; // Let the user know what we are searching for System.out.println("\nSearching for " + searchterm + " in file..."); // Loop through each line, put the line into our line // variable. boolean noMatches = true; while ((line = bf.readLine()) != null) { // Increment the count and find the index of the word linecount++; int indexfound = line.indexOf(searchterm.toLowerCase()); // If greater than -1, means we found a match if (indexfound &gt; -1) { System.out.println("\nContact was FOUND\n" + "\nContact " + linecount + ": " + line); noMatches = false; } } // Close the file after done searching bf.close(); if (noMatches) { System.out.println("\nNO MATCH FOUND.\n"); } } catch (IOException e) { System.out.println("IO Error Occurred: " + e.toString()); } break; case 5: try { System.out.println("\nEnter the Zipcode to search for: "); String searchterm = reader.next(); // Open the file as a buffered reader BufferedReader bf = new BufferedReader(new FileReader( "contactlist.csv")); // Start a line count and declare a string to hold our // current line. int linecount = 0; String line; // Let the user know what we are searching for System.out.println("\nSearching for " + searchterm + " in file..."); // Loop through each line, stashing the line into our line // variable. boolean noMatches = true; while ((line = bf.readLine()) != null) { // Increment the count and find the index of the word. linecount++; int indexfound = line.indexOf(searchterm.toLowerCase()); // If greater than -1, means we found a match. if (indexfound &gt; -1) { System.out.println("\nContact was FOUND\n" + "\nContact " + linecount + ": " + line); noMatches = false; } } // Close the file after done searching bf.close(); if (noMatches) { System.out.println("\nNO MATCH FOUND.\n"); } } catch (IOException e) { System.out.println("IO Error Occurred: " + e.toString()); } break; } } } } </code></pre> <p>And here's Contact.java</p> <pre><code> import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class Contact { private String lastname, firstname, address, city, zip, email, phone, notes; public Contact(String lastnamename, String firstname, String address, String city, String zip, String email, String phone, String notes, String lastname) { this.lastname = lastname; this.firstname = firstname; this.address = address; this.city = city; this.zip = zip; this.email = email; this.phone = phone; this.notes = notes; } public Contact() { } // overrides the default Object method public String toString() { return lastname + ", " + firstname + ", " + address + ", " + city + ", " + zip + ", " + email + ", " + phone + ", " + notes; } /* * Sets the value for lastname to "s". */ public void setLastName(String s) { lastname = s; } /* * Returns the value of lastname. */ public String getLastName() { return lastname; } /* * Sets the value for firstname to "a". */ public void setFirstName(String a) { firstname = a; } /* * Returns the value of firstname. */ public String getFirstName() { return firstname; } /* * Sets the value for address to "b". */ public void setHouseAddress(String b) { address = b; } /* * Returns the value of address. */ public String getHouseAdress() { return address; } /* * Sets the value for city to "c". */ public void setCity(String c) { city = c; } /* * Returns the value of city. */ public String getCity() { return city; } /* * Sets the value for zip to "d". */ public void setZip(String d) { zip = d; } /* * Returns the value of zip. */ public String getZip() { return zip; } /* * Sets the value for phone to "e". */ public void setPhone(String e) { phone = e; } /* * Returns the value of phone. */ public String getPhone() { return phone; } /* * Sets the value for email to "f". */ public void setEmail(String f) { email = f; } /* * Returns the value of email. */ public String getEmail() { return email; } /* * Sets the value for notes to "g". */ public void setNotes(String g) { notes = g; } /* * Returns the value of notes. */ public String getNotes() { return notes; } public void read() { } static void write() { // Writes contact info to file. -Damani // ---------------------------------------------------------- try { Contact contact; contact = new Contact(); Contact c = contact; File file = new File("contactlist.csv"); // If file doesn't exists, then create it. if (!file.exists()) { file.createNewFile(); } try (PrintWriter output = new PrintWriter(new FileWriter( "contactlist.csv", true))) { output.printf("%s\r\n", c); } catch (Exception e) { } System.out.println("Your contact has been saved."); } catch (IOException e) { e.printStackTrace(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T15:30:20.873", "Id": "36684", "Score": "0", "body": "A first glance : in this case I replace the `switch` by a `Observable/Observer` patten, loosely coupled and evolutive" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T16:02:37.773", "Id": "36685", "Score": "1", "body": "Please give your question a meaningful title and also provide with an explanation of what your code, how it works and why it does work the way it does." } ]
[ { "body": "<p>The first thing I would suggest is to replace your magic numbers with meaningful constants:</p>\n\n<pre><code>private static final int NEW_PERSON_ACTION = 1;\nprivate static final int PRINT_PERSON_ACTION = 2;\nprivate static final int SEARCH_LAST_NAME_ACTION = 3;\n//etc...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T15:37:40.357", "Id": "23794", "ParentId": "23793", "Score": "1" } }, { "body": "<p>You can also reduce this (occurred multiple times)</p>\n\n<pre><code>String firstname = reader.next();\ncontact.setFirstName(firstname.toLowerCase());\n</code></pre>\n\n<p>with this</p>\n\n<pre><code>contact.setFirstName(reader.next().toLowerCase());\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T02:54:23.810", "Id": "36810", "Score": "0", "body": "Your code was very helpful as well!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T16:08:55.203", "Id": "23796", "ParentId": "23793", "Score": "2" } }, { "body": "<p>The function you wrote is too long, and handles too many concerns. I would separate it out into either other functions, classes, or preferably, a combination of both.</p>\n\n<p>Comments are overused. Comments should be used to enhance the code, i.e. add an explanation <strong>why</strong> something was done a certain way. They should not describe <strong>what</strong> is being done. If you have to use comments, the section of code is probably better off in a function with a descriptive name.</p>\n\n<p>You don't need to instantiate a new Contact early in your main function. That should be done just before it is needed (like where you create a new contact);</p>\n\n<p>The actions should be put into an enum:</p>\n\n<pre><code>public enum MainMenuAction {\n AddContact,\n PrintContactList,\n FindPersonByLastName,\n FindPersonByEmail,\n SearchByZipCode,\n Quit,\n UnknownCommand\n} \n</code></pre>\n\n<p>I would move the file operations into their own class, using something like a repository pattern. In fact, the <code>ArrayList&lt;Contact&gt;</code> should be put in this class too.</p>\n\n<p>Create a class to handle the main loop, something like</p>\n\n<pre><code>public class ApplicationRunner {\n\n private Scanner reader;\n\n public ApplicationRunner(Scanner reader) {\n\n this.reader = reader;\n }\n\n public void run() {\n\n MainMenuAction action;\n while (action = readAction() != MainMenuAction.Quit) {\n\n switch(action) {\n\n case MainMenuAction.AddContact:\n addAContact();\n break;\n case MainMenuAction.PrintContactList:\n printContactList();\n break;\n // Code the rest of the actions here\n case MainMenuAction.UnknownCommand:\n System.out.println(\"Invalid selection. \");\n break;\n }\n }\n }\n\n private MainMenuAction readAction() {\n\n System.out.println(\"1. Enter a new person\" + \"\\n\"\n + \"2. Print the contact list\" + \"\\n\"\n + \"3. Retrieve a person's information by last name\" + \"\\n\"\n + \"4. Retrieve a person's information by email address\" + \"\\n\"\n + \"5. Retrieve all people who live in a given zip code\" + \"\\n\" \n + \"6. Exit\");\n\n int action = reader.nextInt();\n\n // This might be able to be done more efficiently, I'm not that versed in\n // java syntax.\n switch (action) {\n case 1:\n return MainMenuAction.AddContact;\n // Add rest here\n default:\n return MainMenuAction.UnknownCommand;\n }\n}\n</code></pre>\n\n<p>You have created a Constructor for Contact that takes all of the required values, why not use it. Read all the values into variables (or a Map), then at the end, create the contact with what's there. Data validation should be done in your Contact class, this will ensure invalid data will never appear in it. </p>\n\n<p>The reading of the attributes could be encapsulated into a class:</p>\n\n<pre><code>public class ConsoleContactReader {\n\n private Scanner reader;\n private Map&lt;string, string&gt; enteredValues;\n\n public ConsoleReader(Scanner reader) {\n\n this.reader = reader;\n enteredValues = new Map&lt;string, string&gt;();\n }\n\n public void readConsole(string prompt, string fieldName) {\n\n System.out.printl(prompt);\n enteredValues.put(fieldName, reader.next());\n }\n\n public Contact createContactFromMap() {\n\n return new Contact(\n this.enteredValues.get(\"lastName\"),\n this.enteredValues.get(\"firstName\"),\n // etc...\n );\n }\n</code></pre>\n\n<p>In the addAContact function:</p>\n\n<pre><code> public void addAContact()\n {\n ConsoleContactReader contactReader = new ConsoleContactReader(this.reader);\n\n contactReader.readConsole(\"Enter Contact Last Name: \", \"lastName\");\n contactReader.readConsole(\"Enter Contact First Name: \", \"firstName\");\n // continue with logic\n\n Contact newContact = contactReader.createContactFromMap();\n this.repository.Add(newContact);\n }\n</code></pre>\n\n<p>Add a repository that will deal with the reading/writing and searching of contacts</p>\n\n<pre><code>public class ContactRepository {\n\n private ArrayList&lt;Contact&gt; contacts;\n private ContactFileOperation fileOperations;\n\n public ContactRepository(ContactFileOperation fileOperations) {\n\n this.fileOperations = fileOperations;\n\n this.contacts = new ArrayList&lt;Contact&gt;();\n }\n\n public void addAContact(Contact contact)\n {\n contacts.add(contact);\n fileOperations.save(contact);\n }\n\n // Implement other operations here\n\n}\n</code></pre>\n\n<p>Add a ContactFileOperationsClass which contains all your file read/write logic</p>\n\n<pre><code>public class ContactFileOperation {\n\n private string path;\n\n public ContactFileOperation(string path) {\n\n this.path = path;\n\n createFileIfRequired();\n }\n\n private File createFileIfRequired() {\n\n File file = new File(this.path);\n\n if (!file.exists()) {\n file.createNewFile();\n }\n }\n\n private PrintWriter createPrintWriter() {\n\n return new PrintWriter(new FileWriter(this.Path, true))\n }\n\n public save(Contact contact) {\n\n try (PrintWriter output createPrintWriter()) {\n output.printf(\"%s\\r\\n\", c);\n } catch (Exception e) {\n // NEED TO DO SOMETHING WITH THIS EXCEPTION OR IT WILL SLIP AWAY UNNOTICED\n }\n }\n}\n</code></pre>\n\n<p>Your main function could now be something like:</p>\n\n<pre><code>public class ContactList {\n\n public static void main(String args[]) throws IOException {\n\n Scanner reader = new Scanner(System.in);\n reader.useDelimiter(\"\\n\");\n\n ApplicationRunner runner = new ApplicationRunner(reader);\n\n runner.run;\n}\n</code></pre>\n\n<p>This isn't perfect, but there should be enough here to start with. You should be able to take what I've suggested and apply it to the rest of your code.</p>\n\n<p>You'll have to excuse me if I have some syntax incorrect, I don't have a compiler, and I don't work with Java that often currently.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T21:26:28.790", "Id": "36704", "Score": "0", "body": "Thanks again Jeff! This will help me improve my code and make it more efficient!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T17:27:59.977", "Id": "23800", "ParentId": "23793", "Score": "5" } }, { "body": "<p>ContactList should be what it says it is - something meaningfully related to a list of contacts. </p>\n\n<p>It should probably have these methods to:<br/>\n-addContact()<br/>\n-removeContact()<br/>\n-numContacts()<br />\n-containsLastName()<br/>\n-replaceContact(old, new)<br/>\n-getContact(lastName)<br/>\n-getAllContacts()<br/></p>\n\n<p>Contact has that static method write but it's actually useless (it doesn't do anything- it just creates an empty contact and prints it...) and a bad idea to put it there anyway. You don't want to put File I/O in random spots in your code. Also you don't need comments on your get/set methods, they don't do anything more then their name says. Use comments to illustrate the broad scope of your code, or to explain how a confusing part works.</p>\n\n<p>The main method could be better suited in some method such as ContactHarness and basically put all the parts of your code that aren't related to ContactList or Contact in there. That would be your application loop and your file i/o. </p>\n\n<p>Enums are an improvement over 'private static final int' but in this case, I'd probably just use final ints because it's really simple. These constants would be declared in your ContactHarness/whatever had your loop. You want to avoid 'magic numbers', or numbers that have special meanings in your program, and replace them with appropriately named variables. </p>\n\n<p>I'd replace lines like<br/>\nline = scanner.nextLine()<br/>\nlines.add(line)<br/>\nwith lines.add(scanner.nextLine())<br/></p>\n\n<p>But beyond that I can't understand what your program is trying to do. I mean I kind of do, but I don't know why it does it that way. Why are you constantly reading to/from a file? You declare a list of in a class called ContactList which made me assume you want to use a list of contacts somewhere but you never use the list of contacts. There are reasons not to read the entire contact list into memory immediately (just like there are reasons to use databases as well), but for a beginner project I don't see why you wouldn't read your .csv file in at the start of the program, modify the List you have while the program is running, and finally have an option to export the current list as .csv or something like that. </p>\n\n<p>For instance, your PRINT_LIST option doesn't even involve contacts, all it does is print lines from a file in alphabetical order. </p>\n\n<p>The way you have it now, I don't even know why you have a Contact class - you only use it once. You basically just modify a .csv file a bunch of times. There's no behavior or state associated with your Contact class really. There are a bunch of style things I'd change up in your main class but I can't get over that you never use Contact/ContactList really has nothing to with a List of Contacts. Work on those general ideas first. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T14:59:17.123", "Id": "36759", "Score": "0", "body": "I'm constantly reading to and from a file because I wanted the user to always be able to I guess access the database? All the methods require to read from file correct? To search a contact do I have to read from the existing contacts file? To print existing contacts do I have to read from file? Unless their is another way? Also the print list, I wanted it to print all \"existing\" contacts in alphabetical order by last name. I just wanted to create and modify a contact list. Is that not the purpose of a contact list? create and modify records? I'm no sure what you are trying to say." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T14:06:44.077", "Id": "23846", "ParentId": "23793", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T15:23:16.917", "Id": "23793", "Score": "5", "Tags": [ "java" ], "Title": "Command line Contact Management" }
23793
<p>For my simple Android application, I don't want to use an ORM. I'd like to have a db-communcation layer easy to user, to read and efficient.</p> <p>This is my solution: every entity (ex: Person) as an helper that do the CRUD functions (ex: PersonHelper). The helper extends another class (EntityHelper), that contains the logic not related to the specific entity.</p> <p>This is the code for the EntityHelper:</p> <pre><code>package com.dw.android.db; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import com.dw.android.db.model.Entity; /** * Helper base class used to do CRUD operations * * @param &lt;T&gt; Managed entity class * @author atancredi */ public abstract class EntityHelper&lt;T extends Entity&gt; { protected final SQLiteOpenHelper dbHelper; public EntityHelper(SQLiteOpenHelper dbHelper) { this.dbHelper = dbHelper; } /** * Load a record from database * * @param id Entity id * @return The entity list loaded from entity table */ public T get(long id) { T retv = null; // SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = null; try { SQLiteQueryBuilder qb= new SQLiteQueryBuilder(); qb.setTables(getTable()); cursor = qb.query(db, getColumns(), "_id = ?", new String[]{ String.valueOf(id) }, null, null, null); if(cursor.moveToFirst()) { retv = bind(cursor); } } finally { if(cursor != null) { cursor.close(); } db.close(); } // return retv; } /** * Load all record from database * @return The entity list loaded from entity table */ public List&lt;T&gt; all() { List&lt;T&gt; retv = new ArrayList&lt;T&gt;(); // SQLiteDatabase db = dbHelper.getReadableDatabase(); SQLiteQueryBuilder qb= new SQLiteQueryBuilder(); qb.setTables(getTable()); Cursor cursor = null; try { cursor = qb.query(db, getColumns(), null, null, null, null, null); if(cursor.moveToFirst()) { do { retv.add(bind(cursor)); } while(cursor.moveToNext()); } } finally { if(cursor != null) { cursor.close(); } db.close(); } // return retv; } /** * Update an entity on DB using his id as selection * * @param entity Entity to update * @return true, if a row has been update */ public boolean update(T entity) { SQLiteDatabase db = dbHelper.getWritableDatabase(); boolean updated = true; try { db.beginTransaction(); int count = db.update(getTable(), bind(entity), "_id = ?", new String[]{ String.valueOf(entity.getId()) }); updated = count &gt; 0; db.setTransactionSuccessful(); } finally { db.endTransaction(); db.close(); } return updated; } /** * Insert an entity on the DB * * @param entity Entity to insert * @return The DB generated id for the entity */ public long insert(T entity) { SQLiteDatabase db = dbHelper.getWritableDatabase(); long retv = -1; try { db.beginTransaction(); retv = db.insert(getTable(), null, bind(entity)); db.setTransactionSuccessful(); if(retv &gt;= 0) { entity.setId(retv); } } finally { db.endTransaction(); db.close(); } return retv; } /** * Delete an entity * @param id Entity id * @return true, if the entity was in the DB */ public boolean delete(T entity) { return delete(entity.getId()); } /** * Delete an entity * @param id Entity id * @return true, if the entity was in the DB */ public boolean delete(long id) { SQLiteDatabase db = dbHelper.getWritableDatabase(); boolean deleted = false; try { db.beginTransaction(); int count = db.delete(getTable(), "_id = ?", new String[]{ String.valueOf(id) }); deleted = count &gt; 0; db.setTransactionSuccessful(); } finally { db.endTransaction(); db.close(); } return deleted; } /** * Build the columns array using an enum * * @return The columns array, that can be used for a projection */ protected String[] getColumns() { Enum&lt;?&gt;[] columns = getColumnsEnum(); String[] retv = new String[columns.length]; for(int i = 0, len = columns.length; i &lt; len; i++) { retv[i] = columns[i].name(); } return retv; } /** * Bind a record to an entity for insert. * Remember to not bind the entity id! * * @param cursor Cursor from DB * @return The binded entity */ protected abstract T bind(Cursor cursor); /** * Bind an entity to a ContentValues * * @param entity The entity * @return A ContentValues object that contains the record values */ protected abstract ContentValues bind(T entity); /** * Get the table name for the enttiy * * @return The table name */ public abstract String getTable(); /** * Get the enum that define all columns for the entity table * * @return The enum values */ public abstract Enum&lt;?&gt;[] getColumnsEnum(); } </code></pre> <p>This is an example of class that extends EntityHelper:</p> <pre><code>package com.dw.svegliatest.db.model; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteOpenHelper; import com.dw.android.db.EntityHelper; import com.dw.utils.time.Days; /** * Alarm entity helper * * @author atancredi */ public final class AlarmHelper extends EntityHelper&lt;Alarm&gt; { public AlarmHelper(SQLiteOpenHelper dbHelper) { super(dbHelper); } /** * {@inheritDoc} */ protected ContentValues bind(Alarm entity) { ContentValues record = new ContentValues(); // record.put(Columns.label.name(), entity.getLabel()); record.put(Columns.enabled.name(), entity.isEnabled()); record.put(Columns.time.name(), entity.getTime()); record.put(Columns.days.name(), entity.getDays().flags()); // return record; } /** * {@inheritDoc} */ protected Alarm bind(Cursor cursor) { Alarm alarm = new Alarm(); // alarm.setId(cursor.getLong(Columns._id.ordinal())); alarm.setLabel(cursor.getString(Columns.label.ordinal())); alarm.setEnabled(cursor.getInt(Columns.enabled.ordinal()) == 1); alarm.setTime(cursor.getLong(Columns.time.ordinal())); alarm.setDays(new Days(cursor.getInt(Columns.days.ordinal()))); // return alarm; } /** * {@inheritDoc} */ public String getTable() { return "Alarm"; } /** * {@inheritDoc} */ public Enum&lt;?&gt;[] getColumnsEnum() { return Columns.values(); } /** * Alarm columns definition * * @author atancredi */ public static enum Columns { _id, label, enabled, time, days } } </code></pre> <p>What do you think about the code and the idea of use an enum for table columns?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-04T16:12:11.207", "Id": "80802", "Score": "0", "body": "avoid using enums in Android, use static final fields." } ]
[ { "body": "<p>I'm not familiar with Android development nor SQLite, so just a few minor generic notes:</p>\n\n<ol>\n<li><p>You have the following method in the <code>EntityHelper</code>:</p>\n\n<blockquote>\n<pre><code>/**\n * Bind a record to an entity for insert.\n * Remember to not bind the entity id!\n * \n * @param cursor Cursor from DB\n * @return The binded entity\n */\nprotected abstract T bind(Cursor cursor);\n</code></pre>\n</blockquote>\n\n<p>Despite the javadoc comment the implementation contains an id setting:</p>\n\n<blockquote>\n<pre><code> /**\n * {@inheritDoc}\n */\nprotected Alarm bind(Cursor cursor) {\n Alarm alarm = new Alarm();\n //\n alarm.setId(cursor.getLong(Columns._id.ordinal()));\n ...\n</code></pre>\n</blockquote>\n\n<p>Are you sure that this is right?</p>\n\n<p>If that's important I'd check it in the <code>EntityHelper</code> and throw an exception if the child class was not implemented properly. (See: <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></li>\n<li><p>You could eliminate the <code>retv</code> variable with two return statements:</p>\n\n<pre><code>if (cursor.moveToFirst()) {\n return bind(cursor);\n}\nreturn null;\n</code></pre></li>\n<li><p>Comments like this are rather noise:</p>\n\n<blockquote>\n<pre><code>T retv = null;\n//\nSQLiteDatabase db = dbHelper.getReadableDatabase(); \n</code></pre>\n</blockquote>\n\n<p>I'd remove them.</p></li>\n<li><p>You could change</p>\n\n<blockquote>\n<pre><code>if(cursor.moveToFirst()) {\n do {\n retv.add(bind(cursor));\n } while(cursor.moveToNext());\n }\n</code></pre>\n</blockquote>\n\n<p>to a simpler <code>while</code> loop:</p>\n\n<pre><code>while (cursor.moveToNext()) {\n retv.add(bind(cursor));\n}\n</code></pre></li>\n<li><p>I usually try to avoid abbreviations like <code>retv</code>. They are not too readable and I suppose you have autocomplete (if not, use an IDE, it helps a lot), so using longer names does not mean more typing but it would help readers and maintainers since they don't have to remember the purpose of each variable - the name would express the programmers intent and doesn't force readers to decode the abbreviations every time they read/maintain the code.</p></li>\n<li><p>I would rename the following method to <code>getTableName()</code>:</p>\n\n<blockquote>\n<pre><code>public abstract String getTable();\n</code></pre>\n</blockquote>\n\n<p>It would describe better what it actually does.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-05T19:48:03.490", "Id": "46406", "ParentId": "23807", "Score": "6" } }, { "body": "<p>I think inheritance is unnecessary here. It has some drawbacks:</p>\n\n<ul>\n<li><code>AlarmHelper</code> does not use the <code>SQLiteOpenHelper</code> just passes it to the superclass. This is a superfluous dependency.</li>\n<li>If you want to add a new constructor parameter to <code>EntityHelper</code> (or modify an existing one) you have to change every subclass.</li>\n<li>It's hard to test the logic in <code>AlarmHelper</code>.</li>\n</ul>\n\n<p>I would go with composition.</p>\n\n<p>First, a new <code>EntityMapper</code> interface:</p>\n\n<pre><code>public interface EntityMapper&lt;T extends Entity&gt; {\n T bind(Cursor cursor);\n ContentValues bind(T entity);\n String getTable();\n Enum&lt;?&gt;[] getColumnsEnum();\n}\n</code></pre>\n\n<p>(You might be able to find a better name.)</p>\n\n<p>Then an <code>AlarmMapper</code> (it's methods are the same as <code>AlarmHelper</code>):</p>\n\n<pre><code>public final class AlarmMapper implements EntityMapper&lt;Alarm&gt; {\n public ContentValues bind(Alarm entity) {\n ...\n }\n\n public Alarm bind(Cursor cursor) {\n ...\n }\n\n public String getTable() {\n ...\n }\n\n public Enum&lt;?&gt;[] getColumnsEnum() {\n ...\n }\n}\n</code></pre>\n\n<p>Here is the modified <code>EntityHelper</code>:</p>\n\n<pre><code>public class EntityHelper&lt;T extends Entity&gt; {\n private final SQLiteOpenHelper dbHelper;\n private final EntityMapper&lt;T&gt; entityMapper;\n\n public EntityHelper(SQLiteOpenHelper dbHelper, EntityMapper&lt;T&gt; entityMapper) {\n this.dbHelper = dbHelper;\n this.entityMapper = entityMapper;\n }\n\n ...\n\n public boolean delete(long id) {\n ...\n int count = db.delete(entityMapper.getTable(), \n \"_id = ?\", new String[] { String.valueOf(id) });\n ...\n }\n\n ...\n}\n</code></pre>\n\n<p>Finally, you can create a factory which is the only place where <code>EntityHelper</code> is created and the only place where it has to be changed if it gets a new dependency:</p>\n\n<pre><code>public class EntityHelperFactory {\n\n private final SQLiteOpenHelper dbHelper;\n\n public EntityHelperFactory(SQLiteOpenHelper dbHelper) {\n this.dbHelper = checkNotNull(dbHelper, \"dbHelper cannot be null\");\n }\n\n public &lt;T extends Entity&gt; EntityHelper&lt;T&gt; create(EntityMapper&lt;T&gt; entityMapper) {\n return new EntityHelper&lt;T&gt;(dbHelper, entityMapper);\n }\n}\n</code></pre>\n\n<p>See also: <em>Effective Java, 2nd Edition</em>, <em>Item 16: Favor composition over inheritance</em></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-05T22:22:05.200", "Id": "46412", "ParentId": "23807", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T22:38:19.770", "Id": "23807", "Score": "4", "Tags": [ "java", "android", "database" ], "Title": "Android database access" }
23807
<p>I've started writing a game and I need help, because I know there are many ways to improve what I am doing. I am doing it the basic way I know I can but I know there is more complex ways of doing it.</p> <pre><code>import time print"Created on 3/12/2013" print"ver 1.2" print"Created by: Daniel Vargas" print'At any point type "help" for commands' print"===== Hello =====" print"Welcome to ZOTD3000!" time.sleep(2) print("To find your fate") ### This is the first Fate ### while True: fate = raw_input('Write A, B, or C:\n') if fate == 'A': print"You have selected choice A" time.sleep(2) break elif fate == 'help': print"You can only type A, B, or C." else: print"You can only type A, B, or C." time.sleep(2) ### Here is the first decision ### ### From Fate A ### def Forest(Health,Hunger,Inventory): print'You wake up in the middle of the forest' Inventory = 'Inventory: ' Squirrel = 'Squirrel' while True: Choice1 = raw_input('You...\n') if Choice1 in ('Life', 'life'): print('Health: '+str(Health)) print('Hunger: '+str(Hunger)) elif Choice1 in ('Look', 'look'): print 'You see many trees, and what looks like an edible dead Squirrel, \na waterfall to the north and a village to the south.' elif Choice1 in ('Pickup', 'pickup'): p1 = raw_input('Pickup what?\n') if p1 == Squirrel: if Inventory == 'Inventory: ': print'You picked up a Squirrel!' Inventory = Inventory + Squirrel + ', ' elif Inventory == 'Inventory: Squirrel, ': print'You already picked that up!' else: print"You can't find a "+str(p1)+"." elif Choice1 in ('Inventory', 'inventory'): print Inventory elif Choice1 in ('Eat', 'eat'): print Inventory e1 = raw_input('Eat what?\n') if e1 == Squirrel: while True: if Inventory == 'Inventory: ': print("You don't have one.") break else: print("It taste's funny. You feel sick.") print("Your health is lowered. But your not hungry.") Health = Health - 1 Hunger = Hunger + 1 Inventory = 'Inventory: ' break else: print"You don't have a "+str(e1)+"." elif Choice1 in ('Kill', 'kill'): print'There is nothing to kill.' elif Choice1 in ('Goto', 'goto'): print"There isn't a place you can Goto in sight." elif Choice1 in ('North', 'north'): print('Heading North!') Waterfall(Health,Hunger,Inventory) break elif Choice1 in ('East', 'east'): print('Heading East!') Desert(Health,Hunger) break elif Choice1 in ('South', 'south'): print('Heading South!') Village(Health,Hunger) break elif Choice1 in ('West', 'west'): print('Heading West!') Forest2(Health,Hunger) break elif Choice1 in ('help', 'Help'): print('You can type Inventory, Life, North, East, South, West, Look, Pickup, Eat, Kill, Goto.') else: print"You can't do that! Remember CaSe SeNsItIvE!\n Type"' "help" for commands.' def Waterfall(Health,Hunger,Inventory): while True: Choice2 = raw_input('You...\n') if Choice2 in ('help', 'Help'): print('You can type Inventory, Life, North, East, South, West, Look, Pickup, Eat, Kill, Goto.') elif Choice2 in ('Life', 'life'): print('Health: '+str(Health)) print('Hunger: '+str(Hunger)) elif Choice2 in ('North', 'north'): print("You can't go up the waterfall!") elif Choice2 in ('South', 'south'): print('Heading South!') Forest(Health,Hunger,Inventory) break elif Choice2 in ('East', 'east'): print('Heading East!') Desert(Health,Hunger) break elif Choice2 in ('West', 'west'): print('Heading West!') Hills(Health,Hunger) break elif Choice2 in ('Inventory', 'inventory'): print Inventory else: print"You can't do that! Remember CaSe SeNsItIvE!\n Type"' "help" for commands.' ### From Fate B ### ### From Fate C ### ### Main ### def main(): Inventory = 'Inventory: ' if fate == 'A': Forest(10,10,Inventory) main() </code></pre>
[]
[ { "body": "<p>Here are some small fixes:</p>\n\n<ul>\n<li><strong>Make the input lowercase.</strong> By replacing <code>Choice2 = raw_input('You...\\n')</code> with <code>Choice2 = raw_input('You...\\n').lower()</code> you can replace <code>Choice1 in ('East', 'east')</code> by <code>Choice1 == 'east'</code>.</li>\n<li><strong>Making the inventory a list.</strong> Create it with <code>Inventory = []</code>, adding a item would be <code>Inventory += ['squirrel'])</code> and printing the inventory would be <code>print 'Inventory:' + ', '.join(inventory)</code>.</li>\n</ul>\n\n<p>You can also return the state and the next place in the functions, like this:</p>\n\n<pre><code>def forest(health, hunger, inventory, here=['squirrel']):\n place = forest\n choice = raw_input(\"Forest: \").lower()\n if choice == \"house\":\n place = house\n elif choice in here:\n inventory += [choice]\n here.remove(choice)\n elif choice == \"eat\":\n choice = raw_input(\"Eat what? \").lower()\n if choice in inventory:\n if choice == \"squirrel\":\n inventory.remove(choice)\n health -= 50\n hunger -= 50\n else:\n print \"You don't have %s.\" % choice\n else:\n print \"Err, what?\"\n return (place, health, hunger, inventory))\n\ndef house(health, hunger, inventory):\n print \"You won!\"\n exit(0)\n\ndef main():\n place, health, hunger, inventory = forest, 100, 0, []\n while true:\n if hunger &gt;= 100:\n health -= 10\n if health &lt;= 0: \n print \"You die!\"\n break\n hunger += 10\n\n place, health, hunger, inventory = place(health, hunger, inventory)\n\nmain()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T23:59:00.070", "Id": "36713", "Score": "0", "body": "I know what you meant by\nChoice2 = raw_input('You...\\n').lower()\nbut I like having it as it is it helps my eyes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T00:01:04.063", "Id": "36714", "Score": "0", "body": "But the inventory thing I like and will use thank you for your help!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T00:11:34.487", "Id": "36715", "Score": "0", "body": "I tried it out the way you had it and I got confused?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T23:46:32.913", "Id": "23815", "ParentId": "23808", "Score": "3" } }, { "body": "<p>If you don't like to follow propeller's suggestion of converting input to lowercase, you can do this instead:</p>\n\n<pre><code>Choice1 = raw_input('You...\\n').capitalize()\nif Choice1 == 'Life':\n</code></pre>\n\n<p>This will also accept eg. 'LIFE'. It is easier to maintain than <code>if Choice1 in ('Life', 'life'):</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T10:36:35.000", "Id": "36823", "Score": "0", "body": "You mean `Choice1 = raw_input('You...\\n').capitalize()` (which is robuster, by turning `LIFE` to `Life` as well)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T10:52:44.777", "Id": "36824", "Score": "0", "body": "@JohnOptionalSmith Thanks, I'd forgotten about `capitalize()`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T20:45:17.903", "Id": "23879", "ParentId": "23808", "Score": "0" } }, { "body": "<p>The existing code is not easy to maintain. If you want to add new places or new actions you will have to write a lot of very specific and deeply nested code.</p>\n\n<p>I've never written a game like this, but it's a good case for modelling with classes. You have a <code>Place</code>, which <em>has</em> a set of <code>neighbours</code> which are also <code>Places</code>. You have a <code>Player</code> who <em>has</em> an <code>inventory</code> which <em>contains</em> <code>Items</code>. The <code>Player</code> has a level of <code>health</code> and <code>hunger</code> which can be modified by <code>Items</code> in his inventory. An <code>Item</code> can be a medicine, a source of food, a physical object, etc.</p>\n\n<p>To illustrate one aspect of this, I would consider something like:</p>\n\n<pre><code>class Place(object):\n def __init__(self, name):\n self.name = name\n self.neighbours = {\"North\": None,\n \"South\" : None\n \"East\" : None\n \"West\" : None}\n\n def add_neighbour(self, direction, neighbour):\n self.neighbours[direction] = neighbour\n\n def leave(self):\n # this is maybe one way to handle movement\n # if the player stores a reference to their location\n # but by no means the only way or the best way\n\n # get direction from user\n return self.neighbours[direction]\n</code></pre>\n\n<p>Which will allow you to set up your world separately like:</p>\n\n<pre><code>Waterfall = Place(\"Waterfall\")\nForest = Place(\"Forest\")\nWaterfall.add_neighbour(\"South\", Forest)\n</code></pre>\n\n<p>Your character could look something like (as a starting point)</p>\n\n<pre><code>class Character(object):\n def __init__(self, name, initial_location=None):\n self.name = name\n self.inventory = []\n self.location = initial_location\n self.health = 100\n self.hunger = 0\n</code></pre>\n\n<p>There are ways to make the direction choices robust, for example making sure that a's southern neighbour is b's northern neighbour and so on, but hopefully this gives you a general sense of what I am talking about. Eventually you will get a feel for what the entities in your code <em>are</em> and what they <em>do</em> and how they interact.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T12:38:53.397", "Id": "23906", "ParentId": "23808", "Score": "4" } }, { "body": "<p>Since the game has you traveling, you might want to store your locations in a 2d arrray of functions:</p>\n\n<pre><code>map = [[Forest , Forest2 , Hills], \n [Forest2, Waterfall, Village], \n [Hills , Waterfall, House]]\n</code></pre>\n\n<p>From this type of approach (white space might not be correctly, not a Python expert), you can programatically derive the directions you can go.</p>\n\n<p>You could even create an items map, to place the squirel and other stuff</p>\n\n<pre><code>items = [[\"\" , \"Squirrel\", \"\"], \n [\"Squirrel\" , \"\" , \"\"], \n [\"\" , \"\" , \"\"]]\n</code></pre>\n\n<p>Which would place then squirrels only in Forest2 locations.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T19:38:18.230", "Id": "23931", "ParentId": "23808", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T23:02:53.713", "Id": "23808", "Score": "4", "Tags": [ "python", "adventure-game" ], "Title": "Adventure game in a forest" }
23808
<p>I'm currently writing a WebGL HTML5 game, and large part of the game initialization involved loading assets streamed over a websocket, and saving them to disk using the FileSystem API.</p> <p>As part of optimizing the code, we're trying to eliminate as many memory allocations as we can, which means cutting down on the use of closures, object/array creation during the main game loop and so on.</p> <p>One of the biggest uses of closures left is our interaction with the FileSystem API, namely the part where we write the assets to disk:</p> <pre><code>//Write file to disk directory.getFile( filename, CREATE_TRUE, function(fileEntry) { fileEntry.createWriter( function(fileWriter) { fileWriter.onwriteend=function(e) { finishedRequest(filename); if (onSuccess!==undefined) onSuccess(filename); }; fileWriter.onerror=function(e) { finishedRequest(filename); if (onError!==undefined) onError(filename, "Write error: "+directoryRoot+"/"+filename); }; var dataBlob=new Blob([new Uint8Array(data)]); if (append) fileWriter.seek(fileWriter.length); fileWriter.write(dataBlob,"application/octet-stream"); }, function(e) { finishedRequest(filename); if (onError!==undefined) onError(filename,"File writer creation error: "+directoryRoot+"/"+filename:""); } ); }, function(e) { finishedRequest(filename); if (onError!==undefined) onError(filename,DEVELOPMENT_MODE?"File not found: "+directoryRoot+"/"+filename:""); } ); </code></pre> <p>As you can see, this code involves the creation of something like six new closures for every file write, which isn't the greatest when we're trying to cut down on memory allocation.</p> <p>I initially tried to pull each of the closures out into standalone functions, but obviously I then needed to be able to get references to things like the filename and onSuccess callback function from those standalone functions (whereas previously they would have been able to have access to them from their outer closures):</p> <pre><code>... fileWriter.onwriteend=onFileWrite; ... function onFileWrite=function(e) { finishedRequest(filename); //filename needs to be retrieved from somewhere... if (onSuccess!==undefined) onSuccess(filename); } </code></pre> <p>The problem is that the onFileWrite callback is only supplied with the event object, which contains a reference to the target fileWriter, but nothing higher. Crucially, there seems to be no way to link the fileEntry with the fileWriter that it creates, as the createWriter callback only gets given the FileWriter object - with no meta data about what created it.</p> <p>My question is this: is it possible to rewrite this without using quite some many closures - or ideally none at all?</p> <p><strong>Edit</strong>: I'm convinced that it is (unfortunately) impossible to do this without creating some kind of container for the details of the request, be it a new function whose closure includes the request details, or a new object whose properties have the details. So, this question really then becomes about the best way to achieve the file write with the smallest amount of memory churn.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T15:21:24.063", "Id": "36706", "Score": "0", "body": "I'm going to migrate it in a few minutes, but would you like to award the bounty first so it doesn't get lost on the way?" } ]
[ { "body": "<p>I think the best approach here would be</p>\n\n<ul>\n<li><p>Create a FileWriter wrapper which exposes the functionality through a (jQuery?) Deferred pattern <a href=\"http://api.jquery.com/category/deferred-object/\" rel=\"nofollow\">http://api.jquery.com/category/deferred-object/</a></p></li>\n<li><p>Use this wrapper in your code instead of a pure FileWriter callbacks</p></li>\n<li><p>Then you could avoid clousure mess by using <code>promise()</code>, <code>success()</code>, <code>error()</code> and friends to write more linear code instead of resulting to nesting </p></li>\n<li><p>Note that other libraries also provide Deferred implementation (underscore.js, etc.)</p></li>\n</ul>\n\n<p><a href=\"http://net.tutsplus.com/tutorials/javascript-ajax/wrangle-async-tasks-with-jquery-promises/\" rel=\"nofollow\">http://net.tutsplus.com/tutorials/javascript-ajax/wrangle-async-tasks-with-jquery-promises/</a></p>\n\n<p>Sorry I did not find a better tutorial how to convert existing closures to use Deferred object.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T19:03:44.673", "Id": "36707", "Score": "1", "body": "Thanks for your response, but I'm concerned that this doesn't remove the closures, but rather pushes them into the wrapper that exposes the Deferred pattern. Though this undoubtedly will make the code neater, it doesn't help with my goal of removing the closures due to the associated memory allocation." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T17:52:37.850", "Id": "23810", "ParentId": "23809", "Score": "0" } }, { "body": "<p>Yes, you could rewrite this without using <em>closures</em>.</p>\n\n<p>In your case, all callbacks are called on system events. If you specify a number of standalone functions, which are not changed during runtime, and use those functions as callbacks, you can't really know inside those functions in which state a program was, when you initiated async call.</p>\n\n<p>You have following variables that specify a state: <code>filename, onError, onSuccess, append, directoryRoot, data</code>. When you initiated first <code>directory.getFile</code> call, you know what the state is. If those variables are not changed on runtime, then you could just store them globally. I understande the issue is, that each time you have different values for those variables.</p>\n\n<p>So, on each <code>directory.getFile</code> call all those callbacks should be modified to store those variables somehow. You could avoid <em>closures</em> usage, if by <em>closure</em> is meant a lexical scope of outter function. For this purpose, <code>Function.prototype.bind</code> could be used. Here is modified code:</p>\n\n<pre><code>window.fileWriterSuccess = function (e) {\n this.finishedRequest(this.filename);\n\n if (this.onSuccess !== undefined) this.onSuccess(this.filename);\n};\n\nwindow.fileWriterError = function (e) {\n this.finishedRequest(this.filename);\n\n if (this.onError !== undefined) this.onError(this.filename, \"Write error: \" + this.directoryRoot + \"/\" + this.filename);\n};\n\nwindow.createWriterSuccess = function (fileWriter) {\n fileWriter.onwriteend = fileWriterSuccess.bind(this);\n\n fileWriter.onerror = fileWriterError.bind(this);\n\n var dataBlob = new Blob([new Uint8Array(this.data)]);\n\n if (this.append) fileWriter.seek(fileWriter.length);\n\n fileWriter.write(dataBlob, \"application/octet-stream\");\n\n};\n\nwindow.createWriterError = function(e) {\n this.finishedRequest(this.filename);\n\n if (this.onError !== undefined) this.onError(this.filename, \"File writer creation error: \" + this.directoryRoot + \"/\" + this.filename : \"\");\n};\n\nwindow.getFileSuccess = function (fileEntry) {\n fileEntry.createWriter(createWriterSuccess.bind(obj), createWriterError.bind(obj));\n};\n\nwindow.getFileError = function (e) {\n this.finishedRequest(this.filename);\n\n if (this.onError !== undefined) this.onError(this.filename, DEVELOPMENT_MODE ? \"File not found: \" + this.directoryRoot + \"/\" + this.filename : \"\");\n};\n\n...\n/* Inside some function call */\n\nvar _obj = {\n filename: filename,\n onError: onError,\n onSuccess: onSuccess,\n append: append,\n directoryRoot: directoryRoot,\n data: data\n};\n\ndirectory.getFile(filename, CREATE_TRUE, getFileSuccess.bind(_obj), getFileError.bind(_obj));\n</code></pre>\n\n<p>So, an <code>_obj</code> is created to store a program state, which is then is used to create callbacks. No <em>closures</em> are created, as there are no explicit function literals in the code. But on each call a number of functions which assigned <code>_obj</code> context are created.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T20:40:34.180", "Id": "36708", "Score": "0", "body": "Cheers for your suggestion - I'd not encountered the use of .bind before. However, I'm worried that all this does is hide the creation of new function scopes behind the bind calls, as each one creates a new function - something my code is already doing and something I'm wanting to avoid. Unfortunately, using bind also adds the overhead of creating a new `obj` for every request, so it's actually worse for memory churn than my version." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T13:57:48.320", "Id": "23811", "ParentId": "23809", "Score": "0" } }, { "body": "<p>I think that you will always need some closures, but you can limit what they carry.\nThis was your example:</p>\n\n<pre><code>...\nfileWriter.onwriteend=onFileWrite;\n...\n\nfunction onFileWrite=function(e) {\n finishedRequest(filename); //filename needs to be retrieved from somewhere...\n if (onSuccess!==undefined) onSuccess(filename);\n}\n</code></pre>\n\n<p>I guess that your intention was to define a function for each case and then assign it.\nSo your example transforms into this (I'm just reorganizing your code and fixing a function declaration).</p>\n\n<pre><code>var onFileWrite = function(e) {\n finishedRequest(filename); //filename needs to be retrieved from somewhere...\n if (onSuccess!==undefined) onSuccess(filename);\n}\n\n...\nfileWriter.onwriteend=onFileWrite;\n...\n</code></pre>\n\n<p>This is actually an optimization because you can reuse things, the problem now is how do we get the filename. Well you can write a function that gets the filename and return a new function that only has the filename in its closure and nothing else. Like this: </p>\n\n<pre><code>var onFileWrite = function(filename) {\n return function(e) {\n finishedRequest(filename);\n if (onSuccess!==undefined) onSuccess(filename);\n }\n}\n\n...\nfileWriter.onwriteend=onFileWrite(filename);\n...\n</code></pre>\n\n<p>Note that this way you just pass what you need, variables, functions but always controlling the closure \"size\".</p>\n\n<p>Hope it helps you, good luck with the game!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T03:54:52.900", "Id": "23812", "ParentId": "23809", "Score": "2" } }, { "body": "<p>Here's an approach with very shallow closures, and makes use of prototype to conserve memory.</p>\n\n<pre><code>function SuperFileWriter(filename, directoryRoot, option, data) {\n this.filename = filename;\n this.directoryRoot = directoryRoot;\n this.option = option;\n this.data = data;\n this.fileEntry = null;\n this.fileWriter = null;\n this.start = function() {\n directory.getFile(filename, option, this.onSuccess, this.onFail)\n };\n};\n\nSuperFileWriter.prototype.onSuccess = function(fileEntry) {\n this.fileEntry = fileEntry;\n this.fileEntry.createWriter(onCreateWriterSuccess, onCreateWriterFail)\n}\n\nSuperFileWriter.prototype.onFail = function(e) {\n finishedRequest(this.filename);\n if (onError!==undefined) \n onError(filename, DEVELOPMENT_MODE ? \"File not found: \"+this.directoryRoot+\"/\"+this.filename : \"\");\n}\n\nSuperFileWriter.prototype.onCreateWriterSuccess = function(fileWriter) {\n this.fileWriter = fileWriter;\n this.fileWriter.onwriteend = this.prototype.onWriteEnd;\n this.fileWriter.onerror = this.prototype.onWriteError;\n\n var dataBlob=new Blob([new Uint8Array(this.data)]);\n if (append) fileWriter.seek(this.fileWriter.length);\n this.fileWriter.write(dataBlob,\"application/octet-stream\");\n}\n\nSuperFileWriter.prototype.onCreateWriterFail = function(e) {\n finishedRequest(this.filename);\n if (onError!==undefined) \n onError(this.filename,\"File writer creation error: \"+this.directoryRoot+\"/\"+this.filename);\n} \n\nSuperFileWriter.prototype.onWriteEnd = function(e) {\n finishedRequest(this.filename);\n if (onSuccess!==undefined) onSuccess(this.filename);\n};\n\n\nSuperFileWriter.prototype.onWriteError = function(e) {\n finishedRequest(this.filename);\n if (onError!==undefined) \n onError(this.filename, \"Write error: \"+this.directoryRoot+\"/\"+this.filename);\n}\n</code></pre>\n\n<p>And then to call it...</p>\n\n<pre><code>var sfw = new SuperFileWriter(...);\nsfw.start()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T13:37:05.593", "Id": "36709", "Score": "0", "body": "Unfortunately this doesn't work - when onSuccess is called, `this` points to `window`, rather than my `superFileWriter` instance, so I can't retrieve any of the fields from it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T13:47:39.223", "Id": "36710", "Score": "0", "body": "did you use 'new'?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T14:09:58.030", "Id": "36711", "Score": "0", "body": "Indeed I did - calling `start` is fine, `this` points to what you'd expect, but the callbacks just regard the passed-in function as standalone, so don't bind `this` to my `SuperFileWriter` object. Tis a shame, I thought this was going to be the neatest solution." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T07:44:40.457", "Id": "23813", "ParentId": "23809", "Score": "0" } } ]
{ "AcceptedAnswerId": "23812", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-11T15:35:45.707", "Id": "23809", "Score": "6", "Tags": [ "javascript", "html5", "optimization" ], "Title": "Using Javascript FileWriter with minimal use of closures" }
23809
<p>I have a table full of URLs, some of which will occasionally become invalid. As part of a system I'm writing to go through the links periodically, and test if they are valid (or redirect to valid sites), I wrote the following class. The feedback I'm looking for is primarily related to clean code and best practices--how should the URL be passed into this class, for example? (I have not included the test cases, but they were written first. :) )</p> <p>Originally, I wrote this with the URL passed in on the constructor, but I realized that if I set it later, I could both make the class a dependency of another class without needing to know the URL ahead of time, and use the same object to test multiple URLs. </p> <p>But as it is, my URLisValid function is doing two things: setting a class variable and evaluating the URL. That doesn't seem ideal to me, but neither does having a separate Setter, nor does passing the URL around the class as an argument, nor does passing it in on the constructor. </p> <p>(obviously, I think this works fine as-is, although feel free to point out any real bugs. I'm improving this class as a lesson to myself in making my code as clean as possible).</p> <pre><code>class URLChecker { private $curl; private $url; const HTTP_RESPONSE_OK = 200; public function __construct() { $this-&gt;curl = curl_init(); } public function __destruct() { curl_close( $this-&gt;curl ); } public function URLisValid( $url ) { $this-&gt;url = $url; $httpcode = $this-&gt;getHttpCodeForURL(); return $this-&gt;httpCodeIsValid( $httpcode ); } private function getHttpCodeForURL() { $this-&gt;executeCurlSessionForHeadersOnly(); return $this-&gt;getHttpCodeFromLastTransfer(); } private function executeCurlSessionForHeadersOnly() { $this-&gt;setCurlOptions(); curl_exec( $this-&gt;curl ); } private function getHttpCodeFromLastTransfer() { return curl_getinfo( $this-&gt;curl, CURLINFO_HTTP_CODE ); } private function setCurlOptions() { curl_setopt($this-&gt;curl, CURLOPT_URL, $this-&gt;url); curl_setopt($this-&gt;curl, CURLOPT_NOBODY, true); curl_setopt($this-&gt;curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($this-&gt;curl, CURLOPT_FOLLOWLOCATION, true); } private function httpCodeIsValid( $httpcode ) { return $httpcode == self::HTTP_RESPONSE_OK; } } </code></pre> <p>EDIT: version 2, based in part on some feedback:</p> <pre><code>class URLChecker { private $session; const HTTP_RESPONSE_OK = 200; public function __construct() { $this-&gt;session = curl_init(); $this-&gt;initializeSessionOptions(); } public function urlIsValid( $url ) { $this-&gt;setSessionUrl( $url ); $this-&gt;executeSession(); $httpcode = $this-&gt;getHttpCodeFromLastSession(); return $this-&gt;httpCodeIsValid( $httpcode ); } private function executeSession() { curl_exec( $this-&gt;session ); } private function getHttpCodeFromLastSession() { return curl_getinfo( $this-&gt;session, CURLINFO_HTTP_CODE ); } private function setSessionUrl( $url ) { curl_setopt($this-&gt;session, CURLOPT_URL, $url); } private function initializeSessionOptions() { curl_setopt($this-&gt;session, CURLOPT_NOBODY, true); curl_setopt($this-&gt;session, CURLOPT_RETURNTRANSFER, true); curl_setopt($this-&gt;session, CURLOPT_FOLLOWLOCATION, true); } private function httpCodeIsValid( $httpcode ) { return $httpcode == self::HTTP_RESPONSE_OK; } function __destruct() { curl_close( $this-&gt;session ); } } </code></pre> <p>I've removed $url as a class variable entirely, I've changed some method names to remove references to "curl" where the implementation of the session is not relevant to the logic. I kept the one line functions, because I want someone who does not know exactly how curl works to still be able to read the code. It is now clear that $url is not a property of the class--it is rather a variable to be passed in once, and tested.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T12:15:46.520", "Id": "36742", "Score": "0", "body": "'I kept the one line functions, because I want someone who does not know exactly how curl works to still be able to read the code.' That, is what comments are for." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T13:04:22.050", "Id": "36745", "Score": "0", "body": "And actually someone using your library does not even have to know that cURL is underlying." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T12:53:47.367", "Id": "36829", "Score": "0", "body": "I updated for you update! But as I said it looks pretty good to me now." } ]
[ { "body": "<p>one line functions make your logic hard to follow, I would advise strongly against them.\n<em>Especially</em> if you only call that function only once, which is the case in most of your code.</p>\n\n<p>As a very minor comment, I would put </p>\n\n<pre><code>curl_setopt($this-&gt;curl, CURLOPT_NOBODY, true);\ncurl_setopt($this-&gt;curl, CURLOPT_RETURNTRANSFER, true);\ncurl_setopt($this-&gt;curl, CURLOPT_FOLLOWLOCATION, true); \n</code></pre>\n\n<p>inside <code>__construct()</code>, it should be a tiny bit more efficient.</p>\n\n<p>One more minor comment, $url could easily be passed as a parameter, why make it a property?</p>\n\n<p>All that taken into account, I would rather maintain something like this:</p>\n\n<pre><code>class URLChecker\n{\nprivate $curl;\n\npublic function __construct()\n{\n $this-&gt;curl = curl_init();\n curl_setopt($this-&gt;curl, CURLOPT_NOBODY, true);\n curl_setopt($this-&gt;curl, CURLOPT_RETURNTRANSFER, true);\n curl_setopt($this-&gt;curl, CURLOPT_FOLLOWLOCATION, true); \n}\n\npublic function __destruct()\n{\n curl_close( $this-&gt;curl );\n}\n\npublic function URLisValid( $url )\n{\n $httpcode = $this-&gt;getHttpCodeForURL( $url );\n return $httpcode == 200; //HTTP_RESPONSE_OK\n}\n\nprivate function getHttpCodeForURL( $url )\n{\n curl_setopt($this-&gt;curl, CURLOPT_URL, $url);\n curl_exec( $this-&gt;curl ); \n return curl_getinfo( $this-&gt;curl, CURLINFO_HTTP_CODE );\n}\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T01:48:33.443", "Id": "23817", "ParentId": "23816", "Score": "1" } }, { "body": "<p><strong>Few things about code style:</strong></p>\n\n<ul>\n<li><p>Capitalize your function name the same way</p>\n\n<blockquote>\n <p>URLisValid vs setCurlOptions</p>\n</blockquote>\n\n<p>One is capitalized (<a href=\"http://en.wikipedia.org/wiki/CamelCase\" rel=\"nofollow\">CamelCase</a>), the other is not (camelCase). I advice you choose the latter, which is the Java standard and I must say it is a pretty solid one in terms of code clarity. You may chose the other if you want, but the most important thing : be sure to keep the same pattern everywhere.</p></li>\n<li><p>Build your function names in the same way</p>\n\n<blockquote>\n <p>URLisValid vs setCurlOptions</p>\n</blockquote>\n\n<p>One starts with the verb, the other one with a name. Well I do agree that if makes nicer ifs <code>if(URLisValid($url)</code> vs <code>(if(isURLValid($url)</code> BUT when using an IDE or autocompletion(, and also when reviewing a class file), it's easier if like lets the function name follow the same pattern. Right now if you type in autocomplete <code>is</code> you will have no result. And you have to <em>know</em> that the two function that checks for validity exists. By putting isURLValid and isHTTPCodeValid, you can easily find the function <code>is</code> now returns both of them and you keep some sort of similarity between your function names.</p></li>\n<li><p>Capitalization patterns generally</p>\n\n<blockquote>\n <p>URL vs Http</p>\n</blockquote>\n\n<p>You capitalize URL but not HTTP. Well writing <code>URL</code> or <code>Url</code> doesn't really matters. But be sure to keep the same pattern for every type. If you write <code>URL</code> then write <code>HTTP</code> and vice versa.</p></li>\n</ul>\n\n<hr>\n\n<p><strong>Something you pointed out:</strong></p>\n\n<blockquote>\n <p>But as it is, my URLisValid function is doing two things: setting a class variable and evaluating the URL. That doesn't seem ideal to me, but neither does having a separate Setter, nor does passing the URL around the class as an argument, nor does passing it in on the constructor.</p>\n</blockquote>\n\n<p>Well, setters are meant for object encapsulation and part of this is validation. It would probably be clearer to validate in a setter than to set in a validator. Setters are meant to block people from directly modifying and accessing a variable, else you could just put it as public. You could easily rename your <code>URLisValid</code> function to <code>setURL</code> and throw an exception or return false or w/e that suits your need in the setter function, and that would be clearer (to me) than having a validator that sets a value. </p>\n\n<p><strong>About function length</strong>, well I do think it's OK. It makes it easy to test the class.</p>\n\n<hr>\n\n<p><strong>About your edit :</strong></p>\n\n<p>To me your class looks pretty good. One thing you could do is catching the cURL exceptions to throw your own exception based on what happened (be sure to keep the old one in the stack trace though). By throwing your own exception you increase encapsulation because the person using your class doesn't have to know whats underlying in it. They don't have to get the cURL exceptions directly. But that is not necessary.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T02:16:20.923", "Id": "23818", "ParentId": "23816", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T01:26:35.760", "Id": "23816", "Score": "3", "Tags": [ "php" ], "Title": "How can this this URL Checker be made cleaner?" }
23816
<p>See the examples below:</p> <pre><code>function map_cloning(obj,fn){ result = {}; for (var key in obj) result[key] = fn(obj[key]); return result; }; function map_modifying(obj,fn){ for (var key in obj) obj[key] = fn(obj[key]); return obj; }; function sum_cloning(vector1,vector2){ return [vector1[0] + vector1[1], vector2[0] + vector2[1]]; }; function sum_modifying(vector1,vector2){ vector1.x += vector2.x; vector1.y += vector2.x; return vector1; }; function tail_cloning(obj){ return obj.slice(1); }; function tail_modifying(obj){ obj.splice(0,1); return obj; }; </code></pre> <p>Often you have to chose between cloning or not an object before making a computation. Which is best?</p>
[]
[ { "body": "<p>I suggest cloning. If it was possible (like in Java), I'd even suggest making your objects immutable...</p>\n\n<p>Why do I suggest cloning? Consider being after a busy Friday, with business users ranting all day on some totally unimportant feature, and you see this code fragment all of a sudden, having a, b and c variables:</p>\n\n<pre><code>b=sum_modifying(a,b);\n //some other code here\na=sum_modifying(c,a);\n //some other code here\nb=sum_modifying(c,a);\n</code></pre>\n\n<p>Will you be able to track back what's going on? I woudn't, for sure...</p>\n\n<p>Even this is a tough situation, but at least, the value of the variables change only with the assignment.</p>\n\n<pre><code>b=sum_cloning(a,b);\n //some other code here\na=sum_cloning(c,a);\n //some other code here\nb=sum_cloning(c,a);\n</code></pre>\n\n<p>However, I'd suggest a third alternative: add functions to the objects themselves, to enable schemes like this:</p>\n\n<pre><code>result = a.add(b);\n</code></pre>\n\n<p>I'd find this the most readable of these.\n(I stole the idea mainly from Java's <a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html\" rel=\"nofollow\">BigDecimal</a>.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T13:28:33.100", "Id": "23840", "ParentId": "23819", "Score": "2" } }, { "body": "<p>Definitely default to cloning an object and leaving the original untouched. If the calling code wants to replace the original object, it can assign the function result to that variable. This way it's much clearer what you're doing at each step, and it's much harder to screw something up. It's also in keeping with the mentality of having functions that process input and return output, rather than having functions that perform \"magic\" on state outside of themselves.</p>\n\n<p>I find Underscore/Lodash's <code>_.clone</code> very useful for this, I use it all the time. In fact, I use it almost to the exclusion of <code>new</code> and <code>Object.create</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T13:35:16.103", "Id": "23842", "ParentId": "23819", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T03:09:30.413", "Id": "23819", "Score": "1", "Tags": [ "javascript" ], "Title": "Modify or not modify your objects when creating computing functions?" }
23819
<p>I'm new to JS/jQuery and wrote some JavaScript/jQuery lines to create a <a href="http://jsfiddle.net/drkthng/RJWS2/9/" rel="nofollow">"pulsating" object</a>.</p> <p>I get the "pulse" effect by increasing/resizing the object and then bringing it back to its original state periodically. I was uncomfortable with calculating the necessary values every time they are needed, so I used the first thing that came to my mind - global variables and only modify their values when the page is fully loaded. But I also don't like that approach.</p> <p>What is best practice in JavaScript/jQuery for this kind of problem, and how can I refactor my code accordingly?</p> <p>Here is the code (JavaScript only, please see my link for HTML&amp;CSS):</p> <pre><code>var elementOrigHeight; var elementOrigWidth; var elementIncreasedHeight; var elementIncreasedWidth; var elementNewTop; var elementNewLeft; $(document).ready(function () { var element = $('#circle'); var growInPercent = 100; setGlobalVariables(element, growInPercent); var durationGetBigger = 500; var durationGetSmaller = 100; var frequency = 3; var pause = 3000; pulsate(element, durationGetBigger, durationGetSmaller, frequency, pause); }); function pulsate(element, durationBigger, durationSmaller, frequency, pause) { for (var i = 0; i &lt; frequency; i++) { getBigger(element, durationBigger); getSmaller(element, durationSmaller); } setTimeout(function () { pulsate(element, durationBigger, durationSmaller, frequency, pause) }, pause); } function getBigger(element, duration) { element.animate({ width: elementIncreasedWidth, height: elementIncreasedHeight, top: elementNewTop, left: elementNewLeft, opacity: 1 }, duration, 'linear'); } function getSmaller(element, duration) { element.animate({ width: elementOrigWidth, height: elementOrigHeight, top: 0, left: 0, opacity: 0.5 }, duration, 'linear'); } function setGlobalVariables(element, percent) { elementOrigHeight = element.height(); elementIncreasedHeight = Math.round(elementOrigHeight*(1+percent/100)); if (elementOrigHeight % 2 &gt; 0) { // odd // make sure increased size is odd too elementIncreasedHeight = Math.floor(elementIncreasedHeight/2)*2+1; } else { elementIncreasedHeight = Math.floor(elementIncreasedHeight/2)*2 } elementOrigWidth = element.width(); elementIncreasedWidth = Math.round(elementOrigWidth*(1+percent/100)); if (elementOrigWidth % 2 &gt; 0) { // odd elementIncreasedWidth = Math.floor(elementIncreasedWidth/2)*2+1; } else { elementIncreasedWidth = Math.floor(elementIncreasedWidth/2)*2; } elementNewLeft = -Math.round((elementIncreasedWidth - elementOrigWidth)/2); elementNewTop = -Math.round((elementIncreasedHeight - elementOrigHeight)/2); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T11:44:45.780", "Id": "36740", "Score": "2", "body": "The short answer is to write a plugin. See http://docs.jquery.com/Plugins/Authoring for style advice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-04T22:52:46.180", "Id": "85921", "Score": "0", "body": "You can shorten `$(document).ready(function () {...})` to `$(function () {...})`" } ]
[ { "body": "<p>Ok, so after some (more!) search on the net, I will propose one thing that I was already pondering about (having a little experience mostly with OOP languages Java and C#).<br><br>\ncreating a <strong>class/datastructure</strong> to hold the values<br><br>\nI was inspired by these sources:<br></p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/4190792/should-i-use-a-global-variable-and-if-not-what-instead-javascript\">answer to this question</a> </li>\n<li><a href=\"https://stackoverflow.com/questions/1841916/how-to-avoid-global-variables-in-javascript?rq=1\">answer nr 2 to this question</a> </li>\n<li><a href=\"http://www.webmonkey.com/2010/02/make_oop_classes_in_javascript/\" rel=\"nofollow noreferrer\">and this webmonkey explanation</a></li>\n</ul>\n\n<p>still not sure if this is a <strong>\"better\"</strong> approach in JavaScript, but at least for my rather inexperienced eyes it looks more structured<br><br>\nthe refactored version of my pulsating object is <a href=\"http://jsfiddle.net/RJWS2/11/\" rel=\"nofollow noreferrer\">here</a><br>\nthe slightly changed javascript (find the class ElementWrapper at the end):</p>\n\n<pre><code>$(document).ready(function () {\n var element = $('#circle');\n var growInPercent = 100;\n var elementWrapper = new ElementWrapper(element, growInPercent);\n\n var durationGetBigger = 500;\n var durationGetSmaller = 100;\n var frequency = 3;\n var pause = 3000;\n pulsate(elementWrapper, durationGetBigger, durationGetSmaller,\n frequency, pause);\n});\n\nfunction pulsate(elementWrapper, durationBigger, durationSmaller, frequency, pause) {\n for (var i = 0; i &lt; frequency; i++) {\n getBigger(elementWrapper, durationBigger);\n getSmaller(elementWrapper, durationSmaller);\n }\n setTimeout(function () {\n pulsate(elementWrapper, durationBigger, durationSmaller, frequency, pause)\n }, pause);\n}\n\nfunction getBigger(elementWrapper, duration) {\n elementWrapper.element.animate({\n width: elementWrapper.increasedWidth,\n height: elementWrapper.increasedHeight,\n top: elementWrapper.newTop,\n left: elementWrapper.newLeft,\n opacity: 1\n }, duration, 'linear');\n}\n\nfunction getSmaller(elementWrapper, duration) {\n elementWrapper.element.animate({\n width: elementWrapper.originalWidth,\n height: elementWrapper.originalHeight,\n top: 0,\n left: 0,\n opacity: 0.5\n }, duration, 'linear');\n}\n\nfunction ElementWrapper(element, percent) {\n this.element = element;\n this.originalHeight = element.height();\n this.originalWidth = element.width();\n this.increasedHeight = getIncreasedValue(this.originalHeight, percent);\n this.increasedWidth = getIncreasedValue(this.originalWidth, percent);\n this.newLeft = -Math.round((this.increasedWidth - this.originalWidth) / 2);\n this.newTop = -Math.round((this.increasedHeight - this.originalHeight) / 2);\n\n function getIncreasedValue(originalValue, percent) {\n var increase = Math.round(originalValue * (1 + percent / 100));\n if (originalValue % 2 &gt; 0) { // odd\n // make sure increased size is odd too\n return Math.floor(increase / 2) * 2 + 1;\n } \n else {\n return Math.floor(increase / 2) * 2;\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T16:18:22.313", "Id": "36771", "Score": "3", "body": "Just a quick note: you should use camel casing for functions in JavaScript - the only exception being constructors. So, your `ElementWrapper` is fine, but `GetSmaller` should be `getSmaller` etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T01:43:54.920", "Id": "37059", "Score": "0", "body": "@RobH thanks man, you're totally right, edited my post and answer!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T06:06:20.993", "Id": "23822", "ParentId": "23820", "Score": "3" } }, { "body": "<p>Going of drkthng's answer you can just have 1 global variable. Also it is good practice to declare all global variables at the top of a function using 1 var statement. This also brings a small amount of lines needed for initialization. But still room to change things</p>\n\n<pre><code>var Pulsate = {};\n//Default values. \nPulsate.durationGetBigger = Pulsate.durationGetBigger || 500;\nPulsate.durationGetSmaller = Pulsate.durationGetSmaller || 100;\nPulsate.frequency = Pulsate.frequency || 3;\nPulsate.pause = Pulsate.pause || 3000;\n\nPulsate.Pulsate = function (element, growInPercent) {\n Pulsate.elementWrapper = new Pulsate.ElementWrapper(element, growInPercent);\n for (var i = 0; i &lt; Pulsate.frequency; i++) {\n Pulsate.GetBigger();\n Pulsate.GetSmaller();\n }\n setTimeout(function () {\n Pulsate.Pulsate();\n }, Pulsate.pause);\n}\n\nPulsate.GetBigger = function () {\n Pulsate.elementWrapper.element.animate({\n width: Pulsate.elementWrapper.increasedWidth,\n height: Pulsate.elementWrapper.increasedHeight,\n top: Pulsate.elementWrapper.newTop,\n left: Pulsate.elementWrapper.newLeft,\n opacity: 1\n }, Pulsate.durationGetBigger, 'linear');\n}\n\nPulsate.GetSmaller = function () {\n Pulsate.elementWrapper.element.animate({\n width: Pulsate.elementWrapper.originalWidth,\n height: Pulsate.elementWrapper.originalHeight,\n top: 0,\n left: 0,\n opacity: 0.5\n }, Pulsate.durationGetSmaller, 'linear');\n}\n\nPulsate.ElementWrapper = function (element, percent) {\n this.element = element;\n this.originalHeight = element.height();\n this.originalWidth = element.width();\n this.increasedHeight = getIncreasedValue(this.originalHeight, percent);\n this.increasedWidth = getIncreasedValue(this.originalWidth, percent);\n this.newLeft = -Math.round((this.increasedWidth - this.originalWidth) / 2);\n this.newTop = -Math.round((this.increasedHeight - this.originalHeight) / 2);\n\n function getIncreasedValue(originalValue, percent) {\n var increase = Math.round(originalValue * (1 + percent / 100));\n if (originalValue % 2 &gt; 0) { // odd\n // make sure increased size is odd too\n return Math.floor(increase / 2) * 2 + 1;\n }\n else {\n return Math.floor(increase / 2) * 2;\n }\n }\n}\n\n$(document).ready(function () {\n var element = $('#circle'),\n growInPercent = 100;\n Pulsate.Pulsate(element, growInPercent);\n});\n</code></pre>\n\n<p>Heres the fiddle: <a href=\"http://jsfiddle.net/N86tC/4/\" rel=\"nofollow\">http://jsfiddle.net/N86tC/4/</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T10:35:18.467", "Id": "23832", "ParentId": "23820", "Score": "1" } }, { "body": "<p>This isn't completely how I'd do it as I didn't want the changes to be too different. The main thing that I wanted to do was show you a different way of making your element wrapper. If you notice the way I have written it doesn't expose anything other than a getSmaller function and a getBigger function to the rest of your script. This is information hiding - only expose things to the rest of your script that you want other parts to be able to change: </p>\n\n<pre><code>var Pulsate = Pulsate || {};\n\nPulsate.pulsate = function(elementWrapper, durationBigger, durationSmaller, frequency, pause) {\n for (var i = 0; i &lt; frequency; i++) {\n elementWrapper.getBigger(durationBigger);\n elementWrapper.getSmaller(durationSmaller);\n }\n setTimeout(function () {\n Pulsate.pulsate(elementWrapper, durationBigger, durationSmaller, frequency, pause);\n }, pause);\n};\n\nPulsate.ElementWrapper = function (element, percent) {\n var originalHeight = element.height(),\n originalWidth = element.width(),\n increasedHeight,\n increasedWidth,\n newLeft,\n newTop,\n getIncreasedValue;\n\n getIncreasedValue = function (originalValue) {\n var increase = Math.round(originalValue * (1 + percent / 100));\n if (originalValue % 2 &gt; 0) { // odd\n // make sure increased size is odd too\n return Math.floor(increase / 2) * 2 + 1;\n } \n else {\n return Math.floor(increase / 2) * 2;\n }\n };\n\n increasedHeight = getIncreasedValue(originalHeight);\n increasedWidth = getIncreasedValue(originalWidth);\n newLeft = -Math.round((increasedWidth - originalWidth) / 2);\n newTop = -Math.round((increasedHeight - originalHeight) / 2);\n getIncreasedValue = -Math.round((increasedHeight - originalHeight) / 2);\n\n this.getSmaller = function (duration) {\n element.animate({\n width: originalWidth,\n height: originalHeight,\n top: 0,\n left: 0,\n opacity: 0.5\n }, duration, 'linear');\n };\n\n this.getBigger = function (duration) {\n element.animate({\n width: increasedWidth,\n height: increasedHeight,\n top: newTop,\n left: newLeft,\n opacity: 1\n }, duration, 'linear');\n };\n};\n\n$(document).ready(function () {\n var element = $('#circle');\n var growInPercent = 300;\n var elementWrapper = new Pulsate.ElementWrapper(element, growInPercent);\n Pulsate.pulsate(elementWrapper, 500, 500, 3, 3000);\n});\n</code></pre>\n\n<p>Here's the fiddle: <a href=\"http://jsfiddle.net/dVG7R/2/\" rel=\"nofollow\">http://jsfiddle.net/dVG7R/2/</a> </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T16:48:51.853", "Id": "23868", "ParentId": "23820", "Score": "0" } }, { "body": "<p>To keep the global scope clean and to make this more reusable, create a jQuery plugin. This site has some good starting templates for organizing your code into a plugin:\n<a href=\"http://shichuan.github.com/javascript-patterns/\" rel=\"nofollow\">http://shichuan.github.com/javascript-patterns/</a></p>\n\n<p>Here is an example of your code as a plugin:\n<a href=\"http://jsfiddle.net/phil_mcc/VCUXY/\" rel=\"nofollow\">http://jsfiddle.net/phil_mcc/VCUXY/</a></p>\n\n<pre><code>/**\n* The pulsating plugin will make an element on the page pulsate.\n* Sample usage: \n* $(\"#circle\").pulsate({\n growInPercent: 100,\n durationGetBigger: 500,\n durationGetSmaller: 100,\n frequency: 3,\n pause: 3000\n }); \n*/\n(function($) { //This function wrapper will keep all variables out of the global scope\n var PulsatingElement = {\n init: function( options, elem ) {\n // Mix in the passed-in options with the default options\n this.options = $.extend( {}, this.options, options );\n\n //save references to element\n this.elem = elem;\n this.$elem = $(elem);\n\n this.setupHeightWidth();\n this.animate();\n\n //return copy for chaining\n return this;\n },\n //set default options\n options: {\n growInPercent: 20,\n durationGetBigger: 500,\n durationGetSmaller: 100,\n frequency: 3,\n pause: 3000\n }, \n setupHeightWidth: function () {\n this.originalHeight = this.$elem.height(); \n this.increasedHeight = Math.round(this.originalHeight * (1 + this.options.growInPercent / 100));\n\n if (this.originalHeight % 2 &gt; 0) { // odd\n // make sure increased size is odd too\n this.increasedHeight = Math.floor(this.increasedHeight / 2) * 2 + 1;\n } else {\n this.increasedHeight = Math.floor(this.increasedHeight / 2) * 2\n }\n\n this.originalWidth = this.$elem.width();\n this.increasedWidth = Math.round(this.originalWidth * (1 + this.options.growInPercent / 100));\n if (this.originalWidth % 2 &gt; 0) { // odd\n this.increasedWidth = Math.floor(this.increasedWidth / 2) * 2 + 1;\n } else {\n this.increasedWidth = Math.floor(this.increasedWidth / 2) * 2;\n }\n this.newLeft = -Math.round((this.increasedWidth - this.originalWidth) / 2);\n this.newTop = -Math.round((this.increasedHeight - this.originalHeight) / 2);\n },\n animate: function () {\n for (var i = 0; i &lt; this.options.frequency; i++) {\n this.getBigger(this.options.durationBigger);\n this.getSmaller(this.options.durationSmaller);\n } \n\n var self = this; //need a copy of object that can be referenced in the timeout\n setTimeout(function () {\n self.animate()\n }, this.options.pause);\n },\n getBigger: function (duration) {\n this.$elem.animate({\n width: this.increasedHeight,\n height: this.increasedWidth,\n top: this.newTop,\n left: this.newLeft,\n opacity: 1\n }, duration, 'linear');\n },\n getSmaller: function (duration) {\n this.$elem.animate({\n width: this.originalWidth,\n height: this.originalHeight,\n top: 0,\n left: 0,\n opacity: 0.5\n }, duration, 'linear');\n }\n };\n\n // Object.create support test, and fallback for browsers without it\n if ( typeof Object.create !== 'function' ) {\n Object.create = function (o) {\n function F() {}\n F.prototype = o;\n return new F();\n };\n }\n\n // Create a plugin based on a defined object\n $.plugin = function( name, object ) {\n $.fn[name] = function( options ) {\n return this.each(function() {\n if ( ! $.data( this, name ) ) {\n $.data( this, name, Object.create(object).init(\n options, this ) );\n }\n });\n };\n }; \n\n //create a plugin called pulsate that uses the PulsatingElement Object\n $.plugin('pulsate', PulsatingElement);\n})( jQuery );\n\n\n$(function () {\n $(\"#circle\").pulsate({\n growInPercent: 100,\n durationGetBigger: 500,\n durationGetSmaller: 100,\n frequency: 3,\n pause: 3000\n });\n $(\"#circle2\").pulsate({\n growInPercent: 100,\n durationGetBigger: 100,\n durationGetSmaller: 500,\n frequency: 3,\n pause: 4000\n });\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T18:23:23.810", "Id": "23877", "ParentId": "23820", "Score": "3" } } ]
{ "AcceptedAnswerId": "23877", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T03:18:06.857", "Id": "23820", "Score": "5", "Tags": [ "javascript", "jquery", "beginner" ], "Title": "Providing one-time calculations to frequently used methods" }
23820
<p>This is completely optimization question, I have a pagination query like this:</p> <pre><code>$this-&gt;paginate = array( 'fields' =&gt; array( 'DISTINCT Contact.contact_id', 'Contact.first_name', 'Contact.last_name', 'Contact.email', 'Contact.created', 'ContactGroup.name', ), 'conditions' =&gt; array( $this-&gt;conditions, 'ContactsContactGroup.contact_group_id'=&gt;$viewList, isset($keywordQuery)?$keywordQuery:"", ), 'limit' =&gt; 5, 'group' =&gt; array('Contact.contact_id') ); $data = $this-&gt;paginate('ContactsContactGroup'); $data = $this-&gt;paginate('ContactsContactGroup'); </code></pre> <p>This query is called in every if and else statement, I have four conditions of <code>if</code> and <code>else</code>, and in all conditions the above piece of code is written.</p> <p>I want to optimize, and avoid the big line of code in every condition. How can I optimize it? Any answer will be appreciated.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-01T17:11:41.290", "Id": "85491", "Score": "0", "body": "you can half the cost of that code by calling paginate only once =)" } ]
[ { "body": "<p>Perhaps you could wrap it all in a function:</p>\n\n<pre><code>function pagination($this,$viewList,$keywordQuery)\n{\n $this-&gt;paginate = array(\n 'fields' =&gt; array(\n 'DISTINCT Contact.contact_id',\n 'Contact.first_name',\n 'Contact.last_name',\n 'Contact.email',\n 'Contact.created',\n 'ContactGroup.name',\n ), \n 'conditions' =&gt; array(\n $this-&gt;conditions,\n 'ContactsContactGroup.contact_group_id'=&gt;$viewList, \n isset($keywordQuery)?$keywordQuery:\"\",\n ), \n 'limit' =&gt; 5,\n 'group' =&gt; array('Contact.contact_id')\n );\n\n return $this-&gt;paginate('ContactsContactGroup');\n\n}\n\nif(something())\n{\n //something\n $data=pagination($this,$viewList,$keywordQuery);\n}\nelse\n{\n //other\n $data=pagination($that,$viewList,$keywordQuery);\n}\n</code></pre>\n\n<p>etc..</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T19:51:30.353", "Id": "36866", "Score": "0", "body": "I'm sorry, but really, what sort of code review comes up with an answer that includes `global`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T20:34:17.693", "Id": "36870", "Score": "0", "body": "just a quick way to clean up his duplicate code. either that, or they can just delete it all, start over." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T20:42:20.293", "Id": "36872", "Score": "0", "body": "I get you though. @usii, maybe make the function return $data;" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T19:37:14.410", "Id": "23930", "ParentId": "23821", "Score": "2" } } ]
{ "AcceptedAnswerId": "23930", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T06:03:12.783", "Id": "23821", "Score": "2", "Tags": [ "performance", "php", "php5", "pagination", "cakephp" ], "Title": "How to optimize the pagination query?" }
23821
<p>Is this a good CSS? </p> <pre><code> .table1 thead tr td, .table1 tbody tr td, .table2 thead tr td, .table3 tbody tr td:first-child, .table4 tbody tr td:first-child, .table7 tbody tr td:first-child ,.table7 tbody tr td:nth-child(2), .table8 tbody tr td:first-child, .table9 tbody tr td{background-color:#cfeae6} .table1 thead tr td, .table2 thead tr td, .table7 tbody tr td, .table8 tbody tr td{border-top: 4px solid #a3c6cd; border-bottom:4px solid #a3c6cd} .table1 tbody tr td, .table2 tbody tr td, .table3 tbody tr td, .table9 tbody tr td{border:1px solid #a3c6cd;} .table1 tbody tr td:first-child, .table2 tbody tr td:first-child, .table5 tbody tr td:first-child, .table9 tbody tr td:first-child, .table9 tbody tr td:nth-child(3){border-left:none} .table1 tbody tr td:last-child, .table2 tbody tr td:last-child, .table5 tbody tr td:last-child ,.table8 tbody tr td:last-child, table.borderright thead tr td:last-child, .table9 tbody tr td:last-child, .table9 tbody tr td:nth-child(2){border-right:none} .table2 tbody tr td{background-color:#e8f5f1} .table2 tbody{border-bottom:4px solid #a3c6cd} .table5 tbody tr td{border-left:5px solid #a3c6cd; border-right:5px solid #a3c6cd} .table7 tbody tr td:first-child ,.table7 tbody tr td:nth-child(2), .table8 tbody tr td{border-right:1px solid #a3c6cd} .table9 tbody tr td:first-child{border-right:2px solid #a3c6cd} </code></pre>
[]
[ { "body": "<p>Well, I suggest to use some more whitespace and use a CSS minifier to strip the whitespace in production, this doesn't look that nice... Some things:</p>\n\n<hr>\n\n<pre><code>border-top: 4px solid #a3c6cd; border-bottom:4px solid #a3c6cd\n</code></pre>\n\n<p>This can be easier done by using the <code>border</code> shortcut and the <code>border-style</code> property:</p>\n\n<pre><code>border:4px #a3c6cd;\nborder-style: solid none;\n</code></pre>\n\n<p>Here, <code>border-style: solid none;</code> means <code>&lt;bottom,top&gt; &lt;left, right&gt;</code>.</p>\n\n<hr>\n\n<p>You have much too exact selectors. For instance, this:</p>\n\n<pre><code>.table1 thead tr td, .table1 tbody tr td,\n</code></pre>\n\n<p>Can faster be write as:</p>\n\n<pre><code>.table1 td\n</code></pre>\n\n<p>The same for all other selectors. Don't be exact if you don't need to be exact.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T07:34:50.873", "Id": "23824", "ParentId": "23823", "Score": "5" } }, { "body": "<p>Chris is right, this is over-scoped. I am not sure why you have .table1, .table2, .table3, .table4, but here:</p>\n\n<p>A. Create one <strong>generic</strong> table class</p>\n\n<pre><code>.data\n{\n\n} \n\n.data td\n{\n\n}\n</code></pre>\n\n<p>B. Create modifiers for behavior or <strong>options</strong></p>\n\n<pre><code>.data--hover tr:active td\n{\n\n}\n\n&lt;table class=\"data data--hover\"&gt; &lt;!--See how I conjoin them--&gt;\n\n&lt;/table&gt;\n</code></pre>\n\n<p>C. If they have different appearences, create skin classes</p>\n\n<pre><code>.zebra tr:nth-child(odd) td\n{\n\n}\n\n&lt;table class=\"zebra data data--hover\"&gt;\n\n&lt;/table&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-09T05:18:54.563", "Id": "25970", "ParentId": "23823", "Score": "3" } } ]
{ "AcceptedAnswerId": "23824", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T07:16:13.247", "Id": "23823", "Score": "2", "Tags": [ "css" ], "Title": "CSS Code Quality" }
23823
<p>Is it possible to write the two following lines of code in a more compact one?</p> <pre><code>IEnumerable&lt;int&gt; collection = from partnerNumbers in contract.Contact.PartnerNumbers select partnerNumbers.Pnr; var response = this.otherClass.SomeMethod(collection, DateTime.Now.Date); </code></pre> <p>Additional information:</p> <pre><code>public int SomeMethod(IEnumerable&lt;int&gt; partnerNumbers, DateTime startDate) { ... } ... [Table("Conracts")] public class Contract { public virtual Contact contact { get; set; } } ... public class Contact { public virtual Collection&lt;PartnerNumbers&gt; PartnerNumbers { get; private set; } } ... public class PartnerNumbers { public int Id { get; set; } public virtual int Pnr { get; set; } public string Information { get; set; } public virtual Contact contact { get; set; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T08:37:26.257", "Id": "36730", "Score": "0", "body": "`DateTime.Today`" } ]
[ { "body": "<p>Idon't see why you would want to shorten that piece of code but here's the same result in one line and using a LinQ method-chain instead of query-syntax:</p>\n\n<pre><code>var response = otherClass.SomeMethod(contract.Contact.PartnerNumbers.Select(p =&gt; p.Pnr), DateTime.Now.Date);\n</code></pre>\n\n<p><strong>Edit:</strong></p>\n\n<p>Since you have no parameters that have influence on the calculation of the response, here's a method for re-usability:</p>\n\n<pre><code>public int GetResponse()\n{\n var collection = from partnerNumbers in contract.Contact.PartnerNumbers select partnerNumbers.Pnr;\n var response = this.otherClass.SomeMethod(collection, DateTime.Now.Date);\n return response;\n}\n</code></pre>\n\n<p>or with LinQ method-chain:</p>\n\n<pre><code>public int GetResponse()\n{\n return otherClass.SomeMethod(contract.Contact.PartnerNumbers.Select(p =&gt; p.Pnr), DateTime.Now.Date);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T08:32:31.517", "Id": "36728", "Score": "0", "body": "Thank you for your answer! I want to refactor this code cause it is used not only in one place and I have asked myself - whether it is possible to use some other consruct than 2 lines of code every time I want it. Thats why I have posted my qustion here :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T08:47:52.423", "Id": "36734", "Score": "0", "body": "No problem. Otherwise you should create a method and re-use that method when you need it. Check my edited answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T08:25:29.260", "Id": "23826", "ParentId": "23825", "Score": "5" } }, { "body": "<p>Add this read only property to your <code>Contact</code> class.</p>\n\n<pre><code>public class Contact\n{\n public IEnumerable&lt;int&gt; Pnrs\n {\n get\n {\n return from pn in PartnerNumbers select pn.Pnr;\n }\n }\n }\n</code></pre>\n\n<p>And then you can use it like this:</p>\n\n<pre><code>var response = this.otherClass.SomeMethod(contract.Contact.Pnrs, DateTime.Now.Date);\n</code></pre>\n\n<p>In case your Contact class is automatically generated then you would want to put this in another partial class. Or you may want to add this as an extension method to Contact.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T12:36:45.123", "Id": "23837", "ParentId": "23825", "Score": "2" } } ]
{ "AcceptedAnswerId": "23837", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T07:44:16.930", "Id": "23825", "Score": "3", "Tags": [ "c#", "linq", "entity-framework" ], "Title": "Refactoring from .. in .. select to more compact one" }
23825
<p>I have created a simple DBLayer class. But I am not sure whether this class have any bug/issue using in production. </p> <pre><code>public class DBLayer { private static string connectionString = ConfigurationManager.AppSettings["ConnectionString"]; public static DataTable GetDataTable(string strSQL, CommandType type) { var objCmd = new SqlCommand(strSQL); objCmd.CommandType = type; return GetDataTable(objCmd); } public static DataTable GetDataTable(SqlCommand objCmd) { SqlConnection objConn = null; try { objConn = new SqlConnection(connectionString); objCmd.Connection = objConn; var objAdapter = new SqlDataAdapter(objCmd); var ds = new DataSet(); objAdapter.Fill(ds); return ds.Tables[0]; } finally { objConn.Close(); } } public static int ExecuteNonQuery(SqlCommand objCmd) { int r = -1; SqlConnection objConn = null; try { objConn = new SqlConnection(connectionString); objCmd.Connection = objConn; objConn.Open(); r = objCmd.ExecuteNonQuery(); } finally { objConn.Close(); } return r; } } </code></pre> <p>Please review this code?</p>
[]
[ { "body": "<p>Looks good. You may also want some other things like <code>getScalar</code> (A single object, or string, as in 1 cell), <code>getDataRow</code>, just the top row, <code>getDataRowCollection</code>, i frequently only use datatable to get the rows, and forget about the columns, so I can iterate over it like so....</p>\n\n<pre><code>DataRowCollection drc = getDataRowCollection(\"SELECT * FROM tblTest\");\nfor(DataRow r in drc){\n Console.WriteLine(r[\"name\"]);\n}\n</code></pre>\n\n<p>So you could have <code>NonQuery</code>, you may want to test these before using them....</p>\n\n<pre><code> public DataTable getDataTable(SqlCommand objCmd)\n {\n SqlConnection objConn = null;\n try\n {\n objConn = new SqlConnection(connectionString);\n objCmd.Connection = objConn;\n var objAdapter = new SqlDataAdapter(objCmd);\n var ds = new DataSet();\n objAdapter.Fill(ds);\n return ds.Tables[0];\n }\n finally\n {\n objConn.Close();\n }\n }\n\n public DataRowCollection getDataRowCollection(SqlCommand objCmd)\n {\n return getDataTable(objCmd).Rows;\n }\n\n public DataRow getDataRow(SqlCommand objCmd){\n return getDataRowCollection(objCmd)[0];\n }\n\n public string getScalar(SqlCommand objCmd)\n {\n SqlConnection objConn = null;\n try\n {\n objConn = new SqlConnection(connectionString);\n objCmd.Connection = objConn;\n return objCmd.ExecuteScalar().ToString();\n }\n finally\n {\n objConn.Close();\n }\n }\n\n public int NonQuery(SqlCommand objCmd)\n {\n SqlConnection objConn = null;\n try\n {\n objConn = new SqlConnection(connectionString);\n objCmd.Connection = objConn;\n return objCmd.ExecuteNonQuery();\n }\n finally\n {\n objConn.Close();\n }\n }\n</code></pre>\n\n<p>I would recommend writing quite a few variations of the methods, and implement enums for each connection string so you don't mis-type anywhere and have them set in concrete. </p>\n\n<p>Take a look at my <code>getScalar</code> variations....</p>\n\n<pre><code> public static string getScalar(string query)\n {\n return getScalar(query, defaultConnection);\n }\n\n public static string getScalar(string query, ConnectionString cs)\n {\n return getScalar(query, new { }, cs);\n }\n\n public static string getScalar(string query, object param, ConnectionString cs)\n {\n return getScalar(query, param, cs, defaultTimeout);\n }\n public static string Query(string query, object param, int to)\n {\n return getScalar(query, param, defaultConnection, to);\n }\n\n public static string getScalar(string query, object param, ConnectionString cs, int to)\n {\n return getScalar(ConnectionStringToDb(cs), query, param, to);\n }\n\n public static string getScalar(MySqlConnection db, string query)\n {\n return getScalar(db, query, defaultTimeout);\n }\n\n public static string getScalar(MySqlConnection db, string query, int to)\n {\n return getScalar(db, query, null, to);\n }\n\n public static string getScalar(MySqlConnection db, string query, object param, int to)\n {\n string result = \"\";\n if (db.State != ConnectionState.Open)\n OpenConnection(db);\n MySqlParameter[] p = ObjectToParameters(param);\n using (db)\n {\n try\n {\n MySqlCommand command = new MySqlCommand();\n command.Connection = db;\n command.CommandText = query;\n command.CommandTimeout = to;\n foreach (MySqlParameter pm in p)\n {\n command.Parameters.Add(pm);\n }\n result = command.ExecuteScalar().ToString();\n }\n catch { }\n }\n return result;\n }\n</code></pre>\n\n<p>Also if you class works as expected it should be fine... Looks okay. I use mine day to day, but I use MySql so I'm not to sure on the differences between the two classes, should be relatively the same. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T09:40:57.883", "Id": "23829", "ParentId": "23828", "Score": "3" } }, { "body": "<p>There are several issues in the code:</p>\n\n<ul>\n<li>do use <code>using</code> statement to dispose connections and other disposable objects</li>\n<li>static methods won't allow you to use unit-testing on your business logic.</li>\n<li>don't use <code>obj</code> prefixes or non-descriptive names like <code>r</code></li>\n</ul>\n\n<p>As a result of original code refactoring I got the following:</p>\n\n<pre><code>public interface IDBLayer\n{\n DataTable GetDataTable(SqlCommand command);\n int ExecuteNonQuery(SqlCommand command);\n}\n\npublic static class DBLayerExtensions\n{\n public static DataTable GetDataTable(this IDBLayer dbLayer, string sql, CommandType type)\n {\n using (var command = new SqlCommand(sql))\n {\n command.CommandType = type;\n return dbLayer.GetDataTable(command);\n }\n }\n}\n\npublic class DBLayer : IDBLayer\n{\n private static readonly string _connectionString = ConfigurationManager.AppSettings[\"ConnectionString\"];\n\n public DataTable GetDataTable(SqlCommand command)\n {\n using (var connection = new SqlConnection(_connectionString))\n using (var dataAdapter = new SqlDataAdapter(command))\n {\n command.Connection = connection;\n var result = new DataTable();\n dataAdapter.Fill(result);\n return result;\n }\n }\n\n public int ExecuteNonQuery(SqlCommand command)\n {\n using (var connection = new SqlConnection(_connectionString))\n {\n command.Connection = connection;\n connection.Open();\n return command.ExecuteNonQuery();\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T11:41:45.053", "Id": "36739", "Score": "0", "body": "I like your approach. But the problem is that in the project static methods invocation are spoiled all over places. So, I can't make it instance. However, I will use using clause. Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T10:25:35.043", "Id": "23831", "ParentId": "23828", "Score": "2" } } ]
{ "AcceptedAnswerId": "23829", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T09:10:12.743", "Id": "23828", "Score": "3", "Tags": [ "c#", "sql-server" ], "Title": "Simple DBLayer class review" }
23828
<p>I am learning C# from a book, and there is an exercise as follows:</p> <blockquote> <p>Write a program that has a person enter full name, age, and phone number. Display this information with formatting. Also display the person's initials.</p> </blockquote> <p>I wrote some code and I feel that it could be improved, so I ask anyone to comment on it.</p> <pre><code>using System; using System.Collections.Generic; internal class Person { public string fname; public string mname; public string lname; public int age; public string phnumber; public Person() { fname = KeyInput.keyIn("\n\nPlease enter your first name"); if (fname.ToLower() == "exit") return; mname = KeyInput.keyIn("\nPlease enter your middle name"); lname = KeyInput.keyIn("\nPlease enter your last name"); while (true) { try { age = Convert.ToInt32(KeyInput.keyIn("\nPlease enter your age")); break; } catch (ArgumentException) { Console.WriteLine("No value was entered"); } catch (FormatException) { Console.WriteLine("You didn't entered a valid number"); } catch (Exception e) { Console.WriteLine("Something went wrong with the conversion."); } } phnumber = KeyInput.keyIn("\nPlease enter your phone number"); } public void personDataDisplay() { Console.WriteLine("\nYour name is: " + fname + " " + mname[0] + "." + " " + lname); Console.WriteLine("Your initials are: " + fname[0] + mname[0] + lname[0]); Console.WriteLine("Your age is: " + age); Console.WriteLine("Your phone number is: " + phnumber + "\n"); } } internal class KeyInput { public static string keyIn(string scrtext) { Console.WriteLine(scrtext); string buffer = Console.ReadLine(); return buffer; } } internal class MyApp { public static void Main() { Console.WriteLine("Please enter data for person(s). Enter EXIT to end."); List&lt;Person&gt; list_persons = new List&lt;Person&gt;(); while (true) { Person person = new Person(); list_persons.Add(person); if (person.fname.ToLower() == "exit") break; } foreach (Person person in list_persons) { if (person.fname.ToLower() == "exit") break; person.personDataDisplay(); } } } </code></pre>
[]
[ { "body": "<p>In designing classes we should try and confirm to the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\">Single Responsibility Principle</a>. Each class should only do one thing. Sometimes defining what makes a single responsibility is hard, but your <code>Person</code> class clearly does two things: it represents a person, and it questions the user via the console. This makes it difficult to reuse your <code>Person</code> class: what if you wanted to create a <code>Person</code> from a database, or a file or a web request? You would be better splitting this into a <code>PersonQuestionnaire</code> class which is responsible for creating a <code>Person</code> from a console input.</p>\n\n<p>You should never have any significant logic in your constructor like you have here. <a href=\"http://msdn.microsoft.com/en-gb/library/vstudio/ms229060%28v=vs.100%29.aspx\">Design your constructors to simply save any parameters and set up any default values</a>. Any logic involving external classes, such as the Console, should definitely be placed in another method that is called once the object is constructed. </p>\n\n<p>You should consider using the <a href=\"http://msdn.microsoft.com/en-gb/library/system.int32.tryparse.aspx\"><code>int.TryParse()</code></a> method to read the age. Catching exceptions is slow (you will notice you ever write applications that are doing a lot of this type of thing), verbose, and sometimes unpredictable. You should definitely avoid catching the top level <code>Exception</code> type <a href=\"http://www.codeproject.com/Articles/7557/Exception-Handling-in-C-with-the-quot-Do-Not-Catch\">other than where you can do something meaningful</a>: doing a lot of this will make your applications very difficult to debug.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T12:33:08.153", "Id": "23836", "ParentId": "23835", "Score": "12" } }, { "body": "<p><strong>Person</strong></p>\n\n<p>Split user-input from your class definition. It's not a good practice to mix the input in the definition. Try to decouple as much as possible. I also redefined the properties in the class:</p>\n\n<pre><code>public string FirstName { get; set; }\npublic string MiddleName { get; set; }\npublic string LastName { get; set; }\npublic int Age { get; set; }\npublic string Phone { get; set; }\n</code></pre>\n\n<p>Same goes for displaying the information about the person. It's not a good practice to write it to screen from within this class. Just override the ToString()-method and display this on screen. The FirstChar()-method is there to check if the name exists to take the first character of that name, otherwise return a spacer.</p>\n\n<pre><code>public override string ToString()\n{\n StringBuilder sb = new StringBuilder();\n sb.AppendLine(String.Format(\"Your name is: {0} {1}. {2}\", FirstName, FirstChar(MiddleName), LastName));\n sb.AppendLine(String.Format(\"Your initials are: {0}{1}{2}\", FirstChar(FirstName), FirstChar(MiddleName), FirstChar(LastName)));\n sb.AppendLine(String.Format(\"Your age is: {0}\", Age));\n sb.AppendLine(String.Format(\"Your phone number is: {0}\", Phone));\n\n return sb.ToString();\n}\n\nprivate char FirstChar(string input)\n{\n return String.IsNullOrEmpty(input) ? ' ' : input[0];\n}\n</code></pre>\n\n<p><strong>Input</strong></p>\n\n<p>Since the input is not mixed in the Person-class we have to declare it somewhere else. In this example I put the input-code in the KeyInput class. The method returns an instance of the Person-class and if the user enters \"exit\", null is returned. This way we can later on catch if the user wants to stop.</p>\n\n<pre><code>public static Person NewPerson()\n{\n string first = KeyInput.keyIn(\"Please enter your first name: \");\n if (first.ToLower().Equals(\"exit\"))\n return null;\n\n string middle = KeyInput.keyIn(\"Please enter your middle name: \");\n string last = KeyInput.keyIn(\"Please enter your last name: \");\n int age = 0;\n\n while (true)\n {\n try\n {\n age = Convert.ToInt32(KeyInput.keyIn(\"Please enter your age\"));\n break;\n }\n catch (ArgumentException)\n {\n Console.WriteLine(\"No value was entered\");\n }\n catch (FormatException)\n {\n Console.WriteLine(\"You didn't entered a valid number\");\n }\n catch (Exception)\n {\n Console.WriteLine(\"Something went wrong with the conversion.\");\n }\n }\n\n string phone = KeyInput.keyIn(\"Please enter your phone number\\n\");\n\n return new Person { FirstName = first, MiddleName = middle, LastName = last, Age = age, Phone = phone };\n}\n</code></pre>\n\n<p><strong>Main</strong></p>\n\n<p>Since all previous code has changed, the logic of your Main will change too.</p>\n\n<pre><code>public static void Main()\n{\n Console.WriteLine(\"Please enter data for person(s). Enter EXIT to end.\");\n\n List&lt;Person&gt; people = new List&lt;Person&gt;();\n\n while (true)\n {\n var person = KeyInput.NewPerson();\n\n if(person == null)\n break;\n\n people.Add(person);\n }\n\n foreach (var person in people)\n {\n Console.WriteLine(person.ToString());\n }\n}\n</code></pre>\n\n<p><strong>Summary</strong></p>\n\n<p>I'm not saying that my code is perfect in any way. Probably my code could be revised and corrected as well. I only want to show you the way how you decouple user-input from class-definitions, use proper variable names, bring a proper structure and logic in your code. Please feel free if to comment if anything's wrong with my code.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>Thanks to the valid comments I received, I edited the code. The posters of the comments were absolutely right. I've also rewritten the Initial()-method to a more correct logic. Here's the result in it's entirety:</p>\n\n<pre><code>internal class Person\n{\n public string FirstName { get; set; }\n public string MiddleName { get; set; }\n public string LastName { get; set; }\n public int Age { get; set; }\n public string Phone { get; set; }\n\n public override string ToString()\n {\n var sb = new StringBuilder();\n\n sb.AppendFormat(\"Your name is: {0} {1} {2}\", FirstName, Initial(MiddleName, true), LastName).AppendLine();\n sb.AppendFormat(\"Your initials are: {0}{1}{2}\", Initial(FirstName, false), Initial(MiddleName, false), Initial(LastName, false)).AppendLine();\n sb.AppendFormat(\"Your age is: {0}\", Age).AppendLine();\n sb.AppendFormat(\"Your phone number is: {0}\", Phone).AppendLine();\n\n return sb.ToString();\n }\n\n private static string Initial(string input, bool dot)\n {\n if (String.IsNullOrEmpty(input))\n return input;\n\n if(input.Contains(\" \"))\n return input.Split(' ').Aggregate(\"\", (current, s) =&gt; current + s[0]);\n\n return input[0] + (dot ? \".\" : \"\");\n }\n}\n\ninternal class KeyInput\n{\n public static string KeyIn(string scrtext)\n {\n Console.Write(scrtext);\n var buffer = Console.ReadLine();\n return buffer;\n }\n}\n\ninternal class Program\n{\n public static void Main(string[] args)\n {\n Console.WriteLine(\"Please enter data for one or more person(s).\" + Environment.NewLine);\n\n var people = new List&lt;Person&gt;();\n var newInput = true;\n\n while (newInput)\n {\n var person = GetNewPerson();\n people.Add(person);\n newInput = KeyInput.KeyIn(\"Add another person? (Y/N): \").ToLower().Equals(\"y\");\n }\n\n foreach (var person in people)\n Console.WriteLine(person.ToString() + Environment.NewLine);\n\n Console.ReadKey();\n }\n\n public static Person GetNewPerson()\n {\n var first = KeyInput.KeyIn(\"Please enter your first name: \");\n var middle = KeyInput.KeyIn(\"Please enter your middle name: \");\n var last = KeyInput.KeyIn(\"Please enter your last name: \");\n int age;\n\n while (!int.TryParse(KeyInput.KeyIn(\"Please enter your age: \"), out age))\n Console.WriteLine(\"Invalid input, try again...\");\n\n var phone = KeyInput.KeyIn(\"Please enter your phone number: \");\n\n return new Person { FirstName = first, MiddleName = middle, LastName = last, Age = age, Phone = phone };\n }\n}\n</code></pre>\n\n<p>Still feel free to comment, I'm learning myself! ;)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T15:55:05.087", "Id": "36769", "Score": "5", "body": "NewPerson() feels wrong in the KeyInput class. They are two completely separate operations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T16:02:41.630", "Id": "36770", "Score": "2", "body": "I don't like seeing `while(true)` - it makes me have to figure out why you're looping - I'd change it to `while(!int.TryParse(KeyInput.keyIn(\"Please enter your age\"), out age))` or use a well named variable. I'd also use `sb.AppendFormat(...).AppendLine()` but that's personal preference." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T22:46:47.967", "Id": "36805", "Score": "0", "body": "I edited my answer based on your useful comments :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T09:41:26.000", "Id": "36818", "Score": "0", "body": "Thank you for your effort to provide such a detailed insight into my code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T10:27:32.407", "Id": "36821", "Score": "0", "body": "No problem, I hope it helped you further!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T12:52:59.380", "Id": "23838", "ParentId": "23835", "Score": "4" } }, { "body": "<p>In addition to the other good advice in the other answers, I would add:</p>\n\n<ul>\n<li>Do not catch any exception that you could have prevented. Instead, prevent the exception.</li>\n</ul>\n\n<p>There is never any reason to catch <code>ArgumentException</code> because it should never be thrown in the first place. <em>You</em> are responsible for ensuring that when you pass arguments to a method, that those arguments meet the requirements of the method you're calling. You know if the string you're going to pass is null or empty; if it is, <em>don't pass it</em>. </p>\n\n<p>Read this for more information:</p>\n\n<p><a href=\"http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx\">http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T15:39:33.560", "Id": "23861", "ParentId": "23835", "Score": "12" } }, { "body": "<p>What happens when someone does not have a middle name? I think you'll find that if you test that, nothing good happens.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T18:37:30.080", "Id": "36778", "Score": "0", "body": "You are right, I should better check if it is null or empty, however this is misunderstanding due to language/region barrier, as in my country everyone has a middle name as it is considered to be one of parents name (usually father's name)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T21:00:34.853", "Id": "36794", "Score": "2", "body": "@nenad: I would hazard a guess that *most* of the people in your country have a middle name, not *everyone*. One of the things you learn writing software to be used by people is that assuming that what *most* people do is the same as what *everyone* does just leads to pain later." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T15:41:33.690", "Id": "23862", "ParentId": "23835", "Score": "6" } }, { "body": "<h3>Working our way out of this mess</h3>\n\n<p>You have been given some good tips about separating concerns and coding to prevent exceptions. The application itself should be a very simple loop. Parsing user input and formatting output takes up most of the code.</p>\n\n<p>Ideally, we would like to end up with this loop:</p>\n\n<pre><code>public static void Run()\n{\n UserPane.AppInfo();\n while (true) // until 'EXIT' is typed by user\n {\n UserPane.PersonInfo(UserPane.ReadPerson());\n }\n}\n</code></pre>\n\n<p>To get there, we require some refactoring. Also note, that unlike your perpetual checks for early exit, I would opt to let a low level handler (shown later on) exit the process on one place (<a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a>). This enables us to avoid redundant code in the likes of..</p>\n\n<blockquote>\n<pre><code>if (person.fname.ToLower() == \"exit\") break;\n</code></pre>\n</blockquote>\n\n<p>Let's start with cleaning up <code>Person</code>. As suggested by others, you should adhere to <em>Separation of Concerrns</em>. We will have to take out the <code>Console</code> printing. Furthermore, we need proper naming and member declaration conventions. Do not abbreviate member names. Prefer properties over public fields.</p>\n\n<blockquote>\n<pre><code>public string fname;\npublic string mname;\npublic string lname;\npublic int age;\npublic string phnumber;\n</code></pre>\n</blockquote>\n\n<p>We end up with this POCO:</p>\n\n<pre><code>class Person\n{\n public string FirstName { get; set; }\n public string MiddleName { get; set; }\n public string LastName { get; set; }\n public int Age { get; set; }\n public string PhoneNumber { get; set; }\n}\n</code></pre>\n\n<p>It's time to focus on user input. You already started a class <code>KeyInput</code>, which is a good idea to offset <code>Console</code> interop to. But you could have gone much further with this design to allow for clean application code.</p>\n\n<blockquote>\n<pre><code>internal class KeyInput\n{\n public static string keyIn(string scrtext)\n {\n // .. code omitted for brevity\n }\n}\n</code></pre>\n</blockquote>\n\n<p>This should be avoided in application code:</p>\n\n<blockquote>\n<pre><code>while (true)\n{\n try\n {\n age = Convert.ToInt32(KeyInput.keyIn(\"\\nPlease enter your age\"));\n break;\n }\n\n catch (ArgumentException)\n {\n Console.WriteLine(\"No value was entered\");\n }\n\n // .. code omitted for brevity\n}\n</code></pre>\n</blockquote>\n\n<p>Let's make a class <code>UserPane</code>, which will handle both user input and formatted output. The code method for reading input is <code>Read&lt;T&gt;</code>. It provides a generic way to prompt the user for input, validate the input, allowing for retries, exiting the application on demand and projecting input to any other meaningful type.</p>\n\n<pre><code>static class UserPane\n{\n const string Exit = \"exit\";\n\n static T Read&lt;T&gt;(string prompt, Func&lt;string, bool&gt; validator, Func&lt;string, T&gt; projector,\n string validationMessage = null, Action exitHandler = null)\n {\n string input = default;\n var validated = false;\n Console.WriteLine($\"\\r\\n{prompt}\");\n\n do\n {\n input = Console.ReadLine().Trim();\n\n if (input.ToLowerInvariant().Trim().Equals(Exit))\n {\n if (exitHandler == null)\n {\n exitHandler = () =&gt; {\n Environment.ExitCode = 1;\n Environment.Exit(Environment.ExitCode);\n };\n }\n exitHandler();\n return default;\n }\n\n validated = validator(input);\n\n if (!validated)\n {\n if (validationMessage == null)\n {\n validationMessage = \"Please try again.\";\n }\n Console.WriteLine(validationMessage);\n }\n\n } while (!validated);\n\n\n return projector(input);\n }\n}\n</code></pre>\n\n<p>This allows us to make convenience methods for asking user input. The ones we need for our application are..</p>\n\n<pre><code>static string ReadNonEmptyString(string prompt)\n{\n return Read(prompt, input =&gt; !string.IsNullOrEmpty(input), input =&gt; input);\n}\n\nstatic string ReadString(string prompt)\n{\n return Read(prompt, input =&gt; true, input =&gt; input);\n}\n\nstatic int ReadInt32(string prompt)\n{\n return Read(prompt, input =&gt; int.TryParse(input, out var dummy), input =&gt; int.Parse(input));\n}\n</code></pre>\n\n<p>With all these methods in place, we can now read a <code>Person</code> from user input. Like suggested by others, the middle name is optional. The phone number is parsed as any string. As an exercise, you could extend the parser to allow for a <code>ReadPhoneNumber</code> method.</p>\n\n<pre><code>internal static Person ReadPerson()\n{\n return new Person\n {\n FirstName = ReadNonEmptyString(\"Please enter your first name:\"),\n MiddleName = ReadString(\"Please enter your middle name (optional):\"),\n LastName = ReadNonEmptyString(\"Please enter your last name:\"),\n Age = ReadInt32(\"Please enter your age:\"),\n PhoneNumber = ReadNonEmptyString(\"Please enter your phone number:\")\n };\n}\n</code></pre>\n\n<p>The last step is allowing for custom formatting and outputting to the console.</p>\n\n<pre><code>internal static void PersonInfo(Person person)\n{\n var hasMiddleName = !string.IsNullOrEmpty(person.MiddleName);\n\n if (hasMiddleName)\n {\n Console.WriteLine($\"Your name is: {person.FirstName} {person.MiddleName}. {person.LastName}\");\n Console.WriteLine($\"Your initials are: {person.FirstName[0]}{person.MiddleName[0]}{person.LastName[0]}\");\n }\n else\n {\n Console.WriteLine($\"Your name is: {person.FirstName} {person.LastName}\");\n Console.WriteLine($\"Your initials are: {person.FirstName[0]}{person.LastName[0]}\");\n }\n\n Console.WriteLine($\"Your age is: {person.Age}\");\n Console.WriteLine($\"Your phone number is: {person.PhoneNumber}\");\n}\n</code></pre>\n\n<p>And some app info..</p>\n\n<pre><code>internal static void AppInfo()\n{\n Console.WriteLine(\"This program asks a person to enter full name, age, and phone number.\");\n Console.WriteLine(\"The person's information is then displayed together with the initials.\");\n Console.WriteLine(\"At any time the program could be terminated by typing: EXIT.\");\n}\n</code></pre>\n\n<p>This brings us to the application loop as shown at the start..</p>\n\n<pre><code>public static void Run()\n{\n UserPane.AppInfo();\n while (true)\n {\n UserPane.PersonInfo(UserPane.ReadPerson());\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T08:21:27.337", "Id": "436783", "Score": "1", "body": "This is too cool for this simple app :-P how about decorating properties with some kind of `[Console(prompt:\"Text\")]` attributes and reflecting that with another tool? ;-]" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T08:05:18.440", "Id": "225075", "ParentId": "23835", "Score": "2" } } ]
{ "AcceptedAnswerId": "23836", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T11:51:06.903", "Id": "23835", "Score": "6", "Tags": [ "c#", "console", "formatting" ], "Title": "Displaying a person's personal information with formatting" }
23835
<p>This program use random number generator to create sentences. It prints 20 sentences randomly. Here is the code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;time.h&gt; #include &lt;ctype.h&gt; #define STR_LEN 80 #define MAX_SEN 20 int main(void) { char *article[] = {"the", "a", "one", "some", "any"}; char *noun[] = {"boy", "girl", "dog", "town", "car"}; char *verb[] = {"drove", "jumped", "ran", "walked", "skipped"}; char *preposition[] = {"to", "from", "over", "under", "on"}; int num; char sentence[MAX_SEN][STR_LEN]; char (*i)[STR_LEN]; srand((unsigned) time(NULL)); for(i = sentence; i &lt; sentence + MAX_SEN; i++) { num = rand() % (sizeof(article)/sizeof(article[0])); strcpy(*i, article[num]); num = rand() % (sizeof(noun)/sizeof(noun[0])); strcat(strcat(*i, " "), noun[num]); num = rand() % (sizeof(preposition)/sizeof(preposition[0])); strcat(strcat(*i, " "), preposition[num]); printf("%s.\n", *i); } return 0; } </code></pre> <p>Can you make some improvements on the code especially on the <code>sizeof</code> operator. You can use any things functions, arrays, strings, pointers etc. Also, I don't know how to make first letter capital of each sentence using <code>toupper()</code> function.</p>
[]
[ { "body": "<p>Sorry for no explanation. Not really sure why I wrote this. Just saw your post, got in the zone, and suddenly I have a chunk of code! Hope it is insightful.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;time.h&gt;\n#include &lt;ctype.h&gt;\n\nconst int SEN_LEN = 80;\nconst int MAX_SEN = 20;\n\nconst char* ARTICLES[] = {\"the\", \"a\", \"one\", \"some\", \"any\"};\nconst char* NOUNS[] = {\"boy\", \"girl\", \"dog\", \"town\", \"car\"};\nconst char* VERBS[] = {\"drove\", \"jumped\", \"ran\", \"walked\", \"skipped\"};\nconst char* PREPOSITIONS[] = {\"to\", \"from\", \"over\", \"under\", \"on\"};\nconst int ARTICLES_SIZE = sizeof(ARTICLES)/sizeof(ARTICLES[0]);\nconst int NOUNS_SIZE = sizeof(NOUNS)/sizeof(NOUNS[0]);\nconst int VERBS_SIZE = sizeof(VERBS)/sizeof(VERBS[0]);\nconst int PREPOSITIONS_SIZE = sizeof(PREPOSITIONS)/sizeof(PREPOSITIONS[0]);\n\nchar* generateSentence() {\n char* sentence = calloc((SEN_LEN+1), sizeof(char));\n\n //Build Sentence\n strcat(sentence, ARTICLES[rand()%ARTICLES_SIZE]);\n\n strcat(sentence, \" \");\n strcat(sentence, NOUNS[rand()%NOUNS_SIZE]);\n\n strcat(sentence, \" \");\n strcat(sentence, VERBS[rand()%VERBS_SIZE]);\n\n strcat(sentence, \" \");\n strcat(sentence, PREPOSITIONS[rand()%PREPOSITIONS_SIZE]);\n\n //Capitalize first letter\n sentence[0] = toupper(sentence[0]);\n\n return sentence;\n}\n\nint main(int argc, char* argv[]) {\n srand(time(NULL));\n\n for(int i = 0; i &lt; MAX_SEN; i++) {\n char* sentence = generateSentence();\n printf(\"%s.\\n\", sentence);\n free(sentence);\n }\n\n return 0;\n}\n</code></pre>\n\n<p>Requires C99. (-std=c99 on gcc)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T00:01:48.087", "Id": "36806", "Score": "3", "body": "Well, when you have time please add some explanations." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T23:40:38.753", "Id": "23887", "ParentId": "23845", "Score": "3" } }, { "body": "<p>I can't really say there is anything <strong>wrong</strong> with your code although I really don't like the nested <code>strcat</code>. There are some minor quibbles, such as the opening brace not being in column 0, the parameters missing from main and the stdlib include missing. </p>\n\n<p>However I can offer some alternatives that are not necessarily better, just different. In the code below, I used a typedef to define a sentence type. To my eyes it is easier to handle one-D arrays (ie and array of sentences) that 2-D arrays. But that is just me. I also used a simple index in the loop rather than a pointer to the sentence. - seems more straightforward to me. And I put each array size into a const - in the code it doesn't matter but in something larger you might want the size more than once. I also defined <code>num</code> at the point of first use. I also added some extra vertical spacing to make it clearer, although I probably wouldn't so much in real code.</p>\n\n<pre><code>typedef char sentence[STR_LEN];\n\nint main(int argc, char **argv)\n{\n char *article[] = {\"the\", \"a\", \"one\", \"some\", \"any\"};\n const size_t n_articles = sizeof article /sizeof article[0];\n\n char *noun[] = {\"boy\", \"girl\", \"dog\", \"town\", \"car\"};\n const size_t n_nouns = sizeof noun /sizeof noun[0];\n\n char *preposition[] = {\"to\", \"from\", \"over\", \"under\", \"on\"};\n const size_t n_prepositions = sizeof preposition /sizeof preposition[0];\n\n sentence sentences[MAX_SEN];\n srand((unsigned) time(NULL));\n\n for (int i = 0; i &lt; MAX_SEN; ++i) {\n int num = rand() % n_articles;\n strcpy(sentences[i], article[num]);\n\n num = rand() % n_nouns;\n strcat(sentences[i], \" \");\n strcat(sentences[i], noun[num]);\n\n num = rand() % n_prepositions;\n strcat(sentences[i], \" \");\n strcat(sentences[i], preposition[num]);\n\n printf(\"%s.\\n\", sentences[i]);\n }\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T18:28:42.873", "Id": "23969", "ParentId": "23845", "Score": "1" } } ]
{ "AcceptedAnswerId": "23887", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T14:06:04.993", "Id": "23845", "Score": "2", "Tags": [ "c", "array" ], "Title": "Random Sentences generator" }
23845
<p>Below is the code of a custom C# class I have called UniversalTextBoxTextBinder. I'm interested to hear the code review comments to find out the limitations of this 'universal' solution as well as to get posted here the references on similar solutions. Obviously the solution posted here can be generalized on other types of WinForms controls, WPF(?) controls etc. </p> <p>NB: This solution would not see the light without <a href="https://stackoverflow.com/questions/15375945/binding-custom-properties-values-of-an-instance-of-expandoobject-to-a-net-wind">Hans Passant hint</a>:</p> <pre><code>/// &lt;summary&gt; /// Dynamically binds 'two-way' the properties' values of a (POCO) instance of &lt;paramref name="T"/&gt; /// to the host control textboxes' 'Text' property. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;&lt;/typeparam&gt; public class UniversalTextBoxTextBinder&lt;T&gt; { public UniversalTextBoxTextBinder( Control hostControl, T boundObject, string textBoxNamePrefix = default(string), string textBoxNameSuffix = "TextBox" ) { _hostControl = hostControl; this.BoundObject = boundObject; _expandoObject = new ExpandoObject(); IDictionary&lt;string, object&gt; dictionary = _expandoObject as IDictionary&lt;string, object&gt;; foreach (PropertyInfo propertyInfo in this.BoundObject.GetType().GetProperties()) { if (propertyInfo.CanRead &amp;&amp; propertyInfo.CanWrite) { dictionary[propertyInfo.Name] = propertyInfo.GetValue(this.BoundObject); bind(propertyInfo); } } ((INotifyPropertyChanged)_expandoObject).PropertyChanged += new PropertyChangedEventHandler(propertyChanged); } private Control _hostControl; public T BoundObject { get; private set; } private dynamic _expandoObject; private void bind( PropertyInfo propertyInfo, string controlPropertyNameToBindTo = "Text", string textBoxNamePrefix = default(string), string textBoxNameSuffix = "TextBox" ) { try { bindExpandoField(textBoxNamePrefix + propertyInfo.Name + textBoxNameSuffix, controlPropertyNameToBindTo, propertyInfo.Name); } catch (Exception ex) { Debug.WriteLine("'{0}' error while binding '{1}' property.", ex.Message, propertyInfo.Name); } } private void bindExpandoField( string targetControlName, string targeControlPropertyName, string sourcePropertyName) { Control targetControl = _hostControl.Controls[targetControlName]; var IDict = (IDictionary&lt;string, object&gt;)_expandoObject; var bind = new Binding(targeControlPropertyName, _expandoObject, null); bind.Format += (o, c) =&gt; c.Value = IDict[sourcePropertyName]; bind.Parse += (o, c) =&gt; IDict[sourcePropertyName] = c.Value; targetControl.DataBindings.Add(bind); } private object Convert(object obj, Type t) { if (obj != null) { TypeConverter converter = TypeDescriptor.GetConverter(t); if (converter.CanConvertFrom(obj.GetType())) { return converter.ConvertFrom(obj); } } return null; } private void propertyChanged(object sender, PropertyChangedEventArgs e) { IDictionary&lt;string, object&gt; dict = sender as IDictionary&lt;string, object&gt;; foreach (PropertyInfo info in this.BoundObject.GetType().GetProperties()) { if (info.Name == e.PropertyName) { object value = Convert(dict[e.PropertyName], info.PropertyType); info.SetValue(this.BoundObject, value); } } } } </code></pre> <p>And here is an application of the above 'universal' solution to bind a WinForm to three textboxes named <em>firstNameTextBox</em>, <em>lastNameTextBox</em> and <em>ageTextBox</em> to an instance of a <em>Customer</em> custom class:</p> <pre><code>private UniversalTextBoxTextBinder&lt;Customer&gt; _binder; private void Form_Load(object sender, EventArgs e) { Customer customer = new Customer() { FirstName = "Andrew", LastName = "Chandler", Age = 23 }; _binder = new UniversalTextBoxTextBinder&lt;Customer&gt;(this, customer); } </code></pre> <p>where <em>Customer</em> custom class is as simple as the following:</p> <pre><code>public class Customer { public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } } </code></pre> <p>Thank you.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T13:57:53.980", "Id": "36751", "Score": "1", "body": "By the way, WPF doesn't need that, because it has a `real` binding engine where you can achieve a two-way binding with only doing `<TextBox Text=\"{Binding FirstName}\"/>`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T18:51:23.523", "Id": "36782", "Score": "0", "body": "Additional tests show that the above solution doesn't provide declared in its title 'two-way' binding: the intention was to get a POCO object instance bound 'two-way' (and being 'MVVM-ready') without using INotifyPropertyChanged, but 'two-way MVVM-ready' binding in the above code works only for an ExpandoObject instance dynamically built using a source POCO object instance properties' values. 'two-way MVVM-ready' ExpandoObject does translate changed properties values to the source POCO object but no any translation of changed POCO object values is done in the opposite direction..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T18:56:15.247", "Id": "36784", "Score": "0", "body": "...from POCO object instance to the corresponding ExapandoObject instance properties. So the applicability of the proposed 'universal' solution for MVVM is really questionable: it should work well in a 'disconnected' context only. I have prepared another version of code, which seems to work well in a true MVVM context but it forces to use INotifyPropertyChanged in the source 'POCO' objects, C#5.0 allows to minimize overheads on INotifyPropertyChanged implementation but anyway when INotifyPropertyChanged is implemented for a source 'POCO' objects then they can be 'two-way MVVM-ready' bound" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T19:15:18.693", "Id": "36786", "Score": "0", "body": "...to a WinForm (TextBox) controls without any 'universal binders', and then the only purpose of such a 'universal binder' would be dynamic run-time binding, which will minimize the need in manual coding/designing/declaration of data-binding but in the same time will force to follow some custom conventions and could impose some other limitations as any 'framework' 'universal' solutions do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T08:31:14.387", "Id": "36815", "Score": "0", "body": "@HighCore: Yes, WPF (tested here in VS2012) is able to natively bind two-way ExpandoObject instances' dynamic properties. Thank you." } ]
[ { "body": "<p>I think this code, while fairly impressive, is reinventing a wheel that WinForms wasn't designed to use. Trying to implement the <em>Model-View-ViewModel</em> pattern with WinForms will cause you more trouble than you can possibly imagine, if your application is just a little bit more complex than, say, a calculator app.</p>\n\n<p>You're using reflection quite extensively, so your binding is inherently slow, which means your <em>View</em> has to be as simple as possible, because binding many controls will be more painful than it should.</p>\n\n<p>WinForms applications are better off with the <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter\" rel=\"noreferrer\"><em>Model-View-Presenter</em></a> pattern.</p>\n\n<p>That said your naming and indentation aren't always consistent in terms of <em>PascalCasing</em> method names and line breaks before/after <code>}</code> and <code>)</code>.</p>\n\n<p>I know @HighCore can be a little harsh at times, but he knows his stuff and he's absolutely right: if you want to simulate WPF behavior in WinForms, the <em>real thing</em> will be much less trouble, and leave you with much cleaner code.</p>\n\n<p>Sorry if that's not what you wanted to hear...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-29T09:09:36.977", "Id": "200690", "Score": "1", "body": "MVVM in winforms is a beautiful thing. While quite complex to implement from scratch its a definite must have for any professional winforms developer. I've been using mvvm with winforms for quite a while and I just have to disagee with your opinion in this answer. Have you ever tried it yourself?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-29T13:11:31.877", "Id": "200760", "Score": "1", "body": "@Meehow I *tried*, yes, and failed miserably. Extending it to simulate WPF-like bindings is ...bound to be a frustrating experience. And even if one manages to get a decent binding engine to work, they still have to put up with annoying layouts and the `user32.dll` (which originates in Windows 3.1's `user.dll`) rendering. I'd much rather go full-on WPF than try to turn WinForms into something it wasn't meant to be." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-29T13:55:50.930", "Id": "200771", "Score": "0", "body": "maybe I'm missing something here but `textbox.DataBindings.Add()` along with a ViewModel implementing `INotifyPropertyChanged` works just fine for bindings..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-29T14:27:39.573", "Id": "200780", "Score": "1", "body": "@Meehow nah, that's fine for simple bindings. [Someone blogged about how they survived WinForms databindings here](http://www.whilenotdeadlearn.com/blog/2008/07/surviving-winforms-databinding), good read." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T03:05:33.083", "Id": "35895", "ParentId": "23847", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T13:42:59.797", "Id": "23847", "Score": "4", "Tags": [ "c#", "winforms" ], "Title": "'Universal' WinForms TextBox Text 'Two-Way' Binder" }
23847
<p>I have no idea if I'm doing this efficiently, or ideally, but I've written what I think is a factory. Please help me understand if this is good practice, or if there is another direction I should take this. There's no particular project in mind with this, I'm just farting around. (Written in PHP)</p> <pre><code>class Factory { private function __construct(){} /** * @param $obj Object to Create. * @param $params Params (use array for multiple parameters) to be passed. */ public static function build($obj, $params=null) { switch ($obj) { case 'db': return new DB($params); default: return null; } } } </code></pre> <p>This lets me do something like <code>$db = Factory::build("db","test_database_name");</code> The DB class just builds a PDO connection using appropriate parameters based on the database I'm trying to access, which is useful for me because I deal with MySQL and MS SQL all day long, and I don't want to have to remember all the connection strings, users, and passwords (stored in the DB class). That's kind of besides the point, I just intend this to be expanded as I develop more useful classes, so...</p> <p>I just want to get some opinions on the the topic of a Factory. Is this a good method? are there others that are considered superior? If so, what have I overlooked?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T12:43:51.360", "Id": "37318", "Score": "0", "body": "Is Wouter J the only one with any input on this?" } ]
[ { "body": "<p>In my opinion, a factory should create a specific class, global ones like this one shouldn't be used. For instance, having a PizzaFactory is something like this:</p>\n\n<pre><code>class PizzaFactory\n{\n public static function createPizza($type)\n {\n switch ($type) {\n case 'salami':\n return new SalamiPizza();\n break;\n\n case 'hawai':\n return new HawaiPizza();\n break;\n }\n }\n}\n</code></pre>\n\n<blockquote>\n <p>I just want to get some opinions on the the topic of a Factory. Is this a good method? are there others that are considered superior? If so, what have I overlooked?</p>\n</blockquote>\n\n<p>An upcomming design pattern is <a href=\"/questions/tagged/depedency-injection\" class=\"post-tag\" title=\"show questions tagged 'depedency-injection'\" rel=\"tag\">depedency-injection</a>. Just search for some resoures about that and keep reading. It is used in all modern frameworks (ZF2 and Symfony 2 uses it).</p>\n\n<p>See also this article serie by Fabien Potencier: <a href=\"http://fabien.potencier.org/article/11/what-is-dependency-injection\" rel=\"nofollow\">\"What is Dependency Injection?\"</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T15:53:10.697", "Id": "36768", "Score": "0", "body": "I'd actually agree with the factories building a specific type of thing. The DB class was the only one I had written thus far, although I could use it directly as `$db = new DB(\"db_name\");` to connect to any of my many databases... This Dependency Injection stuff kinda seems (at first glance) like regular factories (as I envision them), but backwards. All it is, is passing objects as parameters into other objects?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T15:21:26.900", "Id": "23858", "ParentId": "23848", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T14:15:39.207", "Id": "23848", "Score": "1", "Tags": [ "php", "object-oriented" ], "Title": "Getting familiar with OOP - Factories" }
23848
<p>The following script should get links which are stored in a text file (line by line), then put them into an array and finally scan each links' source code for a certain line. If this line is found, it will be pasted into a CSV file.</p> <p>It works fine so far, but it takes ages to finish, since each link is 'opened' and the complete source code for that link is scanned for this specific line. </p> <p>I'm looking for ideas on how to optimize the code to run faster. </p> <p>Here is my code:</p> <pre><code>$filename = "products.txt"; $writecsv = "notavailable.csv"; global $products; $ch = curl_init(); curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/abCk.txt"); curl_setopt($ch, CURLOPT_URL,"https://www.websitegoeshere.com"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, "Login=USERNAME&amp;Password=PASSWORD"); ob_start(); // prevent any output curl_exec ($ch); // execute the curl command ob_end_clean(); // stop preventing output curl_close ($ch); unset($ch); $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/abCk.txt"); // Open the file $fp = @fopen($filename, 'r') or die("products.txt not found"); // Add each line to an array if ($fp) { $products = explode("\n", fread($fp, filesize($filename))); } fclose($fp); $fpcsv = fopen($writecsv, 'w') or die("notavailable.csv not found"); foreach($products as $key =&gt; $val) { curl_setopt($ch, CURLOPT_URL,$val); $buf2 = curl_exec ($ch); $html = htmlentities($buf2); if (strpos($html, "/extension/silver.project/design/sc_base/images/available_yes.gif") !== false) { fputcsv($fpcsv, "available"); } else { fputcsv($fpcsv, "not available"); } } fclose($fpcsv); curl_close ($ch); echo "csv written successfully." </code></pre> <p>Any help is really welcomed. Thanks in advance!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T14:57:27.857", "Id": "36758", "Score": "0", "body": "Can you time how long it takes to finish? What you consider \"ages\" to complete might be perfectly acceptable for this type of task. I have a scraper that grabs booking information for arrests from various county websites, one in particular that first grabs a list of links from one page, and then searches each page those links point to for specific information. It does indeed take ages. I don't use cURL." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T15:18:21.390", "Id": "36762", "Score": "0", "body": "it takes about 30 minutes with 700 pages to scan." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T15:22:41.907", "Id": "36763", "Score": "0", "body": "It's essentially \"browsing\" each page (loading the full html)? This sounds about right. It takes my script about 4 minutes or so for around 100 pages. I run mine via CLI. If there ARE any optimizations, I want to hear them too, lol." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T15:24:04.220", "Id": "36764", "Score": "0", "body": "yep, its browsing the full html. well, in this case i'll accept the time. thanks for your help!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T15:31:39.293", "Id": "36942", "Score": "1", "body": "@hurley instead of trying to sequentially download 700 links, you should try to do it concurrently. http://stackoverflow.com/questions/2253791/asynchronous-parallel-http-requests-using-php-curl-multi" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-27T12:01:27.110", "Id": "39599", "Score": "0", "body": "Also, be aware that sometimes you'll need to insert delays into a script like this, to avoid hammering the same server. To be polite, scripts like this can take even **longer** to run." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-02T18:13:23.623", "Id": "46269", "Score": "1", "body": "http://jmuras.com/blog/2010/parallel-downloads-with-wget/" } ]
[ { "body": "<p>Performing this task in parallel would help greatly although PHP is not the best language to do so in.</p>\n\n<p>I would do so by spawning PHP processes by POSTing to other PHP scripts (<a href=\"https://stackoverflow.com/questions/962915/how-do-i-make-an-asynchronous-get-request-in-php/962920#962920\">asynchronously</a>), possibly posting to them the links they should get. You would need to store whether the line is available or not in a database, I would use <a href=\"http://www.php.net/manual/en/class.sqlite3.php\" rel=\"nofollow noreferrer\">SQLite</a> in this case (it doesn't need a server to be setup).</p>\n\n<p>So a possible setup could look something like:</p>\n\n<p><strong>Master Process:</strong> Splits the main link file into n parts then POSTs the parts to the child pages. It would need to know when the child processes are finished, it could do so by having a polling loop that checks if the number of rows in the database is equal to the number of links, you would need to make sure you put in a sleep function so it doesn't poll too often. When the child processes are done and the polling breaks out, you could then take the data in the database and convert it to CSV.</p>\n\n<p><strong>Child Processes:</strong> This page receives a set of links via POST, it then goes through each one checking if it contains the string and marking the result down in the database.</p>\n\n<p>I would not use this for production code, PHP is not made for this and there are lots of things that could go wrong. If it was possible I would do this sort of thing in languages with built in parallelism such as Golang or Clojure.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-04T04:26:46.937", "Id": "25796", "ParentId": "23849", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T14:26:49.587", "Id": "23849", "Score": "3", "Tags": [ "php", "performance", "html", "curl" ], "Title": "Optimizing PHP script fetching entire HTML pages" }
23849
<p>I'm writing a function that takes between one and three arguments <code>(function callback [, number limit] [, regexp pattern])</code>. Since the second two are both optional, I need to determine which argument is being passed when the function is supplied with only two. Below is my solution, but it seems overly verbose. Is there a cleaner way to do this?</p> <pre><code> var get_queued_pages = function() { if(arguments&gt;0){ var callback = arguments[0]; if(arguments.length == 3){ //all arguments are being passed var limit = arguments[1]; var pattern = arguments[2]; } else if(arguments.length == 2){ //only 2 arguments passed if(typeof(arguments[1]) == "number"){ //check if the second one is limit or pattern var limit = arguments[1];//no pattern defined; second argument is limit } } else{ var limit = 1; } } //do stuff } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T14:33:18.627", "Id": "36755", "Score": "0", "body": "Can the order of which they are passed in change? Ie. if there is a second one, will it always be a number etc. Or could the order change possibly? Being were the regexp gets passed in first or vice versa." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T14:42:39.543", "Id": "36756", "Score": "0", "body": "In this example, no. If there is a way to elegantly handle that too it would be extra nice though!" } ]
[ { "body": "<pre><code>function(cb,limit,pattern) {\n limit = typeof(limit) === \"undefined\" ? 1 : limit;\n //do stuff\n}\n</code></pre>\n\n<p>Calling a function with less arguments than declared will just fill them with undefined. You can then check if that is the value, if so fill in your default ones.<br>\nThe I have above will have the same affect as yours, there are always three variables (even in your code, Javascript variables are function scope, all of the var declarations are pulled to the top.).<br>\nThe variables:<br>\ncb - unchanged<br>\nlimit - set to 1 if not supplied\npattern - unchanged (undefined if not supplied)</p>\n\n<p>EDIT:\nI just saw your comment on reordering\nyou can do the following</p>\n\n<pre><code> function foo(cb,limit,pattern) {\n if(limit instanceof RegExp) {\n pattern = limit;\n limit = 1;\n }\n else {\n limit = typeof(limit) === \"undefined\" ? 1 : limit;\n }\n //do stuff\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T14:43:39.923", "Id": "23853", "ParentId": "23850", "Score": "3" } }, { "body": "<p>One thing I did notice in your code is that you're testing if <code>arguments &gt; 0</code>. I assume you mean <code>arguments.length &gt; 0</code>.</p>\n\n<p>Anyway, for simple stuff like this, you don't really need to use <code>arguments.length</code>.</p>\n\n<p>In JavaScript, if you have a function that takes, say three arguments:</p>\n\n<pre><code>function doSomething(callback, limit, pattern) {\n // do something\n}\n</code></pre>\n\n<p>You can still call it passing one argument:</p>\n\n<pre><code>doSomething(foo);\n</code></pre>\n\n<p>What will happen is that inside the function body, the first parameter will be set and other parameters will be <code>undefined</code>. The easiest/shortest way to implement what you want is simply to check if <code>limit</code> and <code>pattern</code> are not <code>undefined</code>:</p>\n\n<pre><code>if (typeof(limit) != 'undefined') { ... }\n</code></pre>\n\n<p><code>arguments</code> is better suited for more complicated variadic functions (think of <code>printf</code> in C, for example, or <code>console.log</code> in JavaScript) that may take arbitrary numbers of arguments.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T18:48:50.750", "Id": "36780", "Score": "0", "body": "You are correct, I did forget length. I see what you are saying in your example, but what if only the first and third arg were passed? Is it a better practice to leave the argument names ambiguous so `pattern` isn't defined as `limit`?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T14:48:02.127", "Id": "23856", "ParentId": "23850", "Score": "2" } }, { "body": "<p>I think that you shouldn't be testing for undefined arguments in order to change your function behavior, you should be aware that someone can call the function with 3 arguments from previous processing, but the content of one of them could be <code>undefined</code>. In that case the best would be testing <code>arguments.length</code> before validating argument contents.</p>\n\n<p>Seems to me a better practice to declare and respect each function signature, for example:</p>\n\n<pre><code>function Operation() {\n this.setLimit('default limit here');\n this.setPattern(/default pattern here/);\n}\n\nOperation.prototype.limit = function(limit) {\n // validate limit here\n this.limit = limit;\n return this;\n};\n\nOperation.prototype.pattern = function(pattern) {\n // validate pattern here\n this.pattern = pattern;\n return this;\n};\n\nOperation.prototype.execute = function(callback) {\n // operation here, then call `callback`\n};\n\nvar op = new Operation();\nop.limit(142)\n .pattern(/^.*$/i)\n .execute(function() {});\n\n// you can set or modify all parameters as you wish, in any order, each with their proper signature, and execute it when ready.\n</code></pre>\n\n<p>or use a options hash, for optional params:</p>\n\n<pre><code>function realizeOperation(callback, options) {\n var limit = options &amp;&amp; options.limit || 'default limit here';\n var pattern = options &amp;&amp; options.pattern || /default pattern here/;\n\n // option validations here\n // operation here\n}\n</code></pre>\n\n<p>There are also plenty of libs for handling and validating parameters, if you really want to do it: <a href=\"https://www.npmjs.com/browse/keyword/parameters\" rel=\"nofollow\">https://www.npmjs.com/browse/keyword/parameters</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-30T17:38:12.537", "Id": "79112", "ParentId": "23850", "Score": "2" } }, { "body": "<p>What about passing an object?</p>\n\n<pre><code>var foo = function(param) {\n var p1 = param.p1 || null;\n var p2 = param.p2 || 'default';\n var p3 = param.p3 || {};\n\n // ....\n}\n\nfoo({p3: 3.14, p1: function() {...}});\n</code></pre>\n\n<p>I've found this to be elegant, simple and easy to extend.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-30T20:48:20.233", "Id": "79136", "ParentId": "23850", "Score": "0" } } ]
{ "AcceptedAnswerId": "23853", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T14:28:09.867", "Id": "23850", "Score": "1", "Tags": [ "javascript", "node.js" ], "Title": "Handling an unknown number of arguments" }
23850
<p>I'm wondering if the way I wrote our TextHelper class is a really a proper way to do it.<br> We have products that are interlinked in different ways and every product has multiple text fields that might be empty.</p> <p>Now depending on where the text is supposed to show up, we want different texts.<br> A simple example would be:<br> On the product detail page it should show the shop specific text, if not available, the main description, if that is not available, the main description of it's parent product and the short description of the parents' subproducts.</p> <p>So much for the motivation. I tried to shorten and simplify the code as much as I could. Is this a good way to use enums or should this be done completely different?</p> <pre><code>public class ProductTextHelper { public static String getTextInOrder(TextType[] order, IProduct p) { for (TextType t : order) { if (!t.getText(p).equals("")) return t.getText(p); } } public enum TextType { text1 { public String getText(IProduct p) { return p.getText1; } }, text2 { public String getText(IProduct p) { String t = p.getText2; return t.equals("") ? "" : t + TextType.text1.getText(p); } }, text3 { public String getText(IProduct p) { StringBuilder sb = new StringBuilder(); sb.append(p.getText3()); for (IProduct subP : p.getRelatedProducts()) { sb.append(TextType.text2.getText(subP)); } } }, // more enums public static final TextType[] useCase1 = {text1, text2}; public static final TextType[] useCase2 = {text4, text1, text3}; public static final TextType[] useCase3 = {text3, text2}; // a few more arrays public abstract String getText(IProduct p); } } </code></pre> <p>And this gets called like that:</p> <pre><code>ProductTextHelper.getTextInOrder(TextType.usecase2, product); </code></pre>
[]
[ { "body": "<p>My answer to your main question is you gotta do what you gotta do. Just so you feel more comfortable; this pattern has a name <strong>strategy enum</strong>. It is even in <em>Effective Java</em>.</p>\n\n<p>But I have a criticism for this bit:</p>\n\n<pre><code> public static final TextType[] useCase1 = {text1, text2};\n</code></pre>\n\n<p>Arrays are mutable. You should not implement <a href=\"https://stackoverflow.com/questions/2842169/why-are-public-static-final-array-a-security-hole\">class constants as final arrays</a>. Use unmodifiable collections instead:</p>\n\n<pre><code> public static final List&lt;TextType&gt; useCase1 = Collections.unmodifiableList(\n Arrays.asList(text1, text2));\n</code></pre>\n\n<p>Also each time you add another use case you should not need to modify this enum, that is by adding another <code>useCase</code>. Those should be moved to wherever they are used.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T15:49:34.233", "Id": "36766", "Score": "0", "body": "I really need to read Effective Java properly. Thanks!\nAnd I thought about the Unmodifiable List myself while simplifying the code. Thanks again :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T15:52:51.110", "Id": "36767", "Score": "0", "body": "I did not know it was in the book either. I googled it. :))" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T15:37:20.963", "Id": "23860", "ParentId": "23851", "Score": "3" } } ]
{ "AcceptedAnswerId": "23860", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T14:39:30.963", "Id": "23851", "Score": "3", "Tags": [ "java", "enum" ], "Title": "Enums with different methods, useful or abuse?" }
23851
<p>I'm trying to establish a concurrency violation verification in my SQL updates using C# and raw SQL.</p> <p>What I'm doing now is storing the <code>TimeStamp</code> value in a <code>byte[]</code> upon selection and before updating I'm checking if the stored value is equal to the current value. here's the code:</p> <pre><code>static void update() { using (SqlConnection connection = new SqlConnection("")) { try { //open connection connection.Open(); //select row for update - for testing purposes it's in the same block SqlCommand select = connection.CreateCommand(); select.CommandText = "SELECT timeStamp FROM Person WHERE ID = 1"; //store the time stamp in a byte[] byte[] ts = (byte[])select.ExecuteScalar(); //check if the time stamp hasn't changed if (ByteArraysEqual(ts, (byte[])select.ExecuteScalar())) { //Update SqlCommand command = connection.CreateCommand(); command.CommandText = "Update Person SET Age=1111 WHERE ID = 1"; command.ExecuteNonQuery(); } else { //cocurrency violation occured Console.WriteLine("concurrency error!"); } } catch (Exception ex) { Console.WriteLine("Update error:\n" + ex.Message); } finally { connection.Close(); } } } static bool ByteArraysEqual(byte[] b1, byte[] b2) { if (b1 == b2) return true; if (b1 == null || b2 == null) return false; if (b1.Length != b2.Length) return false; for (int i = 0; i &lt; b1.Length; i++) { if (b1[i] != b2[i]) return false; } return true; } </code></pre> <p>I wonder if this is the right approach to verify the <code>Person</code> has not been updated by another user between the selection and the actual update?</p>
[]
[ { "body": "<blockquote>\n<pre><code> using (SqlConnection connection = new SqlConnection(\"\"))\n {\n try\n {\n //open connection\n if (connection.State != System.Data.ConnectionState.Open)\n</code></pre>\n \n <p>Why check connection state for just created connection? It will always be Closed :)</p>\n</blockquote>\n\n<p>I suggest you to do update in stored procedure. This will allow you to do update in one DB call and using transactions will ensure that Person record is not modified between selection of timestamp and actual update.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T15:55:47.433", "Id": "23863", "ParentId": "23852", "Score": "0" } }, { "body": "<p>What optimistic concurrency usually does is update the row specifying the old value in the where clause:</p>\n\n<pre><code>var command = connection.CreateCommand();\ncommand.CommandText = \"Update Person SET Age = @age timeStamp = @newTimeStamp WHERE ID = @id AND timeStamp = @originalTimeStamp\";\ncommand.Parameters.Add(\"@age\", 1111);\ncommand.Parameters.Add(\"@newTimeStamp\", DateTime.Now);\ncommand.Parameters.Add(\"@id\", 1);\ncommand.Parameters.Add(\"@originalTimeStamp\", originalTimeStamp);\nint affected = command.ExecuteNonQuery();\n\nif (affected == 0)\n{\n throw new OptimisticConcurrencyException(\"Data was changed by someone else, please refresh and try again\");\n}\n</code></pre>\n\n<p>Also, please use parameters for your SQL queries!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T17:55:41.407", "Id": "36773", "Score": "0", "body": "thanks for clarifying things for me. and i am using parameters, i just removed them to in order to improve readability :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T22:11:57.597", "Id": "36802", "Score": "1", "body": "@Yoav in future don't, the point of code review is to ask for peer reviews of the actual code, it makes it easier for people to make relevant suggestions if it matches." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T15:57:18.340", "Id": "23864", "ParentId": "23852", "Score": "3" } }, { "body": "<p>Use optimistic locking when the logic requires separating a read and update of the same row into two transactions, usually because you're showing the original data to a user and letting them edit it. The example in your question doesn't need it because you're simply overwriting the existing age with a new value.</p>\n\n<p>Trevor is correct about how to implement the optimistic locking check (3 and 4 below). The only part missing is how to get the original timestamp.</p>\n\n<ol>\n<li><p>Read the existing values along with the current timestamp.</p>\n\n<pre><code>name, age, ts = select name, age, update_ts from person where id = 5;\n</code></pre></li>\n<li><p>Allow the user to update the values on a form.</p>\n\n<p>Here another user may come along and do the same thing. Because there are\ntwo values, this could cause a problem. For example, user A fixes the \nperson's name while user B fixes their age (both were incorrect).\nWithout some form of locking, one of the updates would be overwritten.</p></li>\n<li><p>Store the new values and timestamp while checking the old timestamp.</p>\n\n<pre><code>rows = update person \n set name = @name, \n age = @age, \n update_ts = now() \n where id = 5 \n and update_ts = @ts;\n</code></pre></li>\n<li><p>If the update failed, start over.</p>\n\n<pre><code>if (rows == 0) {\n throw new OptimisticLockException();\n}\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T17:09:12.417", "Id": "23871", "ParentId": "23852", "Score": "1" } } ]
{ "AcceptedAnswerId": "23864", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T14:41:06.363", "Id": "23852", "Score": "4", "Tags": [ "c#", "sql", "exception-handling" ], "Title": "Handling optimistic concurrency violations" }
23852
<p>I have done a lot of research on OOP and I keep seeming to read different opinions on several items, especially the scope resolution operator (<code>::</code>) and handling class containing private functions.</p> <p>When calling a private function from within the <code>class</code> it seems that a majority of programmers recommend <code>self::method()</code>, is this accurate? I have also seen and tested <code>Class::method()</code>.</p> <p>Also, I am looking for more information, or recommendations on appropriate ways to instantiate class variables, whether it be <code>protected</code>, <code>private</code>, <code>var</code>, etc...</p> <p>Take this <code>Timer</code> class I wrote for example:</p> <pre><code>class Timer { protected $_start, $_pause, $_stop, $_elapsed; protected $_laps = array(); protected $_count = 1; protected $_lapTotalTime = 0; public function __construct($start = '') { $start = strtolower($start); ($start === 'start') ? self::start() : NULL; } public function start( ) { $this-&gt;_start = Timer::getMicroTime(); } public function stop( ) { $this-&gt;_stop = Timer::getMicroTime(); } public function pause( ) { $this-&gt;_pause = Timer::getMicroTime(); $this-&gt;_elapsed += ($this-&gt;_pause - $this-&gt;_start); } public function resume( ) { $this-&gt;_start = Timer::getMicroTime(); } // Used to build an array of times for multiple timers public function lap($key = '') { ($key === '') ? $key = 'Lap' : $key = $key; if (isset($this-&gt;_start)) { self::stop(); $this-&gt;_lapTotalTime += ($this-&gt;_stop - $this-&gt;_start); $this-&gt;_laps[$key.' '.$this-&gt;_count] = self::getLapTime(); self::start(); $this-&gt;_count++; } } public function getTime() { if (!isset($this-&gt;_stop)) { $this-&gt;_stop = Timer::getMicroTime(); } if (!empty($this-&gt;_laps)) { $this-&gt;_laps['Total'] = self::timeToString($this-&gt;_lapTotalTime); return $this-&gt;_laps; } return self::timeToString(); } // PRIVATE CLASS FUNCTIONS private function getLapTime() { return self::timeToString(); } private function getMicroTime( ) { list($usec, $sec) = explode(' ', microtime()); return ((float) $usec + (float) $sec); } private function timeToString($seconds = '') { if ($seconds === '') { $seconds = ($this-&gt;_stop - $this-&gt;_start) + $this-&gt;_elapsed; } $seconds = Timer::roundMicroTime($seconds); $hours = floor($seconds / (60 * 60)); $divisor_for_minutes = $seconds % (60 * 60); $minutes = floor($divisor_for_minutes / 60); return $hours . "h:" . $minutes . "m:" . $seconds . "s"; } private function roundMicroTime($microTime) { return round($microTime, 4, PHP_ROUND_HALF_UP); } } </code></pre> <p>All of my instantiated variables are declared as <code>protected</code>. My reasoning, if I am understanding correctly is because although this Class doesn't <code>extend</code> another class, the other class may <code>extend</code> <code>Timer</code>. Am I on the right track?</p> <p>Example of <code>Timer</code> use with laps:</p> <pre><code>$t = new Timer('start'); usleep(3215789); // Declare a key for the lap array $t-&gt;lap('Sleep'); usleep(4445666); // No key declaration $t-&gt;lap(); usleep(1000000); echo "&lt;pre&gt;"; if (is_array($t-&gt;getTime())) { print_r($t-&gt;getTime()); } else { echo $t-&gt;getTime(); } echo "&lt;/pre&gt;"; </code></pre> <p>Output:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Array ( [Sleep 1] =&gt; 0h:0m:3.2154s [Lap 2] =&gt; 0h:0m:4.4462s [Total] =&gt; 0h:0m:7.6616s ) </code></pre> </blockquote> <hr> <p>Without laps:</p> <pre class="lang-php prettyprint-override"><code>$t = new Timer('start'); usleep(3215789); usleep(1000000); echo "&lt;pre&gt;"; if (is_array($t-&gt;getTime())) { print_r($t-&gt;getTime()); } else { echo $t-&gt;getTime(); } echo "&lt;/pre&gt;"; </code></pre> <p>Output:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>0h:0m:4.2158s </code></pre> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T15:09:39.143", "Id": "36760", "Score": "1", "body": "the `::` operator, or `T_PAAMAYIM_NEKUDOTAYIM` if you like that, is an operator for static methods and class constants, to call a method use `$this->method()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T15:17:44.737", "Id": "36761", "Score": "0", "body": "@WouterJ Ah yes, I remember learning this at one point. Thank you, I will correct." } ]
[ { "body": "<ol>\n<li>Never ever use <code>var</code>. That's a deprecated form of <code>public</code>;</li>\n<li>Avoid using <code>public</code> on your properties, you want to have controll about the value of every property in your class;</li>\n<li><p>If you use <code>protected</code> or <code>private</code> doesn't make much sense. Protected means it can't be accessed from the outer scope, but it can be accessed from another class which extends this class. Private means it can only be accessed from the class where it is defined.</p>\n\n<p>I like to have getters/setters for every property and never use <code>$this-&gt;property</code> directly inside my class, some other don't like that. See also this article by Fabien Potencier: <a href=\"http://fabien.potencier.org/article/47/pragmatism-over-theory-protected-vs-private\" rel=\"nofollow\">\"Pragmatism over Theory: Protected vs Private\"</a>;</p></li>\n<li>The <code>::</code> operator, or <code>T_PAAMAYIM_NEKUDOTAYIM</code>, should only be used by accessing class constants and static vars/methods;</li>\n<li>Avoid using static vars/methods;</li>\n<li>Use <code>$this-&gt;method()</code> or <code>$this-&gt;property</code> to access properties from the inside of a class. It works just like you use it outside the class, except that you use the <code>$this</code> variable (which contains a reference to the current instance of the class).</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T15:15:42.413", "Id": "23857", "ParentId": "23854", "Score": "2" } } ]
{ "AcceptedAnswerId": "23857", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T14:45:28.453", "Id": "23854", "Score": "2", "Tags": [ "php", "object-oriented", "timer" ], "Title": "Timer class in PHP OOP" }
23854
<p>I wrote a basic Clojure single-threaded socket server, mostly following Java examples; in particular I'd appreciate feedback on three things, </p> <ul> <li>how I handle mutable state (I/O, managing connections).</li> <li>how I pass the server around among the create-server/run/app functions. </li> <li>my setup to enable working with the server in the REPL. </li> </ul> <p>To work at the REPL I start the server in another thread with future and use an atom to coordinate stopping it from the main thread. </p> <pre><code>(ns exvarcis.core (:import [java.net InetAddress InetSocketAddress Socket] [java.nio ByteBuffer] [java.nio.charset Charset] [java.nio.channels ServerSocketChannel SocketChannel Selector SelectionKey])) (defn buf-seq ([buf] (buf-seq buf 0)) ([buf i] (lazy-seq (when (&lt; i (.limit buf)) (cons (.get buf i) (buf-seq buf (inc i))))))) (let [c (atom 0)] (defn new-connection [] {:id (swap! c inc) :writebuf (ByteBuffer/allocate 8096) :readbuf (ByteBuffer/allocate 8096)})) (defmulti select-op (fn [k] (.readyOps k))) (defmethod select-op :default [k] (println "Default op.")) (defmethod select-op (SelectionKey/OP_ACCEPT) [k] (-&gt; (.accept (.channel k)) (.configureBlocking false) (.register (.selector k) (SelectionKey/OP_READ)) (.attach (new-connection))) (println "client registered")) (defn close-connection [k] (println "closing connection" (.channel k)) (.cancel k) (.close (.channel k))) (defmethod select-op (SelectionKey/OP_READ) [k] (let [readbuf (-&gt; (.attachment k) (:readbuf)) bytes-read (.read (.channel k) readbuf)] (when (= bytes-read -1) (close-connection k)))) (defn select! [selector] (.select selector 50) (let [ks (.selectedKeys selector)] (doseq [k ks] (select-op k)) (.clear ks))) (defn get-lines [buf] (let [dup-buf (.duplicate buf) original-limit (-&gt; dup-buf .flip .limit) last-newline (.lastIndexOf (vec (buf-seq dup-buf)) 10)] (when-not (= last-newline -1) (.flip buf) (.limit buf (inc last-newline)) (let [lines (-&gt;&gt; buf (.decode (Charset/defaultCharset)) .toString clojure.string/split-lines)] (.limit buf original-limit) (.compact buf) lines)))) (defn write-lines [lines k] (let [encoded-lines (-&gt;&gt; lines (.encode (Charset/defaultCharset))) buf (-&gt; (.attachment k) (:writebuf))] (when (&gt; (.limit encoded-lines) 0) (.put buf encoded-lines) (.flip buf) (.write (.channel k) buf) (.compact buf)))) (defn echo-all [ks] (let [readbufs (map #(-&gt; (.attachment %) (:readbuf)) ks) lines (mapcat get-lines readbufs) lines-with-crlf (str (clojure.string/join "\r\n" lines) "\r\n")] (doseq [k ks] (write-lines lines-with-crlf k)))) (defn create-server [] (let [acceptor (-&gt; (ServerSocketChannel/open) (.configureBlocking false) (.bind (InetSocketAddress. "127.0.0.1" 0))) selector (Selector/open) server {:acceptor acceptor :selector selector}] (.register acceptor selector (SelectionKey/OP_ACCEPT)) server)) (defn run [handler] (let [running? (atom true) server (assoc (create-server) :running? running?) server-thread (future (handler server)) stop (fn [] (reset! running? false)) selector (:selector server) shutdown (fn [] (println "Shutting down...") (doseq [k (.keys selector)] (.close (.channel k))) (.close selector) (println "...done."))] { :server server :server-thread server-thread :stop stop :shutdown shutdown})) (defn app [server] (let [acceptor (:acceptor server) selector (:selector server) running? (:running? server)] (println "Starting Ex v Arcis on" (.getLocalAddress acceptor)) (while @running? (select! selector) (echo-all (filter #(and (.isValid %) (.attachment %)) (.keys selector))) (Thread/sleep 3000)))) (defn -main [] (:start (run #'app))) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T15:26:54.230", "Id": "23859", "Score": "3", "Tags": [ "clojure" ], "Title": "single-threaded socket server" }
23859
<p>I am working on the following problem (<a href="http://www.enigmagroup.org/missions/programming/9/" rel="nofollow">http://www.enigmagroup.org/missions/programming/9/</a>).</p> <p>You have a 6x6 table where the first 5 columns and rows are comprised of different types of shapes, 5 total. The sixth row contains the sum of the values of the shapes for all columns for each column. And the sixth column contains the sum of the values of the shapes for all rows for each row. </p> <p>I have to figure out the values for each of the shapes, and trying to do this by solving a system of five linear equations. Right now my problem is a brute force approach but it's not working out very well -- it freezes the browser (in Firefox scratchpad) when I try to run it. </p> <p>How can I make it more efficient?</p> <pre><code>"use strict"; var CIRCLE = 1; var HEART = 2; var SQUARE = 3; var TRIANGLE = 4; var STAR = 5; var BLANK = 6; var tableData = []; // 5x5, length = 25 var sumRight = []; // 1x5, length = 5 var sumBottom = []; // 5x1, length = 5 var countCircle = 0; var countHeart = 0; var countSquare = 0; var countStar = 0; var countTriangle = 0; var countBlank = 0; var removeTags = function(s) { return s.replace(/&lt;([^&gt;]+)&gt;/ig, ''); }; var at = function(x, y) { var index = y*5 + x; return (index &gt;= 0 &amp;&amp; index &lt; tableData.length) ? tableData[index] : 0; }; var validSolution = function(v) { var right = []; var bottom = []; v[BLANK] = 0; v[CIRCLE] = v["CIRCLE"]; v[SQUARE] = v["SQUARE"]; v[TRIANGLE] = v["TRIANGLE"]; v[STAR] = v["STAR"]; for (var y = 0; y &lt; 5; y++) { var rowSum = 0; for (var x = 0; x &lt; 5; x++) rowSum += v[at(x, y)]; right.push(rowSum); }; for (var x = 0; x &lt; 5; x++) { var colSum = 0; for (var y = 0; y &lt; 5; y++) colSum += v[at(x, y)]; bottom.push(colSum); } return right == sumRight &amp;&amp; bottom == sumBottom; }; var table = document.getElementById("game_grid"); // Parse input data into a readable format for (var r = 0; r &lt; table.rows.length; r++) { for (var c = 0; c &lt; table.rows[r].cells.length; c++) { var cell = table.rows[r].cells[c]; if (r &lt; 5 &amp;&amp; c &lt; 5) { var img = cell.getElementsByTagName('img'); if (img.length == 0) { tableData.push(BLANK); countBlank++; } else { var src = img[0].src.split("/"); src = src[src.length - 1]; switch (src) { case "circle.png": tableData.push(CIRCLE); countCircle++; break; case "heart.png": tableData.push(HEART); countHeart++; break; case "square.png": tableData.push(SQUARE); countSquare++; break; case "triangle.png": tableData.push(TRIANGLE); countTriangle++; break; case "star.png": tableData.push(STAR); countStar++; break; } } } else if (r == 5 &amp;&amp; c &lt; 5) sumBottom.push(parseInt(removeTags((cell.innerHTML)))); else if (c == 5 &amp;&amp; r &lt; 5) sumRight.push(parseInt(removeTags((cell.innerHTML)))); } } // Calculate a solution var K = sumRight.concat(sumBottom).reduce(function(a, b) { return a + b; }); var minBound = 1; var maxBound = 300; var solution = (function() { for (var vC = minBound; vC &lt;= maxBound; vC++) { if (vC*countCircle &lt;= K) { for (var vH = minBound; vH &lt;= maxBound; vH++) { if (vC*countCircle + vH*countHeart &lt;= K) { for (var vT = minBound; vT &lt;= maxBound; vT++) { if (vC*countCircle + vH*countHeart + vT*countTriangle &lt;= K) { for (var vSQ = minBound; vSQ &lt;= maxBound; vSQ++) { if (vC*countCircle + vH*countHeart + vT*countTriangle + vSQ*countSquare &lt;= K) { for (var vSR = minBound; vSR &lt;= maxBound; vSR++) { if (vC*countCircle + vH*countHeart + vT*countTriangle + vSQ*countSquare + vSR*countStar == K) { var solution = { CIRCLE: vC, HEART: vH, TRIANGLE: vT, SQUARE: vSQ, STAR: vSR }; if (validSolution(solution)) return solution; } } } } } } } } } } return null; })(); // Submit the solution alert(solution); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T09:45:55.363", "Id": "36819", "Score": "2", "body": "You could use [Gaussian Elimination](http://en.wikipedia.org/wiki/Gaussian_elimination) to do the solution of your equations, just put your linear equations in a 5x6 matrix first." } ]
[ { "body": "<ol>\n<li><p>I'm not a JavaScript developer but two things which could help: <a href=\"https://codereview.stackexchange.com/questions/23867/solving-systems-of-linear-equations#comment36819_23867\">another algorithm, as <em>RobH</em> mentioned in his comment</a> or running the calculations in a background thread. <a href=\"https://developer.mozilla.org/en-US/docs/Web/Guide/Performance/Using_web_workers\" rel=\"nofollow noreferrer\">Web workers</a> might fit but I'm not familiar with the topic. Maybe there are other solutions too.</p></li>\n<li><p>In the <code>solution</code> function you could use <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow noreferrer\">guard clauses</a> to make the code flatten and readable</p>\n\n<pre><code>for (var vC = minBound; vC &lt;= maxBound; vC++) {\n if (vC*countCircle &gt; K) {\n continue;\n }\n for (var vH = minBound; vH &lt;= maxBound; vH++) {\n if (vC*countCircle + vH*countHeart &gt; K) {\n continue;\n }\n for (var vT = minBound; vT &lt;= maxBound; vT++) {\n ...\n }\n }\n}\n</code></pre></li>\n<li><p>As far as I see <code>vC*countCircle</code> is calculated in every inner loop, <code>vH*countHeart</code> is calculated every inner loop except the first one, etc. but their values are rarely change. I don't know how far modern JavaScript engines optimize these loops but you could use local variables to avoid the unnecessary multiplications.</p>\n\n<pre><code>for (var vC = minBound; vC &lt;= maxBound; vC++) {\n var s1 = vC*countCircle;\n if (s1 &gt; K) {\n continue;\n }\n for (var vH = minBound; vH &lt;= maxBound; vH++) {\n var s2 = s1 + vH*countHeart;\n if (s2 &gt; K) {\n continue;\n }\n for (var vT = minBound; vT &lt;= maxBound; vT++) {\n var s3 = s2 + vT*countTriangle;\n if (s3 &gt; K) {\n continue;\n }\n ...\n }\n }\n}\n</code></pre>\n\n<p>Use better variable names than <code>s1</code>, <code>s2</code> etc. It would make the code readable. (<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G19: Use Explanatory Variables</em>; <em>Refactoring: Improving the Design of Existing Code by Martin Fowler</em>, <em>Introduce Explaining Variable</em>)</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-17T00:05:22.503", "Id": "44538", "ParentId": "23867", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T16:35:28.973", "Id": "23867", "Score": "7", "Tags": [ "javascript", "optimization", "algorithm", "json", "programming-challenge" ], "Title": "Solving systems of linear equations" }
23867
<p>I have a small function which I regularly use to check if a variable contains only [a-z][0-9] and the special chars '-' and '_'. Currently I'm using the following:</p> <pre><code>function is_clean($string){ $pattern = "/([a-z]|[A-Z]|[0-9]|-|_)*/"; preg_match($pattern, $string, $return); $pass = (($string == $return[0]) ? TRUE : FALSE); return $pass; } </code></pre> <p>1 - Can anyone tell me if this is the best/most efficient way to do this and if not try to explain why?</p> <p>2 - When I view this function through my IDE I get a warning that $return is uninitialized... should I be initializing variables in advance with php, if so how and why?</p>
[]
[ { "body": "<p>No need for all that. Just use one bracket group, negate it (be prepending a <code>^</code>), and use the return value directly:</p>\n\n<pre><code>function is_clean ($string) {\n return ! preg_match(\"/[^a-z\\d_-]/i\", $string);\n}\n</code></pre>\n\n<hr>\n\n<p>Here's a quote from <a href=\"http://php.net/manual/en/function.preg-match.php\" rel=\"nofollow\">the PHP docs</a>:</p>\n\n<blockquote>\n <p><strong>Return Values</strong><br>\n <code>preg_match()</code> returns <code>1</code> if the pattern matches given subject, <code>0</code> if it does not, or <code>FALSE</code> if an error occurred.</p>\n</blockquote>\n\n<p>In the regex above, we're looking for any characters in the string that are <em>not</em> in the bracket group. If none are found, <code>preg_match</code> will return 0 (which when negated will result in <code>true</code>). If any of those characters are found, <code>1</code> will be returned and negated to <code>false</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T13:31:11.367", "Id": "36924", "Score": "0", "body": "Certainly cleaner looking code with this approach - thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-10T13:34:23.330", "Id": "119697", "Score": "0", "body": "Did some tests with a few different strings, `preg_match('@[^a-z\\d-_]@i', $string)` is consistently slower than `preg_match('@^[a-z\\d-_]+$@i', $string)`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T18:15:18.257", "Id": "23875", "ParentId": "23872", "Score": "2" } }, { "body": "<p>Just an other method without regex.</p>\n\n<pre><code>function is_clean ($string) {\n{\n return ctype_alnum(str_replace(array('-', '_'), '', $input);\n}\n</code></pre>\n\n<p><strike>Maybe I find the time later this day to compare the performance, but I guess 'efficient' in your question was related to the code not the execution time?</strike> Letharion did the work for me :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T07:37:32.160", "Id": "36814", "Score": "1", "body": "I spent some time with this yesterday. ctype alone is fastest, then comes short preg_match, ctype with str_replace, and finally the original. In many cases, ctype _should_ be the best way to do this, as it will, unlike the regexp, work with characters like é. However, I didn't post an answer, because I couldn't get it to behave properly when trying out it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T11:00:55.253", "Id": "36826", "Score": "0", "body": "Maybe we should combine both approaches. Only if the plain ctype fails we use the regex. That might result in the best performance in the average if we can assume that there are not to many strings with - and _." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T13:34:26.573", "Id": "36925", "Score": "0", "body": "Thanks for the suggestion - if I can get it working then probably a better than a regex as far as performance is concerned. Will have a play and come back" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T05:06:09.440", "Id": "23895", "ParentId": "23872", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T17:37:44.967", "Id": "23872", "Score": "1", "Tags": [ "php", "regex" ], "Title": "php most efficient way to check if a variable contains only certain chars" }
23872
<p>I want to get a better feeling for how JavaScript works and how to use it well. I coded up this Tetris game, and have iterated over the code base and improved it a couple of times now.</p> <p>I hope the state of the code is fairly good at this point, but also that someone more familiar with the language can suggest further improvements.</p> <p>I've deliberately avoided the use of any kind of supporting framework to get a feel for JS in general, instead of learning a specific tool.</p> <p>Game running in <a href="http://jsfiddle.net/ZpXtB/" rel="nofollow">jsfiddle</a>.</p> <p>Minimal HTML that can start the game:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type = "text/javascript" src = "tetris.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body onLoad = "Tetris.init('tetris_canvas');"&gt; &lt;canvas id = "tetris_canvas" width = "170" height = "300"&gt;&lt;/canvas&gt; &lt;div id = "score"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Actual game code:</p> <pre><code>/** * @file * Tetris game. */ var Tetris = (function() { "use strict"; /** * Initialize the game. */ function Tetris() { var state, renderer, keyboard, gameLoopTimerID; var gameLoop = function() { if (state.block.replace === true) { state.block = new Block(state); if (state.gameField.check_direction(state.block)) { clearInterval(gameLoopTimerID); gameOver(); this.init(state.canvas_id); } } down.call(this); renderer.draw(state); }; var right = function() { if (state.block.x &lt; (state.playAreaX - state.block.width())) { var hit_something = state.gameField.check_direction(state.block, "r"); if (!hit_something) { state.block.x++; renderer.draw(state); } } }; var left = function() { if (state.block.x &gt; 0) { var hit_something = state.gameField.check_direction(state.block, "l"); if (!hit_something) { state.block.x--; renderer.draw(state); } } }; var up = function() { state.block.orientation += 90; if (state.block.orientation &gt;= 360) { state.block.orientation -= 360; } renderer.draw(state); }; var down = function() { state.block.down(); renderer.draw(state); clearInterval(gameLoopTimerID); gameLoopTimerID = setInterval( (function(self) { return function() { gameLoop.call(self); }; })(this), calculate_loop_timer(state.loop_timer, state.level) ); }; /** * Function for decrementing the timer interval as the level goes up. * @TODO How expensive is pow()? Could it ever be worthwhile to memoize this? */ var calculate_loop_timer = function(start, level) { return start * Math.pow(0.95, level); }; this.init = function(canvas_id) { var debug = getUrlVars().debug; state = new GameState(); state.canvas_id = canvas_id; renderer = new Canvas_renderer(canvas_id); keyboard = new Keyboard(); document.onkeydown = keyboard.event; gameLoopTimerID = setInterval( (function(self) { return function() { gameLoop.call(self); }; })(this), state.loop_timer ); if (debug) { render_debug_grid(); } // Map keypresses to function calls. keyboard.add(keyboard.right, right); keyboard.add(keyboard.left, left); keyboard.add(keyboard.up, up); keyboard.add(keyboard.down, (function(self) { return function() { down.call(self); }; })(this)); renderer.draw(state); }; var gameOver = function() { alert("Game over\nYour score is: " + state.score.getScore() + "\nPress ok to start a new game"); }; var render_debug_grid = function() { var t = document.createElement("table"), tb = document.createElement("tbody"), tr, td, y, x; for (y = 0; y &lt; state.playAreaY; y++) { tr = document.createElement("tr"); for (x = 0; x &lt; state.playAreaX; x++) { td = document.createElement("td"); td.appendChild(document.createTextNode(x + "," + y)); td.style.width = "21"; td.style.height = "23"; tr.appendChild(td); } tb.appendChild(tr); } t.style.position = "absolute"; t.style.fontSize = "10px"; t.appendChild(tb); document.getElementById("debug_grid").appendChild(t); }; } /** * Keep track of the games internal state. */ function GameState() { // Numbers make the layouts much easier to read, therefore relying on JS // to cast 0 to false and 1 to true instead of using real booleans. this.available_layouts = [ [ [0,1,0], [1,1,1] ], [ [0,0,1], [1,1,1] ], [ [1,0,0], [1,1,1] ], [ [0,1,1], [1,1,0] ], [ [1,1,0], [0,1,1] ], [ [1], [1], [1], [1] ], [ [1,1], [1,1] ] ]; // @TODO Improve color selection http://gamedev.stackexchange.com/questions/46463/is-there-an-optimum-set-of-colors-for-10-players/46467#46467 this.layout_colors = [ "rgb(255, 0, 0)", "rgb(255, 255, 0)", "rgb(255, 0, 255)", "rgb(127, 0, 0)", "rgb(127, 127, 0)", "rgb(127, 0, 127)", "rgb(127, 127, 127)" ]; this.playAreaX = 11; this.playAreaY = 20; this.blockSize = 15; this.block = new Block(this); this.gameField = new GameField(this); this.score = new Score(); this.loop_timer = 1000; this.removed_lines = 0; this.level = 0; this.canvas_id = ''; } function GameField(gameState) { var state = gameState, gameField = [], x, y; for (x = 0; x &lt; state.playAreaX; x++) { gameField[x] = []; for (y = 0; y &lt; state.playAreaY; y++) { gameField[x][y] = false; } } /** * Render the gamefield onto the canvas. */ this.draw = function(ctx) { var i, x, y; // Clear out the play field. ctx.fillStyle = "rgb(255, 255, 255)"; ctx.fillRect(0, 0, (state.playAreaX * state.blockSize), (state.playAreaY * state.blockSize)); //Background stripes, mostly for debugging. ctx.fillStyle = "rgba(127, 75, 0, 0.3)"; for (i = 0; i &lt; (state.playAreaX * state.blockSize); i += state.blockSize * 2) { ctx.fillRect(i, 0, state.blockSize, (state.playAreaY * state.blockSize)); } ctx.fillStyle = "rgb(255, 255, 0)"; for (x = 0; x &lt; state.playAreaX; x++) { for (y = 0; y &lt; state.playAreaY; y++) { if (gameField[x][y] === true) { ctx.fillRect(x * state.blockSize + 1, y * state.blockSize + 1, state.blockSize - 2, state.blockSize - 2); } } } }; /** * Check whether the next square in any direction is filled. */ this.check_direction = function(block, direction) { var hit_something = false, render_offsets = { "x": 0, "y": 0 }, step, filled, render_coord_x, render_coord_y; for (step = 0; step &lt; block.width() * block.height(); step++) { render_coord_x = state.block.x + render_offsets.x; render_coord_y = state.block.y + render_offsets.y; switch (direction) { case "u": render_coord_y--; break; case "r": render_coord_x++; break; case "d": render_coord_y++; break; case "l": render_coord_x--; break; } if (gameField[render_coord_x][render_coord_y]) { filled = block.piece_filled(step); if (filled) { hit_something = true; break; } } render_offsets = block.update_render_offsets(render_offsets); } return hit_something; }; /** * Check the current position of the active block and take appropriate action. * @TODO Function naming doesn't make sense anymore. */ this.check_hit_bottom = function(block) { var hit_something = this.check_direction(block, "d"), render_offsets, render_coord_x, render_coord_y, step, filled; if (block.y + block.height() &gt;= gameField[0].length) { hit_something = true; } if (!hit_something) { return; } // The active block has hit something below, and should be pushed to the // permanent gamefield. block.replace = true; render_offsets = { "x": 0, "y": 0 }; for (step = 0; step &lt; block.width() * block.height(); step++) { render_coord_x = block.x + render_offsets.x; render_coord_y = block.y + render_offsets.y; filled = block.piece_filled(step); if (filled) { gameField[render_coord_x][render_coord_y] = true; } render_offsets = block.update_render_offsets(render_offsets); } this.check_for_full_lines(); }; /** * Scan a line for it being full. If so remove it. * * @TODO This logic could be easier if the gamefield array's were inverted, * but that might complicate a lot of other logic. Investigate? */ this.check_for_full_lines = function() { var full_lines = 0, y, x, line_piece_count; for (y = 0; y &lt; gameField[0].length; y++) { line_piece_count = 0; for (x = 0; x &lt; gameField.length; x++) { gameField[x][y] &amp;&amp; line_piece_count++; } if (line_piece_count === gameField.length) { full_lines++; for (x = 0; x &lt; gameField.length; x++) { gameField[x].splice(y, 1); gameField[x].unshift(false); } } } if (full_lines &gt; 0) { state.score.removed_lines(full_lines); } state.level += 0.1 * full_lines; }; } function Score() { var score = 0, line_score = 1000, multi_line_bonus = true; this.removed_lines = function(num_lines) { var bonus = num_lines * line_score; if (multi_line_bonus) { bonus *= num_lines; } score += bonus; }; this.draw = function() { var score_div = document.getElementById("score"); if (score_div !== null) { score_div.innerHTML = score; } }; this.getScore = function() { return score; }; } /** * Functionality of a single falling tetris block. */ function Block(state) { this.type = Math.ceil(Math.random() * 7) - 1; this.color = state.layout_colors[this.type]; this.orientation = 0; var layout = state.available_layouts[this.type]; this.height = function () { if (this.orientation === 0 || this.orientation === 180) { return layout.length; } return layout[0].length; }; this.width = function () { if (this.orientation === 90 || this.orientation === 270) { return layout.length; } return layout[0].length; }; this.x = Math.floor(state.playAreaX / 2 - this.width() / 2); this.y = 0; this.draw = function (ctx) { ctx.fillStyle = this.color; var render_offsets = { "x": 0, "y": 0 }, step, filled, render_coord_x, render_coord_y; for (step = 0; step &lt; this.width() * this.height(); step++) { filled = this.piece_filled(step); // Render if necessary. if (filled) { render_coord_x = (this.x + render_offsets.x) * state.blockSize; render_coord_y = (this.y + render_offsets.y) * state.blockSize; ctx.fillRect(render_coord_x + 1, render_coord_y + 1, state.blockSize - 2, state.blockSize - 2); } render_offsets = this.update_render_offsets(render_offsets); } }; /** * The naming and use of this function needs a review. */ this.update_render_offsets = function(render_offsets) { render_offsets.x++; if (render_offsets.x &gt;= this.width()) { render_offsets.y++; render_offsets.x = 0; } return render_offsets; }; /** * Figure out if the current piece in a block is filled.. */ this.piece_filled = function (step) { var coordinates = this.step_to_rotated_coordinates(step), filled = layout[coordinates.y][coordinates.x]; return !!filled; }; /** * Converts "search steps" into local x/y coordinates. */ this.step_to_coordinates = function(step) { var coords = { x: 0, y: 0 }; if (this.orientation === 0 || this.orientation === 180) { coords.x = step % this.width(); coords.y = Math.floor(step / this.width()); } else { coords.x = Math.floor(step / this.width()); coords.y = ((step + 1) % this.width()); } return coords; }; /** * Converts "search steps" into local x/y coordinates adjusted for piece * rotation. */ this.step_to_rotated_coordinates = function(step) { var coords = this.step_to_coordinates(step); if (this.orientation === 180) { coords.x = this.width() - coords.x - 1; coords.y = this.height() - coords.y - 1; } else if (this.orientation === 270) { coords.x = this.width() - coords.x; // @TODO Ugly hack. Figure out and fix. if (this.type === 6) { coords.x--; } if (this.width() === 4) { coords.x -= 4; } coords.y = this.width() - coords.y - 1; } return coords; }; this.down = function () { state.gameField.check_hit_bottom(state.block, "d"); if (state.block.replace !== true) { this.y += 1; } }; } /** * Render the game surface on a canvas. */ function Canvas_renderer(canvas_id) { this.draw = function(state) { var canvas = document.getElementById(canvas_id), ctx = canvas.getContext("2d"); state.gameField.draw(ctx); state.block.draw(ctx); state.score.draw(); }; } /** * Keep track of list of keypress to function callback mapping. */ function Keyboard() { // Make assigning keys easier. this.up = 38; this.right = 39; this.left = 37; this.down = 40; var callbacks = {}; //Register a new hook this.add = function(key, callback) { callbacks[key] = callback; }; // onkeydown callback. this.event = function(e) { if (callbacks[e.keyCode] === undefined) { return; } callbacks[e.keyCode](); }; } /** * Print, debugging tool. */ function p(text) { var debug_div = document.getElementById("debug_messages"); if (debug_div !== null) { debug_div.innerHTML = text + '&lt;br/&gt; ' + debug_div.innerHTML; } } function getUrlVars() { var vars = {}; window.location.href.replace(/[?&amp;]+([^=&amp;]+)=([^&amp;]*)/gi, function(m, key, value) { vars[key] = value; }); return vars; } return new Tetris(); })(); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T18:27:38.437", "Id": "36776", "Score": "2", "body": "Don't you think there's a little too much code in one file?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T18:32:13.287", "Id": "36777", "Score": "1", "body": "I don't know, is it? Is that a JS idiosyncracy? In other languages I wouldn't expect anyone to say that off 500 - 600 lines of code. Do you have specific suggestions for how to split it up?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T18:39:58.750", "Id": "36779", "Score": "2", "body": "Well, JS isn't a verbose language like Java. You usually start wondering how to split up objects responsibilities (or \"modules\") around 100 lines or so (or even before)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T18:56:09.650", "Id": "36783", "Score": "1", "body": "Well, it seems to be cleanly broken up into a couple isolated components already. Keeping them all in one file seems like no biggie unless you think that it will encourage hidden dependencies." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T11:35:56.787", "Id": "36914", "Score": "0", "body": "I would generally split it up into a couple .js files and call them from the `<head>`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T16:23:03.477", "Id": "37190", "Score": "0", "body": "The code lines shouldn't be a problem when you minify and compress (you are doing that right?). Also don't split your files because that increases HTTP requests which slows loading time. You can understand this better by reading: http://developer.yahoo.com/performance/rules.html#external\n Notice how http requests is the first thing on their list." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T20:56:05.317", "Id": "37212", "Score": "0", "body": "I'm aware the code should be minified and compressed, but I'm hardly releasing this code onto the world. There are enough tetris clones out there already, most of them significantly better than this. I'm more concerned with code than loading time, here. :) I guess I should take the lack of answers as a sign that there's aren't any large obvious issues with it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T05:47:18.753", "Id": "58276", "Score": "1", "body": "@Letharion You should take the lack of answers as a sign that there is too much code to review. Take a Sample section of it and ask for a review on that. Then Alter your code accordingly. Rinse and repeat with a new question and new section until you are happy it is clean." } ]
[ { "body": "<p>From a one-time reading:</p>\n\n<ul>\n<li><p>Functions <code>left</code>, <code>right</code>, <code>up</code> and <code>down</code> do model changes and deal with the view. Ideally, you would have a controller functionality that calls those functions when required, and afterwards the controller can then call <code>renderer.draw(state)</code>. </p></li>\n<li><p>I don't think you have to memoize <code>pow()</code>.</p></li>\n<li><p>Magic numbers are present in <code>render_debug_grid</code>. I am guessing those values ought to be based on <code>blockSize</code>.</p></li>\n<li><p>For initializing, if you are willing to deal with falsey values, you could just create the x arrays, and treat undefined as false, or otherwise you could create a y array and <code>slice</code> it x times.</p></li>\n<li><p>I think the code would be cleaner if <code>check_direction</code> was called with the offsets straight away instead of deriving them from u/r/d/l.</p></li>\n<li><p>There is some copy-pasted code in <code>check_hit_bottom</code> and <code>check_direction</code>, which you could make DRY'er.</p></li>\n<li><p>As per your comment, it is not clear for the casual reader what function <code>update_render_offsets</code> does, nor any other function under it in <code>Block</code>.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T14:20:50.140", "Id": "36959", "ParentId": "23873", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T18:07:15.050", "Id": "23873", "Score": "10", "Tags": [ "javascript", "beginner", "game", "tetris" ], "Title": "Learning the basics of JavaScript with a Tetris game" }
23873
<p>I'm trying to change the background color of each <code>.achievement</code> div. The content is being generated dynamically so I can't add a class easily to each one.</p> <p>I have it working with selectors like <code>.achievements .grid-row:nth-child(odd) .col-1-2:nth-child(even) .achievement</code> but they seem a little bloated. The problem I'm having is that the <code>.achievement</code> div is nested a few deep so I can't just use an <code>:nth-child</code> or <code>:nth-of-type</code> on it.</p> <p>I'm just checking to see if there is a better way to select those that I'm missing out on.</p> <p><a href="http://jsfiddle.net/ferne97/gxLqV/" rel="nofollow noreferrer">jsFiddle</a></p> <p><strong>HTML</strong></p> <pre class="lang-html prettyprint-override"><code>&lt;div class="achievements"&gt; &lt;div class="grid-row"&gt; &lt;div class="col-1-2"&gt; &lt;div class="achievement"&gt; &lt;p&gt;Testing...&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-1-2"&gt; &lt;div class="achievement"&gt; &lt;p&gt;Testing...&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="grid-row"&gt; &lt;div class="col-1-2"&gt; &lt;div class="achievement"&gt; &lt;p&gt;Testing...&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-1-2"&gt; &lt;div class="achievement"&gt; &lt;p&gt;Testing...&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>CSS</strong></p> <pre class="lang-css prettyprint-override"><code>.achievements .grid-row:nth-child(odd) .col-1-2:nth-child(even) .achievement { background: #5891bc; } .achievements .grid-row:nth-child(even) .col-1-2:nth-child(odd) .achievement { background: #96c3e6; color: #585858; } .achievements .grid-row:nth-child(even) .col-1-2:nth-child(even) .achievement { background: #d3dfe7; color: #585858; } </code></pre>
[]
[ { "body": "<p>You should probably take out the class selectors (<code>.grid-row</code> and <code>.col-1-2</code>) because <code>nth-child</code> <a href=\"https://stackoverflow.com/questions/5428676/nth-child-doesnt-respond-to-class\">doesn't respond to them</a> (i.e. they're not doing anything):</p>\n\n<pre><code>.achievements :nth-child(even) :nth-child(odd) .achievement\n</code></pre>\n\n<p>In the future, CSS3's <code>toggle()</code> function (which cycles through values) could simplify things:</p>\n\n<pre><code>.achievement {\n background: toggle(#ccc, #5891bc, #96c3e6, #d3dfe7);\n}\n</code></pre>\n\n<p>Sadly this <a href=\"http://css3clickchart.com/#toggle\" rel=\"nofollow noreferrer\">isn't supported by any browsers</a> yet. Also proposed is an <a href=\"http://dev.w3.org/csswg/selectors4/#nth-match-pseudo\" rel=\"nofollow noreferrer\"><code>:nth-match</code> selector</a>, which would let you do:</p>\n\n<pre><code>:nth-of-type(n4+1 of .achievement) {\n background: #5891bc;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T22:44:27.487", "Id": "36804", "Score": "0", "body": "You can use a class with :nth-child selectors, it just needs to have a parent. http://jsfiddle.net/ferne97/fZGvH/90/. Thanks for the links, wasn't aware of those ones yet, they look cool." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T00:34:44.817", "Id": "36807", "Score": "0", "body": "No problem! Hmm nope, that doesn't work for me on the latest Chrome (25). It sort of works on FF/Safari, but it breaks if there are any sibling elements (which sort of defeats the point of using the class selector in the first place)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T22:23:40.573", "Id": "23884", "ParentId": "23880", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T21:23:46.370", "Id": "23880", "Score": "3", "Tags": [ "html", "css" ], "Title": "CSS3 Selectors for achievements" }
23880
<p>I am new with <code>SignalR</code> and still a newbie with <code>IoC Container</code> <code>SimpleInjector</code> and I am wondering if there are any side effects and/or if I'm save with my chosen approach.</p> <p>In my web app I have a <code>SetupHub</code> that invokes a method on an object resolved with <code>SimpleInjector</code>. This method may do anything that I'm not aware about. Maybe it contains <code>Tasks</code> and it may consume x units of time.</p> <p>During this Setup process I want to inform the client of the progress. This is my current implementation and it works fine:</p> <pre><code>public class SetupHub : Hub { public void Start() { // My SimpleInjector resolve wrapper IocContainer.Instance.GetInstance&lt;ISetup&gt;().Start(UpdateProgress); } private void UpdateProgress(double percentage) { Clients.Caller.updateProgress(percentage); } } public class Setup : ISetup { public void Start(Action&lt;double&gt; updateProgress) { Task.Factory.StartNew(() =&gt; { updateProgress(10); // Bogus progress Thread.Sleep(100); // Simulate x units of time CreateRoles(); updateProgress(25); Thread.Sleep(400); CreateUsers(); updateProgress(60); Thread.Sleep(200); CreateRelations(); updateProgress(100); //CreateRelationGroups(); }); } } public interface ISetup { void Start(Action&lt;double&gt; updateProgress); } </code></pre>
[]
[ { "body": "<p>Currently, your setup doesn't allow for any cancellation or error handling. The latter is an implementation detail, so I guess you've handled that in the actual code. I would consider the following:</p>\n\n<ul>\n<li>Return the started task out of <code>Start</code></li>\n<li>Will you ever need to provide a result from the started task? If so, provide an overload for <code>Func&lt;double,T&gt;</code></li>\n<li>Provide cancellation support via a cancellation token (if business logic dictates this is acceptable)</li>\n<li>Provide a <code>Stop</code> method that also that can stop the task created by <code>Start</code></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-27T11:34:21.520", "Id": "48317", "ParentId": "23881", "Score": "6" } }, { "body": "<h1>Service Locator Alert!!</h1>\n<p>Your <code>SetupHub</code> class has a hardwired dependency on the IoC container itself - this is <strong>not</strong> dependency injection. When DI is done right, <em>you cannot tell whether you're using an IoC container or if you're injecting the dependencies by hand</em> - because the <strong>only</strong> place in your entire program that <em>needs</em> the IoC container, is the <em>composition root</em>.</p>\n<p><a href=\"http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/\" rel=\"nofollow noreferrer\">This is an <strong>anti-pattern</strong></a>:</p>\n<blockquote>\n<pre><code>public void Start()\n{\n // My SimpleInjector resolve wrapper\n IocContainer.Instance.GetInstance&lt;ISetup&gt;().Start(UpdateProgress);\n}\n</code></pre>\n</blockquote>\n<p>It also seems <code>IocContainer.Instance</code> is a <em>Singleton</em> instance. <em>Service Locator</em> and <em>Singleton</em> are two patterns that directly contradict <em>Inversion of Control</em> and <em>Dependency Injection</em>.</p>\n<p>Instead, you should be <em>injecting</em> the <code>ISetup</code> dependency through the constructor, along with the method you're depending on, like this:</p>\n<pre><code>public class SetupHub : Hub\n{\n private readonly ISetup _setup;\n private readonly Action&lt;double&gt; _updateProgress;\n\n public SetupHub(ISetup setup, Action&lt;double&gt; updateProgress)\n {\n _setup = setup;\n _updateProgress = updateProgress;\n }\n\n public void Start()\n {\n _setup.Start(_updateProgress);\n }\n}\n</code></pre>\n<p>Wiring this up with the IoC container is going to be tricky, but it could be simplified if the <code>ISetup</code> was injected in a factory class' constructor - first we need an abstraction for the <code>Hub</code>:</p>\n<pre><code>public interface IHub\n{\n void Start();\n}\n</code></pre>\n<p>Now let's create a <em>factory</em> class whose sole responsibility is to create <code>IHub</code> instances:</p>\n<pre><code>public class SetupHubFactory\n{\n private readonly ISetup _setup;\n\n public SetupHubFactory(ISetup setup)\n {\n _setup = setup;\n }\n\n public IHub Create(Action&lt;double&gt; updateProgress)\n {\n return new SetupHub(_setup, updateProgress);\n }\n}\n</code></pre>\n<p>Make that factory an <em>abstraction</em>:</p>\n<pre><code>public class SetupHubFactory : IHubFactory\n{\n // ...\n} \n\npublic interface IHubFactory\n{\n IHub Create(action&lt;double&gt; updateProgress);\n}\n</code></pre>\n<p>This <code>IHubFactory</code> is an <em>abstract factory</em> - the client code receives <em>any HubFactory</em>, and works against an <em>abstraction</em>, instead of being tied to a single specific implementation:</p>\n<pre><code>public class ClientObject\n{\n private readonly IHubFactory _hubFactory;\n\n public ClientObject(IHubFactory hubFactory)\n {\n _hubFactory = hubFactory;\n }\n\n public void DoSomething()\n {\n // hub is of type IHub - ClientObject isn't tied to a specific implementation.\n // inject a new implementation of the `IHubFactory` and no changes needed,\n // this method will create an instance of the new hub implementation:\n var hub = _hubFactory.Create(UpdateProgressBar);\n hub.Start();\n }\n\n private void UpdateProgressBar(double progress)\n {\n // ...\n }\n}\n</code></pre>\n<p>DI <em>statically declares the dependencies</em> in your constructors. If a class has too many dependencies / constructor arguments, it's generally a sign that you're starting to break the <em>Single Responsibility Principle</em>.</p>\n<p>Then you have a composition root / entry point somewhere:</p>\n<pre><code>public void Run()\n{\n // 1. Instantiate your favorite IoC container.\n // 2. Configure your favorite IoC container.\n // 3. Resolve the entire app's dependency graph at once.\n \n // 4. Profit: // \n var client = _ioc.GetInstance&lt;ClientObject&gt;();\n client.DoSomething();\n\n /* */\n\n // or..\n // go with Poor Man's DI if you don't have a favorite IoC container:\n var setup = new Setup();\n var factory = new SetupHubFactory(setup);\n var client = new ClientObject(factory);\n\n client.DoSomething();\n}\n</code></pre>\n<p>It's your IoC container's job to <code>new</code> up the dependencies and automagically inject them into all the required constructors when you <em>ask</em> for a <code>ClientObject</code> (&quot;ask&quot; is important here). It works automagically because all the classes involved in the dependency graph <em>tell</em> exactly everything they need (&quot;tell&quot; is important here); only <em>infrastructure code</em> directly works with the IoC container, the rest of the application is blissfully unaware of its existence.</p>\n<blockquote>\n<p><em>Tell, don't ask.</em></p>\n</blockquote>\n<p>Also, with DI/IoC you need to follow the <em>Hollywood Principle</em>:</p>\n<blockquote>\n<p><em>Don't call them, they'll call you!</em></p>\n<p><sub><em>(don't call into the IoC container, the IoC container will call into your constructor)</em></sub></p>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-27T19:55:20.700", "Id": "48365", "ParentId": "23881", "Score": "6" } } ]
{ "AcceptedAnswerId": "48365", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T21:55:43.597", "Id": "23881", "Score": "10", "Tags": [ "c#", "dependency-injection", "signalr" ], "Title": "Send message with SignalR to client(s) from injected (IoC) method" }
23881
ASP.NET SignalR is a new library for ASP.NET developers that makes it incredibly simple to add real-time web functionality to your applications. What is "real-time web" functionality? It's the ability to have your server-side code push content to the connected clients as it happens, in real-time.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T22:22:54.870", "Id": "23883", "Score": "0", "Tags": null, "Title": null }
23883
Apache Subversion is an open-source centralized version control system.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T22:26:56.253", "Id": "23886", "Score": "0", "Tags": null, "Title": null }
23886
<p>I started feeling like my code was becoming a little cluttered in the graphics:</p> <pre><code>void render() { BufferStrategy bs = getBufferStrategy(); if (bs == null) { createBufferStrategy(3); return; } Graphics2D g = (Graphics2D) bs.getDrawGraphics(); g.setColor(Color.BLACK); g.fillRect(0, 0, getWidth(), getHeight()); g.drawImage(chalkBoard, 0, 0, getWidth(), getHeight(), null); g.drawImage(gallows, 0, 65, gallows.getWidth(), gallows.getHeight(), null); g.setColor(Color.WHITE); g.setFont(dFont.deriveFont((float) 38)); g.drawString("Hangman", 45, 58); g.drawString("X", 445, 58); g.setFont(dFont.deriveFont((float) 15)); g.drawString("Xid Studios", 200, 58); if (currentState == State.START_MENU) { g.setFont(dFont.deriveFont((float) 28)); g.drawString("One Player", 240, 100); g.drawImage(btnBorder, 233, 75, 150, 33, null); g.drawImage(startDisplayHanger, 240, 90, 56, 128, null); g.drawString("Two Players", 240, 225); g.drawImage(btnBorder, 233, 200, 175, 33, null); g.drawImage(startDisplayHanger, 240, 220, 56, 128, null); g.drawImage(startDisplayHanger, 296, 220, 56, 128, null); } else if ((currentState == State.PLAYER_ONE_MENU) || (currentState == State.PLAYER_TWO_MENU)) { g.setFont(dFont.deriveFont((float) 28)); g.drawString("PLAY", 400, 330); g.drawImage(btnBorder, 390, 295, 80, 50, null); if (currentState == State.PLAYER_ONE_MENU) { g.drawString("Player One's Name", 240, 100); // g.drawString(playerOne, 240, 125); g.setFont(dFont.deriveFont((float) 20)); for (int p = 0; p &lt; pOne.length; p++) { g.drawString(pOne[p], 240 + (p * 15), 125); } g.setFont(dFont.deriveFont((float) 28)); g.drawString("Categories", 240, 175); g.setFont(dFont.deriveFont((float) 15)); for (int c = 0; c &lt; categories.length; c++) { g.drawString(categories[c], 250, 200 + (c * 15)); } } else if (currentState == State.PLAYER_TWO_MENU) { g.drawString("Player One's Name", 240, 100); g.drawString("Player Two's Name", 240, 175); g.drawString("Custom Puzzle:", 240, 250); g.setFont(dFont.deriveFont((float) 15)); g.drawString("6 Letters Max", 240, 262); } } else if (currentState == State.PLAY_SCREEN) { setHangerImage(); g.drawImage(line, 225, 290, 225, 26, null); g.drawImage(hanger, 80, 90, 113, 256, null); g.setFont(dFont.deriveFont((float) 31)); g.drawString(chancesLeft + "", 100, 330); g.drawString("Player One", 240, 100); g.setFont(dFont.deriveFont((float) 20)); for (int p = 0; p &lt; pOne.length; p++) { g.drawString(pOne[p], 240 + (p * 20), 125); } g.setFont(dFont.deriveFont((float) 28)); if (puzzleCreated) { for (int x = 0; x &lt; puzLength; x++) { g.drawString("" + hid[x], 250 + (x * 20), 330); } } g.setFont(dFont.deriveFont((float) 31)); g.drawString("Category:", 240, 160); g.setFont(dFont.deriveFont((float) 20)); g.drawString(category, 240, 185); } else if (currentState == State.LOSE_SCREEN) { g.drawImage(line, 225, 290, 225, 26, null); g.setFont(dFont.deriveFont((float) 28)); g.drawString("LOSE", 100, 330); // setHangerImage(); g.drawImage(hanger, 80, 90, 113, 256, null); for (int x = 0; x &lt; puzLength; x++) { g.drawString("" + puzzleSplit[x], 250 + (x * 20), 330); } } else if (currentState == State.WIN_SCREEN) { g.drawImage(line, 225, 290, 225, 26, null); g.setFont(dFont.deriveFont((float) 28)); g.drawString("WIN", 100, 330); // setHangerImage(); g.drawImage(hanger, 80, 90, 113, 256, null); for (int x = 0; x &lt; puzLength; x++) { g.drawString("" + puzzleSplit[x], 250 + (x * 20), 330); } } g.dispose(); bs.show(); } </code></pre> <p>State is an enum that i created to differentiate the states of the game.</p> <pre><code>public enum State { START_MENU, PLAYER_ONE_MENU, PLAYER_TWO_MENU, WIN_SCREEN, LOSE_SCREEN, PLAY_SCREEN } </code></pre> <p>Would it be possible to put each part into a separate method/class and then call it and how would I go about it?</p> <p>I was thinking about maybe:</p> <pre><code>if (currentState == State.START_SCREEN) { drawStartMenu(); } </code></pre> <p>I was wondering if anybody knows how to do this or has a better way of rendering the screen and if they could help me with this. </p> <p>If you want to see how I'm using this, check out <a href="https://github.com/Xid-Studios/Hangman" rel="nofollow">this</a>.</p>
[]
[ { "body": "<p>To answer real fast about your switch, you can do the following :</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>function whatEverName(State state){\n\n switch(state){\n case START_MENU:\n drawStartMenu();\n //..\n break;\n case PLAYER_ONE_MENU:\n //..\n break;\n case START_MENU:\n //..\n break;\n //...\n default:\n //..\n break;\n } \n}\n</code></pre>\n\n<hr>\n\n<p>By the length of that function, it could be cut into more functions, but even more it could closely be a class itself.</p>\n\n<p>Anyway, If I were you, I'd make the function with the switch as short as possible. Probably only the switch itself. Separate the initialization of the <code>Graphics2D</code>, from the switch. The shortest and the more specific the methods are, the easier to test.</p>\n\n<p>So put from <code>BufferStrategy bs = getBufferStrategy();</code> to <code>g.drawString(\"Xid Studios\", 200, 58);</code> in a function (all on his own). Then, everything that is in a if clause presently should get his own method, try have methods of 20 and less lines.</p>\n\n<p><em>When I say 20 lines, don`t count braces or wrapped line. Only lines of code.</em></p>\n\n<hr>\n\n<p>Also I've seen that you wanted to call one method <code>drawSTARTMENU</code>, the name is verbose,(that's great) but try staying in the Java conventions which are camelCase method name. It's OK to capitalize an acronym (eg: URL) but try to keep words in lowercase, and caps only the first letter of any word following the first one. That make the code easier to read and makes all the code look the same way.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T00:22:27.577", "Id": "23890", "ParentId": "23888", "Score": "1" } }, { "body": "<p>I agree to a small degree with Hugo about seperating all the graphics portions within each if statement. But this is a prime example of how inheritance comes to play. You have a switch statement inside your logic method (some people have different names for this, but it basically just means where you do all the work)</p>\n\n<p>You are on the right track with having a state. You are also on the right track with having a enum. Where I feel that you go wrong is by putting all those in the logic method (in this case render) So I would make a abstract class that returns a instance of itself based upon the state. It would have 1 abstract method called render.</p>\n\n<pre><code>public abstract class AbstractWindowBufferStrategy\n{\n public static AbstractWindowBufferStrategy(State state, BufferStrategy bs)\n {\n switch(state)\n {\n case START_MENU:\n return new StartMenuBufferStrategy(bs);\n case PLAYER_ONE_MENU:\n return new PlayerOneMenuBufferStrategy(bs);\n case PLAYER_TWO_MENU:\n return new PlayerTwoMenuBufferStrategy(bs);\n case WIN_SCREEN:\n return new WinScreenBufferStrategy(bs);\n case LOSE_SCREEN:\n return new LoseScreenBufferStrategy(bs);\n case PLAY_SCREEN:\n return new PlayScreenBufferStrategy(bs);\n }\n abstract void render();\n }\n}\npublic class StartMenuBufferStrategy extends AbstractWindowBufferStragey\n{\n public StartmenuBufferStrategy(BufferStrategy bs)\n {\n //do something with bs to set g\n }\n private Graphics2D g;\n public void renderRest()\n {\n g.setColor(Color.BLACK);\n g.fillRect(0, 0, getWidth(), getHeight());\n g.drawImage(chalkBoard, 0, 0, getWidth(), getHeight(), null);\n\n g.drawImage(gallows, 0, 65, gallows.getWidth(), gallows.getHeight(), null);\n\n g.setColor(Color.WHITE);\n g.setFont(dFont.deriveFont((float) 38));\n g.drawString(\"Hangman\", 45, 58);\n g.drawString(\"X\", 445, 58);\n\n g.setFont(dFont.deriveFont((float) 15));\n g.drawString(\"Xid Studios\", 200, 58);\n g.setFont(dFont.deriveFont((float) 28));\n g.drawString(\"One Player\", 240, 100);\n g.drawImage(btnBorder, 233, 75, 150, 33, null);\n g.drawImage(startDisplayHanger, 240, 90, 56, 128, null);\n\n g.drawString(\"Two Players\", 240, 225);\n g.drawImage(btnBorder, 233, 200, 175, 33, null);\n g.drawImage(startDisplayHanger, 240, 220, 56, 128, null);\n g.drawImage(startDisplayHanger, 296, 220, 56, 128, null);\n\n g.dispose();\n bs.show(); //might want to change to setVisible(true) to keep current.\n }\n}\n//etc for rest of the classes\n</code></pre>\n\n<p>now you will be able to do somethign like this</p>\n\n<pre><code>public void foo()\n{\n AbstractWindowBufferStrategy awbs = AbstractWindowBufferStrategy.getBufferStrategy(currentState, bs);\n //will never have to change. It depends on a difficult to change abstract class.\n awbs.render(); \n}\n</code></pre>\n\n<p>for extra points you can figure out how to put the common render portion into the abstract class, and have all the child classes do only what they need to.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T04:06:35.927", "Id": "36811", "Score": "0", "body": "what do you mean \"do something with bs to set g\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T04:15:31.103", "Id": "36812", "Score": "0", "body": "I actually have no idea what you did. Sorry, I've never done any abstract anything, and I'm relatively new to using buffered anything" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T14:04:07.847", "Id": "36835", "Score": "1", "body": "@Exikle I mean that in your draw method you check if bs is null. If it is you created a buffer strategy. So in this case you'd move that code to your constructor. You then take the graphics from BufferStrategy and set it to g. Hence my comment of Do something with bs to set g." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T14:06:03.880", "Id": "36836", "Score": "0", "body": "@Exikle Using abstract classes has nothing to do with Buffered Strategy. This particular case is Polymorphism. Something I would recommend researching as it is what you are trying to do, but Polymorphism is the clean way of doing it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T14:08:28.497", "Id": "36837", "Score": "1", "body": "@Exikle I found a good article on Java website http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T02:07:07.620", "Id": "23893", "ParentId": "23888", "Score": "1" } }, { "body": "<p>Firstly, If possible then avoid switch because </p>\n\n<ul>\n<li>Using a switch is a sign of code smell.</li>\n<li>Switch statement can be replaced by polymorphism(InternalPolymorphisim)</li>\n</ul>\n\n<p>For more info just google or <a href=\"http://c2.com/cgi/wiki?SwitchStatementsSmell\" rel=\"nofollow\">read</a></p>\n\n<p>Secondly use inheritance where its really need , <a href=\"https://en.wikipedia.org/wiki/Composition_over_inheritance\" rel=\"nofollow\">otherwise prefer composition</a></p>\n\n<p>Below is how we can refactor the code</p>\n\n<p>You can create a map in the class where you have created the method <strong>void render()</strong> , like this</p>\n\n<pre><code>private static final Map&lt;State, IRenderer&gt; RENDERERS_MAP;\n</code></pre>\n\n<p>We declared a hash map which is static -> meaning class member and final -> so that it can be initialized only once. Since we want to use enum types as hash map keys , we will use create map's instance using EnumMap</p>\n\n<p>We can initialize the map in static block(static block is executed ONLY once , no matter how many objects you create). </p>\n\n<pre><code> static { \n RENDERERS_MAP= new EnumMap&lt;State, IRenderer&gt;(State.class);\n\n for (State state : State.values()) {\n RENDERERS_MAP.put(state, getRender());\n }\n}\n</code></pre>\n\n<p><strong>NOTE</strong> If you want to avoid using static block then just move the code from static block into a static method and call it like this</p>\n\n<pre><code>private static final Map&lt;State, IRenderer&gt; m = getMap(); \n</code></pre>\n\n<p>Now the method <strong>render()(which you pasted above)</strong> can be refactor like this(that the beauty of OOP) :</p>\n\n<pre><code>void render() {\n Renderer currentRenderer = RENDERERS_MAP.get(currentState);\n if (ren != null) {\n currentRenderer.render();\n }\n}\n</code></pre>\n\n<p>The <strong>Enum State</strong> , can be refactored to include information about renderer </p>\n\n<pre><code>public enum State {\n START_MENU() {\n @Override\n public Renderer getRenderer() {\n return new StartMenuRenderer();\n }\n },\n PLAYER_ONE_MENU() {\n @Override\n public Renderer getRenderer() {\n return new PlayerOneRenderer();\n }\n },\n PLAYER_TWO_MENU() {\n @Override\n public Renderer getRenderer() {\n return new PlayerTwoRenderer();\n }\n },\n WIN_SCREEN() {\n @Override\n public Renderer getRenderer() {\n return null; //TODO: implement body\n }\n },\n LOSE_SCREEN() {\n @Override\n public Renderer getRenderer() {\n return null; //TODO: implement body\n }\n },\n PLAY_SCREEN() {\n @Override\n public Renderer getRenderer() {\n return null; //TODO: implement body\n }\n };\n\n public abstract Renderer getRenderer();\n}\n</code></pre>\n\n<p>The interface Renderer look like this(you can change it according to your needs)</p>\n\n<pre><code>public interface Renderer {\n\n void render(Graphics2D g);\n}\n</code></pre>\n\n<p>Now we can create classes which implements Renderer using <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">Single_responsibility_principle</a></p>\n\n<pre><code>public class StartMenuRenderer implements Renderer {\n @Override\n public void render(Graphics2D g) {\n //TODO: implement body\n }\n}\n</code></pre>\n\n<p>And Since there is some common logic shared between PlayerOne and PlayerTwo We can create a class called PlayerMenuRenderer like this</p>\n\n<pre><code>public abstract class PlayerMenuRenderer implements Renderer {\n\n protected void init(Graphics2D g) {\n g.setFont(dFont.deriveFont((float) 28));\n g.drawString(\"PLAY\", 400, 330);\n g.drawImage(btnBorder, 390, 295, 80, 50, null);\n }\n\n}\n</code></pre>\n\n<p>And subclasses <strong>PlayerOneRenderer</strong> and <strong>PlayerTwoRenderer</strong> can be created like this</p>\n\n<pre><code>public class PlayerOneRenderer extends PlayerMenuRenderer {\n @Override\n public void render(Graphics2D g) {\n init(g);\n //TODO: implement body\n }\n}\n\n\npublic class PlayerTwoRenderer extends PlayerMenuRenderer {\n @Override\n public void render(Graphics2D g) {\n init(g);\n //TODO: implement body\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T03:36:40.553", "Id": "36971", "Score": "0", "body": "i understood everything except the first 2 bits of code, could you explain how they work in more detail?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T08:33:37.447", "Id": "36973", "Score": "0", "body": "@Exikle , by **first 2 bits** i guess you mean the code regarding with Map creation and static block. The answer is updated." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T14:49:40.063", "Id": "23959", "ParentId": "23888", "Score": "2" } } ]
{ "AcceptedAnswerId": "23959", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T23:45:03.420", "Id": "23888", "Score": "1", "Tags": [ "java", "graphics", "hangman" ], "Title": "Set visible interface from method/class" }
23888
<p>I point to my problem in the comments of my code.</p> <p>I have a class RomanNumeral:</p> <pre><code>public class RomanNumeral { private String romaNumera; private String romans = "IVXLCDM"; public RomanNumeral(String rn) { //sets rn to romaNumera and checks if rn is a valid roman numeral } public boolean equals(RomanNumeral rn) { //overrides .equals } public String toString() { //overrides toString(); } public int getDecimalValue() { float[] valueOfNumeral = new float[romaNumera.length()]; int result = 0; float calculatedRomanDecimal=.5f; for(int i = 0; i&lt;romaNumera.length(); i++) { /* My attempt at shortening the code for(int j = 0; j&lt;romans.length(); j++) { if ( romans.charAt(j)==( romaNumera.charAt(i) ) &amp;&amp; (j)%2==0 ) {valueOfNumeral[i] = calculatedRomanDecimal*2f;} if ( romans.charAt(j)==( romaNumera.charAt(i) ) &amp;&amp; (j)%2==1 ) {valueOfNumeral[i] = calculatedRomanDecimal*5f;} */ //What I am trying to do above and what I did bellow was check which Roman numeral was which, and assign a float value to the corresponding index in a float array. Say that I have a Roman numeral MCM. MCM is romaNumera of type string, and I compare each character in romaNumera to each character in romans. Since romaNumera.charAt(0)==romans.charAt(6), I assign valueOfNumeral[0] the value of 1000 //The stuff bellow works, but I feel like there is a more efficient way if (romans.charAt(0)==(romaNumera.charAt(i))) {valueOfNumeral[i] = 1;} if (romans.charAt(1)==(romaNumera.charAt(i))) {valueOfNumeral[i] = 5;} if (romans.charAt(2)==(romaNumera.charAt(i))) {valueOfNumeral[i] = 10;} if (romans.charAt(3)==(romaNumera.charAt(i))) {valueOfNumeral[i] = 50;} if (romans.charAt(4)==(romaNumera.charAt(i))) {valueOfNumeral[i] = 100;} if (romans.charAt(5)==(romaNumera.charAt(i))) {valueOfNumeral[i] = 500;} if (romans.charAt(6)==(romaNumera.charAt(i))) {valueOfNumeral[i] = 1000;} } result = Math.round(valueOfNumeral[romaNumera.length()-1]); for (int j = valueOfNumeral.length-2; j&gt;=0; j--){ if (valueOfNumeral[j]&lt;valueOfNumeral[j+1]) result -= Math.round(valueOfNumeral[j]); else result += Math.round(valueOfNumeral[j]); } return result; } } // class RomanNumerals </code></pre> <p>This compiles and does what I want it to do, however, I am trying to find a way to shorten the program so it doesn't require so many <code>if</code> statements.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T04:56:02.140", "Id": "36813", "Score": "1", "body": "Why are you using `float`s when roman numerals represent integers?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T12:23:38.603", "Id": "36976", "Score": "0", "body": "You should add checks for invalid roman numbers. Note that even using only roman digits, not all numbers should be valid, e.g. \"IIII\", \"DM\" or \"VX\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T19:14:08.317", "Id": "37353", "Score": "0", "body": "@Chase I would like to know what do you think about the feedback you received? Anything more you'd like to know/need help with ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T19:32:52.983", "Id": "37355", "Score": "0", "body": "@Hugo I actually learned a lot from the answer I just accepted now (for some reason I couldn't accept it before). I have no complaints, and I had already finished the project, I was just looking for better ways to do the same thing. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T19:36:06.213", "Id": "37356", "Score": "0", "body": "@Chase glad I could help!" } ]
[ { "body": "<p>First thing you can do is put them in <code>else if</code> statements. It doesn't reduce the code but it do at least reduce the number of case the program has to check each time.</p>\n\n<p>Because right now if the first match is good, it'll still check all the other statements.</p>\n\n<hr>\n\n<p><strong>To remove the <code>ifs</code>:</strong></p>\n\n<p>The other thing you could do is a <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Map.html\" rel=\"nofollow noreferrer\">Map</a>. Doing that would not really reduced the amount of code but would make the code more readable. See <a href=\"https://stackoverflow.com/questions/10901752/what-is-the-significance-of-load-factor-in-hashmap#10901823\">this topic</a> to learn more about the load factor in the map and how to initialize it.</p>\n\n<pre><code>private static final Map&lt;String, Integer&gt; ROMAN_MAP;\nstatic\n{\n // Note1 : Since you know the number of items in the map, you can initialize\n // the map directly with 7 safe \"spots\".\n // Note2 : We initialize it at 10 which is Roughly (N / load) + 1\n Map&lt;Character, Integer&gt;tempMap = new HashMap&lt;Character, Integer&gt;(10);\n tempMap.put('I', 1);\n tempMap.put('V', 5);\n tempMap.put('X', 10);\n tempMap.put('L', 50);\n tempMap.put('C', 100);\n tempMap.put('D', 500);\n tempMap.put('M', 1000);\n romanMap= Collections.unmodifiableMap(tempMap);\n}\n</code></pre>\n\n<p>Then you can access it just like that :</p>\n\n<pre><code>ROMAN_MAP.get(romaNumera.charAt(i));\n</code></pre>\n\n<hr>\n\n<p><strong>Changes with the use of a map :</strong></p>\n\n<p>Also, as mentioned, get rid of the <code>float</code>s AND of the <code>Math.round()</code> calls they are useless since your function returns an int anyway an that there is no possibility of displaying floating points anyway.</p>\n\n<p>Your function can then be reduced to the following : </p>\n\n<pre><code>public int getDecimalValue() {\n int result = 0;\n int length = romaNumera.length();\n\n for(int i = 0; i &lt; length; i++){\n int current = ROMAN_MAP.get(romaNumera.chartAt(i));\n int j = i+1;\n\n // Check if there is a next element and if it's bigger than current\n if(j &lt; length &amp;&amp; current &lt; ROMAN_MAP.get(romaNumera.chartAt(j)){\n result -= current;\n } else {\n result += current;\n }\n }\n return result;\n}\n</code></pre>\n\n<p>I've put <code>{</code> everywhere since they don't slow the process running in anyway and to me they make the code more readable and reduce the possibilities of error when refactoring.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T13:21:54.617", "Id": "36831", "Score": "0", "body": "+1 for using map (you can now use also EnumMap). I'm not certain that `valueOfNumera` will be useful for good coding" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T13:26:21.543", "Id": "36832", "Score": "0", "body": "@cl-r Agree with you with \"valueOfNumera\". I'll try update later on! (I didn't know about EnumMap, I'll take a look at it)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T16:23:22.310", "Id": "36842", "Score": "0", "body": "You will find good explanation in Effective Java, Joshua Bloch's book, §33" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T22:08:11.977", "Id": "37146", "Score": "0", "body": "You can use `Map<Character, Integer>tempMap = new HashMap<Character, Integer>(7, 1.0f);` isntead." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T01:17:27.010", "Id": "23892", "ParentId": "23891", "Score": "8" } }, { "body": "<p>Your first loop can be reduced to something like this:</p>\n\n<pre><code>String romans = \"IVXLCDM\";\nint roman_values[] = new int[] {1,5,10,50,100,500,1000};\nint result = 0;\n\nfor(int i=0;i&lt;n;i++)\n result += roman_values[romans.indexOf(romaNumera.charAt(i))];\n</code></pre>\n\n<p>Also, there is NO REASON to have floating-point stuff in a Roman numeral parser. Get rid of it!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T13:18:46.823", "Id": "36830", "Score": "0", "body": "-1 : more difficult to use : how do you retrieve 'D' easily ? +1 to point out `int`usage." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T04:52:13.457", "Id": "23894", "ParentId": "23891", "Score": "1" } } ]
{ "AcceptedAnswerId": "23892", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T00:51:18.857", "Id": "23891", "Score": "7", "Tags": [ "java", "classes", "roman-numerals" ], "Title": "Reducing verbosity of RomanNumeral class" }
23891
<p>I have developed a system whereby I use an attribute to state which <code>SelectList</code> to use for an 'FK' property. I would appreciate some feedback mainly on by good practice, and also on any ways to do this better. Let me start my exposition with a demo view model:</p> <pre><code>public class DemoModel { [DropDownList("LanguageSelect")] public int? LanguageId { get; set; } public SelectList LanguageSelect { get; set; } } </code></pre> <p>Now when I use the Razor markup <code>@EditorFor(m =&gt; m.LanguageId)</code>, I get a drop-down populated from the <code>LanguageSelect</code> list. I get this because the <code>DropDownListAttrbute</code> class attaches the select list name to the <code>LanguageId</code> model:</p> <pre><code>public class DropDownListAttribute : UIHintAttribute, IMetadataAware { public DropDownListAttribute(string selectListName) : base(KnownUiHints.DropDown, KnownPresentationLayers.Mvc, selectListName) { SelectListName = selectListName; } public string SelectListName { get; set; } public void OnMetadataCreated(ModelMetadata metadata) { var listProp = metadata.ContainerType.GetProperty(SelectListName); metadata.AdditionalValues[KnowMetadataKeys.SelectListName] = SelectListName; } } </code></pre> <p>All my view models derive from <code>ViewModel</code>, which offers a <code>SelectListDictionary</code> property:</p> <pre><code>private IDictionary&lt;string, SelectList&gt; _selectListdictionary; public virtual IDictionary&lt;string, SelectList&gt; SelectListDictionary { get { if (_selectListdictionary == null) { var props = GetType().GetProperties().Where(p =&gt; p.PropertyType == typeof(SelectList)); _selectListdictionary = props.ToDictionary(prop =&gt; prop.Name, prop =&gt; (SelectList)prop.GetValue(this, null)); } return _selectListdictionary; } } </code></pre> <p>In my base controller, I override the <code>View</code> method to pull the entire select list dictionary from the view model, and insert it into the view's viewdata, making it available for the editor template:</p> <pre><code>protected override ViewResult View(string viewName, string masterName, object model) { var result = base.View(viewName, masterName, model); if ((model is ViewModel) &amp;&amp; (!ViewData.ContainsKey(KnowMetadataKeys.ViewDataSelectLists))) { var vm = (ViewModel)model; result.ViewData.Add(KnowMetadataKeys.ViewDataSelectLists, vm.SelectListDictionary); } return result; } </code></pre> <p>The editor template then retrieves the list it requires from the select list dictionary and builds a <code>select</code> input element:</p> <pre><code>@using Erisia.Constants @{ var list = (SelectList)ViewData.ModelMetadata.AdditionalValues[ViewData.ModelMetadata.AdditionalValues[KnowMetadataKeys.SelectListName].ToString()]; var listWithSelected = new SelectList(list.Items, list.DataValueField, list.DataTextField, Model); } @Html.DropDownListFor(m =&gt; Model, listWithSelected, " - select - ") </code></pre> <p>So what say you all?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-31T20:21:30.377", "Id": "350397", "Score": "0", "body": "I stumbled across this post and noticed that in your DropDownListAttribute class, OnMetadataCreated(), you are assigning a value to local variable listProp, but not assigning that anywhere. Haven't had a chance to sift through it yet for MVC6 but something seems off with this?" } ]
[ { "body": "<p>I'm assuming this code hasn't been reviewed yet because it's... <strong>beautiful</strong> - and I'm still searching for a better word. I mean, <em>wow that's clever, I want that!!</em></p>\n\n<p>The only thing I can see here, is in the <code>View</code> method:</p>\n\n<blockquote>\n<pre><code>protected override ViewResult View(string viewName, string masterName, object model)\n{\n var result = base.View(viewName, masterName, model);\n if ((model is ViewModel) &amp;&amp; (!ViewData.ContainsKey(KnowMetadataKeys.ViewDataSelectLists)))\n {\n var vm = (ViewModel)model;\n result.ViewData.Add(KnowMetadataKeys.ViewDataSelectLists, vm.SelectListDictionary);\n }\n return result;\n}\n</code></pre>\n</blockquote>\n\n<p>I would suggest a <em>safe cast</em> instead of <code>model is ViewModel</code> followed by a cast, so it would look more like this - note that I dropped a few redundant parentheses:</p>\n\n<pre><code>protected override ViewResult View(string viewName, string masterName, object model)\n{\n var result = base.View(viewName, masterName, model);\n var vm = model as ViewModel;\n if (vm != null &amp;&amp; !ViewData.ContainsKey(KnowMetadataKeys.ViewDataSelectLists))\n {\n result.ViewData.Add(KnowMetadataKeys.ViewDataSelectLists, vm.SelectListDictionary);\n }\n return result;\n}\n</code></pre>\n\n<p>Other than that, I agree with your naming (except <em>maybe</em> <code>vm</code> could be called <code>viewModel</code>, but <code>vm</code> is pretty descriptive in this specific context) and naming conventions, and there's nothing much left to say as far as I'm concerned - good job! :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-19T13:46:42.190", "Id": "37747", "ParentId": "23897", "Score": "6" } } ]
{ "AcceptedAnswerId": "37747", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T06:23:13.340", "Id": "23897", "Score": "11", "Tags": [ "c#", ".net", "asp.net", "asp.net-mvc-4" ], "Title": "Injecting SelectList objects into ViewData to enable using EditorFor on dropdown based properties" }
23897
<p>I'm using the following function to fuzzy match strings:</p> <pre><code>function fuzzy_match(str,pattern){ pattern = pattern.split("").reduce(function(a,b){ return a+".*"+b; }); return (new RegExp(pattern)).test(str); }; </code></pre> <p>Example:</p> <pre><code>fuzzy_match("fogo","foo") //true fuzzy_match("jquery.js","jqjs") //true fuzzy_match("jquery.js","jr") //false </code></pre> <p>It's very slow, though. How can I optimize that function?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T09:02:03.457", "Id": "36816", "Score": "2", "body": "Why is [360k operations per second](http://jsperf.com/fuzzy-match) slow? If your application is slow, I think the problem is not there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T09:07:48.713", "Id": "36817", "Score": "1", "body": "The third example returns `true` as well. `jquery.js` does match `j.*r`." } ]
[ { "body": "<pre><code>function fuzzy_match(str,pattern){\n pattern = pattern.split(&quot;&quot;).reduce(function(a,b){ return a+&quot;.*&quot;+b; });\n return (new RegExp(pattern)).test(str);\n};\n</code></pre>\n<ol>\n<li><p>String concatenation is slow. The reason is that you need to allocate new memory anytime you concatenate two strings. A smart compiler may optimise that, but not too much. However, what you are trying to do with that <code>reduce</code> already exists, and it's called <code>join</code>:</p>\n<pre><code> pattern = pattern.split(&quot;&quot;).join(&quot;.*&quot;)\n</code></pre>\n</li>\n<li><p>The regex itself can be optimised: <code>.*</code> initially grabs as much as possible, then retracts only if the rest doesn't match. This takes a larger than neccessary amount of backtracking to find out. Instead, you could use a reluctant quantifier: <code>.*?</code>. This attempts to match as little as possible. If a match is found, it is found without backtracking. However, it still does a lot of backtracking if there is no match. We can do better: <code>a[^b]*b</code> (at this point, it doesn't really matter if the quantifier is greedy). A possessive quantifier (<code>a[^b]*+b</code>) would be even better, but <a href=\"https://stackoverflow.com/a/2824334/499214\">javascript doesn't support these</a>. Using a character class deprives us of a join, but see the next point.</p>\n<pre><code> pattern = pattern.split(&quot;&quot;).reduce(function(a,b){ return a+'[^'+b+']*'+b; });\n</code></pre>\n</li>\n<li><p>Since you are complaining about an operation that <a href=\"http://jsperf.com/fuzzy-match\" rel=\"nofollow noreferrer\">takes about 3000 ns</a> (as noted in the comments), it can be assumed you are doing a <em>lot</em> of queries. If there are very few patterns, you can cache your regexes. <a href=\"http://underscorejs.org\" rel=\"nofollow noreferrer\">Underscore.js</a> has a handy function that I'll demonstrate, but you could easily build the cache yourself.</p>\n<pre><code> var cache = _.memoize(function(pattern){\n return new RegExp(pattern.split(&quot;&quot;).reduce(function(a,b){\n return a+'[^'+b+']*'+b;\n })\n })\n function fuzzy_match(str,pattern){\n return cache(pattern).test(str)\n };\n</code></pre>\n</li>\n<li><p>If there is a lot of repetition among the tested strings, you should use these as a pattern instead, and the pattern as the tested string. This is even easier. I will also demonstrate how to scope your variables using the export pattern. Also, a bugfix must be inserted here (we can't assume all characters in the string are alphanumeric), to properly escape non-alphanumeric characters:</p>\n<pre><code> var fuzzy_match = (function(){\n var cache = _.memoize(function(str){\n return new RegExp(&quot;^&quot;+str.replace(/./g, function(x){\n return /[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]/.test(x) ? &quot;\\\\&quot;+x+&quot;?&quot; : x+&quot;?&quot;;\n })+&quot;$&quot;);\n });\n return function(str, pattern){\n return cache(str).test(pattern)\n });\n })();\n</code></pre>\n</li>\n</ol>\n<hr />\n<p>Concerning the last regex:</p>\n<p>Given some pattern <code>&quot;ace&quot;</code>, the regex you build (<code>/a.*c.*e/</code>) tests if the string contains the characters of the pattern in the string, in the correct order.</p>\n<p>If you want to test if a given string &quot;abcde&quot; is matched some pattern: The pattern must only contain the characters of the string, in the correct order: <code>/^a?b?c?d?e?$/</code>. To do this, we regex-escape every regex special character (pattern source: <a href=\"https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex\">CoolAj86</a>), make every character optional (<code>?</code>), and flank the regex with string boundary anchors.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T13:27:20.820", "Id": "36833", "Score": "0", "body": "Awesome answer, thank you very much. If not abuse might I ask you to elaborate only a little bit on that last regexp?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T13:50:53.577", "Id": "36834", "Score": "1", "body": "@Dokkat explanation added. Proper escaping added." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-03-14T12:37:33.953", "Id": "23905", "ParentId": "23899", "Score": "38" } }, { "body": "<p>My solution might be not fast enough for you (200k ops/s) :) but beside true/false it also provides informations about the match:</p>\n\n<p>In some cases, you might need to know it eg. to make parts of your input bold in the search results</p>\n\n<p>It's written in typescript (if you want to use it - I've published it here - <a href=\"https://github.com/pie6k/fuzzystring\" rel=\"nofollow noreferrer\">https://github.com/pie6k/fuzzystring</a>) and demo here <a href=\"https://pie6k.github.io/fuzzystring/\" rel=\"nofollow noreferrer\">https://pie6k.github.io/fuzzystring/</a></p>\n\n<p>It works like:</p>\n\n<pre><code>fuzzyString('liolor', 'lorem ipsum dolor sit');\n\n// returns\n{\n parts: [\n { content: 'l', type: 'input' },\n { content: 'orem ', type: 'fuzzy' },\n { content: 'i', type: 'input' },\n { content: 'psum d', type: 'fuzzy' },\n { content: 'olor', type: 'input' },\n { content: ' sit', type: 'suggestion' },\n ],\n score: 0.87,\n}\n</code></pre>\n\n<p>Here is full implementation (Typescript)</p>\n\n<pre><code>type MatchRoleType = 'input' | 'fuzzy' | 'suggestion';\n\ninterface FuzzyMatchPart {\n content: string;\n type: MatchRoleType;\n}\n\ninterface FuzzyMatchData {\n parts: FuzzyMatchPart[];\n score: number;\n}\n\ninterface FuzzyMatchOptions {\n truncateTooLongInput?: boolean;\n isCaseSesitive?: boolean;\n}\n\nfunction calculateFuzzyMatchPartsScore(fuzzyMatchParts: FuzzyMatchPart[]) {\n const getRoleLength = (role: MatchRoleType) =&gt;\n fuzzyMatchParts\n .filter((part) =&gt; part.type === role)\n .map((part) =&gt; part.content)\n .join('').length;\n\n const fullLength = fuzzyMatchParts.map((part) =&gt; part.content).join('')\n .length;\n const fuzzyLength = getRoleLength('fuzzy');\n const inputLength = getRoleLength('input');\n const suggestionLength = getRoleLength('suggestion');\n\n return (\n (inputLength + fuzzyLength * 0.7 + suggestionLength * 0.9) / fullLength\n );\n}\n\nfunction compareLetters(a: string, b: string, isCaseSensitive = false) {\n if (isCaseSensitive) {\n return a === b;\n }\n return a.toLowerCase() === b.toLowerCase();\n}\n\nfunction fuzzyString(\n input: string,\n stringToBeFound: string,\n { truncateTooLongInput, isCaseSesitive }: FuzzyMatchOptions = {},\n): FuzzyMatchData | false {\n // make some validation first\n\n // if input is longer than string to find, and we dont truncate it - it's incorrect\n if (input.length &gt; stringToBeFound.length &amp;&amp; !truncateTooLongInput) {\n return false;\n }\n\n // if truncate is enabled - do it\n if (input.length &gt; stringToBeFound.length &amp;&amp; truncateTooLongInput) {\n input = input.substr(0, stringToBeFound.length);\n }\n\n // if input is the same as string to be found - we dont need to look for fuzzy match - return it as match\n if (input === stringToBeFound) {\n return {\n parts: [{ content: input, type: 'input' }],\n score: 1,\n };\n }\n\n const matchParts: FuzzyMatchPart[] = [];\n\n const remainingInputLetters = input.split('');\n\n // let's create letters buffers\n // it's because we'll perform matching letter by letter, but if we have few letters matching or not matching in the row\n // we want to add them together as part of match\n let ommitedLettersBuffer: string[] = [];\n let matchedLettersBuffer: string[] = [];\n\n // helper functions to clear the buffers and add them to match\n function addOmmitedLettersAsFuzzy() {\n if (ommitedLettersBuffer.length &gt; 0) {\n matchParts.push({\n content: ommitedLettersBuffer.join(''),\n type: 'fuzzy',\n });\n ommitedLettersBuffer = [];\n }\n }\n\n function addMatchedLettersAsInput() {\n if (matchedLettersBuffer.length &gt; 0) {\n matchParts.push({\n content: matchedLettersBuffer.join(''),\n type: 'input',\n });\n matchedLettersBuffer = [];\n }\n }\n\n for (let anotherStringToBeFoundLetter of stringToBeFound) {\n const inputLetterToMatch = remainingInputLetters[0];\n\n // no more input - finish fuzzy matching\n if (!inputLetterToMatch) {\n break;\n }\n\n const isMatching = compareLetters(\n anotherStringToBeFoundLetter,\n inputLetterToMatch,\n isCaseSesitive,\n );\n\n // if input letter doesnt match - we'll go to the next letter to try again\n if (!isMatching) {\n // add this letter to buffer of ommited letters\n ommitedLettersBuffer.push(anotherStringToBeFoundLetter);\n // in case we had something in matched letters buffer - clear it as matching letters run ended\n addMatchedLettersAsInput();\n // go to the next input letter\n continue;\n }\n\n // we have input letter matching!\n\n // remove it from remaining input letters\n remainingInputLetters.shift();\n\n // add it to matched letters buffer\n matchedLettersBuffer.push(anotherStringToBeFoundLetter);\n // in case we had something in ommited letters buffer - add it to the match now\n addOmmitedLettersAsFuzzy();\n\n // if there is no more letters in input - add this matched letter to match too\n if (!remainingInputLetters.length) {\n addMatchedLettersAsInput();\n }\n }\n\n // if we still have letters left in input - means not all input was included in string to find - input was incorrect\n if (remainingInputLetters.length &gt; 0) {\n return false;\n }\n\n // lets get entire matched part (from start to last letter of input)\n const matchedPart = matchParts.map((match) =&gt; match.content).join('');\n\n // get remaining part of string to be found\n const suggestionPart = stringToBeFound.replace(matchedPart, '');\n\n // if we have remaining part - add it as suggestion\n if (suggestionPart) {\n matchParts.push({ content: suggestionPart, type: 'suggestion' });\n }\n const score = calculateFuzzyMatchPartsScore(matchParts);\n\n return {\n score,\n parts: matchParts,\n };\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-07T08:22:59.970", "Id": "404293", "Score": "0", "body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-07T04:50:01.610", "Id": "209194", "ParentId": "23899", "Score": "0" } } ]
{ "AcceptedAnswerId": "23905", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T06:38:25.573", "Id": "23899", "Score": "16", "Tags": [ "javascript", "strings", "regex" ], "Title": "Faster JavaScript fuzzy string matching function?" }
23899
<p><strong>Note:</strong> This ended up being much longer than I was expecting. I have a number of side questions that relate to specific parts of the code for if you don't want to slog through all this mess.</p> <h2>Background</h2> <p>I have had some experience in Java, but recently decided to learn C#. I would like to know if my first program is idiomatic.</p> <p>I got the idea for this program out of a Java textbook I had lying around. Here's what it says:</p> <blockquote> <p>Write a program that evaluates expressions typed in by the user. The expressions can use real numbers, variables, arithmetic operators, parentheses, and standard functions (sin, cos, tan, abs, sqrt, and log.) A line of input must contain exactly one such expression. If extra data is found on a line after an expression has been read, it is considered an error. A variable name must consist of letters. Names are case-sensitive. The program should accept commands of two types from the user. For a command of the form <code>print &lt;expression&gt;</code>, the expression is evaluated and the value is output. For a command of the form <code>let &lt;variable&gt; = &lt;expression&gt;</code>, the expression is evaluated and the value is assigned to the variable. If a variable is used in an expression before it has been assigned a value, an error occurs.</p> </blockquote> <p>I learned about using <a href="http://broadcast.oreilly.com/2010/08/understanding-c-text-mode-games.html">text mode</a> in C#, so I went a little crazy with it.</p> <h2>Structure</h2> <p>My program is probably over 1000 lines long, so I'm not going to post the whole thing. Here's the basic breakdown of all the classes:</p> <ul> <li><strong>BraceMatcher.cs</strong> Contains a class that validates that the braces in an expression match.</li> <li><strong>CommandHandler.cs</strong> Contains a class that handles the commands sent from the user. A private nested inner exception class called <strong>MalformedAssignmentException</strong> deals with variable assignment commands that are malformed.</li> <li><strong>ConsoleFormatter.cs</strong> Contains a class that formats the Console IO for text mode.</li> <li><strong>IExpression.cs</strong> Contains an interface that represents a mathematical expression. The only method it defines is <code>double Evaluate()</code>.</li> <li><strong>TermExpression.cs</strong> Contains a class that implements IExpression for addition and subtraction operations.</li> <li><strong>FactorExpression.cs</strong> Contains a class that implements IExpression for multiplication, division, and modulo operations.</li> <li><strong>FunctionExpression.cs</strong> Contains a class that implements IExpression for the standard functions.</li> <li><strong>NumericExpression.cs</strong> Contains a class that implements IExpression as a simple wrapper around a real number.</li> <li><strong>ExpressionReader.cs</strong> Contains a class that reads expressions and returns a simplified form. The main method exposed is <code>public IExpression Read()</code> which will return a NumericExpression when called from outside the class.</li> <li><strong>HelpCommandInfo.cs</strong> Contains a class that formats the information relating to commands given in the help menu. A public nested struct named <strong>CommandPair</strong> associates a command example with its corresponding explanation.</li> <li><strong>InvalidExpressionException.cs</strong> Contains a class that represents an exception thrown when the user enters an invalid expression.</li> <li><strong>TextReaderExtensions.cs</strong> Contains a static class that extends TextReader by providing two additional methods: <code>public static string ReadLetters(this TextReader source)</code> which reads only a sequence of letters from the stream and <code>public static void SkipBlanks(this TextReader source)</code> which reads and ignores whitespace.</li> <li><strong>Program.cs</strong> - The main program.</li> </ul> <h2>Example Code</h2> <p>Because my code is so large, I will be showing bits and pieces of files.</p> <h3>IExpression.cs</h3> <pre><code>namespace SimpleInterpreter { /// &lt;summary&gt; /// Represents a mathematical expression. /// &lt;/summary&gt; interface IExpression { /// &lt;summary&gt; /// Returns the value of the expression. /// &lt;/summary&gt; /// &lt;returns&gt;The value of the expression.&lt;/returns&gt; double Evaluate(); } } </code></pre> <h3>TermExpression.cs</h3> <pre><code>namespace SimpleInterpreter { using System; using System.Collections.Generic; /// &lt;summary&gt; /// An expression take operates on two terms. /// &lt;/summary&gt; class TermExpression : IExpression { private static readonly Dictionary&lt;char, Operator&gt; Operators = new Dictionary&lt;char, Operator&gt;() { { '+', Operator.Addition }, { '-', Operator.Subtraction } }; private enum Operator { Addition, Subtraction } readonly IExpression x, y; readonly Operator termOperator; /// &lt;summary&gt; /// Creates a new TermExpression that operates of the specified inner /// expressions. /// &lt;/summary&gt; /// &lt;param name="x"&gt;The first term.&lt;/param&gt; /// &lt;param name="operatorSymbol"&gt; /// The symbol that represents the operator this expression uses. /// &lt;/param&gt; /// &lt;param name="y"&gt;The second term.&lt;/param&gt; /// &lt;exception cref="ArgumentException"&gt; /// If &lt;paramref name="operatorSymbol"/&gt; refers to an invalid operator. /// &lt;/exception&gt; public TermExpression(IExpression x, char operatorSymbol, IExpression y) { this.x = x; this.y = y; try { termOperator = Operators[operatorSymbol]; } catch (KeyNotFoundException) { throw new ArgumentException( String.Format("Invalid operator: {1}", operatorSymbol)); } } public double Evaluate() { switch (termOperator) { case Operator.Addition: return x.Evaluate() + y.Evaluate(); case Operator.Subtraction: return x.Evaluate() - y.Evaluate(); default: throw new InvalidOperationException( "Should not be reached."); } } public override string ToString() { return Convert.ToString(Evaluate()); } } } </code></pre> <h3>TextReaderExtensions.cs</h3> <pre><code>/// &lt;summary&gt; /// Provides a set of static methods for specialized reading. /// &lt;/summary&gt; static class TextReaderExtensions { /// &lt;summary&gt; /// Reads a sequence of letters. /// &lt;/summary&gt; /// &lt;param name="source"&gt;A TextReader to read from.&lt;/param&gt; /// &lt;returns&gt;The letters read.&lt;/returns&gt; public static string ReadLetters(this TextReader source) { var wordBuilder = new StringBuilder(); var i = source.Peek(); if (i == -1) { i = source.Read(); var ch = Convert.ToChar(i); if (!Char.IsLetter(ch)) return Convert.ToString(ch); wordBuilder.Append(ch); i = source.Peek(); } while (true) { var ch = Convert.ToChar(i); if (!Char.IsLetter(ch)) return wordBuilder.ToString(); wordBuilder.Append(ch); source.Read(); i = source.Peek(); } } // snip } </code></pre> <h3>InvalidExpressionException.cs</h3> <pre><code>/// &lt;summary&gt; /// An exception that is thrown when the user enters an invalid expression. /// &lt;/summary&gt; [Serializable()] class InvalidExpressionException : Exception { public InvalidExpressionException() : base() { } public InvalidExpressionException(string message) : base(message) { } public InvalidExpressionException(string message, Exception inner) : base(message, inner) { } protected InvalidExpressionException( SerializationInfo info, StreamingContext context) : base(info, context) { } } </code></pre> <h3>HelpCommandInfo.cs</h3> <pre><code>/// &lt;summary&gt; /// Formats the information relating to commands given in the help menu. /// &lt;/summary&gt; class HelpCommandInfo : IEnumerable&lt;HelpCommandInfo.CommandPair&gt; { /// &lt;summary&gt; /// Associates a command to its description. /// &lt;/summary&gt; public struct CommandPair { readonly string command; readonly List&lt;string&gt; description; /// &lt;summary&gt; /// Gets the command. /// &lt;/summary&gt; /// &lt;value&gt;The command.&lt;/value&gt; public string Command { get { return command; } } /// &lt;summary&gt; /// Gets the formatted description of the command. /// &lt;/summary&gt; /// &lt;value&gt;The formatted description of the command.&lt;/value&gt; public List&lt;string&gt; Description { get { return description; } } /// &lt;summary&gt; /// Creates a new CommandPair that associates the specified command /// to its specified description. /// &lt;/summary&gt; /// &lt;param name="command"&gt;The command.&lt;/param&gt; /// &lt;param name="description"&gt;The description.&lt;/param&gt; public CommandPair(string command, List&lt;string&gt; description) { this.command = command; this.description = description; } } // snip } </code></pre> <h3>ExpressionReader.cs</h3> <pre><code> double ReadNumber() { var numberBuilder = new StringBuilder(); var hasDecimal = false; while (true) { var ch = Convert.ToChar(reader.Peek()); var isUnaryMinus = ch == '-' &amp;&amp; numberBuilder.Length == 0; var isDecimalPoint = ch == '.'; if (isDecimalPoint) { if (hasDecimal) { throw new FormatException( "Number cannot have multiple decimal points."); } hasDecimal = true; } if (!Char.IsDigit(ch) &amp;&amp; !isDecimalPoint &amp;&amp; !isUnaryMinus) { return Convert.ToSingle(numberBuilder.ToString()); } numberBuilder.Append(ch); reader.Read(); } } </code></pre> <h3>ConsoleFormatter.cs</h3> <pre><code>/// &lt;summary&gt; /// Creates a new ConsoleFormatter that resizes the Console to the /// specified width, uses the specified color for the background of /// Console output, and initially outputs the specified introduction. /// &lt;/summary&gt; /// &lt;param name="intro"&gt;The introduction.&lt;/param&gt; /// &lt;param name="consoleWidth"&gt; /// The width to resize the Console to. /// &lt;/param&gt; /// &lt;param name="outputBackground"&gt; /// The color of the background for Console output. /// &lt;/param&gt; /// &lt;exception cref="ArgumentNullException"&gt; /// If &lt;paramref name="intro"/&gt; is null. /// &lt;/exception&gt; public ConsoleFormatter(string intro, int consoleWidth=75, ConsoleColor outputBackground=ConsoleColor.DarkCyan, ConsoleColor foreground=ConsoleColor.White) { if (intro == null) { throw new ArgumentNullException("intro"); } this.consoleWidth = consoleWidth; ValidateConsoleWidth(); this.outputBackground = outputBackground; Console.ForegroundColor = foreground; Console.WindowWidth = consoleWidth; Console.CursorVisible = false; WriteCentered(intro); inputX = Console.CursorLeft; inputY = Console.CursorTop; } </code></pre> <h3>BraceMatcher.cs</h3> <pre><code>static readonly Dictionary&lt;char, char&gt; Braces = new Dictionary&lt;char, char&gt;() { { '(', ')' }, { '[', ']' }, { '&lt;', '&gt;' }, { '{', '}' } }; /// &lt;summary&gt; /// Returns true if the specified character is a left brace. /// &lt;/summary&gt; /// &lt;param name="brace"&gt; /// The character tested for whether it is a left brace. /// &lt;/param&gt; /// &lt;returns&gt; /// &lt;c&gt;true&lt;/c&gt; if &lt;paramref name="brace"/&gt; is a left brace. /// &lt;/returns&gt; public static bool IsLeftBrace(char brace) { return Braces.ContainsKey(brace); } /// &lt;summary&gt; /// Returns true if the specified character is a right brace. /// &lt;/summary&gt; /// &lt;param name="brace"&gt; /// The character tested for whether it is a right brace. /// &lt;/param&gt; /// &lt;returns&gt; /// &lt;c&gt;true&lt;/c&gt; if &lt;paramref name="brace"/&gt; is a right brace. /// &lt;/returns&gt; public static bool IsRightBrace(char brace) { return Braces.ContainsValue(brace); } readonly TextReader reader; readonly Stack&lt;char&gt; braceMatcher; public bool IsEmpty { get { return braceMatcher.Count == 0; } } </code></pre> <h3>CommandHandler.cs</h3> <pre><code>readonly ConsoleFormatter formatter; readonly ExpressionReader expressionReader; readonly Dictionary&lt;string, string&gt; helpCommandInfo; readonly Dictionary&lt;string, string&gt; specificHelpCommandInfo; readonly Dictionary&lt;string, CommandHandlerFunc&gt; commandHandler; int numBadCommands; delegate void CommandHandlerFunc(); /// &lt;summary&gt; /// Creates a new CommandHandler that uses the specified /// ConsoleFormatter to format its output. /// &lt;/summary&gt; /// &lt;param name="formatter"&gt;Formats the output.&lt;/param&gt; /// &lt;exception cref="ArgumentNullException"&gt; /// If &lt;paramref name="formatter"/&gt; is null. /// &lt;/exception&gt; public CommandHandler(ConsoleFormatter formatter) { if (formatter == null) { throw new ArgumentNullException("formatter"); } this.formatter = formatter; expressionReader = new ExpressionReader(Console.In); helpCommandInfo = new Dictionary&lt;string, string&gt;() { { "let &lt;name&gt; = &lt;expression&gt;", "Assigns the value of the expression " + "into the variable name" }, { "print &lt;expression&gt;", "Outputs the value of the expression" }, { "help &lt;command&gt;", "Prints a help message that explains " + "how to use the command" }, { "quit", "Ends the program" } }; specificHelpCommandInfo = new Dictionary&lt;string, string&gt;() { { "let", "Format:\tlet &lt;name&gt; = &lt;expression&gt;\n" + "The 'let' command assigns an expression to\n" + "a variable. Valid names must have only letters.\n" + "Names are case-sensitive letters and must not be one\n" + "of the standard functions (sin, cos, tan, abs, sqrt,\n" + "log) or a command for this program (let, print, help,\n" + "quit). You can store mathematical expressions in the\n" + "variable you create. You can combine real numbers,\n" + "arithmetic operators, parenthetical expressions, the\n" + "built-in functions, and even other variables within\n" + "your expression. You can redefined your variables as\n" + "many times as you want. The mathematical constants\n" + "'e' and 'pi' have already been defined for you." }, { "print", "Format:\tprint &lt;expression&gt;\n" + "The 'print' command outputs the value of the\n" + "expression you enter. You may use combinations of\n" + "real numbers, arithmetic operators, parenthetical\n" + "expressions, standard functions (sin, cos, tan, abs,\n" + "sqrt, log), and variables you have already defined\n" + "using the 'let' command." } }; commandHandler = new Dictionary&lt;string, CommandHandlerFunc&gt;() { { "let", ReadVariable }, { "print", WriteExpression }, { "help", WriteHelp }, { "quit", Quit } }; } void ReadVariable() { try { numBadCommands = 0; var name = ReadVariableName(); ReadAssignmentOperator(); var value = expressionReader.Read().Evaluate(); expressionReader.StoreVariable(name, value); formatter.WriteOutput( String.Format("{0} set to {1}", name, value)); } catch (Exception ex) { if (Console.In.Peek() != -1) Console.ReadLine(); if (!(ex is MalformedAssignmentException) &amp;&amp; !(ex is InvalidExpressionException)) { throw; } formatter.WriteOutput(ex.Message); } } </code></pre> <h3>Program.cs</h3> <pre><code>/// &lt;summary&gt; /// The main program for the Simple Interpreter. /// &lt;/summary&gt; class Program { static void Main(string[] args) { var formatter = new ConsoleFormatter( intro: "\nWelcome to my Simple Interpreter!\n" + "Please enter a command (or enter \"help\" for help).\n"); var commandHandler = new CommandHandler(formatter); string command; do { formatter.ColorInputBackground(ConsoleColor.DarkBlue); Console.In.SkipBlanks(); command = Console.In.ReadLetters().ToLower(); } while (commandHandler.Execute(command)); formatter.MakeOutputInvisible(); Console.ReadLine(); } } </code></pre> <h2>Questions</h2> <p>My main question is</p> <blockquote> <p>Where does my code stray from idiomatic C#?</p> </blockquote> <p>Additional Questions:</p> <ol> <li>In <strong>ExpressionReader.cs</strong>, I wrote a method <code>double ReadNumber()</code> which manually checks for numeric input. Usually I frown at this, but I couldn't find a method where I could just get the next numbers in the stream. Is there one that I'm missing?</li> <li>I used default parameters in the constructor for the <strong>ConsoleFormatter.cs</strong> and call it in <strong>Program.cs</strong>. It seems to me like a cleaner alternative to the <a href="http://en.wikipedia.org/wiki/Builder_pattern">Builder Pattern</a>. Am I on the right track here?</li> <li>In <strong>BraceMatcher.cs</strong>, I made a property <code>IsEmpty</code> that doesn't have an analog in a member variable. I haven't seen this anywhere else. Is that bad practice?</li> <li>In <strong>CommandHandler.cs</strong>, I use a delegate <code>void CommandHandlerFunc()</code> purely for the purpose of putting functions in a Dictionary. I saw delegates used in conjunction with events elsewhere, but I didn't understand it very well. Is it common to use delegates by themselves without events?</li> <li>Java 7 has a very handy multi-catch exception feature. I was trying a workaround for it in the <code>void ReadVariable()</code> method in <strong>CommandHandler.cs</strong>. Is there a better way to do that?</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T15:16:01.663", "Id": "36937", "Score": "1", "body": "You should look into automatic properties. You can write things like `public string Command { get; private set; }` and not need backing fields." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T02:01:48.633", "Id": "36968", "Score": "0", "body": "@Bobson I don't like setters. I also saw [this](http://blog.ploeh.dk/2011/05/26/CodeSmellAutomaticProperty/)," }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T02:58:15.547", "Id": "36969", "Score": "1", "body": "I never understood why, but Mark only talks about fully public properties in that article. Properties with private setters aren't as bad - but you can't make them `readonly`. On a different note, the mostly missing access modifiers are mildly irritating to me; you don't see that much in C#. That can also make it trickier for you, since I seem to remember that Java's defaults are different from those in C#." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T13:21:57.800", "Id": "37095", "Score": "1", "body": "@Eva - I disagree with that article, but to each his own." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T21:48:36.727", "Id": "37428", "Score": "2", "body": "@Eva I read that article as being about encapsulation. The difference is between `{get;set;}` and `{get;private set;}`. I don't think the author was saying auto-property setters are bad but that setting fields (from a property in this case) from outside is not good. The suggestion made by @Bobson will generate a backing field for you automagically. The only thing you really lose (assuming JIT in-lining) is `readonly` which is a shame but you will move on with your life, I promise. Also if you want you can apply Contract.Invariant to a property using Microsoft Code Contracts." } ]
[ { "body": "<p>First off, for somebody who is just learning C# you use it better than some of the people I work with.</p>\n\n<p>Now to answer your questions:</p>\n\n<ol>\n<li><p>You are correct, there is no native way to read numbers from the <code>Console</code> in C#. You could look at <code>decimal.TryParse</code> which tries parsing the input.</p>\n\n<p>The code would look something like this:</p>\n\n<pre><code>var input = Console.ReadLine();\n\nvar inputAsNumber = 0d;\nif (!decimal.TryParse(input, out inputAsNumber)\n{\n // throw favorite exception\n}\n</code></pre></li>\n<li><p>There is nothing wrong with default parameters. I like them better than having multiple constructors. I too think it's much cleaner.</p></li>\n<li><p>There is nothing wrong with an <code>IsEmpty</code> method. C# has one for strings <code>string.IsNullOrEmpty(string)</code></p></li>\n<li><p>Using delegates this way is perfectly acceptable. I would look into <code>Action</code> and <code>Action&lt;paramTypes[]&gt;</code> though. I think they are a little more common.</p></li>\n<li><p>Your exception handling could be improved. You can catch multiple exceptions from one call:</p>\n\n<pre><code>try\n{\n numBadCommands = 0;\n var name = ReadVariableName();\n ReadAssignmentOperator();\n\n var value = expressionReader.Read().Evaluate();\n\n expressionReader.StoreVariable(name, value);\n\n formatter.WriteOutput(\n String.Format(\"{0} set to {1}\", name, value));\n}\ncatch (MalformedAssignmentException ex)\n{\n throw;\n}\ncatch (InvalidExpressionException ex)\n{\n throw;\n}\ncatch (Exception ex)\n{\n if (Console.In.Peek() != -1) \n {\n Console.ReadLine();\n }\n formatter.WriteOutput(ex.Message);\n}\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T15:18:34.113", "Id": "36938", "Score": "6", "body": "As for default parameters, be careful with those, especially if you expose those calls as some kind of public API - default parameter values will be compiled into the **calling** assembly. That means if you have a library that uses default parameters and later change those values, it will not be enough to exchange the DLL file - all calling assemblies will have to be recompiled against the new version to pick up the updated default values. This is something to keep in mind when using default parameters. (As a matter of fact, I never use them at all, not least because of this.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T03:31:27.353", "Id": "36970", "Score": "3", "body": "This: \"for somebody who is just learning C# you use it better than some of the people I work with\". I was very impressed how good your code was and the fact you were using languages features not in Java, like extensions methods and delegates." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T17:21:46.210", "Id": "36990", "Score": "0", "body": "Thanks! Action is quite handy. I have been putting it in other places where I have delegates in Dictionaries." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T15:55:24.380", "Id": "37035", "Score": "2", "body": "`var inputAsNumber = 0d;` I think `decimal inputAsNumber;` is better, because it ensures you won't use the default value." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T21:49:58.980", "Id": "37429", "Score": "0", "body": "> First off, for somebody who is just learning C# you use it better than some of the people I work with.\n\n@Eva For sure it looks good!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T14:42:30.433", "Id": "23958", "ParentId": "23900", "Score": "13" } }, { "body": "<p>Have you considered subclassing <code>TermExpression</code> for the various operations? This way you don't have to worry, in <code>Evaluate</code>, if the state of the object is incorrect (which can't be, but code changes...).</p>\n\n<p>Building on the above: instead of using a <code>Dictionary&lt;char, Operator&gt;</code> and catch <code>KeyNotFoundException</code>s you could use a switch to build the correct subclass of <code>TermExpression</code>. This way you only switch once, while building, and then every subclass can just do math without having to check who it is everytime.</p>\n\n<p>Another thing I'm not completely convinced with is your use of <code>Dictionary</code> everywhere. They're usually useful for bigger collections that two or three elements.</p>\n\n<p>Oh, and remember that <code>ContainsValue</code> is O(n). Although n is fixed in your code, bear that in mind.</p>\n\n<p>As Jeff said, the code is clean and idiomatic.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T14:39:04.897", "Id": "36982", "Score": "0", "body": "I actually use dictionaries quite often for small \"decision tables\" as well - it's easily understood and easily extended." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T17:20:04.307", "Id": "36989", "Score": "0", "body": "You're right. Dictionary has been my Swiss army knife whenever I have key-value pairs or just a list of pairs I want to keep together. What should I use instead of Dictionary?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T21:43:11.473", "Id": "37143", "Score": "0", "body": "Dictionaries are usually good, but consider using a Good Old Switch, or polymorphism. This isn't a rule in either direction though, it depends on readability/speed requirements" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T12:05:05.547", "Id": "23984", "ParentId": "23900", "Score": "4" } } ]
{ "AcceptedAnswerId": "23958", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T06:52:53.837", "Id": "23900", "Score": "13", "Tags": [ "c#" ], "Title": "Am I coding Java in C#?" }
23900
<p>I'm mostly looking for performance suggestions. Feel free to include more than just that.</p> <p>Since Google Code Jam is coming around, I thought I would look at some of the previous questions. <a href="https://code.google.com/codejam/contest/90101/dashboard#s=p0" rel="nofollow">Alien Language</a> is the one I picked and did this in my lunch / spare time / while waiting for the build to complete.</p> <p>It's a little messy and this is the third (or fourth) iteration I've done. I'm starting to get quite curious about writing quicker running code. (Not something I would normally focus on.)</p> <p><strong>Firstly</strong> I'd open the file and pull all the relevant sections out. At this point I wasn't worried about performance.</p> <pre><code>// Open File: var inputLines = System.IO.File.ReadAllLines(@"C:\A-large-practice.in"); //GetWordlength / DictionaryLength / Number of testCases int[] ldnValues = inputLines.First().Split(' ').Select(intString =&gt; int.Parse(intString)).ToArray(); var LettersInWord = ldnValues[0]; var WordsInLanguage = ldnValues[1]; var NumberOfTestCases = ldnValues[2]; string[] vocabulary = inputLines.Skip(1).Take(WordsInLanguage).OrderBy(word =&gt; word).ToArray(); IEnumerable&lt;string&gt; testCases = inputLines.Skip(1).Skip(WordsInLanguage).Take(NumberOfTestCases); </code></pre> <p><strong>Next</strong> I turn the Language (vocabulary) into a bunch of arrays. I do this so that later it can do a straight compare with the substring. Also turn the list of test cases into a pair of (int, string) so that I can use the <code>Linq.AsParallel</code></p> <pre><code>// Create a dictionary of (test case number , test case string) so that it can be paralellised and still keep its test number int index = 1; Dictionary&lt;int, string&gt; testCasesWithIndex = testCases.ToDictionary(x =&gt; index++, x =&gt; x); var resultDict = new Dictionary&lt;int, string&gt;(); // Create an array of distinct strings for increasing lengths and put into a list. var allVocabs = new List&lt;string[]&gt;(); for (var i = 1; i &lt;= LettersInWord; i++) { allVocabs.Add(vocabulary.Select(word =&gt; word.Substring(0, i)).Distinct().OrderBy(word =&gt; word).ToArray()); } </code></pre> <p><strong>I chose a regular expression to split the test cases up:</strong></p> <pre><code>var pattern = new System.Text.RegularExpressions.Regex(@"([a-z]|\([a-z]+\))", System.Text.RegularExpressions.RegexOptions.Compiled); </code></pre> <p><strong>Then</strong> comes the bad part: looping.</p> <p>Notes:</p> <ol> <li>any characters in the test case within brackets are possible characters. (choose one)</li> <li>Since I'm looping through to work out all possible combinations I'm testing the substring to see if the dictionary allows it.</li> <li>This is the section I've changed the most.</li> </ol> <pre><code>System.Globalization.CompareInfo ci = System.Globalization.CultureInfo.CurrentCulture.CompareInfo; //Parallelize the test cases and test each against the dictionary testCasesWithIndex.AsParallel().ForAll(kvp =&gt; { int testCaseNumber = kvp.Key; string testCase = kvp.Value; // Do a REGEX on the test case split by either a single character or brackets (...) var matchCollection = pattern.Matches(testCase); List&lt;string&gt; possibleValues = new List&lt;string&gt;() { "" }; // Loop through all characters (or brackets containing possible characters) // and search for words in the dictionary for (int currentMatch = 0; possibleValues.Count &gt; 0 &amp;&amp; currentMatch &lt; matchCollection.Count; currentMatch++) { var match = matchCollection[currentMatch]; string matchValue = match.Value.Replace("(", "").Replace(")", ""); List&lt;string&gt; newPossibles = new List&lt;string&gt;(); // Through each position in the word find out if the substring is in the language foreach (char character in matchValue) { foreach (string possibleValue in possibleValues) { string currentValue = possibleValue + character; int currentvalueLength = currentValue.Length; bool validWord = Array.BinarySearch(allVocabs[currentvalueLength -1], currentValue) &gt; -1; if (validWord) { newPossibles.Add(currentValue); } } } possibleValues = newPossibles; } string result = string.Format("Case #{0}: {1}", testCaseNumber, possibleValues.Count); resultDict[kvp.Key] = result; }); </code></pre> <p><strong>Then</strong> use the dictionary to output all the lines (and for debugging):</p> <pre><code>string output = System.String.Join("\n", resultDict.Select(kvp =&gt; kvp.Value)); System.IO.File.WriteAllText(@"c:\output.txt", output); </code></pre> <p>I admit that the solution is definitely messy.</p>
[]
[ { "body": "<p>You need a clever data structure in order to avoid to check all possible combinations. I would suggest Trie structure with some additional statistic for every char position. Using Trie you can pretty quick find which letter is possible in which position and which isn't possible.</p>\n\n<p>One more and better idea - use regexp, the every test case looks like a regexp condition ;) All you need is just correct test case string, loop over all dictionary words and execute the match(corrected_test_case_string), and increase the counter if it matches.</p>\n\n<p>I would post python code, as a pseudo code, it's tiny and you can see the idea behind the second approach:</p>\n\n<pre><code>import sys, re\nf = open(sys.argv[1])\n_, d, n = map(int, f.readline().split())\ndict = ''.join([next(f) for _ in range(d)])\ni = 1\nfor test_case in f:\n regexp = '^' + test_case.replace(\"(\",\"[\").replace(\")\",\"]\")\n print(\"Case #%d: %d\" % (i, len(re.findall(regexp, dict, re.M))))\n i += 1\n</code></pre>\n\n<p>C# version:</p>\n\n<pre><code>using System;\nusing System.Text.RegularExpressions;\n\nnamespace AlienLanguage\n{\n class Program\n {\n static void Main(string[] args)\n {\n var allLines = System.IO.File.ReadAllLines(@\"\\path\\to\\A-large-practice.in\");\n string[] p = allLines[0].Split(' ');\n String words = \"\";\n for (int i = 1; i &lt;= int.Parse(p[1]); i++)\n {\n words += allLines[i] + \" \";\n }\n for (int i = int.Parse(p[1]); i &lt;= int.Parse(p[2]); i++)\n {\n int result = new Regex(allLines[i].Replace(\"(\", \"[\").Replace(\")\", \"]\")).Matches(words).Count;\n Console.WriteLine(\"Case #{0}: {1}\", i + 1 - int.Parse(p[1]), result);\n }\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T23:07:21.163", "Id": "36886", "Score": "0", "body": "Can you elaborate? With some sample code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T10:16:24.493", "Id": "36904", "Score": "0", "body": "Sure, I've updated the answer with pseudo code in python." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T02:50:56.330", "Id": "37063", "Score": "0", "body": "While I can read (and enjoy writing) python, could you write this in c#?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T10:41:11.340", "Id": "37085", "Score": "1", "body": "Never used C#, but..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T00:33:14.500", "Id": "37153", "Score": "0", "body": "I didn't think a Regex would be quicker but it is noticeably quicker. More importantly it is correct!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T00:39:31.113", "Id": "37154", "Score": "0", "body": "Also edited the c# example so it would closer match code for anyone else looking to use it. Hope you don't mind." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T11:27:46.853", "Id": "37165", "Score": "0", "body": "Interesting to compare performance: 2 seconds (python 2.7) vs 7 seconds (C#) on A-large-practice.in :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T22:23:29.027", "Id": "37224", "Score": "0", "body": "That would be the way its implemented. My c# version takes a lot less (about 1.5 seconds)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T22:31:36.397", "Id": "37227", "Score": "0", "body": "I cleaned out all my debugging statements and put up a gist https://gist.github.com/JamesKhoury/5200737" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T10:24:35.957", "Id": "37240", "Score": "0", "body": "I've updated the python solution, now it takes 1.4 sec vs 3.4 seconds (your multithreaded solution) on my C2D cpu." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T03:41:03.580", "Id": "37300", "Score": "0", "body": "I've updated the gist with a couple of minor improvements but the only thing that I can see is that the python script doesn't write to a file. Could that be the reason you're seeing a difference?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T10:55:35.610", "Id": "37311", "Score": "0", "body": "2 times faster version uses multiline regexpr search:\nhttp://pastebin.com/W5ktwpN4" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T04:39:32.070", "Id": "37583", "Score": "0", "body": "That is amazing. You should update your answer. I'd still like to know if you worked out the difference between python and c#" } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T15:25:25.867", "Id": "23914", "ParentId": "23901", "Score": "2" } }, { "body": "<p>To build on what cat_baxter suggested with regular expressions, try this:</p>\n\n<ol>\n<li>Concatenate all \"words\" into a single string separated by spaces.</li>\n<li>For each pattern:\n<ol>\n<li>Turn <code>()</code> into <code>[]</code>.</li>\n<li>Use <code>new Regex(pattern).Matches(wordList).Count()</code> to get the number of possible words.</li>\n<li>Output results for that pattern</li>\n</ol></li>\n</ol>\n\n<p>Regular expressions can get slow, but it's very straight forward code.</p>\n\n<hr>\n\n<p>Another possibility would be to store the words in a dictionary of nested dictionaries. The key would be a letter, and the value is another dictionary of every letter that can follow that. Repeat until you've reached the maximum depth.</p>\n\n<p>For the sample case, this would look like </p>\n\n<pre><code>{'a', {'b', {'c'}}}\n{'b', {'c', {'a'}}}\n{'c', {'b', {'a'}}}\n{'d', {'a', {'c'}},\n {'b', {'a'}}}\n</code></pre>\n\n<p>Then you can use LINQ to find matches by recursively building up a query which looks like:</p>\n\n<p><strong>(ab)(bc)(ca)</strong></p>\n\n<pre><code>wordArray.Where(x =&gt; x.Key == 'a' || x.Key == 'b').SelectMany(x =&gt; x.Value)\n .Where(x =&gt; x.Key == 'b' || x.Key == 'c').SelectMany(x =&gt; x.Value)\n .Where(x =&gt; x.Key == 'c' || x.Key == 'a').SelectMany(x =&gt; x.Value)\n .Count();\n</code></pre>\n\n<p>Here's a pseudo-coded recursive function to build the query, since I'm feeling lazy and don't want to double check all the string functions. I haven't tested it for speed - it might be too slow, but I think it should work.</p>\n\n<pre><code>class WordList\n{\n public Dictionary&lt;char, WordList&gt; Words { get; set;}\n}\npublic int ParseWord(IEnumerable&lt;WordList&gt; query, string remainingWord)\n{\n if (remainingWord == \"\") \n {\n return query.Count();\n }\n else if (remainingWord[0] == '(')\n {\n var options = remainingWord.Substring(/* read to first ')' */);\n var remainder = remainingWord.Substring(/* everything after the ')' */);\n return ParseWord(query.Select(x =&gt; x.Words).Where(x =&gt; options.Any(o =&gt; x.Key == o).SelectMany(x =&gt; x.Value), remainder);\n }\n else\n {\n var letter = remainingWord[0];\n var remainder = remainingWord.Substring(/* everything after the first character */);\n return ParseWord(query.Select(x =&gt; x.Words).Where(x =&gt; options.Any(o =&gt; x.Key == o).SelectMany(x =&gt; x.Value), remainder);\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T23:09:37.823", "Id": "36887", "Score": "0", "body": "I think id like to try the regex idea but I took a lot of Linq out as it was actually slower the way I implemented it. How would you build up linq from these strings in such a way that it would still be fast?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T13:50:49.793", "Id": "36929", "Score": "0", "body": "@JamesKhoury - I've added an example, although I haven't done any testing on it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T17:10:05.730", "Id": "23918", "ParentId": "23901", "Score": "1" } } ]
{ "AcceptedAnswerId": "23914", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T07:31:15.460", "Id": "23901", "Score": "4", "Tags": [ "c#", "programming-challenge" ], "Title": "Another iteration of Alien Language" }
23901
<p>I wrote two functions for determining leap years. ("Kabisat" means "leap year" in Indonesia.)</p> <pre><code>def kabisat? y return false if y%4!=0 return true if y%100!=0 y%400==0 end def kabisat_2? y return true if y%400==0 return false if y%100==0 y%4==0 end require 'date'; (1..Date.today.year).each { |y| puts y if kabisat?(y)!=kabisat_2?(y) } </code></pre> <p>Is it correct? And it is possible to write a shorter one?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T10:06:20.757", "Id": "36820", "Score": "4", "body": "Why not use the built-in [`Date#leap?`](http://ruby-doc.org/stdlib-1.9.3/libdoc/date/rdoc/Date.html#method-i-leap-3F) method?\n\nIn any event, your `kabisat_1` function is broken. It'll return `true` for, say, 2013, because it's not divisible by 100. But 2013 certainly isn't a leap year." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T10:30:10.480", "Id": "36822", "Score": "0", "body": "no it is not? kabisat? 2013 == false" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T10:55:50.217", "Id": "36825", "Score": "0", "body": "Yes, your method checks `y%4!=0` first, so it'll return the right thing. But reversing the checks is suspect. The logic is that \"if a year _is_ divisible by 100, it's _not_ a leap year\". But that does not mean, that every year that _isn't_ divisible automatically _is_ a leap year. I.e. the check against 100 can only can only tell you if something's _not_ a leap year; it can't tell you if it is." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T11:32:12.473", "Id": "36827", "Score": "0", "body": "You should test it with some corner cases, e.g. 1900, 2000, 2004." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T23:34:44.440", "Id": "36888", "Score": "1", "body": "Why don't u google? http://rosettacode.org/wiki/Leap_year#Ruby" } ]
[ { "body": "<p>Some notes:</p>\n\n<ul>\n<li>I assume that, for some reason, you want to write your own function/method instead of the existing <a href=\"http://ruby-doc.org/stdlib-1.9.3/libdoc/date/rdoc/Date.html#method-i-leap-3F\" rel=\"nofollow\">Date#leap?</a> that @Flambino linked above.</li>\n<li><code>kabisat?</code> We all love our mother tongue, but in computing English is the lingua franca, specially when you share your code with people around the world. It's a nice word to learn, though :-)</li>\n<li>This is a personal advice, not all Ruby programmers agree: don't use inline returns. Use the good old full-fledged conditionals, it's much more clear. In general, use expressions instead of statements.</li>\n</ul>\n\n<p>Let's see the standard <a href=\"http://en.wikipedia.org/wiki/Leap_year#Algorithm\" rel=\"nofollow\">algorithm</a>. Ok, I'll just translate it to Ruby (if I felt fancy I'd even add <code>Integer#divisible_by?(n)</code> for a fully declarative code):</p>\n\n<pre><code>def is_leap_year?(year)\n if year % 400 == 0 \n true\n elsif year % 100 == 0\n false\n elsif year % 4 == 0\n true\n else\n false\n end\nend\n</code></pre>\n\n<p>Too verbose? use boolean logic:</p>\n\n<pre><code>def is_leap_year?(year)\n (year % 400 == 0) || (year % 100 != 0 &amp;&amp; year % 4 == 0)\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T12:05:41.663", "Id": "36828", "Score": "0", "body": "i like the boolean logic :3" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T10:37:54.017", "Id": "23903", "ParentId": "23902", "Score": "3" } } ]
{ "AcceptedAnswerId": "23903", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T07:48:16.810", "Id": "23902", "Score": "2", "Tags": [ "algorithm", "ruby", "datetime" ], "Title": "Leap year algorithm?" }
23902
<p>Please check my code below. I don't have any problems but I'm not aware how far the code will work, release and kill excel instances..</p> <pre><code>try { wBook = xCel.Workbooks.Open(excelfilepath); xCel.Visible = false; this.xCel.DisplayAlerts = false; wSheet = (Excel.Worksheet)wBook.Worksheets.get_Item(1); wSheet.Copy(Type.Missing, Type.Missing); wSheet = (Excel.Worksheet)wBook.Sheets[1]; wSheet.SaveAs("1.xls"); } catch { } finally { if (wBook != null) { try { wBook.Close(); } catch { } Thread.Sleep(500); } if (excelprocid &gt; 0) { Process xcelp = Process.GetProcessById(excelprocid); xcelp.Kill(); } try { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } catch{} Marshal.FinalReleaseComObject(wSheet); wSheet = null; Marshal.FinalReleaseComObject(wBook); wBook = null; } </code></pre>
[]
[ { "body": "<p>Since Excel runs via COM, it won't be released from memory until you remove all references to it. Your example (above) does a pretty good job, but after you say wBook.Close(), you should say wBook = null. Likewise Excel won't gracefully close-down while your xCel object refers to an instance of Excel.\nThis article on CodeProject shows the recommended/industry-standard way of closing-down excel. ffwd down to Sections 13 and 14.\n<a href=\"http://www.codeproject.com/Articles/404688/Word-Excel-ActiveX-Controls-in-ASP-NET\" rel=\"nofollow\">http://www.codeproject.com/Articles/404688/Word-Excel-ActiveX-Controls-in-ASP-NET</a> </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T14:09:15.720", "Id": "23908", "ParentId": "23907", "Score": "3" } }, { "body": "<p>In .NET 2.0 I used this method to release everything after my operations:</p>\n\n<pre><code>private void ReleaseCOM()\n{\n _book.Close(true, System.Reflection.Missing.Value, System.Reflection.Missing.Value);\n _app.Quit();\n\n System.Runtime.InteropServices.Marshal.ReleaseComObject(_sheet);\n System.Runtime.InteropServices.Marshal.ReleaseComObject(_book);\n System.Runtime.InteropServices.Marshal.ReleaseComObject(_app);\n GC.Collect();\n}\n</code></pre>\n\n<p>Haven't actually done any COM-stuff in later .NET versions so I don't know wether this will work for newer versions. Hope this can help.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T14:22:55.470", "Id": "23909", "ParentId": "23907", "Score": "0" } } ]
{ "AcceptedAnswerId": "23908", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T13:35:49.643", "Id": "23907", "Score": "1", "Tags": [ "c#", "exception-handling", "excel" ], "Title": "Excel instances: release and kill" }
23907
<p>Is this code correct?</p> <p>This code was adapted from <a href="http://chessprogramming.wikispaces.com/Alpha-Beta#Implementation-Negamax%20Framework" rel="nofollow">this</a> alphabeta pseudocode. AlphaBeta search is often mentioned but getting the code 100% correct is tricky.</p> <p><code>IGame</code> is an interface with two methods: <BR /> <code>getScore()</code> - evaluates the current game state from the viewpoint of the AI <BR /> <code>generateMoves()</code> - creates possible moves from the current game state.</p> <pre><code>class Search { Move bestMove; Move findBestMove(int ply, IGame g) { bestMove = null; alpha_beta(ply, g, Integer.MINIMUM, Integer.MAXIMUM); return bestMove; } int alpha_beta(int depth, IGame g, int alpha, int beta) { if (depth == 0 || g.isGameFinished()) return g.getScore(); Move[] gameMove = g.generateMoves(); for (int i = 0; i &lt; gameMove.length; i++) { g.execute(gameMove[i]); int score = -alpha_beta(depth - 1, -beta, -alpha); g.undo(gameMove[i]); if (alpha &lt; score) { alpha = score; bestMove = gameMove[i]; } if (beta &lt;= alpha) return alpha; } return alpha; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T15:56:17.927", "Id": "36840", "Score": "3", "body": "Even if the algorithm is know as \"alphabeta\", \"minimax\", etc, you should find better variable names that \"alpha\" and \"beta\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T15:57:58.237", "Id": "36841", "Score": "2", "body": "By the way, what is the question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T05:40:13.537", "Id": "36972", "Score": "0", "body": "@Sulthan, firstly, the question explicitly states the question: \"is this correct.\" Secondly, this is Code Review. Every question is a code review, and we don't need to explicitly state a question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T10:41:33.160", "Id": "36975", "Score": "0", "body": "@WinstonEwert firstly, the \"is this correct\" question was added some time after my comment. Secondly, per Code Review FAQ, only working code should be here. It seems to me that the OP doesn't even know if the code is working." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T19:56:17.080", "Id": "37001", "Score": "2", "body": "@Sulthan, actually the faq says: \"To the best of my knowledge, does the code work?\" As long as the poster is unaware of the flaws, asking for help in spotting them is on-topic." } ]
[ { "body": "<p>My last AI course was too long time ago so just some generic notes and some modifications for easier testing.</p>\n\n<ol>\n<li><p>Fields should be <code>private</code>. (<em>Item 13</em> of <em>Effective Java 2nd Edition</em>: <em>Minimize the accessibility of classes and members</em>)</p></li>\n<li><p><code>IGame</code> could be <code>Game</code>.</p>\n\n<blockquote>\n <p>I don’t want my users knowing that I’m handing them an interface. \n I just want them to know that it’s a <code>ShapeFactory</code>.</p>\n</blockquote>\n\n<p>Source: <em>Clean Code</em> by <em>Robert C. Martin</em>, <em>Interfaces and Implementations</em>, p24</p></li>\n<li><p>Class names should be nouns, instead of verbs, like <code>Search</code>:</p>\n\n<blockquote>\n <p>Class and Interface Type Names</p>\n \n <p>Names of class types should be descriptive nouns or noun phrases, not overly long, in mixed\n case with the first letter of each word capitalized.</p>\n</blockquote>\n\n<p>Source: <a href=\"http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html\">The Java Language Specification, Java SE 7 Edition, 6.1 Declarations</a></p></li>\n<li><p>What is <code>ply</code>? I guess <code>maxDepth</code> would be a more descriptive name.</p></li>\n<li><p>Short variable names (like <code>g</code>) are not too readable. I suppose you have autocomplete, so using longer names does not mean more typing but it would help readers and maintainers a lot since they don't have to remember the purpose of each variable - the name would express the programmers intent. (<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>Avoid Mental Mapping</em>, p25)</p></li>\n</ol>\n\n<h2>Make it testable</h2>\n\n<blockquote>\n <p>Good design is testable, and design that isn't testable is bad. </p>\n</blockquote>\n\n<p>(Source <em>Michael C. Feathers</em>: <em>Working Effectively with Legacy Code</em>)</p>\n\n<p>I made some changes in the API (<code>Game</code> and <code>Move</code> classes to make it easier to test). </p>\n\n<ol>\n<li><p>I've added a <code>Move</code> parameter to the <code>generateMoves()</code> method to make it stateless. It results easier mocking since the output only depends only on the input parameter.</p></li>\n<li><p>I'm using <code>move.isLeaf()</code> instead of <code>g.isGameFinished()</code> (for the same reason). It could be <code>game.isFinishingMove(Move move)</code> too but the former was simpler.</p></li>\n<li><p>I've created a new method for the Move class:</p>\n\n<pre><code>public String getName() { ... }\n</code></pre>\n\n<p>It will helper when we'll verificate the test results.</p></li>\n<li><p>I've also changed the loop to a foreach. It also eliminated the duplicated <code>gameMove[i]</code> access.</p></li>\n</ol>\n\n<p>So, the <code>AlphaBetaSearcher</code> class is the following now:</p>\n\n<pre><code>private Move bestMove;\n\npublic Move findBestMove(int maxDepth, Game game, Move root) {\n bestMove = null;\n alpha_beta(maxDepth, game, root, \n Integer.MIN_VALUE, Integer.MAX_VALUE);\n return bestMove;\n}\n\nprivate int alpha_beta(final int depth, final Game game, \n final Move move, int alpha, final int beta) {\n if (depth == 0 || move.isLeaf()) {\n return game.getScore();\n }\n\n final Move[] moves = game.generateMoves(move);\n for (final Move currentMove: moves) {\n game.execute(currentMove);\n final int score = \n -alpha_beta(depth - 1, game, currentMove, -beta, -alpha);\n game.undo(currentMove);\n\n if (alpha &lt; score) {\n alpha = score;\n bestMove = currentMove;\n }\n if (beta &lt;= alpha) {\n return alpha;\n }\n }\n return alpha;\n}\n</code></pre>\n\n<h2>Test data</h2>\n\n<p>For the test below I've used the leftmost part of the <a href=\"https://en.wikipedia.org/wiki/File%3aAB_pruning.svg\">sample tree</a> from <a href=\"https://en.wikipedia.org/wiki/Alpha%E2%80%93beta_pruning\">Wikipedia</a>.</p>\n\n<h2>Test framework</h2>\n\n<p>I'm using Mockito and JUnit here. A mocking framework makes possible to test the Alpha-beta implementation without the actual Game and Move classes. In isolation you can make sure that the pruning works well before you integrate it into the game. If it isn't completely bug-free it's easier to debug and modify in isolation. </p>\n\n<p>JUnit tests are self-checking, you don't have to check the output and decide if it's OK or not. The <code>assert*</code> assertion methods throws an exception when the tested class does not return the excepted value.</p>\n\n<h2>Test code</h2>\n\n<pre><code>import static org.junit.Assert.assertEquals;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.when;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mock;\nimport org.mockito.runners.MockitoJUnitRunner;\n\n@RunWith(MockitoJUnitRunner.class)\npublic class AlphaBetaSearcherOrigTest {\n\n private final AlphaBetaSearcherOrig searcher = \n new AlphaBetaSearcherOrig();\n\n // Mockito creates a dummy, programmable Game instance for us\n @Mock\n private Game game;\n\n @Test\n public void testSubTree() {\n // we are creating the move tree with names and scores\n final Move root = createMockedMove(\"root\");\n final Move moveA = createMockedMove(\"A\");\n final Move moveB = createMockedMove(\"B\");\n final Move moveAA = createLeafMove(\"AA\", 5);\n final Move moveAB = createLeafMove(\"AB\", 6);\n final Move moveBA = createLeafMove(\"BA\", 7);\n final Move moveBB = createLeafMove(\"BB\", 4);\n final Move moveBC = createLeafMove(\"BC\", 5);\n\n // programming the dummy Game instance\n // calling generateMoves() with the root node will \n // return moveA and moveB\n when(game.generateMoves(root)).\n thenReturn(newMoveArray(moveA, moveB));\n when(game.generateMoves(moveA)).\n thenReturn(newMoveArray(moveAA, moveAB));\n when(game.generateMoves(moveB)).\n thenReturn(newMoveArray(moveBA, moveBB, moveBC));\n\n final Move bestMove = searcher.findBestMove(5, game, root);\n // checking the name of the best move\n assertEquals(\"BA\", bestMove.getName());\n }\n\n private Move createMockedMove(String name) {\n // creating a dummy/programmable Move instance \n // whose getName() method will return name\n final Move mock = mock(Move.class);\n when(mock.getName()).thenReturn(name);\n return mock;\n }\n\n private Move createLeafMove(String name, int score) {\n final Move move = createMockedMove(name);\n when(move.isLeaf()).thenReturn(true);\n when(move.getScore()).thenReturn(score);\n return move;\n }\n\n private Move[] newMoveArray(Move... moves) {\n return moves;\n }\n}\n</code></pre>\n\n<p>The algorithm currently return with <code>BA</code>. If I'm right it should be <code>A</code> but I'm really not sure.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-01T16:56:06.230", "Id": "43150", "ParentId": "23911", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T15:01:45.857", "Id": "23911", "Score": "5", "Tags": [ "java", "search", "ai" ], "Title": "Java alphabeta search" }
23911
<p>I'm not entirely sure on how to handle errors on this:</p> <ul> <li>Is returning a <code>nullptr</code> in case of bad parameters okay, or is it better to return a <code>ENFMPCodegenData.Empty</code>, like there is <code>Rectangle.Empty</code> or Point.Empty in the .NET Framework?</li> <li>What about handling errors, if any should occur when creating the native object <em>Codegen</em>?</li> <li>Should I just encompass this in a <code>try</code> / <code>catch</code> block and wrap a native exception inside a managed one?</li> </ul> <p>This my first attempt on creating such helper. It's working, but I'm not really sure about its robustness.</p> <pre><code>public ref class ENMFPCodegen { private: ENMFPCodegen() { } public: static ENMFPCodegenData ^ GetData ( array&lt;float&gt; ^ pcm , uint numberOfSamples, uint start_offset ) { if ( pcm == nullptr || pcm-&gt;Length &lt;= 0 || numberOfSamples &lt;= 0 ) return nullptr; pin_ptr&lt;float&gt; pFloat = &amp;pcm[0]; Codegen * codegen = new Codegen ( pFloat, numberOfSamples, start_offset ); if ( codegen == nullptr ) return nullptr; std::string codeString = codegen-&gt;getCodeString(); const char* chars = codeString.c_str(); String ^ code = gcnew System::String ( chars ); int numCodes = codegen-&gt;getNumCodes(); float version = codegen-&gt;getVersion(); delete codegen; ENMFPCodegenData ^ data = gcnew ENMFPCodegenData ( code, numCodes, version ); return data; } }; public ref class ENMFPCodegenData { internal: ENMFPCodegenData ( String ^ code, int numCodes, float version ) { Code = code; NumCodes = numCodes; Version = version; } public: String ^ Code; int NumCodes; float Version; virtual String ^ ToString() override { StringBuilder ^ sb = gcnew StringBuilder; sb-&gt;AppendFormat ( "{{Version: {0}, NumCodes: {1}, Code: {2}}}", Version, NumCodes, Code ); return sb-&gt;ToString(); } }; </code></pre>
[]
[ { "body": "<blockquote>\n <p>Is returning a <code>nullptr</code> in case of bad parameters okay?</p>\n</blockquote>\n\n<p>No, you should instead throw an <code>ArgumentException</code> (or possibly one of its derived types). This way, if an user of your code makes a mistake, they will get an exception clearly explaining the problem, instead of getting a confusing <code>NullReferenceException</code> at a later point.</p>\n\n<blockquote>\n <p>What about handling error if any should occur when creating the native object <code>Codegen</code>?</p>\n</blockquote>\n\n<p>Again, you should throw a suitable .Net exception. In this case, I think a custom exception would be appropriate.</p>\n\n<blockquote>\n <p>Should I just encompass this in a <code>try</code>/<code>catch</code> block and wrap a native exception inside a managed one?</p>\n</blockquote>\n\n<p>Not necessarily. Unmanaged exceptions are represented as the managed <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.sehexception.aspx\" rel=\"nofollow\"><code>SEHException</code></a>. So, if that's enough for you, you don't have to do anything.</p>\n\n<p>But if you want to be able to handle some specific unmanaged exceptions from the managed code, or if you want to preserve some information from the unmanaged exception (<code>SEHException</code> doesn't really do that), you should catch the unmanaged exception and throw a new managed exception. For example:</p>\n\n<pre><code>public ref class UnmanagedException : Exception\n{\npublic:\n UnmanagedException(String^ message)\n : Exception(message)\n {\n }\n};\n\n…\n\ntry\n{\n // call some code that can throw std::exception here\n}\ncatch (const std::exception &amp;ex)\n{\n throw gcnew UnmanagedException(gcnew String(ex.what()));\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T16:52:27.300", "Id": "24014", "ParentId": "23916", "Score": "3" } } ]
{ "AcceptedAnswerId": "24014", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T16:33:49.060", "Id": "23916", "Score": "4", "Tags": [ "c#", "c++", "c++11", "c++-cli" ], "Title": "Implementation of a managed wrapper DLL" }
23916
<p>I'm trying to find a good pattern for new applications (and for refactoring old ones).</p> <p>Maybe it's just me, but I dislike spawning my main logic thread from inside my main form thread (so far I always have 2+ threads in my apps and beefy hardware, also .NET 4.5). I feel it conflicts with the separation of concerns principle.</p> <p>So is this a good pattern?</p> <p><strong>Program.cs</strong></p> <pre class="lang-cs prettyprint-override"><code>using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using System.Threading.Tasks; namespace MyApp { static class Program { /// &lt;summary&gt; /// The main entry point for the application. /// &lt;/summary&gt; [STAThread] static void Main() { try { // Prevent multiple instances of the application from opening using (new SingleGlobalInstance(1000)) { // Run Main Logic/Sequence Task Task.Factory.StartNew(() =&gt; { new MainTask() .Run(); }); // Display GUI Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); // Blocks until Form Closes } } catch (TimeoutException) { MessageBox.Show("An instance of the application is already open."); } catch (Exception ex) { // Log Error // ... log to file... // Display Error to User MessageBox.Show(ex.Message); } } } } </code></pre> <p><strong>MainTask.cs</strong></p> <pre class="lang-cs prettyprint-override"><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace MyApp { public class MainTask { // Do Work public void Run() { Console.WriteLine("MainTask - Running"); Thread.Sleep(10000); } // Constructor public MainTask() { Console.WriteLine("MainTask - Constructed"); } //// Destructor //~MainTask() //{ // // Destructor defined for purposes of debugging // Console.WriteLine("MainTask - Destructed"); //} } } </code></pre> <p><strong>MainForm</strong></p> <pre class="lang-cs prettyprint-override"><code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace MyApp { public partial class MainForm : Form { // Constructor public MainForm() { InitializeComponent(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T13:39:46.500", "Id": "36927", "Score": "1", "body": "Are you planning on having the `MainTask` method actually do any work? If not, why have it? If so, how will it interact with the UI if it has no reference to the UI and the UI has no reference to it?" } ]
[ { "body": "<p>I would second Steven Doggart's comment about it being pointless to spawn a thread that does nothing.</p>\n\n<p>To address your separation of concerns issue, though: If you are using one of a number of design patterns for your UI (e.g., MVC, MVVM, MVP, etc.), your MainForm class will merely be binding to one or more data objects and raising events from the user. The real work and asynchrony will be done in another class.</p>\n\n<p>For example, in the MVP pattern, you might have MainForm, MainPresenter, and MainViewModel.</p>\n\n<ul>\n<li>MainForm binds various controls to properties exposed by MainViewModel</li>\n<li>MainViewModel implements INotifyPropertyChanged and raises PropertyChangedEvents when those properties change.</li>\n<li>MainForm updates those properties as the result of users manipulating those controls.</li>\n<li>MainPresenter responds to events raised by MainForm and updates MainViewModel properties as well, causing MainForm to respond through the PropertyChangedEvents</li>\n</ul>\n\n<p>It is then up to MainPresenter (or more appropriately, other classes MainPresenter uses) to figure out how to handle threading. MainForm itself never has to know or care that you are using separate threads.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T20:21:17.967", "Id": "36963", "Score": "0", "body": "Yes, I started to work through fleshing out my code above and found it to be a bit tedious. The \"thread that doesn't do anything\" in my case would monitor PLC inputs/sensors as this is for an industrial machine I'm working on. I did make a failed attempt at understanding MVP about 2 or 3 months ago... and the thing that I didn't really understand was how to cause an action without changing a property. Like calling a method on the Model that has no inputs from the Presenter? Would you use a dummy bool for this sort of thing? like Set Started = True? and Started would set itself false?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T17:55:30.510", "Id": "23967", "ParentId": "23917", "Score": "2" } }, { "body": "<p>After some more research, I just wanted to add that the correct answer for my use-case and intuitions is actually the <a href=\"http://en.wikipedia.org/wiki/Presenter_First\" rel=\"nofollow\">Presenter First</a> variant of MVP (Model-View-Presenter). It's a design pattern that pivots from the Presenter to create references for both the Model and the View, rather than starting with the View and creating the Presenter which creates the Model.</p>\n\n<p>Here's the snippet for the main thread entry methods of the Presenter First pattern</p>\n\n<p>Code from <a href=\"http://www.atomicobject.com/pages/Presenter+First\" rel=\"nofollow\">C# Presenter First example – VS2003 project for a sliding puzzle game</a></p>\n\n\n\n<pre><code>using System;\nusing System.Windows.Forms;\n\nnamespace wsm.Puzzle\n{\n /// &lt;summary&gt;\n /// Summary description for PuzzleMain.\n /// &lt;/summary&gt;\n public class PuzzleMain\n {\n [STAThread]\n static void Main()\n {\n ILoadImageModel loadImageModel = new LoadImageModel();\n ILoadImageView loadImageView = new LoadImageDialog();\n new LoadImagePresenter(loadImageModel, loadImageView);\n\n IImageCutter imageCutter = new ImageCutter();\n\n PuzzleForm view = new PuzzleForm();\n IPuzzleModel model = new PuzzleModel(loadImageModel, imageCutter);\n new PuzzlePresenter(model, view);\n\n model.Initialize();\n\n Application.Run(view);\n }\n }\n}\n</code></pre>\n\n<p>The pattern plays very well into my kind of scenarios where my controls come from PLCs (Programmable Logic Controller), sensors, cylinders, a user Form, etc... typically I deal as much or more with machine IO, than I do with humans/operators. Intuitively this pattern just feels better and makes more sense for my particular scenarios.</p>\n\n<p>I should also note that Steven Doggart and Dan Lyons were both correct about the irrelevance of multithreading in my original question. The proposed question actually missed the point of the real problem I had.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T21:30:40.757", "Id": "24260", "ParentId": "23917", "Score": "0" } } ]
{ "AcceptedAnswerId": "23967", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T16:58:26.353", "Id": "23917", "Score": "2", "Tags": [ "c#", "multithreading" ], "Title": "Multi-threaded Winforms Conventions for Main()" }
23917
<p>This is K.I.S.S, but how about some error and misuse control? I am wishing it were .NET.</p> <pre><code>&lt;?php function array_group_by($arr, $key_selector) { $result = array(); foreach($arr as $i){ $key = $key_selector($i); if(!array_key_exists($key, $result)) { $result[$key] = array(); } $result[$key][] = $i; } return $result; } $data = array( array(1, "Andy", "PHP"), array(1, "Andy", "C#"), array(2, "Josh", "C#"), array(2, "Josh", "ASP"), array(1, "Andy", "SQL"), array(3, "Steve", "SQL"), ); $grouped = array_group_by($data, function($i){ return $i[0]; }); var_dump($grouped); ?&gt; </code></pre>
[]
[ { "body": "<ol>\n<li>Using the <code>[]</code> syntax for adding array items, allows PHP to create the array as necessary. Thus you can scrap the <code>if</code> statement for a modest performance increase off 10 to 15% in my own testing. (Unlike if you used <a href=\"http://php.net/manual/en/function.array-push.php\" rel=\"nofollow\"><code>array_push()</code></a> which would throw a warning instead.</li>\n<li><p>The unused <code>$group</code> variable appears to be a mistake, as the function appears to fulfill it's purpose without it. Code reduced to:</p>\n\n<pre><code>function array_group_by($arr, $key_selector) {\n $result = array();\n foreach ($arr as $i) {\n $key = $key_selector($i);\n $result[$key][] = $i;\n }\n return $result;\n}\n</code></pre></li>\n<li>At this point, the <code>$key</code> <em>could</em> also be left out, but it's almost free in terms of performance, and increases readability, so I left it there.</li>\n<li><p>I'm not sure how much misuse and error handling you need, the function is pretty simple. I would stick with type-hinting the arguments. <code>array</code> is available since PHP 5.1, <code>callable</code> since 5.4. The signature would become</p>\n\n<pre><code>function array_group_by(array $arr, callable $key_selector);\n</code></pre>\n\n<p>Then PHP will at run-time throw a fatal error at anyone trying to call the function with incorrect parameters. Generally I think that's good, but in this particular case, it introduces a problem.\n<code>array('class_A', 'method_B')</code>, is a valid callable, that won't work with with the fast <code>$function($arg);</code>. For any valid callable to get executed, you need to use <a href=\"http://php.net/manual/en/function.call-user-func.php\" rel=\"nofollow\"><code>call_user_func()</code></a> instead, which is a bit slower. In my testing however, the removal of the <code>if</code> has bigger impact than the use of <code>call_user_func()</code>, so if this isn't performance critical, stick with callable and <code>call_user_func()</code>.</p></li>\n</ol>\n\n<p>Final code:</p>\n\n<pre><code>function array_group_by(array $arr, callable $key_selector) {\n $result = array();\n foreach ($arr as $i) {\n $key = call_user_func($key_selector, $i);\n $result[$key][] = $i;\n } \n return $result;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T19:06:41.837", "Id": "36856", "Score": "0", "body": "Type hinting... Yeah I am rusty on PHP. This is a great answer. I'll give others a chance to bite before marking it as the answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T19:07:59.307", "Id": "36857", "Score": "0", "body": "Glad I could help. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T19:09:21.613", "Id": "36858", "Score": "0", "body": "How about an array walk instead of a foreach? Will that just make it less readable?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T19:14:37.557", "Id": "36859", "Score": "0", "body": "I pondered various native array functions for a moment, but I think most (all?) of them want to act directly on the individual elements of the array, which makes them unsuitable to use when you want out data with a different structure than the in data. I could be wrong on this though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T19:57:06.423", "Id": "36867", "Score": "0", "body": "I changed \"callable\" to \"closure\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T20:55:57.957", "Id": "36875", "Score": "0", "body": "1) I had no idea that was valid, and 2) I can't find that documented under [type_hinting](http://php.net/manual/en/language.oop5.typehinting.php). What in the world!? It behaves as expected though. Cool, I learned something new." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T13:50:34.603", "Id": "36928", "Score": "0", "body": "I got an error when I had it as callable instead of closure. We must be using a different version. The error is that when passing in an anonymous function, it says \"expected callable, got closure\"" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T18:58:36.983", "Id": "23926", "ParentId": "23919", "Score": "4" } } ]
{ "AcceptedAnswerId": "23926", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T17:33:41.113", "Id": "23919", "Score": "3", "Tags": [ "php", "array" ], "Title": "Generic array group by using lambda" }
23919
<p>I made this class to handle any min max integer value and return a random number in the entered parameter range. I tested it to work with all combinations(I think). But is this totally wrong or written with unnecessary amounts of code? Are there obvious Java convention violations or obvious redundancy in this?</p> <p>I was wondering if it was possible to do the same without instantiating <code>Random</code>, since I have read that object instantiation is more resource demanding than method invoking, like invoking <code>Math.random()</code>. I just couldn't make that work, unfortunately, as I didn't save the strange non-working code that that ended with.</p> <p>I tried the solution <a href="https://stackoverflow.com/questions/3383286/create-a-random-even-number-between-range">here</a>. However, I don't understand what the <code>rand()</code> part is, which is too bad since it seemed really simple with just one line of code.</p> <pre><code>abstract class RandomInteger { static int randomNumber; public static int returnRandomIntRange(int start, int end){ if(end &lt; start){ throw new IllegalArgumentException("Start cannot exceed End."); } else if(end == 0 &amp;&amp; start == 0){ throw new IllegalArgumentException("Start and End can't both be 0."); } else if(end == start){ throw new IllegalArgumentException("Start and End can't be the same."); } else if(end &gt;= 0 &amp;&amp; start &lt;= 0){ Random random=new Random(); int range; range = end - start + 1; System.out.println("aEnd &gt; 0 &amp;&amp; aStart &lt; 0. 1range is: " + range); randomNumber=(random.nextInt(range))+(start); System.out.println("aEnd &gt; 0 &amp;&amp; aStart &gt;= 0. invoked. 1randomNumber is: " + randomNumber); } else if(end &gt; 0 &amp;&amp; start &gt; 0){ Random randomGenerator=new Random(); int range; range = end - start + 1; System.out.println("aEnd &gt; 0 &amp;&amp; aStart &gt;= 0. invoked. 2range is: " + range); randomNumber = randomGenerator.nextInt(range) + start; System.out.println("aEnd &gt; 0 &amp;&amp; aStart &gt;= 0. invoked. 2randomNumber is: " + randomNumber); } else if(end &lt; 0 &amp;&amp; start &lt; 0){ Random randomGenerator=new Random(); int range; range = (start - end -1) * -1; System.out.println("aEnd &lt;= 0 &amp;&amp; aStart &lt; 0. invoked. 3range is: " + range); randomNumber = ((randomGenerator.nextInt(range)+ start)); System.out.println("aEnd &lt;= 0 &amp;&amp; aStart &lt; 0. invoked. 3randomNumber is: " + randomNumber); } return randomNumber; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T22:00:04.820", "Id": "36845", "Score": "1", "body": "The `rand()` is for a different programming language, C++." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T22:03:23.723", "Id": "36846", "Score": "0", "body": "http://stackoverflow.com/questions/2444019/how-do-i-generate-a-random-integer-between-min-and-max-in-java" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T13:02:05.133", "Id": "37091", "Score": "0", "body": "Your `end == 0 && start == 0` case is included in your `end == start` case." } ]
[ { "body": "<p>That does look a little confusing. The example you looked at is for C, not Java. I would do this:</p>\n\n<pre><code>int random = (int) Math.floor(Math.random() * (max - min + 1) ) + min;\n</code></pre>\n\n<p>It works like this: <code>Math.random()</code> returns a <code>double</code> between 0 and 1 (although never actually equal to 1). The full range of values you want is <code>(max - min + 1)</code> (the <code>+1</code> is because you probably want <code>max</code> to <code>min</code> <em>inclusive</em>), so this will scale the number over the correct number of integer values. We <code>floor</code> it (round down) because we want an <code>int</code>, and finally shift it upwards by adding <code>min</code> to put the numbers in the correct range. We also cast to an <code>int</code> since we don't want it as a double.</p>\n\n<p><strong>EDIT:</strong> On further inspection, this is better; no casting and rounding of <code>doubles</code>:</p>\n\n<pre><code>Random rand = new Random();\nint random = rand.nextInt(max - min + 1) + min;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T22:06:19.153", "Id": "36847", "Score": "1", "body": "This solution works except in the case where `min = 0` and `max = int.maxValue`. In that case, you end up with overflow problems and you need slightly different logic. Other than that... +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T22:16:33.730", "Id": "36848", "Score": "0", "body": "Thanks! that seems very simple and clever solutions, Im gonna go for that! This doesn't take into account if max being less than min, but that could perhaps just be done by using an if check and throwing and exception?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T22:20:24.630", "Id": "36849", "Score": "0", "body": "@jazzbassrob in your edit you instantiate Random, will it we more perfomance cost?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T22:32:27.220", "Id": "36850", "Score": "0", "body": "I should have written in first post that it's for shooting rectangles around the screen making them land at random x,y offset ranges. Using Random object should only be instantiated once, but maybe Random object could be created once in the main update method and be passed as parameter into the random-method every time a new random number is needed" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T22:53:09.790", "Id": "36851", "Score": "0", "body": "@user1949930 I would be surprised if it made a large performance difference, but nonetheless I would try to keep the same instance if you can. Your random method must be in a class somewhere, so I would create it once as an instance variable of the class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T06:06:50.867", "Id": "36852", "Score": "2", "body": "It is important to reuse the Random object because when it is created it uses the current time as the seed. If you create two Random objects within a millisecond (or 10ms, depending on the clock resolution) they will produce the same \"random\" values." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T20:33:47.610", "Id": "36869", "Score": "0", "body": "Joni, I follow you on that :). But not using a Random object at all, instead invoking Math.floor(Math.random()). Wont this give better performance?" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T22:00:29.190", "Id": "23921", "ParentId": "23920", "Score": "5" } }, { "body": "<p>You can try something like the following, which will also work if start is less than end or when either number is negative:</p>\n\n<pre><code>abstract class RandomInteger {\n public static int returnRandomIntRange(int start, int end) {\n int range = Math.abs(end - start);\n if (range == 0) {\n return start; // Or throw your illegal argument exception\n }\n return Math.min(start, end) + new Random().nextInt(range + 1);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T22:10:14.397", "Id": "23922", "ParentId": "23920", "Score": "0" } }, { "body": "<p>Instead of </p>\n\n<pre><code>if(end &lt; start){\n throw new IllegalArgumentException(\"Start cannot exceed End.\");\n</code></pre>\n\n<p>I would</p>\n\n<pre><code>if(end &lt; start){\n return returnRandomIntRange(end, start);\n</code></pre>\n\n<p>This would make your method more robust.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T13:00:41.923", "Id": "37090", "Score": "0", "body": "That kind of robustness might be undesirable. Frankly, I consider the IllegalArgumentException solution to be perfectly acceptable." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T12:48:39.160", "Id": "24036", "ParentId": "23920", "Score": "0" } }, { "body": "<blockquote>\n <p>BTW Is it true that not using a Random object improves perfomance?</p>\n</blockquote>\n\n<p>No (not in your case). <code>Math.random()</code> just creates an instance of <code>Random</code>:</p>\n\n<pre><code>//from java.lang.Math\npublic static double random() {\n Random rnd = randomNumberGenerator;\n if (rnd == null) rnd = initRNG();\n return rnd.nextDouble();\n}\n\nprivate static synchronized Random initRNG() {\n Random rnd = randomNumberGenerator;\n return (rnd == null) ? (randomNumberGenerator = new Random()) : rnd;\n}\n</code></pre>\n\n<p>If you create some random numbers, just create a <code>ThreadLocalRandom</code> instance and use it. If you have speed problems, I am quite sure, it is not related to the random number generator. If you think so, profile it.</p>\n\n<p>A good way to implement the required functionality is already shown by jazzbassrob.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T01:47:11.223", "Id": "24134", "ParentId": "23920", "Score": "0" } } ]
{ "AcceptedAnswerId": "23921", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T21:52:15.650", "Id": "23920", "Score": "1", "Tags": [ "java", "performance", "random" ], "Title": "Random number wrapper class" }
23920
<p>I have a function that searches the shortest vector in a vector of vectors of pointers.</p> <p>Which is a better way?</p> <pre><code>std::vector&lt;std::vector&lt;void*&gt;&gt; const&amp; ways { size_t i = SIZE_MAX; for(auto&amp; it : ways) { if(i &gt; it.size()) i = it.size(); } } </code></pre> <p>OR</p> <pre><code>std::vector&lt;std::vector&lt;void*&gt;&gt; const&amp; ways { size_t i = SIZE_MAX; for(auto&amp; it : ways) { const auto temp = it.size(); if(i &gt; temp) i = temp; } } </code></pre> <p>As far as I can see size() does not return reference so second one is a better way, is it true?</p> <p><strong>Also</strong>, is there any other approach you can suggest for this method?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T01:59:21.390", "Id": "36889", "Score": "0", "body": "This is the wrong site for this type of question. You are going to get a lot more responses on SO." } ]
[ { "body": "<p>Calling <code>size()</code> twice, like you are, almost definitely get's optimized out in any modern compiler. How you are doing it is perfectly fine. You could also do it with <code>std::max_element</code>...</p>\n\n<pre><code>auto max = std::max_element(ways.begin(), ways.end(), \n [](const std::vector&lt;void*&gt;&amp; left, const std::vector&lt;void*&gt;&amp; right)\n { \n return left.size() &lt; right.size(); \n })-&gt;size();\n</code></pre>\n\n<p>Or maybe you write the lambda as a functor instead and a little more generic, like:</p>\n\n<pre><code>struct ContainerSizeComparer\n{\n template&lt;typename Container&gt;\n bool operator()(const Container&amp; left, const Container&amp; right)\n {\n return left.size() &lt; right.size();\n }\n};\n\nauto max = std::max_element(ways.begin(), ways.end(), ContainerSizeComparer())-&gt;size();\n</code></pre>\n\n<p>This is one of those interesting times when hand rolling the loop is actually more readable and as small as using standard algorithms though. Unless you have a reason to write ContainerSizeComparer and use it in multiple places I would personally stick with what you were doing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T04:44:05.440", "Id": "36890", "Score": "2", "body": "So in a multi-threaded environment there's no chance that `i.size()` can change between calls?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T08:59:05.667", "Id": "36896", "Score": "0", "body": "@DavidHarkness you need to use some kind of synchronization object to prevent that, like a mutex. As with all multithreading, it's safe to read from multiple threads at a time but not safe to write from multiple threads at the same time and not safe to read on some threads and write on others at the same time. Calling size even once might return garbage results if someone added an element at the same time as the call on another thread." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T09:06:35.620", "Id": "36897", "Score": "1", "body": "@DavidHarkness if you were saying that as an argument that the compiler shouldn't optimize it out, optimizations are never effected by the possibility of multithreading. They are effected by memory barriers like mutexes though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T18:49:35.353", "Id": "36951", "Score": "0", "body": "Thanks, that's exactly what I meant. I haven't used C++ in multi-threaded programs before, only other languages. Though thinking about it more, I believe it would work the same in Java." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T22:18:25.320", "Id": "23934", "ParentId": "23927", "Score": "3" } } ]
{ "AcceptedAnswerId": "23934", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T19:09:22.223", "Id": "23927", "Score": "1", "Tags": [ "c++", "vectors" ], "Title": "Should I call a method (i.e. size()) multiple times or store it (if I know the value will not change)" }
23927
<p>I am learning about the class and methods in Python.</p> <p>The class Accuracy is a class of several (13 in total) statistic values between a reference polygon and one or more segmented polygons based on shapely module.</p> <p><img src="https://i.stack.imgur.com/sg0ar.jpg" alt="enter image description here"></p> <pre><code>from numpy import average #some stat def ra_or(ref, seg): return average([(ref.intersection(s).area/ref.area) for s in seg]) def ra_os(ref, seg): return average([(ref.intersection(s).area/s.area) for s in seg]) def sim_size(ref, seg): return average([(min(ref.area, s.area)/max(ref.area,s.area)) for s in seg]) def AFI(ref,seg): return (ref.area - max([s.area for s in seg]))/ref.area </code></pre> <p>where <code>ref.intersection(s).area</code> is the area of intersection between <code>reference</code> and <code>segmented polygon-i</code></p> <p>my class design (really basic and probably to improve) is:</p> <pre><code>class Accuracy(object): def __init__ (self,ref,seg = None, noData = -9999): if seg == None: self.area = ref.area self.perimeter = ref.length self.centroidX = ref.centroid.x self.centroidY = ref.centroid.y self.data = [self.centroidX, self.centroidY, self.area, self.perimeter, noData, noData, noData, noData, noData] else: self.area = ref.area self.perimeter = ref.length self.centroidX = ref.centroid.x self.centroidY = ref.centroid.y self.segments = len(seg) self.RAor = ra_or(ref,seg) self.RAos = ra_os(ref,seg) self.SimSize = sim_size(ref,seg) self.AFI = AFI(ref,seg) self.data = [self.centroidX, self.centroidY, self.area, self.perimeter, self.segments, self.RAor, self.RAos, self.SimSize, self.AFI] from shapely.geometry import Polygon p1 = Polygon([(2, 4), (4, 4), (4, 2), (2, 2), (2, 4)]) p2 = Polygon([(0, 3), (3, 3), (3, 0), (0, 0), (0, 3)]) accp1 = Accuracy(p1,[p2]) accp1.data [3.0, 3.0, 4.0, 8.0, 1, 0.25, 0.1111111111111111, 0.44444444444444442, -1.25] accp1 = Accuracy(p1) accp1.data [3.0, 3.0, 4.0, 8.0, -9999, -9999, -9999, -9999, -9999] </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T19:33:06.900", "Id": "36862", "Score": "0", "body": "Will you ever be calling the four functions `ra_or`, `ra_os`, etc. outside of `Accuracy`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T19:34:11.533", "Id": "36863", "Score": "1", "body": "Are you looking for speed or convenience?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T19:37:13.420", "Id": "36864", "Score": "0", "body": "@unutbu both if it's possibile" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T19:37:54.993", "Id": "36865", "Score": "0", "body": "@unutbu \"ra_or, ra_os, etc. outside of Accuracy\" not necessary. Do you think it's convenient call inside the class?" } ]
[ { "body": "<p>If you plan on calling the four functions <code>ra_or</code>, <code>ra_os</code>, <code>sim_size</code> and <code>AFI</code> outside of <code>Accuracy</code> then it is good to keep them as functions. If they never get called except through <code>Accuracy</code>, then they should be made methods.</p>\n\n<hr>\n\n<p>Classes can help organize complex code, but they generally do not make your code faster. Do not use a class unless there is a clear advantage to be had -- through inheritance, or polymorphism, etc. </p>\n\n<p>If you want faster code which uses less memory, avoid using a class here. Just define functions for each attribute.</p>\n\n<p>If you want \"luxurious\" syntax -- the ability to reference each statistic via an attribute, then a class is fine.</p>\n\n<hr>\n\n<p>If you plan on instantiating instances of <code>Accuracy</code> but not always accessing all the attributes, you don't need to compute them all in <code>__init__</code>. You can delay their computation by using properties.</p>\n\n<pre><code> @property\n def area(self):\n return self.ref.area\n</code></pre>\n\n<p>Note that when you write <code>accp1.area</code>, the area method above will be called. Notice there are no parentheses after <code>accp1.area</code>. </p>\n\n<p>To be clear, the advantage to using properties is that each instance of <code>Accuracy</code> will not compute all its statistical attributes until they are needed. The downside of using a property is that they are recomputed everytime the attribute is accessed. That may not be a downside if <code>self.ref</code> or <code>self.seg</code> ever change.</p>\n\n<p>Moreover, you can cache the result using <a href=\"http://code.activestate.com/recipes/276643-caching-and-aliasing-with-descriptors/\" rel=\"nofollow\">Denis Otkidach's CachedAttribute decorator.</a> Then the attribute is only computed once, and simply looked up every time thereafter.</p>\n\n<hr>\n\n<p>Don't use an arbitrary value for <code>noData</code> like <code>noData = -9999</code>. Use <code>noData = np.nan</code>, or simply skip <code>noData</code> and use <code>np.nan</code> directly. </p>\n\n<hr>\n\n<pre><code>import numpy as np\nfrom shapely.geometry import Polygon\nnan = np.nan\n\nclass Accuracy(object):\n def __init__(self, ref, seg=None):\n self.ref = ref\n self.seg = seg\n\n @property\n def area(self):\n return self.ref.area\n\n @property\n def perimeter(self):\n return self.ref.length\n\n @property\n def centroidX(self):\n return self.ref.centroid.x\n\n @property\n def centroidY(self):\n return self.ref.centroid.y\n\n @property\n def data(self):\n return [self.centroidX,\n self.centroidY,\n self.area,\n self.perimeter,\n self.segments,\n self.RAor,\n self.RAos,\n self.SimSize,\n self.AFI]\n\n @property\n def segments(self):\n if self.seg:\n return len(self.seg)\n else:\n return nan\n\n @property\n def RAor(self):\n if self.seg:\n return np.average(\n [(self.ref.intersection(s).area / self.ref.area) for s in self.seg])\n else:\n return nan\n\n @property\n def RAos(self):\n if self.seg:\n return np.average(\n [(self.ref.intersection(s).area / s.area) for s in self.seg])\n else:\n return nan\n\n @property\n def SimSize(self):\n if self.seg:\n return np.average(\n [(min(self.ref.area, s.area) / max(self.ref.area, s.area))\n for s in self.seg])\n else:\n return nan\n\n @property\n def AFI(self):\n if self.seg:\n return (self.ref.area - max([s.area for s in self.seg])) / self.ref.area\n else:\n return nan\n\np1 = Polygon([(2, 4), (4, 4), (4, 2), (2, 2), (2, 4)])\np2 = Polygon([(0, 3), (3, 3), (3, 0), (0, 0), (0, 3)])\n\naccp1 = Accuracy(p1, [p2])\nprint(accp1.data)\n# [3.0, 3.0, 4.0, 8.0, 1, 0.25, 0.1111111111111111, 0.44444444444444442, -1.25]\n\naccp1 = Accuracy(p1)\nprint(accp1.data)\n# [3.0, 3.0, 4.0, 8.0, nan, nan, nan, nan, nan]\n</code></pre>\n\n<p>Here is how you could save your data (as a numpy array) to a CSV file:</p>\n\n<pre><code>np.savetxt('/tmp/mytest.txt', np.atleast_2d(accp1.data), delimiter=',')\n</code></pre>\n\n<p>And here is how you could read it back:</p>\n\n<pre><code>data = np.genfromtxt('/tmp/mytest.txt', dtype=None)\nprint(data)\n# [ 3. 3. 4. 8. nan nan nan nan nan]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T20:14:57.800", "Id": "36868", "Score": "0", "body": "Thanks @unutbu, you are really good as usual. Just some explanation about noData. I wish to print on text file the result. For this reason i choose (just in code beta version) a value to print out and save in a text file. I am really interest in you opinion about this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T20:37:13.883", "Id": "36871", "Score": "0", "body": "`np.genfromtxt` can parse csv files that use `'None'`, or `'NaN'`. So you can use `None` or `NaN` just as easily as you could `-9999`. In fact, `NaN` may be a better choice since `np.genfromtxt` will make the column of dtype `float`, which is better for numerical work than the `dtype` of `object` that you would get from using `None`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T20:45:03.820", "Id": "36873", "Score": "0", "body": "np.genfromtxt it's the first time i heard about this. Normally i use f = open(\"mytest.txt\", \"w\")\nf.write(accp1.data) #fake\nf.close()" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T20:45:25.097", "Id": "36874", "Score": "0", "body": "could you write two lines as example please" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T21:14:41.960", "Id": "36876", "Score": "0", "body": "thanks. In the text file i will have nan write instead of -999 (more elegant approach)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T22:09:06.193", "Id": "36880", "Score": "0", "body": "unutbu, whit np.savetxt don't save me a text file line-by-line and not several line" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T22:19:14.920", "Id": "36881", "Score": "1", "body": "This is due to an unfortunate design decision in np.savetxt. When the array is 1-dimensional, the contents are printed one **item** per line. When the array is 2-dimensinoal, the contents are printed one **row** per line. You can get the 1-dimensional data on 1 line using `np.atleast_2d(...). See edit, above." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T22:25:01.083", "Id": "36883", "Score": "0", "body": "can i save in streaming (several lines)? you are right, it's an unfortunate design decision" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T22:29:21.603", "Id": "36884", "Score": "0", "body": "Opening and closing a file once per line is very slow. It is better to build up your data into a sizeable list (of many rows) and then call `savetxt` once. If the data is too large to store in memory, then save it in chunks. You can open a file in append mode: `f = open(filename, 'a')`, and write to it multiple times with `np.savetxt(f, datachunk)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T22:30:36.440", "Id": "36885", "Score": "0", "body": "often i use append mode, i think is really smart" } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T19:55:24.590", "Id": "23932", "ParentId": "23929", "Score": "2" } }, { "body": "<p>I would approach this class the same way that unutbu did, by just storing the polygons as attributes of the class, and using properties and methods for the analysis. I think the only thing I'd do differently would be to implement this as a subclass of Polygon, so any given instance could compare itself to any other polygon on demand. I'm not going to sketch out the details, but I would want it to work like this:</p>\n\n<pre><code>sp1 = SmartPolygon([(2, 4), (4, 4), (4, 2), (2, 2), (2, 4)])\nsp2 = SmartPolygon([(0, 3), (3, 3), (3, 0), (0, 0), (0, 3)])\n\nsp1.accuracy()\n&gt;&gt;&gt; (3.0, 3.0, 4.0, 8.0, nan, nan, nan, nan, nan)\n\nsp1.accuracy(sp2)\n&gt;&gt;&gt; (3.0, 3.0, 4.0, 8.0, 1, 0.25, 0.1111111111111111, 0.44444444444444442, -1.25)\n</code></pre>\n\n<p>Other thoughts, in no particular order:</p>\n\n<hr>\n\n<p>As its own class, I personally would use a different name. 'Accuracy' is an aspect of what you want to learn from the object, but not really representative of what the object <em>is</em>. I would call this class something like PolygonComparison, or something as descriptive but ideally more concise. I don't know if this Officially Pythonic or not, but I think of classes as nouns and functions/methods as verbs, and usually name them that way.</p>\n\n<hr>\n\n<p>You have a few minor inconsistencies in your style, mainly by sometimes including spaces where you shouldn't or vice versa. These are generally things that won't affect how your code runs, but more how readable, understandable, and debuggable it is. For example,</p>\n\n<pre><code>def __init__ (self,ref,seg = None, noData = -9999):\n# Note spacing: ^ ^ ^ ^\n</code></pre>\n\n<p>would typically be written as</p>\n\n<pre><code>def __init__(self, ref, seg=None, noData=-9999):\n</code></pre>\n\n<p>Then it's much easier to see at a glance that the method has three parameters, two of which have defaults. I'd suggest taking a look at <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8</a>, the Python style guide.</p>\n\n<hr>\n\n<p>Finally, note that you have some redundancy in your <code>__init__</code> method:</p>\n\n<pre><code>def __init__(self, ref, seg=None):\n if seg == None:\n self.area = ref.area\n self.perimeter = ref.length\n self.centroidX = ref.centroid.x\n self.centroidY = ref.centroid.y\n ... # etc.\n else:\n self.area = ref.area\n self.perimeter = ref.length\n self.centroidX = ref.centroid.x\n self.centroidY = ref.centroid.y\n ...\n</code></pre>\n\n<p>could be reduced to</p>\n\n<pre><code>def __init__(self, ref, seg=None):\n self.area = ref.area\n self.perimeter = ref.length\n self.centroidX = ref.centroid.x\n self.centroidY = ref.centroid.y\n\n # Typically you check if something *is* None, rather than *equals* None.\n if seg is None:\n ...\n else:\n ...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T00:24:04.840", "Id": "24225", "ParentId": "23929", "Score": "1" } } ]
{ "AcceptedAnswerId": "23932", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T19:27:14.750", "Id": "23929", "Score": "4", "Tags": [ "python", "classes", "extension-methods" ], "Title": "improve the design of class “accuracy” in Python" }
23929
<p>Is there a better, more elegant solution to the following method?</p> <pre><code>Boolean[] spades = new Boolean[10]; // 40 cards deck foreach (Card card in m_Cards.Where(card =&gt; (card.Suit == Suit.Spades))) spades[(Int32)card.Rank] = true; // Rank goes from Ace (0) to King (10) if (spades[0] &amp;&amp; spades[1] &amp;&amp; spades[2]) { points += 3; for (Int32 i = 3; i &lt; spades.Length; ++i) { if (spades[i]) ++points; else break; } } </code></pre> <p>In fact, the function awards 3 points to the player only if he owns Ace, Two and Three... and, always if this condition is satisfied, it awards him a point for every card that extends the sequence. Examples:</p> <pre><code>Ace + Three + Five = 0 Points Ace + Two + Three = 3 Points Ace + Two + Three + Five = 3 Points Ace + Two + Three + Four + Five + Six = 6 Points </code></pre> <p>Every kind of better solution is accepted, such as Linq and enumerable extensions.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-24T00:28:15.753", "Id": "63223", "Score": "1", "body": "What is your `m_cards` variable? What kind of game is this?" } ]
[ { "body": "<p>We can use the fact that in the ordered sequence of cards the cards that match your requirement will be located at the beginning of sequence, and their rank will match their position:</p>\n\n<pre><code>var count = _cards.Where(card =&gt; card.Suit == Suit.Spades)\n .Select(card =&gt; (int)card.Rank) //we only need the rank\n .Distinct() //ignoring multiple cards with the same rank\n .OrderBy(rank =&gt; rank) //sorting by rank\n .TakeWhile((rank, index) =&gt; rank == index) //taking all initial cards with index matching their rank\n .Count();\n\nreturn count &lt; 3 ? 0 : count;\n</code></pre>\n\n<p>Note that your code will perform better than this one (you'll notice that only if you run it thousands times a second) since you're using the fact that there are only 10 sequential values present in <code>Rank</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T08:55:02.143", "Id": "23944", "ParentId": "23940", "Score": "10" } }, { "body": "<p>This is a little nicer in my opinion. Here are the changes:</p>\n\n<ul>\n<li>Start counting points from ace and reset to <code>0</code> if it's less than <code>3</code></li>\n<li>Magic numbers named as constants</li>\n<li>Primitive alias' used instead of the actual type keywords (<code>int</code> over <code>Int32</code>)</li>\n<li>Put into a method</li>\n<li><code>points</code> declared ;)</li>\n</ul>\n\n<p></p>\n\n<pre><code>private int GetSuitPoints(IEnumerable&lt;Card&gt; deck, Suit suit) {\n const int pointThreshold = 3;\n const int cardsPerSuit = 10;\n\n bool[] cards = new bool[cardsPerSuit];\n int i = 0;\n int points = 0;\n\n foreach (Card card in deck.Where(card =&gt; card.Suit == suit))\n cards[(int)card.Rank] = true;\n\n while (points == i) {\n if (cards[i++])\n points++;\n }\n\n if (points &lt; pointThreshold)\n points = 0;\n\n return points;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T12:55:38.340", "Id": "36922", "Score": "1", "body": "+1 but you need to add in a return statement at the end `return points;` - also it might be good to rename the spades variable as you've made the method accept a suit argument." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T14:11:50.247", "Id": "36930", "Score": "0", "body": "+RobH cheers, fixed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T09:00:50.170", "Id": "23945", "ParentId": "23940", "Score": "7" } } ]
{ "AcceptedAnswerId": "23945", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T04:59:37.613", "Id": "23940", "Score": "7", "Tags": [ "c#", "algorithm", ".net", "game", "playing-cards" ], "Title": "Playing card game method" }
23940
<p>I know I should be using vectors, but I want to learn something.</p> <p>Please review it and point out any mistakes. Thank you. Here it is:</p> <pre><code>template&lt; typename T &gt; class Table2D { public: Table2D( unsigned int sizeX, unsigned int sizeY ) : m_sizeX( sizeX ) , m_sizeY( sizeY ) { try { m_2DTable = new T[ m_sizeX * m_sizeY ]( ); } catch( std::bad_alloc ) { std::cerr &lt;&lt; "bad_alloc...\n"; } } ~Table2D( ) { delete [ ] m_2DTable; } private: unsigned int m_sizeX; unsigned int m_sizeY; T* m_2DTable; public: void set( unsigned int x, unsigned int y, T val ) { m_2DTable[ x + ( y * m_sizeX ) ] = val; }; T get( unsigned int x, unsigned int y ) { return m_2DTable[ x + ( y * m_sizeX ) ]; }; }; </code></pre> <p>Usage example:</p> <pre><code>Table2D&lt; unsigned int &gt; ui_2DTable( 50, 50 ); ui_2DTable.set( 10, 20, 50 ); std::cout &lt;&lt; ui_2DTable.get( 10, 20 ) &lt;&lt; std::endl; Table2D&lt; float &gt; f_2DTable( 3, 7 ); f_2DTable.set( 1, 4, 1.75 ); std::cout &lt;&lt; f_2DTable.get( 1, 4 ) &lt;&lt; std::endl; </code></pre>
[]
[ { "body": "<p>Firstly, I assume you have something like <code>#define __in</code> up the top. This is sort of a Microsoft-ism, and really isn't needed in most of these parameter sets. When you're passing types that are neither pointers nor references, it's pretty obvious that they're input values. To me, it's simply extra clutter which makes the code harder to read and provides no benefit.</p>\n\n<p>Secondly, this seems like an extremely memory heavy way of doing what is basically a map. You allocate space for <code>m_SizeX * m_SizeY</code> elements, but if the table is sparse, a majority of that space is going to go unused. </p>\n\n<p>Thirdly, you should be passing and returning certain values by <code>(const) &amp;</code>. For example, in your <code>set</code> method should probably be:</p>\n\n<pre><code>void set(unsigned int x, unsigned int y, const T&amp; val)\n</code></pre>\n\n<p>And your get method should be:</p>\n\n<pre><code>T&amp; get(unsigned int x, unsigned int y)\n</code></pre>\n\n<p>This should also have a <code>const</code> overload:</p>\n\n<pre><code>const T&amp; get(unsigned int x, unsigned int y) const\n</code></pre>\n\n<p>Note that if you haven't initialized a value, it will happily return you whatever junk happened to be there when <code>new</code> allocated the memory. This is probably not what you want - you should likely have it return either a default value or error. </p>\n\n<p>If I were to write this, I'd utilize a <code>std::map</code> and something like the following:</p>\n\n<pre><code>#include &lt;map&gt;\n#include &lt;utility&gt;\n\ntemplate &lt;typename T&gt;\nclass Table2D\n{\nprivate:\n std::map&lt;std::pair&lt;unsigned, unsigned&gt;, T&gt; table;\n\npublic:\n T&amp; operator()(unsigned x, unsigned y)\n {\n std::pair&lt;unsigned, unsigned&gt; p = std::make_pair(x, y);\n return table[p];\n }\n\n const T&amp; operator()(unsigned x, unsigned y) const\n {\n std::pair&lt;unsigned, unsigned&gt; p = std::make_pair(x, y);\n return table[p];\n }\n};\n</code></pre>\n\n<p>This code assumes you want a default <code>T()</code> value (which will be <code>0</code> for all numeric types) to be inserted if it doesn't exist. Utilizing <code>operator()</code> returning a <code>T&amp;</code> allows us to set and get values utilizing the same method:</p>\n\n<pre><code>Table2D&lt;unsigned int&gt; ui_2DTable;\nui_2DTable(10, 20) = 50;\nstd::cout &lt;&lt; ui_2DTable(10, 20) &lt;&lt; \"\\n\";\n</code></pre>\n\n<p>Further, if we do something like:</p>\n\n<pre><code>std::cout &lt;&lt; f_2DTable.get(10, 10) &lt;&lt; \"\\n\";\n</code></pre>\n\n<p>We'll simply return a default value. Currently, this will return something from a random bit of memory, and causes undefined behaviour, which is bad.</p>\n\n<p>Finally, your code can cause undefined behaviour if the user tries to utilize the copy constructor or copy assignment operator. That is:</p>\n\n<pre><code>Table2D&lt;unsigned int&gt; ui_2DTable( 50, 50 );\nui_2DTable.set( 10, 20, 50 );\nTable2D&lt;unsigned int&gt; ui_construct(ui_2DTable);\nTable2D&lt;unsigned int&gt; ui_copy = ui_2DTable;\n</code></pre>\n\n<p>will have the pointer <code>m_2DTable</code> pointing to the same memory in all 3. If one goes out of scope, the memory will be deleted, while the others will still try to access it - if you're lucky, this will crash. I won't go into complete detail on how to fix this, but you can read about the so called \"Rule of Three\" <a href=\"https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three\">here</a>. Suffice to say, the version using <code>std::map</code> doesn't suffer from this problem (one of the nice benefits of standard containers is this comes \"for free\").</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T06:51:04.530", "Id": "36891", "Score": "0", "body": "This post deserve + 1 and above." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T06:53:56.023", "Id": "36892", "Score": "0", "body": "`std::cout << f_2DTable.get(10, 10) << \"\\n\";` will cause an undefined behavior right? Hm, how would I resolve that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T06:58:41.853", "Id": "36893", "Score": "0", "body": "@Noobie You need to do some bounds checking. Check if `x >= m_SizeX || y >= m_SizeY` and either do something like `throw std::out_of_range` or return some kind of default value." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T06:59:42.117", "Id": "36894", "Score": "0", "body": "Thank you @Yuushi. Your post taught and helped me a lot. Thank you. Now, I need to go study the Rule of Three and Five. :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T06:45:50.870", "Id": "23943", "ParentId": "23941", "Score": "2" } } ]
{ "AcceptedAnswerId": "23943", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T06:07:44.630", "Id": "23941", "Score": "2", "Tags": [ "c++" ], "Title": "C++ Simple 2D Array Wrapper" }
23941
<p>Recently I needed to manipulate with cookies using JavaScript, so I wrote a class:</p> <pre><code>function Cookies() { var cookieLifeTime = null; this.setCookie = setCookie; this.getCookie = getCookie; this.deleteCookie = deleteCookie; this.setLifeTime = setLifeTime; function setLifeTime(lifeTime) { cookieLifeTime = lifeTime; } function setCookie(name, value) { if (this.lifeTime !== null) { var date = new Date(); date.setTime((date.getTime() + cookieLifeTime)); var expires = '; expires=' + date.toGMTString(); } else { var expires = ''; } document.cookie = name + '=' + value + expires + '; path=/'; } function getCookie(name) { name += '='; var ca = document.cookie.split(';'); for(var i=0; i &lt; ca.length; i++) { var c = ca[i]; while (c.charAt(0) === ' ') c = c.substring(1, c.length); if (c.indexOf(name) === 0) return c.substring(name.length, c.length); //Edited. Reduced not extra iterations } return null; } function deleteCookie(name) { setCookie(name, '', -1); } } </code></pre> <p>I am not a JavaScript developer so maybe I've over-complicated things. Are there parts that can be optimized (I mean readability mostly)? I am also interested if there could be some edge-cases where this script will fail.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T11:31:34.580", "Id": "36913", "Score": "0", "body": "As far as I'm aware, there is already a plugin for it in the wild. Why not use it instead?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T12:47:25.223", "Id": "36919", "Score": "0", "body": "@JanDvorak Usually, I don't work with javascript. So I am not familiar with its plugins and implementing this class was not a big deal. That's why I went on my own." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T13:09:45.837", "Id": "36923", "Score": "1", "body": "Your code seems very readable to me. It would pass my code review ;-)" } ]
[ { "body": "<p>The only thing I'd suggest is that there is no real need for it being a class, since it's basically a singleton. So I'd use:</p>\n\n<pre><code>var Cookies = {\n // The same as your function\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T14:33:34.983", "Id": "36933", "Score": "0", "body": "I was thinking the same thing, but it does have the `cookieLifeTime` \"private\" instance var" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T14:41:05.550", "Id": "36935", "Score": "0", "body": "Right, I missed that. But it would make sense to turn the life time into a argument for `setCookie` anyway." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T14:28:34.943", "Id": "23955", "ParentId": "23949", "Score": "2" } }, { "body": "<p>As Dvorak said in the comments, your code is fine as-is. Still, I have some suggestions:</p>\n\n<ol>\n<li><p>I'd forego the <code>*Cookie</code> suffix on the function names. Seems too verbose, considering the constructor is called <code>Cookies</code> already. Only trick is that you can't have function called <code>delete</code> as that's a reserved word, but <code>remove</code> works fine too.</p></li>\n<li><p>I think you have a bug: In <code>deleteCookie</code> you call your own <code>setCookie</code> with a negative lifetime - but setCookie doesn't take a lifetime argument, so the cookie won't be deleted as expected.<br>\nI'd fix this by adding such a 3rd argument to <code>setCookie</code> but making it optional:</p>\n\n<pre><code>function setCookie(name, value, lifetime) {\n var date, expires = '';\n // default to cookieLifeTime if no arg was passed\n if( typeof lifetime !== 'undefined' ) {\n lifetime = cookieLifeTime);\n }\n if( lifetime ) {\n date = new Date();\n date.setTime(date.getTime() + lifetime);\n expires = '; expires=' + date.toGMTString()\n } \n document.cookie = name + '=' + value + expires + '; path=/';\n}\n</code></pre></li>\n<li><p>The <code>getCookie</code> can be made considerably shorter with a bit or regular expression magic.</p>\n\n<pre><code>function getCookie(name) {\n var pattern = new RegExp(name + '=([^;]+)', ''),\n match = document.cookie.match(pattern);\n if(match) {\n return match[1];\n }\n return null;\n}\n</code></pre></li>\n<li><p>As RoToRa says in another answer, a simple object literal might be neater, if you're willing to either skip the <code>cookieLifeTime</code> instance variable, or make it completely global. Here's how I'd probably write it:</p>\n\n<pre><code>// lowercase, as it's no longer a constructor\nwindow.cookies = {\n set: function (name, value, lifetime) {\n var date, expires = '';\n // for mysterious reasons `NaN` is a number in JS,\n // so check for NaN too\n if( typeof lifetime === 'number' &amp;&amp; !isNaN(lifetime) ) {\n date = new Date();\n date.setTime(date.getTime() + lifetime);\n expires = '; expires=' + date.toGMTString()\n } \n document.cookies = name + '=' + value + expires + '; path=/';\n },\n\n get: function (name) {\n var pattern = new RegExp(name + '=([^;]+)', ''),\n match = document.cookie.match(pattern);\n if(match) {\n return match[1];\n }\n return null;\n },\n\n remove: function(name) {\n window.cookies.setCookie(name, '', -1);\n }\n};\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T14:39:20.780", "Id": "36934", "Score": "0", "body": "+1 Nice review. Thanks for noticing bug. :) BTW, should not it be `typeof lifetime === 'undefined'`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T14:51:44.280", "Id": "36936", "Score": "0", "body": "@PLB you could do that, yes, but as `typeof lifetime !== 'undefined'` (note the negation). But checking for number is stricter, and perhaps better, since the var will be used for some math. However, I'm noticing a ton of typos in my code, so I'll be editing it a little :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T14:32:24.377", "Id": "23957", "ParentId": "23949", "Score": "4" } } ]
{ "AcceptedAnswerId": "23957", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T10:20:12.747", "Id": "23949", "Score": "4", "Tags": [ "javascript" ], "Title": "Class to interact with cookies" }
23949
<p>I wrote a simple JSON schema validator. The full code is over <a href="https://gist.github.com/pramodliv1/5168625" rel="nofollow noreferrer">here</a> on gist.github.com However, the code without comment is...</p> <pre><code>validate = function(schema, instance) { var i; var errors = 0; var getType = function(attr) { return Object.prototype.toString.call(attr); } var addError = function(msg, attrs) { console.error(msg, attrs); errors += 1; } if(getType(schema) !== getType(instance)) { addError(&quot;Type Mismatch&quot;, [schema, instance]); return errors; } for(i in schema) { if(schema.hasOwnProperty(i)) { if(instance[i] == undefined) { addError(&quot;Property Not found&quot;, i); } //Special Handling for arrays else if( getType(schema[i]) === getType([]) ) { var zeroSchema = schema[i][0]; var zeroInstance = instance[i][0]; if(zeroInstance === undefined) { continue; } for(var j=0;j&lt;instance[i].length;j++) { errors += validate(zeroSchema, instance[i][j]); } } //Special Handling for nested objects else if( getType(schema[i]) === getType({}) ) { errors += validate(schema[i], instance[i]); } } } return errors; } </code></pre> <p>The code doesn't need the schema object to explicitly specify the type of object properties unlike the <a href="http://json-schema.org/examples.html" rel="nofollow noreferrer">official one</a></p> <p>I'm fairly new to javascript. How do I improve the code?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T11:30:49.887", "Id": "36912", "Score": "0", "body": "Edited your question putting the code from the link into it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T12:23:39.833", "Id": "36915", "Score": "0", "body": "You could pass your script through [Javascript Lint](http://javascriptlint.com/online_lint.php) to check for missing semicolons and things like that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T12:49:44.273", "Id": "36921", "Score": "2", "body": "@palacsint Thanks. ProfPickle helped add the code" } ]
[ { "body": "<p>I'd definitely change:</p>\n\n<pre><code>if(instance[i] == undefined) {\n addError(\"Property Not found\", i);\n}\n</code></pre>\n\n<p>to something more robust, e.g.</p>\n\n<pre><code>if (!instance.hasOwnProperty(i)) {\n addError(\"Property Not found\", i);\n}\n</code></pre>\n\n<p>Stylistically I'd change a few things as well:</p>\n\n<p>Add a space between function names and (): <code>function()</code> to <code>function ()</code><br>\nAdd a space between if, for etc and (: <code>for(i in schema)</code> to <code>for (i in schema)</code><br>\nAdd in semi-colons after defining your functions:</p>\n\n<pre><code>var getType = function(attr) {\n return Object.prototype.toString.call(attr);\n}; // &lt;-- here.\n</code></pre>\n\n<p>Also, because JavaScript doesn't have block scope I like to define all my variables at the top of the function. e.g. you have:</p>\n\n<pre><code>validate = function (schema, instance) {\n\n // omitted code.\n\n for(var j=0; j&lt;instance[i].length; j++) {\n errors += validate(zeroSchema, instance[i][j]); \n }\n\n // more code.\n}\n</code></pre>\n\n<p>Whereas I would prefer j defined at the top of the function (as well as the extra spaces I've added).</p>\n\n<p>Having said all of that, I wonder whether your solution is flexible enough - how would you specify an optional property? A property with a minimum and/or maximum value?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T13:14:16.697", "Id": "23952", "ParentId": "23950", "Score": "4" } } ]
{ "AcceptedAnswerId": "23952", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T10:35:56.720", "Id": "23950", "Score": "3", "Tags": [ "javascript", "json" ], "Title": "JSON schema validator" }
23950
<p>How can I verify that <code>ohterClassMock.MethodToTest()</code> was called with <code>contracts</code>?</p> <p>That it was called with <code>contract</code>, that have <code>Id = 1</code> and <code>Param2 = 34</code> and also with <code>contract2</code>, which has <code>Id = 2</code> and <code>Param2 = 56</code>.</p> <p>This is my code:</p> <pre><code>GoodClass goodClass = new GoodClass(ohterClassMock); ... var contracts = new List&lt;Contract&gt;(); var contract = new Contract{ Id = 1, Param2 = 34 }; contracts.Add(contract); var contract2 = new Contract { Id = 2, Param2 = 56 }; contracts.Add(contract2); goodClass.DoSomething(contracts); ohterClassMock.Verify(mock =&gt; mock.MethodToTest(It.IsAny&lt;contracts&gt;())); </code></pre> <p>I know that it can be tested for every item in the collection:</p> <pre><code>ohterClassMock.Verify(mock =&gt; mock.MethodToTest(It.Is&lt;Contract&gt;(contract =&gt; contract.Id == 1))); ... </code></pre> <p>but maybe there is some other syntax to call it in one line of code?</p> <p><em>Updated:</em></p> <pre><code>goodClass.DoSomething(contracts); </code></pre> <p>calls </p> <pre><code>foreach(Contract contract in contracts) { ohterClassMock.MethodToTest(contract); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T10:22:12.720", "Id": "36906", "Score": "2", "body": "Not very clear. What do you want to test exactly? That the contracts were not modified?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T10:24:56.960", "Id": "36907", "Score": "0", "body": "@HenkHolterman - I want to test, that ohterClassMock was called with contracts. And to test that all the items of contracts have the right value." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T10:27:02.183", "Id": "36908", "Score": "0", "body": "So you want to test the Test? The call is right there. You should be wondering about the results of DoSomething()." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T10:36:23.503", "Id": "36910", "Score": "0", "body": "@HenkHolterman - I want to test, that if I call goodClass.DoSomething(contracts) - ohterClassMock.MethodToTest(contract) will be called with all the items from contracts Collection and that all this item have the valid parameters" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T15:21:07.403", "Id": "36939", "Score": "2", "body": "You shouldn't test that a function calls another function correctly. You should test that A) function #1 returns or manipulates the contracts correctly, without knowing anything about *how* it does it, and B) that the second function does the right thing when given a correctly manipulated set of input." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T09:53:59.027", "Id": "37079", "Score": "0", "body": "@Bobson - maybe you are right ) Sometimes I write this kind of tests - verify that A calls B.." } ]
[ { "body": "<p>Strictly to answer the question at hand, you have local variables for the individual contracts already, so you can just re-use them:</p>\n\n<pre><code>ohterClassMock.Verify(mock =&gt; mock.MethodToTest(It.Is&lt;Contract&gt;(c =&gt; contract.Equals(c))));\nohterClassMock.Verify(mock =&gt; mock.MethodToTest(It.Is&lt;Contract&gt;(c =&gt; contract2.Equals(c))));\n</code></pre>\n\n<p>This assumes you have implemented <code>IEquatable&lt;Contract&gt;</code> and/or overridden <code>Object.Equals</code> on your Contract object.</p>\n\n<p>Given the behavior of most test and mocking frameworks, it will probably save you a lot of grief to go ahead and override <code>Object.ToString</code> so that failed tests will print out nicer expected/actual values than the fully-qualified type names.</p>\n\n<p>Also, as an aside, you can create your list with a collection initializer if you do so after building your individual contracts:</p>\n\n<pre><code>var contracts = new List&lt;Contract&gt; { contract, contract2 };\n</code></pre>\n\n<p>Or, if your method takes in <code>IEnumerable&lt;Contract&gt;</code>, it may be even simpler to use:</p>\n\n<pre><code>var contracts = new [] { contract, contract2 };\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T17:18:37.083", "Id": "23964", "ParentId": "23951", "Score": "2" } } ]
{ "AcceptedAnswerId": "23964", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T10:19:33.750", "Id": "23951", "Score": "1", "Tags": [ "c#", "unit-testing", "moq" ], "Title": "Verify collection as a method parameter" }
23951
<p>I often have method like this one with two or more render to do due to catching the error for example. I currently do something like this:</p> <pre><code>def update @user = current_user if params[:user][:camera_type].present? &amp;&amp; params[:user][:lens_type].present? &amp;&amp; params[:user][:photo].present? r = Photo.instance.Upload(camera_type: @user.id, album: @user.default_album, photo: params[:user][:photo], lens_type: params[:user][:lens_type], camera_type: params[:user][:camera_type]) @user.camera_type = params[:user][:camera_type] @user.lens_type = params[:user][:lens_type] @user.photo = params[:user][:photo] @user.save! render action: 'edit' return end rescue Photo =&gt; e redirect_to photo_path, :flash =&gt; { :alert =&gt; t(:text_photo_edit_failed) } end </code></pre> <p>But may be there is a better way to do it ?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T22:27:50.263", "Id": "36965", "Score": "0", "body": "can you fix the indentation?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T23:37:42.857", "Id": "36966", "Score": "1", "body": "@tokland Fixed it - was thinking about doing that earlier, but wasn't even sure I knew how. A lot going on there, none of it clear :/" } ]
[ { "body": "<p>Some notes:</p>\n\n<ul>\n<li>Keep your controllers lean, this is too much code for an action. </li>\n<li>The photo upload should be done as a part of the object's save chain (after validation), so create a <code>before_save</code> callback in the <code>User</code> model that returns <code>false</code> if the upload fails. </li>\n<li>You set <code>r</code> (cryptic name) but don't use it anywhere? does the upload raise an exception on error?</li>\n</ul>\n\n<p>At the end the controller should look extremely simple, something like:</p>\n\n<pre><code>def update\n @user = current_user\n\n if @user.update_attributes(params[:user])\n render action: 'edit'\n else\n redirect_to photo_path, flash: {alert: t(:text_photo_edit_failed)}\n end\nend\n</code></pre>\n\n<p>Any additional logic should be in <code>User</code>. Models are easy to test in isolation, controllers on the other hand have a lot of state to worry about.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T19:24:09.270", "Id": "36959", "Score": "1", "body": "Agreed, most of this should be moved into models. There's also some weirdly suspect bits of code here suggesting you need to work out some kinks in your model layer, like `Upload` as a method name, or `camera_type: @user.id`. What is a user's ID doing there, being called a \"camera_type\"? You also generally shouldn't have to check for specific parameters to be present, rather you prevent models from being moved into an invalid state *at the model level*, via validations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T23:47:31.057", "Id": "36967", "Score": "0", "body": "@meagar `camera_type: @user.id` is the typo mistake. my bad." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T15:27:08.833", "Id": "23962", "ParentId": "23954", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T14:09:22.763", "Id": "23954", "Score": "2", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "two or more render/redirect in the same method" }
23954
<p>Just trying to work out some simple graceful connection handling code in Haskell to get my head around some of the IO/Networking/Threading stuff, some tips where I'm doing things poorly would be appreciated! I'm sure I could just use a module like network pipes that would handle all the graceful stuff for me out of the box, but this was just an exercise to try and understand basic network/multithreaded IO handling in haskell.</p> <pre><code>import Network import Control.Concurrent import Control.Concurrent.STM import Control.Exception import System.IO type Connection = (Handle, HostName, PortNumber) type ConnectionHandler = Connection -&gt; IO () type Pool = [(ThreadId, Connection)] main = runConn fst' (a,b,c) = a connFromPool (a,(b,c,d)) = b runConn = withSocketsDo $ do s &lt;- (listenOn (PortNumber 1234)) p &lt;- atomically (newTVar ([]::Pool)) t &lt;- forkIO (repeatAccept s p) repeatUntilExit stdin stdout putChar "" p' &lt;- atomically $ readTVar p mapM_ killThread (t:map fst p') sClose s putStrLn "Enter to exit." &gt;&gt; getLine repeatAccept s p = do c &lt;- accept s t &lt;- forkFinally (echoHandler c) (exitPool p) atomically $ do p' &lt;- readTVar p writeTVar p ((t,c):p') repeatAccept s p exitPool :: TVar Pool -&gt; a -&gt; IO () exitPool pool = \_ -&gt; do tid &lt;- myThreadId print $ "Exiting: " ++ (show tid) p &lt;- (atomically $ readTVar pool) h &lt;- hdl p tid open &lt;- hIsOpen h if open then do hPutStrLn h "bye\n" &gt;&gt; hFlush h &gt;&gt; hClose h else return () atomically $ do pool' &lt;- readTVar pool writeTVar pool $ filter ((/=tid).fst) pool' return () where hdl p tid = return.connFromPool $ head $ filter ((==tid).fst) p echoHandler :: ConnectionHandler echoHandler a@(hdl,_,_) = repeatUntilExit hdl hdl echoToHandleAndStdout "" where echoToHandleAndStdout x = hPutChar hdl x &gt;&gt; putChar x repeatUntilExit :: Handle -&gt; Handle -&gt; (Char -&gt; IO ()) -&gt; [Char] -&gt; IO () repeatUntilExit hIn hOut f "exit\n" = return () repeatUntilExit hIn hOut f x = do c &lt;- hGetChar hIn f c repeatUntilExit hIn hOut f (appendToLastFive c) where appendToLastFive a = (reverse . (:)a . take 4 . reverse) x -- this is just here because I'm using an older version of base which doesn't have it yet forkFinally :: IO a -&gt; (Either SomeException a -&gt; IO ()) -&gt; IO ThreadId forkFinally action and_then = mask $ \restore -&gt; forkIO $ try (restore action) &gt;&gt;= and_then </code></pre>
[]
[ { "body": "<p>Just one remark: When handling <code>IO</code> resources, I'd strongly suggest using <a href=\"http://hackage.haskell.org/package/base-4.8.0.0/docs/Control-Exception-Base.html#v:bracket\" rel=\"nofollow\"><code>bracket</code></a> for resources that are obtained at some point and later released. Not only it makes your code much safer, it clearly demarcates which resource is used in which parts. And that also prevents separating opening and closing of resources, which is often a hard-to-find error.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-14T20:20:57.457", "Id": "86910", "ParentId": "23963", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T17:05:43.190", "Id": "23963", "Score": "4", "Tags": [ "multithreading", "haskell", "networking", "server" ], "Title": "Haskell network connection graceful handler" }
23963
<p>I have implemented the DBSCAN algorithm for clustering image keypoints. I have been following the pseudocode on the <a href="http://en.wikipedia.org/wiki/DBSCAN" rel="noreferrer">wiki</a> page pretty strictly, and it's working, but I get the feeling its a very naive implementation and could be improved in terms of performance. I was hoping you could offer me some feedback on how to improve it.</p> <pre><code>/* DBSCAN - density-based spatial clustering of applications with noise */ vector&lt;vector&lt;KeyPoint&gt;&gt; DBSCAN_keypoints(vector&lt;KeyPoint&gt; *keypoints, float eps, int minPts) { vector&lt;vector&lt;KeyPoint&gt;&gt; clusters; vector&lt;bool&gt; clustered; vector&lt;int&gt; noise; vector&lt;bool&gt; visited; vector&lt;int&gt; neighborPts; vector&lt;int&gt; neighborPts_; int c; int noKeys = keypoints-&gt;size(); //init clustered and visited for(int k = 0; k &lt; noKeys; k++) { clustered.push_back(false); visited.push_back(false); } //C =0; c = 0; clusters.push_back(vector&lt;KeyPoint&gt;()); //will stay empty? //for each unvisted point P in dataset keypoints for(int i = 0; i &lt; noKeys; i++) { if(!visited[i]) { //Mark P as visited visited[i] = true; neighborPts = regionQuery(keypoints,&amp;keypoints-&gt;at(i),eps); if(neighborPts.size() &lt; minPts) //Mark P as Noise noise.push_back(i); else { clusters.push_back(vector&lt;KeyPoint&gt;()); c++; //expand cluster // add P to cluster c clusters[c].push_back(keypoints-&gt;at(i)); //for each point P' in neighborPts for(int j = 0; j &lt; neighborPts.size(); j++) { //if P' is not visited if(!visited[neighborPts[j]]) { //Mark P' as visited visited[neighborPts[j]] = true; neighborPts_ = regionQuery(keypoints,&amp;keypoints-&gt;at(neighborPts[j]),eps); if(neighborPts_.size() &gt;= minPts) { neighborPts.insert(neighborPts.end(),neighborPts_.begin(),neighborPts_.end()); } } // if P' is not yet a member of any cluster // add P' to cluster c if(!clustered[neighborPts[j]]) clusters[c].push_back(keypoints-&gt;at(neighborPts[j])); } } } } return clusters; } vector&lt;int&gt; regionQuery(vector&lt;KeyPoint&gt; *keypoints, KeyPoint *keypoint, float eps) { float dist; vector&lt;int&gt; retKeys; for(int i = 0; i&lt; keypoints-&gt;size(); i++) { dist = sqrt(pow((keypoint-&gt;pt.x - keypoints-&gt;at(i).pt.x),2)+pow((keypoint-&gt;pt.y - keypoints-&gt;at(i).pt.y),2)); if(dist &lt;= eps &amp;&amp; dist != 0.0f) { retKeys.push_back(i); } } return retKeys; } </code></pre>
[]
[ { "body": "<p>Your implementation is fine. There's a few little things that could change but overall wouldn't do much for efficiency. For instance, having the <code>noise</code> vector doesn't really do anything and <code>sqrt()</code> is computationally-demanding, so squaring <code>eps</code> before the loop then checking <code>if(dist &lt;= epsSquared)</code> etc. </p>\n\n<p>These are little things, and I imagine you are talking about the algorithm overall? If so, then there's little you can do. It is an \\$O(n^2)\\$ complexity algorithm so there's nothing you can really do to speed it up. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-26T03:26:05.053", "Id": "27790", "ParentId": "23966", "Score": "2" } }, { "body": "<p>Just for correctness and not for performance reasons:<br/>\nYou nowhere mark any key as being clustered. As a result, keys may be clustered multiple times. In case all keys shall be clustered maximum one time, one may do the following modifications to the code above:</p>\n\n<p>Add a following first line </p>\n\n<pre><code>clustered[i] = true; \n</code></pre>\n\n<p>behind</p>\n\n<pre><code>// add P to cluster c\nclusters[c].push_back(keypoints-&gt;at(i));\n</code></pre>\n\n<p>and a following second line</p>\n\n<pre><code>clustered[neighborPts[j]] = true;\n</code></pre>\n\n<p>after</p>\n\n<pre><code>clusters[current_cluster].push_back(keypoints-&gt;at(neighborPts[j]));\n</code></pre>\n\n<p>Concerning the second line, make sure that it is inserted within the if-statement.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T12:09:11.933", "Id": "36129", "ParentId": "23966", "Score": "9" } }, { "body": "<p>The only chance is you can introduce an indexing structure (as said in the wiki article) to execute in neighborhood query. Once I had to cluster a set of points with their spatial coordinates in an image, and I found that use of the color information of points for indexing could greatly reduce the execution time of the algorithm. Finding an indexing structure may not possible for all applications but it is worth to give a try to find a one.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-02T07:37:56.260", "Id": "38411", "ParentId": "23966", "Score": "0" } } ]
{ "AcceptedAnswerId": "36129", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T17:47:14.777", "Id": "23966", "Score": "12", "Tags": [ "c++", "performance", "algorithm", "clustering", "opencv" ], "Title": "Density-based clustering of image keypoints" }
23966
<p>OpenCV is the most popular and advanced code library for Computer Vision related applications today, spanning from many very basic tasks (capture and pre-processing of image data) to high-level algorithms (feature extraction, motion tracking, machine learning). It is free software and provides a rich API in C, C++, Java and Python. Other wrappers are available. The library itself is platform-independent and often used for real-time image processing and computer vision (e.g. tracking in videos).</p> <p>OpenCV was officially launched by Intel in 1999 and is now supported by Itseez. Version 2.0 (2009) was an important landmark as it introduced the new, comprehensive C++ interface, which since then is also to be used internally in the library. Since this release, OpenCV saw a strong acceleration of development in improving the library and adding new features. More information may be found <a href="http://en.wikipedia.org/wiki/OpenCV" rel="nofollow">in Wikipedia</a>.</p> <p><strong>Homepage:</strong> <a href="http://opencv.org" rel="nofollow">http://opencv.org</a></p> <hr> <h3>Some Frequently Asked Questions</h3> <p><strong>Compiling OpenCV</strong></p> <ul> <li><a href="http://stackoverflow.com/questions/7011238/opencv-2-3-c-visual-studio-2010/7014918#7014918">How to configure OpenCV 2.3 on VS2010?</a> </li> <li><a href="http://stackoverflow.com/questions/3856063/compiling-opencv/3857711#3857711">Compiling OpenCV</a> </li> <li><a href="http://stackoverflow.com/a/8559953/799155">Compile OpenCV (2.3.1+) for OS X Lion / Mountain Lion with Xcode</a></li> <li><a href="http://stackoverflow.com/questions/10860352/getting-started-with-opencv-2-4-on-windows-7">Getting started with OpenCV 2.4 on Windows 7</a></li> <li><a href="http://stackoverflow.com/questions/11470217/compile-opencv-2-4-2-for-debian-lenny">Compile OpenCV 2.4.2 for Debian Lenny</a></li> </ul> <p><strong>Basic processing</strong></p> <ul> <li><a href="http://stackoverflow.com/questions/3400908/how-to-save-output-video-into-a-file-in-opencv">How to save output video into a file in opencv?</a></li> <li><a href="http://stackoverflow.com/questions/3907028/opencv-every-frame-processing/3919216#3919216">OpenCV every frame processing</a></li> <li><a href="http://stackoverflow.com/questions/4350698/opencv-how-to-split-a-video-into-image-sequence">How to split a video into image sequence?</a></li> <li><a href="http://stackoverflow.com/a/9021811/951860">Basic color segmentation</a></li> </ul> <p><strong>Object detection</strong>:</p> <ul> <li><a href="http://stackoverflow.com/questions/6416117/simple-object-detection-using-opencv-and-machine-learning/6416361#6416361">Detecting Circles</a> </li> <li><a href="http://stackoverflow.com/a/8863060/176769">Detecting a sheet of paper</a></li> <li><a href="http://stackoverflow.com/q/10533233/176769">Advanced square detection</a></li> <li><a href="http://stackoverflow.com/questions/9413216/simple-digit-recognition-ocr-in-opencv-python/9620295#comment13090771_9620295">Simple OCR</a></li> <li><a href="http://stackoverflow.com/questions/9854384/detecting-crosses-in-an-image">Template matching and shape detection</a></li> <li><a href="http://stackoverflow.com/questions/8218997/how-to-detect-the-sun-from-the-space-sky-in-opencv">Detecting sun with template matching</a></li> <li><a href="http://stackoverflow.com/questions/8202997/how-to-find-laser-cross-center-with-open-cv">Laser cross detection</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T18:34:16.707", "Id": "23971", "Score": "0", "Tags": null, "Title": null }
23971
OpenCV (Open Source Computer Vision) is a cross-platform library of programming functions for real time computer vision.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T18:34:16.707", "Id": "23972", "Score": "0", "Tags": null, "Title": null }
23972
<p>In effort to streamline applicable PHP file <code>include</code> or <code>require</code> functions I thought that making a class to handle this might be a good idea.</p> <p>Originally I had an <code>includes/init.php</code> file that included everything, I wanted to make this more dynamic to the specific page the user was on. For example, some pages require the Google maps script or custom <code>Javascript</code> that other pages don't need.</p> <p>Here is a quick simplified example that doesn't address the dynamic <code>include</code> declarations yet:</p> <pre><code>class JIncludes { public function getClasses() { foreach (glob("includes/classes/*.php") as $filename) { require_once($filename); } } public function getCoreTop() { require_once('includes/core/head.php'); require_once('includes/core/header.php'); } public function getCoreBottom() { require_once('includes/core/footer.php'); } } </code></pre> <p>Is this even a good idea? Will creating this Class object cause more overhead then the alternative?</p> <p>I have tested this with the following in my <code>index.php</code>:</p> <pre><code>$include = new JIncludes(); $include-&gt;getClasses(); $include-&gt;getCoreTop(); $db = new DB('local'); $db-&gt;prepare('String'); </code></pre> <p>The source shows the html from my <code>head.php</code> file fine and my <code>PDO</code> <code>DB</code> class works as well. Am I over-complicating things?</p>
[]
[ { "body": "<h2>Mixing</h2>\n\n<p>You are mixing 2 things:</p>\n\n<ul>\n<li>class loading</li>\n<li>\"template\" loading</li>\n</ul>\n\n<p>You aren't over complicating things - you try to over simplify them.</p>\n\n<h2>Class loading</h2>\n\n<p>In your solution you are loading all classes if only (for example) 2 of them required to serve the request the loading of the other 52321 class is just a waste of time and resources.</p>\n\n<p>Read about automatic class loading: <a href=\"http://php.net/manual/en/language.oop5.autoload.php\" rel=\"nofollow\">Autoloading Classes</a></p>\n\n<p>With this feature in your mind you can create a custom logic to load the necessary classes (name resolution, class location in file system etc.).</p>\n\n<h2>Template</h2>\n\n<p>The other thing what you want is loading your templates into the rendering process. This is hard to do it right, all depends on your \"framework\" solutions for example naming conventions, is your app frame an MVC based stuff etc.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T21:43:58.203", "Id": "23977", "ParentId": "23976", "Score": "2" } }, { "body": "<p>What you may not know, is that class loading, mostly, already has several <a href=\"http://www.mwop.net/blog/245-Autoloading-Benchmarks.html\" rel=\"nofollow\">well established solutions</a>.</p>\n\n<p>First and foremost, PHP supports, as of version 5, <a href=\"http://php.net/manual/en/language.oop5.autoload.php\" rel=\"nofollow\">Class auto loading</a>. (There's still no (planned) function auto loading unfortunately.)</p>\n\n<p>Fundamentally, when a class is instantiated that doesn't already exist, PHP executes the <a href=\"http://www.php.net/manual/en/function.autoload.php\" rel=\"nofollow\"><code>__autoload()</code></a> magic function, allowing it to <code>include</code>/<code>require</code> the class' file as necessary.</p>\n\n<p>As so often, compared to having a manually written, hand-tuned and very precise include/require strategy, there's will be a negative performance impact.</p>\n\n<p>However, compared to \"just include everything on every run\", an autoloader is a big performance benefit, as you then only pull into memory exactly the classes that you need.</p>\n\n<p>My recommendation for solution, is <em>not</em> to implement <code>__autoload</code>, but rather stick with <a href=\"https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md\" rel=\"nofollow\">PSR-0</a> loading. PSR-0 is an autoloading standard used by a <a href=\"http://www.php-fig.org/\" rel=\"nofollow\">large number of large projects</a>. For the vast majority of use-cases, it's \"good enough\".</p>\n\n<p>Using PSR-0 means you can also autoload any of the classes from other projects that use the standard, which makes interoperability much, much, easier.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T10:23:05.643", "Id": "23982", "ParentId": "23976", "Score": "2" } } ]
{ "AcceptedAnswerId": "23977", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T20:46:24.727", "Id": "23976", "Score": "1", "Tags": [ "php", "object-oriented" ], "Title": "PHP Class that handles all includes / required files" }
23976
<p>I initialized a tree using a nested hash as input, but when I recursively call <code>Tree.new</code> on the children, it doesn't seem to pass each child as a hash. As a pretty ugly, but working, alternative, I translated everything to arrays.</p> <p>Is there a way to preserve the hash?</p> <p>I'm doing this exercise using Ruby 1.9.3, so I can't use Ruby 2.0.0's <code>to_h</code> method.</p> <pre><code>class Tree attr_accessor :node_name, :children def initialize(arr) arr = arr.to_a unless arr.is_a?(Array) arr.flatten! @node_name = arr.first @children = [] arr.last.each { |c| @children &lt;&lt; Tree.new(c) } end def visit(&amp;block) block.call self end def visit_all(&amp;block) visit &amp;block children.each { |c| c.visit_all(&amp;block) } end end family_tree = Tree.new({'grandpa' =&gt; { 'dad' =&gt; { 'child 1' =&gt; {}, 'child 2' =&gt; {} }, 'uncle' =&gt; {'child 3' =&gt; {}, 'child 4' =&gt; {} } } }) family_tree.visit_all { |node| p node.node_name } </code></pre>
[]
[ { "body": "<p>Some notes:</p>\n\n<ul>\n<li>The <code>initialize</code> method of a class should be its most basic and fundamental constructor, don't use it as a \"helper\". A tree has a name and some children, so these should be the arguments. You want to construct a Tree from a hash to make things easier for the caller? then create a helper classmethod, for example <code>Tree::new_from_hash(hash)</code>.</li>\n<li><code>Tree#visit</code>. That's an imperative construct, I'd write first the functional ones (which can also be used imperatively if needed).</li>\n<li><code>node.node_name</code>: That repetition is a cue that <code>node_name</code> is redundant, <code>name</code> is enough.</li>\n<li>(Subjective) I prefer to write hash literals without losing indentation space.</li>\n</ul>\n\n<p>I'd write (I'd inherit from <code>Struct</code> to save some lines, not really needed):</p>\n\n<pre><code>class Tree &lt; Struct.new(:name, :children)\n def self.new_from_hash(hash)\n name, children_hash = hash.first\n children = children_hash.map { |k, v| Tree.new_from_hash({k =&gt; v}) }\n Tree.new(name, children)\n end\n\n def visit_all(&amp;block)\n yield(self)\n children.each { |c| c.visit_all(&amp;block) }\n end\nend\n\nfamily_tree = Tree.new_from_hash({\n 'grandpa' =&gt; {\n 'dad' =&gt; {'child 1' =&gt; {}, 'child 2' =&gt; {}},\n 'uncle' =&gt; {'child 3' =&gt; {}, 'child 4' =&gt; {}},\n },\n})\n\nfamily_tree.visit_all { |node| puts node.name }\n</code></pre>\n\n<p>Additional notes:</p>\n\n<ul>\n<li>Include module <code>Enumerable</code> and implement <code>Tree#each</code> so you can use all enumerable methods for you trees. Note that enumerable methods assume a single-level iteration, so you'd still need custom methods (like <code>visit_all</code>/<code>map_all</code>) that perform nested operations.</li>\n<li>If that's a learning code I'd explore this path: create a <code>NestedEnumerable</code> module -very similar to <code>Enumerable</code>- which would provide some <code>xyz_all</code> (or <code>xyz_nested</code>, whatever) methods. Like <code>Enumerable</code>, you would only be required to implement the \"each\" method (i.e. <code>each_all</code>).</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T04:06:15.377", "Id": "37012", "Score": "0", "body": "Thanks, this is exactly what I needed. I am doing this as a learning exercise. https://gist.github.com/yubrew/5175022 I implemented the Enumerable, but not really sure what to do to make NestedEnumerable. I'm not sure how to recognize 'children' inside NestedEnumerable. Is there some tutorial or a hint you can give me?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T09:33:12.303", "Id": "37017", "Score": "0", "body": "Ruby is not very orthodox on that matter, if you include `Enumerable` you get methods on each element individually, that may or may not be useful. On custom data containers the idea is that map/select/reject/... equivalents return the same input structure, with the block applied/filtering the value of each node (here you only have `name` to play with). That's for example how Haskell and Functors work (see `fmap` for a `Tree` for example). If you're not familiar with the language is quite a task to understand it though. http://learnyouahaskell.com/functors-applicative-functors-and-monoids" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T09:36:34.467", "Id": "37018", "Score": "0", "body": "At the end it all depends on what operations you want on the trees. `visit` has the problem that only works through side-effects. That's a pity in a language like Ruby. More on functional programming: https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T12:26:13.667", "Id": "23986", "ParentId": "23979", "Score": "1" } } ]
{ "AcceptedAnswerId": "23986", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T04:49:51.960", "Id": "23979", "Score": "1", "Tags": [ "ruby", "tree" ], "Title": "Making a tree with hash input" }
23979
<p>Here is a solution to the <a href="http://pl.spoj.com/problems/JPESEL/" rel="nofollow">SPOJ's JPESEL problem</a>. Basically the problem was to calculate cross product of 2 vectors modulo 10. If there is a positive remainder, it's not a valid <a href="http://en.wikipedia.org/wiki/PESEL" rel="nofollow">PESEL number</a>; (return <code>D</code>) if the remainder equals <code>0</code>, it's a valid number (return <code>N</code>).</p> <pre><code>import re, sys n = input() t = [1,3,7,9,1,3,7,9,1,3,1] while(n): p = map(int, re.findall('.',sys.stdin.readline())) # Another approach I've tried in orer to save some memory - didn't help: # print 'D' if sum([int(p[0]) * 1,int(p[1]) * 3,int(p[2]) * 7,int(p[3]) * 9,int(p[4]) * 1,int(p[5]) * 3,int(p[6]) * 7,int(p[7]) * 9,int(p[8]) * 1,int(p[9]) * 3,int(p[10]) * 1]) % 10 == 0 else 'N' print 'D' if ( sum(p*q for p,q in zip(t,p)) % 10 ) == 0 else 'N' n-=1 </code></pre> <p>The solution above got the following results at SPOJ:</p> <p>Time: 0.03s<br> Memory: 4.1M</p> <p>where the best solutions (submitted in Python 2.7) got:</p> <p>Time: 0.01s<br> Memory: 3.7M</p> <p>How can I optimize this code in terms of time and memory used?</p> <p>Note that I'm using different function to read the input, as <code>sys.stdin.readline()</code> is the fastest one when reading strings and <code>input()</code> when reading integers.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T17:58:26.517", "Id": "36992", "Score": "0", "body": "Why do you need to read from STDIN? I guess it will be faster with a file." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T18:02:45.890", "Id": "36993", "Score": "0", "body": "You mean to read the whole input at once? I need STDIN because that's how the program sumbitted to SPOJ should work." } ]
[ { "body": "<p>Likely what is taking up extra time is the line:</p>\n\n<pre><code> p = map(int, re.findall('.',sys.stdin.readline()))\n</code></pre>\n\n<p>There are a few things here. Firstly, regular expressions are relatively expensive. Underneath, it likely needs to compile the regular expression (which in this case is very simple, but still). Further, you don't need regular expressions to do this in python. For example, assume the string was something like <code>'343898934'</code>. Then this is equivalent to:</p>\n\n<pre><code>p = [int(k) for k in '343898934']\n</code></pre>\n\n<p>The above will likely be slightly faster.</p>\n\n<p>The second place here that could be optimized (memory wise) is that <code>map</code> in Python 2.x returns a list as opposed to a generator. So instead we could do:</p>\n\n<pre><code>p = (int(k) for k in sys.stdin.readline())\n</code></pre>\n\n<p>The fact that this also removes the <code>re</code> import may also impact timing and memory usage, depending on how they measure.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T13:40:28.347", "Id": "36977", "Score": "0", "body": "Thanks. I understand it should run faster after such changes but I've changed my solution exactly as you said and now it's actually slower: time: `0.11`, memory: `4.5M`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T14:22:07.750", "Id": "36981", "Score": "0", "body": "Interesting. I can understand that it might be slower (perhaps the overhead of setting up a generator here is worse than simply creating a small list). Likewise the memory usage. Perhaps try using the list comprehension version?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T17:26:45.377", "Id": "36991", "Score": "0", "body": "After changing to list comprehension: time: `0.12` (longer), memory: `4.5M` (same as before). I'm wondering whether this can be related to SPOJ's timing system." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T18:33:25.773", "Id": "36994", "Score": "0", "body": "`map` can be faster here (you can test it with [timeit](http://docs.python.org/2.7/library/timeit.html) module). I think you should try `readline = sys.stdin.readline` before the loop and then `map(int, readline().rstrip())` inside the loop." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T12:07:39.340", "Id": "23985", "ParentId": "23981", "Score": "1" } }, { "body": "<p>You can try to replace <code>re</code> module with just a <code>sys.stdin.readline()</code> and replace <code>zip</code> interator with <code>map</code> and <code>mul</code> function from <a href=\"http://docs.python.org/2.7/library/operator.html\" rel=\"nofollow\">operator</a> module like this:</p>\n\n<pre><code>from sys import stdin\nfrom operator import mul\n\nreadline = stdin.readline\nn = int(readline())\nt = [1,3,7,9,1,3,7,9,1,3,1]\n\nwhile n:\n p = map(int, readline().rstrip())\n print 'D' if (sum(map(mul, t, p)) % 10) == 0 else 'N'\n n -= 1\n</code></pre>\n\n<h2>Update</h2>\n\n<p>It seems getting item from a small dictionary is faster than <code>int</code> so there is a version without <code>int</code>:</p>\n\n<pre><code>from sys import stdin\n\nreadline = stdin.readline\nval = {\"0\": 0, \"1\": 1, \"2\": 2, \"3\": 3, \"4\": 4, \"5\": 5, \"6\": 6,\n \"7\": 7, \"8\": 8, \"9\": 9}\nval3 = {\"0\": 0, \"1\": 3, \"2\": 6, \"3\": 9, \"4\": 12, \"5\": 15, \"6\": 18,\n \"7\": 21, \"8\": 24, \"9\": 27}\nval7 = {\"0\": 0, \"1\": 7, \"2\": 14, \"3\": 21, \"4\": 28, \"5\": 35, \"6\": 42,\n \"7\": 49, \"8\": 56, \"9\": 63}\nval9 = {\"0\": 0, \"1\": 9, \"2\": 18, \"3\": 27, \"4\": 36, \"5\": 45, \"6\": 54,\n \"7\": 63, \"8\": 72, \"9\": 81}\n\nn = int(readline())\nwhile n:\n # Expects only one NL character at the end of the line\n p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, _ = readline()\n print 'D' if ((val[p1] + val3[p2] + val7[p3] + val9[p4]\n + val[p5] + val3[p6] + val7[p7] + val9[p8]\n + val[p9] + val3[p10] + val[p11]) % 10 == 0) else 'N'\n n -= 1\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T19:12:36.463", "Id": "36999", "Score": "0", "body": "Much better time: `0.02` (is it because of using `readline()` instead of `input()`?), slightly better memory: `4.0M`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T16:10:47.063", "Id": "37040", "Score": "0", "body": "(after your update) It's still slower than the best implementations on SPOJ but I've learned a few things - thanks." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T18:49:19.997", "Id": "23993", "ParentId": "23981", "Score": "1" } }, { "body": "<p>There are a few tricks you can try to improve upon hdima's answer.</p>\n\n<ul>\n<li>Put all the code in a function because <a href=\"http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Local_Variables\" rel=\"nofollow\">Python accesses local variables more efficiently than global variables.</a></li>\n<li><code>for i in xrange(n)</code> is faster than <code>while n: n -= 1</code>, but even better is to avoid the counter variable:</li>\n<li>Use <code>itertools.islice</code> to read <code>n</code> lines: <code>for line in islice(stdin, n)</code></li>\n<li><code>stdout.write('D\\n')</code> is faster than <code>print 'D'</code></li>\n<li>Even faster is to write all once by <code>stdout.write(\"\".join( &lt;list comprehension&gt; ))</code> but this makes memory usage dependent on size of input. To avoid that, you could add an outer loop that splits the work in chunks.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T08:24:31.737", "Id": "24032", "ParentId": "23981", "Score": "1" } } ]
{ "AcceptedAnswerId": "23993", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T09:30:44.913", "Id": "23981", "Score": "1", "Tags": [ "python", "optimization", "programming-challenge", "python-2.x" ], "Title": "SPOJ \"Pesel\" challemge" }
23981
<p>I am searching a recursive solution space and would like to return the first match I find. (I am using this to solve sudoku, but I guess this would apply to any recursively defined problem or datastructure).</p> <p>So, in pseudocode, I need to call a function repeatedly with a set of possible input values, and return the first non-nil result:</p> <pre><code>for each possible input i: r = do-something(i) if r &lt;&gt; nil: return r return nil </code></pre> <p>My first attempt was to just translate this into clojure:</p> <pre><code>(defn find-first [func values] (loop [v values] (if (empty? v) nil (if-let [ret (func (first v))] ret (recur (rest v)))))) </code></pre> <p>But whenever I use (loop) it feels like I am programming C and not clojure, so I tried looking at this as applying a function to a sequence and returning the first non-nil result:</p> <pre><code>(defn find-first-2 [do-something range] (-&gt;&gt; range (map do-something) (remove nil?) first)) </code></pre> <p>This looks more like clojure, and should work the same way because of lazy sequences. However, lazy sequences actually chunk items in sets of 32, so when my ranges are shorter than 32 items this isn't really lazy at all.</p> <p>I have found the "<a href="https://stackoverflow.com/questions/3407876/how-do-i-avoid-clojures-chunking-behavior-for-lazy-seqs-that-i-want-to-short-ci">unchunk</a>"-trick creating really lazy sequences, but this also doesn't really "feel" right...</p> <p>What would be other ways of implementing this?</p>
[]
[ { "body": "<p>You can use <code>drop-while</code> instead of mapping over the given sequence.</p>\n\n<pre><code>(defn find-first-3 [do-something range]\n (first (drop-while #(nil? (do-something %)) range)))\n</code></pre>\n\n<p>This should be minimally lazy (since you don't need laziness here), won't traverse unnecessary parts of the list, and concise.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T20:00:20.257", "Id": "37055", "Score": "0", "body": "Hm, but I need the result of do-something (that will be my solved sudoku-board), so wouldn't I need to do: (first (drop-while nil? (map do-something range)))" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T09:32:12.323", "Id": "37078", "Score": "0", "body": "In that case, you can just call `do-something` as the last step (you may need to check non-`nil`)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T17:32:19.980", "Id": "24015", "ParentId": "23983", "Score": "0" } }, { "body": "<p>If the non-nil results of <code>do-something</code> are guaranteed to be logical true, you can easily use <a href=\"http://clojuredocs.org/clojure_core/clojure.core/some\" rel=\"nofollow\"><code>some</code></a>:</p>\n\n<blockquote>\n <p>(some pred coll) </p>\n \n <p>Returns the first logical true value of (pred x) for any x in coll,\n else nil. One common idiom is to use a set as pred, for example\n this will return :fred if :fred is in the sequence, otherwise nil:\n (some #{:fred} coll)</p>\n</blockquote>\n\n<pre><code>(defn find-first-3\n [do-something range]\n (some do-something range)\n)\n</code></pre>\n\n<p>If you expect <code>do-something</code> to return <code>false</code> as possible, non-nil value, you could use <a href=\"http://clojuredocs.org/clojure_core/clojure.core/keep\" rel=\"nofollow\"><code>keep</code></a>:</p>\n\n<blockquote>\n <p>(keep f coll) </p>\n \n <p>Returns a lazy sequence of the non-nil results of (f item). Note,\n this means false return values will be included. f must be free of\n side-effects.</p>\n</blockquote>\n\n<pre><code>(defn find-first-4\n [do-something range]\n (first (keep do-something range))\n)\n</code></pre>\n\n<p>As for the chunk-issue: You should not bother if you're not hitting any performance issues or other problems. Otherwise, if you <em>really</em> want to get rid of it, the unchunk-trick you mentioned is totally fine IMHO, until Clojure will offer an official, built-in option (maybe it will someday).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T14:28:17.000", "Id": "37183", "Score": "0", "body": "ah, (some) is exactly what I am looking for. As for performance issues, I have several ideas for algorithms I would like to try, and to be able to compare the relative performance of these, atleast I need to make sure that they are not doing any un-neccessary work. (My current example is solving sudoku, and I am pretty sure there is only one solution to each puzzle, ie. it is futile to search for more solutions after finding one)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T12:44:32.337", "Id": "24100", "ParentId": "23983", "Score": "2" } } ]
{ "AcceptedAnswerId": "24100", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T10:47:53.203", "Id": "23983", "Score": "2", "Tags": [ "clojure", "recursion" ], "Title": "Finding first match in recursive search" }
23983
<p>I would like to know if this is being done correctly.</p> <pre><code>using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Linq; using System.Text; public class InnerJoinTables { public List&lt;InnerJoinTable&gt; Items = new List&lt;InnerJoinTable&gt;(); } public class InnerJoinTable { public int ID { get; set; } public string RightTable { get; set; } public string LeftTable { get; set; } public InnerJoinTable(int ID, string RightTable, string LeftTable) { this.ID = ID; this.RightTable = RightTable; this.LeftTable = LeftTable; } } </code></pre> <p>Calling code:</p> <pre><code>InnerJoinTables m = new InnerJoinTables(); m.Items.Add(new InnerJoinTable(1, "A", "B")); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T14:15:47.803", "Id": "36978", "Score": "1", "body": "Does it seem to work? What exactly are you worried about? Why do you think it might not be the correct way?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T16:30:41.627", "Id": "36987", "Score": "0", "body": "You can achieve the same result using a stored procedure, an ORM or LINQ. What do you find the need to implement this join yourself?" } ]
[ { "body": "<p>The code will work, so from that point of view, it is correct.</p>\n\n<p>But there are also some issues with it:</p>\n\n<ol>\n<li>I don't see any reason for the <code>InnerJoinTables</code> class to exist. You should just use <code>List&lt;InnerJoinTable&gt;</code> directly in the calling code. That's unless there's something else going on that you're not showing.</li>\n<li>Public fields should not be used. Use a property instead.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T14:18:36.960", "Id": "23989", "ParentId": "23987", "Score": "6" } }, { "body": "<p>You can directly derive your InnerJoinTables class with List. Then you can use it as normal list object. No need of having items as member there. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T13:14:28.507", "Id": "37170", "Score": "2", "body": "This is not necessarily a good idea. I prefer composition over inheritance, given a choice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T22:39:53.363", "Id": "37292", "Score": "0", "body": "Could you explain how is that better than using `List` directly?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-09T08:09:51.833", "Id": "38463", "Score": "0", "body": "It just change the way you would use that object in your code. If you have an InnerJoinTables and Items as collection of InnerJoinTable object. Each time you want to access the object you would write innerJoinTables.Items.Add(). If you just have it derived with list then it would be like innerJoinTables.Add(new InnerJoinTable()), that's why I thought its better than using list directly." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T12:11:38.797", "Id": "24097", "ParentId": "23987", "Score": "0" } } ]
{ "AcceptedAnswerId": "23989", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T14:01:23.667", "Id": "23987", "Score": "0", "Tags": [ "c#", "object-oriented", "generics" ], "Title": "Creating and populating a generic list" }
23987
<p>I received the following feedback for my code:</p> <hr> <p>"I still do not see a design here that will work.</p> <p>It is a very bad idea to have the big switch and loop at this point. All you need in your <code>main()</code> method is to create one object of each class and call the methods on them.</p> <h3>In class <code>Contact</code>:</h3> <ul> <li>Every class needs a comment. The first thing you need to do is to write a comment for this class that starts with the words "one object of this class stores..." Once you are very clear on what one object of this class represents, the rest of the program (and my comments) will make sense. Until you can write a comment like this, nothing will make sense.</li> <li>any method in this class has access to only one single contact. Therefore, your method <code>printContacts()</code> does not belong here.</li> <li>every method should do just one thing. Therefore, the method <code>printContacts()</code> — whatever class it is in — will <em>not</em> both read and print.</li> <li>I really think you need to throw away that method <code>printContacts()</code>. I don't believe that you will ever use that code. That is exactly why I asked you to leave all the method definitions blank for this deliverable.</li> <li>the welcome and the menu do not belong inside this class either. Methods in this class all must pertain <em>only</em> to exactly <em>one</em> contact</li> </ul> <h3>In class <code>ContactArray</code>:</h3> <p>I have no idea what this class is supposed to do, since you have no comment.</p> <p>I still do not see a design here that will work for this project. What you need is three classes:</p> <ol> <li>one class where one object of the class stores and manipulates the contact info for one person.</li> <li>one class where one object of the class stores and manipulates the info for all of the people in the whole list. I do not see a class like this in your code, and that is why your design will not work.</li> <li>one class with just a simple <code>main()</code> that just creates one object of each of the other two classes and calls all the methods on them. This is just for testing, to see that you know what each object represents and what you can do with each object.</li> </ol> <p>The lesson here is to <em>never</em> try to code a class before you can write a comment that tells what one object of the class represents. Writing in Java is so much harder than writing in English, if you can't write it in English, you will never be able to write it in code.</p> <p>The lack of comments for each class tells me that it was not reviewed carefully, quietly and independently by each team member. All of you have been working with the program guidelines all quarter, and so all of you should have caught this omission.</p> <p>Please take your time and come up with a design that contains exactly three classes, as I described above. No menu, no user input, no code inside the <code>{ }</code> of the method definitions (except <code>main()</code>). <em>No file I/O</em>!</p> <p>We are just trying to get a workable design here, struggling with the compiler is a time drain."</p> <hr> <p>This is my code. </p> <h3>CONTACTLIST.JAVA</h3> <pre><code>import java.util.Scanner; public class ContactList { public static void main(String args[]) { Scanner reader = new Scanner(System.in); reader.useDelimiter("\n"); ContactRunner runner; runner = new ContactRunner(reader); runner.run(); } } </code></pre> <h3>CONTACT.JAVA</h3> <pre><code>import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class Contact { private String lastname, firstname, address, city, zip, email, phone, notes; public Contact(String lastnamename, String firstname, String address, String city, String zip, String email, String phone, String notes, String lastname) { this.lastname = lastname; this.firstname = firstname; this.address = address; this.city = city; this.zip = zip; this.email = email; this.phone = phone; this.notes = notes; } public Contact() { } // overrides the default Object method public String toString() { return lastname + ", " + firstname + ", " + address + ", " + city + ", " + zip + ", " + email + ", " + phone + ", " + notes; } /* * Sets the value for lastname to "s". */ void setLastName(String s) { lastname = s; } /* * Returns the value of lastname. */ String getLastName() { return lastname; } /* * Sets the value for firstname to "a". */ void setFirstName(String a) { firstname = a; } /* * Returns the value of firstname. */ String getFirstName() { return firstname; } /* * Sets the value for address to "b". */ void setHouseAddress(String b) { address = b; } /* * Returns the value of address. */ String getHouseAdress() { return address; } /* * Sets the value for city to "c". */ void setCity(String c) { city = c; } /* * Returns the value of city. */ String getCity() { return city; } /* * Sets the value for zip to "d". */ void setZip(String d) { zip = d; } /* * Returns the value of zip. */ String getZip() { return zip; } /* * Sets the value for phone to "e". */ void setPhone(String e) { phone = e; } /* * Returns the value of phone. */ String getPhone() { return phone; } /* * Sets the value for email to "f". */ void setEmail(String f) { email = f; } /* * Returns the value of email. */ String getEmail() { return email; } /* * Sets the value for notes to "g". */ void setNotes(String g) { notes = g; } /* * Returns the value of notes. */ String getNotes() { return notes; } void welcome() { // Welcomes the user to the program for the first time. System.out.println("\nYou are in the Contact List DB. " + "What would you like to do? \n"); } void menu() { // Prints out user menu written by Daniela. System.out.println("1. Enter a new person" + "\n" + "2. Print the contact list" + "\n" + "3. Retrieve a person's information by last name" + "\n" + "4. Retrieve a person's information by email address" + "\n" + "5. Retrieve all people who live in a given zip code" + "\n" + "6. Exit"); } void printContacts() { // Read from file, print to console. by Damani Brown &amp; Seth // ---------------------------------------------------------- int counter = 0; String line = null; // Location of file to read File file = new File("contactlist.csv"); // Sort contacts and print to console try { Scanner scanner = new Scanner(file); // Before printing, add each line to a sorted set. by Seth // Copeland Set&lt;String&gt; lines = new TreeSet&lt;&gt;(); while (scanner.hasNextLine()) { line = scanner.nextLine(); lines.add(line); counter++; } // Print sorted contacts to console. for (String fileLine : lines) { String outlook = fileLine.substring(0, 1).toUpperCase() + fileLine.substring(1); System.out.println(outlook); } // --------------------------------------------------------------------- // Sort contacts code. by Seth Copeland scanner.close(); } catch (FileNotFoundException e) { } System.out.println("\n" + counter + " contacts in records.\n"); } } </code></pre> <h3>CONTACTARRAY.JAVA</h3> <pre><code>import java.io.FileWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class ContactArray { private static Scanner reader; public static void getContact() { reader = new Scanner(System.in); reader.useDelimiter("\n"); /** * Array list created by Daniela Villalobos, used to create running list * of object contacts with lastname, firstname, address, city, zip, * phone, email, and notes */ ArrayList&lt;Contact&gt; contacts = new ArrayList&lt;Contact&gt;(); Contact contact; contact = new Contact(); /** * Gets users contact information and adds the contact as a string in * our contact arraylist. - written by Daniela Vallalobos. */ /** * Gets users contact information and adds the contact as a string in * our contact arraylist. - written by Daniela Vallalobos. */ System.out.println("\nEnter Contact Last Name:"); String lastname = reader.next(); if (lastname == null) { System.out.println("Invalid entry.\n"); } else { contact.setLastName(lastname); } System.out.println("Enter Contact First Name: "); contact.setFirstName(reader.next().toLowerCase()); System.out.println("Enter Contact Street Address: "); contact.setHouseAddress(reader.next().toLowerCase()); System.out.println("Enter Contact City: "); contact.setCity(reader.next().toLowerCase()); System.out.println("Enter Contact Zip Code: "); contact.setZip(reader.next().toLowerCase()); System.out.println("Enter Contact Email: "); contact.setEmail(reader.next().toLowerCase()); System.out.println("Enter Contact Phone Number: "); contact.setPhone(reader.next().toLowerCase()); System.out.println("Enter Contact Notes: "); contact.setNotes(reader.next().toLowerCase()); contacts.add(contact); /** * Writes contact information from user to file written by Damani Brown */ FileOperations.write(); Contact c = contact; try (PrintWriter output = new PrintWriter(new FileWriter( "contactlist.csv", true))) { output.printf("%s\r\n", c); } catch (Exception e) { } System.out.println("Your contact has been saved.\n"); } } </code></pre> <p><strong>CONTACTRUNNER.JAVA</strong></p> <pre><code>import java.util.Scanner; public class ContactRunner { private Scanner reader; public ContactRunner(Scanner reader) { this.run(); } public void run() { Contact contact; contact = new Contact(); int action = 0; contact.welcome(); /** * While loop created to bring up user's choices - loop written by * Daniela Villalobos */ while (action != 6) { contact.menu(); reader = new Scanner(System.in); reader.useDelimiter("\n"); action = reader.nextInt(); /* * DV - if statement permits only actions 1-6 to execute a case */ if (action &lt;= 0 || action &gt; 6) { System.out.println("Invalid selection. "); } /** * Switch statement written by Daniela Villalobos */ switch (action) { case 1: { /** * Gets users contact information and adds the contact as a * string in our contact arraylist. - written by Daniela * Vallalobos. */ ContactArray.getContact(); break; } /** * Prints out all records from file in alphabetical order */ case 2: { contact.printContacts(); /** * Reads contacts from file, sorts and prints them to console. */ break; } /** * Ask's user to search for a lastname. Matches user input to record * of contacts, and prints out matching contact. - Coded by Seth &amp; * Damani */ case 3: { System.out.println("\nEnter the last" + "name to search for: "); /** * Gets the searchterm from the user and Matches user input to * existing contact records. */ FileOperations.match(); break; } /** * Ask's user to search for a email. Matches user input to record of * contacts, and prints out matching contact. - Coded by Seth &amp; * Damani */ case 4: { System.out.println("\nEnter the email " + "address to search for: "); /** * Gets the searchterm from the user and Matches user input to * existing contact records. */ FileOperations.match(); break; } /** * Ask's user to search for a zipcode. Matches user input to record * of contacts, and prints out matching contact. - Coded by Seth &amp; * Damani */ case 5: { System.out.println("\nEnter the Zipcode " + "to search for: "); /** * Gets the searchterm from the user and Matches user input to * existing contact records. */ FileOperations.match(); break; } case 6: { System.out.println("\nNow quitting application..."); System.exit(action); } } } } } </code></pre> <h3>FILEOPERATIONS.JAVA</h3> <pre><code>import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Scanner; public class FileOperations { private static Scanner reader; public static void write() { // Creates and writes to file try { File file = new File("contactlist.csv"); // If file doesn't exists, then create it. if (!file.exists()) { file.createNewFile(); } } catch (IOException e) { e.printStackTrace(); } } static void match() { // Matches user input to existing contact records. try { // Open the file as a buffered reader BufferedReader bf = new BufferedReader(new FileReader( "contactlist.csv")); // Start a line count and declare a string to hold our // current line. int linecount = 0; String line; reader = new Scanner(System.in); String searchterm = reader.next(); // Let the user know what we are searching for System.out.println("\nSearching for " + searchterm + " in file..."); // Loop through each line, putting the line into our line // variable. boolean noMatches = true; while ((line = bf.readLine()) != null) { // Increment the count and find the index of the word. linecount++; int indexfound = line.indexOf(searchterm); // If greater than -1, means we found a match. if (indexfound &gt; -1) { System.out.println("\nContact was FOUND\n" + "\nContact " + linecount + ": " + line); noMatches = false; } } // Close the file after done searching bf.close(); if (noMatches) { System.out.println("\nNO MATCH FOUND.\n"); } } // Catches any exception errors catch (IOException e) { System.out.println("IO Error Occurred: " + e.toString()); } } } </code></pre> <p>First she says we don't have enough classes and our <code>main</code> was too long. Suggested moving our <code>main</code> and our array list into different classes. We did that, and she's still says it's not a workable design. Program seem to run fine to me, how is it not workable? There is just no pleasing her. Can anyone translate her feedback into English so a beginner coder can understand. This is my 3rd time resubmitting this design document. We are already suppose to be starting the next step, but she won't let us continue until we have a "Workable" design. (yet program runs fine). So now I have to pretty much erase my whole code (which I worked countless days and nights on) and make a "workable" design/skeleton with pretty much no code that pleases her. Any help so that I can move forward would simply be AMAZING. </p> <p>Regards,</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T15:59:17.923", "Id": "36983", "Score": "3", "body": "Explaining what the code is supposed to be doing would be nice. A bit hard to review without any context. Also, could you perhaps give the question a real title?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T16:19:23.513", "Id": "36984", "Score": "1", "body": "The code is suppose to create a contact list where a user can add contacts, print all contacts to console, search a contact by last name, search a contact by email, and search a contact by zipcode." } ]
[ { "body": "<p>If I understand the requirements correctly, then you were tasked to <em>design</em> not to <em>implement</em> such a system. So you were asked to specify the interface, or API.</p>\n<h2>Example in English:</h2>\n<h3>Class Contact:</h3>\n<p>represents a contact. Has getters/setters for name, email, etc.</p>\n<h3>Class AddressBook:</h3>\n<p>a collection where contacts can be <code>add</code>ed and <code>remove</code>d. Provides <code>searchFoo</code> methods that take a string and returns a List of contacts whose <code>foo</code> field contains that string as substring (where <code>foo</code> is name, email, etc).</p>\n<p>(If you know SQL, the interface of <code>AddressBook</code> would mirror <code>INSERT foo</code>, <code>DELETE foo</code> and <code>SELECT foo WHERE bar</code> like actions)</p>\n<p>The AB also has a method to write a representation itself to a Writer, or to load contacts from a Reader. A constructor that would initialize the AB from a file would be pretty nifty.</p>\n<h3>Class Shell:</h3>\n<p>provides a text interface to <code>AddressBook</code>. Has methods to display forms like</p>\n<pre><code>Contact createContactDialog(); // guide the user through creating a new contact\nvoid changeContactDialog(Contact c); // change fields of existing contact\nvoid displayContact(Contact c); // just display the contact\nvoid searchDialog(); // start dialog to search the AB\n</code></pre>\n<p>Each Shell has fields <code>in</code> and <code>out</code> which are a Reader and Writer, and an <code>AddressBook ab</code>.</p>\n<p>The Shell has a <code>run</code> method which will start the shell, and basically handles the rest of the control flow. (Internally, this would be a <code>while (true)</code> loop that prompts the user for some action, and then dispatches appropriate dialogs. The loop (an the <code>run</code> method) is left by a command like <code>exit</code>)</p>\n<p>No other class will have user interface code!</p>\n<p>(Especially your <code>FileOperations</code> class is bad: This class is just a collection of helper functions, and does not represent a useful entity in itself. Classes containing only <code>static</code> stuff are not object oriented. Compare OOP to procedural programming, like in C or Pascal or whatnot)</p>\n<h3>The main():</h3>\n<p>Here you create some <code>Contact</code>s, put them into an <code>AddressBook</code>, create a <code>Shell</code> with that, and let it <code>run</code>.</p>\n<hr />\n<p>Now, you translate all that to Java (without specifying the implementation except for <code>main</code>), put pretty comments everywhere and are done.</p>\n<p>Some hints for the actual implementation:</p>\n<ul>\n<li>Don't require the user to type numbers. Use meaningful full-text commands (like <code>new</code>, <code>update</code>, <code>search</code>), or at least mnemonic letters (<code>c</code> for create, <code>u</code> for update, <code>/</code> for search, like in Vim). You can easily compare given input via regular expression. Java is quite good with “Regexes”.</li>\n<li>Don't lowercase the data in your contacts. If you want to search for contacts case-insensitively, then you can lowercase the data for comparision. However, storing the changed data is a bug, as lowercasing changes the meaning of text.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T19:32:07.600", "Id": "37053", "Score": "0", "body": "Sir, this was in English! Congrats. I had no clue what she was saying. But you've cleared it up. Thanks. Although it's only suppose to be three classes. This should be enough to get me started." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T18:33:32.960", "Id": "23992", "ParentId": "23990", "Score": "3" } } ]
{ "AcceptedAnswerId": "23992", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T15:43:28.663", "Id": "23990", "Score": "1", "Tags": [ "java", "array" ], "Title": "Help creating a workable design?" }
23990
<p>Say I have a data structure like this:</p> <pre><code>array(3) { ["id"]=&gt; int(1) ["name"]=&gt; string(3) "foo" ["message"]=&gt; array(1) { ["action"]=&gt; string(3) "PUT" } } </code></pre> <p>Where 'message' and 'action' are both optional. To check if they're present my first attempt would be to write something like this:</p> <pre><code>if (array_key_exists('message', $array) &amp;&amp; array_key_exists('action', $array['message'])){ } </code></pre> <p>Is there a cleaner implementation?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T00:40:26.233", "Id": "125246", "Score": "0", "body": "See also: http://stackoverflow.com/questions/2948948/array-key-exists-is-not-working You can write an array_key_exists utility function which works recursively." } ]
[ { "body": "<p>No, this is just the way of doing it.</p>\n\n<blockquote>\n <p>Even when I'm not limited to a certain script language, I can't think of an cleaner solution?</p>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T19:46:32.340", "Id": "23994", "ParentId": "23991", "Score": "2" } }, { "body": "<p>You can just do this!</p>\n\n<pre><code>if (isset($array[\"message\"][\"action\"])) { /*...*/ }\n</code></pre>\n\n<p>Proof:</p>\n\n<pre><code>&lt;?php\n\nerror_reporting(E_ALL);\nini_set('error_reporting', E_ALL);\nini_set('display_errors', 1);\n\n$array = [\n \"id\" =&gt; 1,\n \"name\" =&gt; \"foo\",\n \"message\" =&gt; [\n \"action\" =&gt; \"PUT\",\n ],\n];\n\nvar_dump(isset($array[\"message\"][\"action\"])); // true\n\n\n$array = [\n \"id\" =&gt; 1,\n \"name\" =&gt; \"foo\"\n];\n\nvar_dump(isset($array[\"message\"][\"action\"])); // false\n</code></pre>\n\n<p>No log entries.</p>\n\n<p>Do note that if your value is <code>null</code>, then isset will also return false. You probably shouldn't be creating values with <code>null</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-01T23:13:11.093", "Id": "125213", "Score": "0", "body": "This answer is also missing a `)` and may cause a log entry to be generated due to not checking `isset($array['message'])` before dereferencing it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-02T05:10:16.673", "Id": "125243", "Score": "0", "body": "@Brythan no it does not cause a log entry. But yes it is missing a `)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-02T05:21:53.177", "Id": "125244", "Score": "0", "body": "Sorry, I meant to point out that you'd have to crank your error reporting. It absolutely causes a log entry if you have your error reporting set for it. I've had it spam my logs with that previously. This was the default logging at one point. It may not be the default now (or your host may have dialed down error reporting), but I am absolutely sure that that situation can generate a log entry under certain configurations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-02T05:29:01.910", "Id": "125245", "Score": "0", "body": "No it really doesn't I tested it with all error reporting switched on!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-01T15:52:53.657", "Id": "68608", "ParentId": "23991", "Score": "3" } }, { "body": "<p>Not clearer but probably the fastest solution:</p>\n\n<pre><code>if ((isset($array[\"message\"][\"action\"]) ||\n (array_key_exists('message', $array) &amp;&amp; array_key_exists('action', $array['message']))) {\n /* ... */\n}\n</code></pre>\n\n<p>The second check is needed because some values evaluated with <code>isset()</code> will result false despite the index does exist.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-01T18:04:26.723", "Id": "68610", "ParentId": "23991", "Score": "1" } }, { "body": "<p>I'm using this in a project of mine, but I'm using <code>null</code> as a muted state. (php 5.6)</p>\n\n<pre><code>&lt;?php\n\nfunction &amp;option_select($options, $default, ...$path) {\n if(!isset($path[0])) { return $options; }\n $cursor = &amp;$options;\n foreach($path as $key) {\n if(isset($cursor[$key])) { $cursor = &amp;$cursor[$key]; } else { return $default; }\n } return $cursor;\n}\n</code></pre>\n\n<p>It's a function that will lookup a <code>path</code> in a tree.</p>\n\n<pre><code>echo option_select([A=&gt;[B=&gt;[C=&gt;'hello world']]], 'NO?', 'A', 'B', 'C');\n</code></pre>\n\n<p>As you can see. I'm looping over the values over a array: <code>path</code>. In the beginning I'm setting a cursor as reference to a array I have to search in. Every time I find a <code>new</code> key, I'm setting the reference of the cursor to the current key I'm searching for. If you have <code>xdebug</code> and a good GUI, you can rewrite it to the algorithm you want. It's the <code>isset($cursor[$key])</code> you have to change. Or inject it as a function: <code>f($cursor, $key, $default) =&gt; (bool)</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-29T01:45:04.370", "Id": "187138", "Score": "0", "body": "You have provided an alternate solution but have not reviewed the code. Please add explanation about why this would be a better solution for the OP, rather than what they already have." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-13T15:56:03.260", "Id": "191251", "Score": "0", "body": "Because it isn't strongly typed SirPython. This way i can test it with unit tests, without making a unit test for every 'hardcoded-string'. So has to with testability and the speed i can create working code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-28T23:28:45.860", "Id": "102226", "ParentId": "23991", "Score": "0" } }, { "body": "<p>Been looking for a similar solution myself and came up with this. Works to determine if the key is set at all - and will return TRUE even if the value of the \"action\" key is NULL.</p>\n\n<pre><code>if (isset($array['message']) &amp;&amp; array_key_exists('action',$array['message'])) {\n /* ... */\n}\n</code></pre>\n\n<p>If <code>$array['message']</code> has no keys, the <code>isset</code> will return FALSE stopping the IF statement. If <code>$array['message']</code> has any keys - even ones with NULL values - <code>isset</code> will return TRUE, allowing you to safely check if the <code>'action'</code> array key exists in <code>$array['message']</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-24T21:31:33.293", "Id": "123808", "ParentId": "23991", "Score": "0" } } ]
{ "AcceptedAnswerId": "23994", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T18:02:38.540", "Id": "23991", "Score": "8", "Tags": [ "php", "array" ], "Title": "Checking for existing key in multi-dimensional array" }
23991
<p>At the "if(a==2)" part of my code below, the android emulator takes 8 seconds to process and display some data in a list. I need to reduce this time to 1 second or less. I am accessing a 50 KB .txt file with 3200 lines, comparing each line with a string passed by another function, and whichever line matches the string, I am printing that in a list. The format of data in the .txt file is like this: </p> <pre><code>0,1&gt;Autauga; 0,2&gt;Baldwin; 0,3&gt;Barbour; 1,69&gt;Aleutians East; 1,68&gt;Aleutians West; </code></pre> <p>etc... and it goes on for 3200 lines. The number before the comma is compared to the string I passed from another function. If they match, I print the line. Here is the code:</p> <pre><code>package com.example.countylists; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.StringTokenizer; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleAdapter; public class ListViewA extends Activity{ List&lt;HashMap&lt;String, String&gt;&gt; fillMaps = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;(); int a=1;//stores instance number of the list /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ListView lv= (ListView)findViewById(R.id.listview); String newString;//item clicked in previous list int instanceposition;//tells me which instance number is running int position=0;//position of the click Bundle extras; if (savedInstanceState == null) { extras = getIntent().getExtras(); if(extras == null) { newString= null; instanceposition=1; Log.d(Integer.toString(instanceposition),"value of instanceposition"); a=instanceposition; position=0; } else { newString= extras.getString("Key"); instanceposition=extras.getInt("instpos"); Log.d(Integer.toString(instanceposition),"value of instanceposition"); a=instanceposition; position=extras.getInt("position"); } } else { newString= (String) savedInstanceState.getSerializable("Key"); } // create the grid item mapping String[] from = new String[] {"col_1"}; int[] to = new int[] {R.id.item2}; String[] array; Log.d(Integer.toString(a),"value of a"); //list of states if(a==1) { String z=""; try{ InputStream is = getAssets().open("USSTATES.txt"); InputStreamReader iz=new InputStreamReader(is); BufferedReader bis = new BufferedReader(iz); int v=0; v=count("USSTATES.txt"); Log.d(Integer.toString(v),"value of v"); array=new String[v]; for(int i=0;i&lt;v;i++){ z=bis.readLine(); array[i]=z; } // prepare the list of all records for(int q = 0; q &lt;v; q++){ HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); map.put("col_1", array[q]); fillMaps.add(map); lv.setOnItemClickListener(onListClick); } }catch(Exception E){E.printStackTrace(); } } else if(a==2){ String z=""; try{ InputStream is = getAssets().open("USCOUNTIES.txt"); InputStreamReader iz=new InputStreamReader(is); BufferedReader bis = new BufferedReader(iz); int v=0; //finding no. of counties to be displayed v=count("USCOUNTIES.txt"); int counter=0; String pos; pos=Integer.toString(position); try{ for(int i=0;i&lt;v;i++){ z=bis.readLine(); //int x=pos.length(); boolean a; //using stringtokenizer StringTokenizer st = new StringTokenizer(z, ","); String substring; substring=(String) st.nextElement(); a=substring.equals(pos); if(a==true){ counter=counter+1; } }}catch(Exception e){e.printStackTrace();} String array1[]=new String[counter]; try{ InputStream ig = getAssets().open("USCOUNTIES.txt"); InputStreamReader ia=new InputStreamReader(ig); BufferedReader bos = new BufferedReader(ia); int j=0; for(int i=0;i&lt;v;i++){ z=bos.readLine(); Log.d(z,"Value of zyo"); String[] split = z.split(","); if(split[0].equals(pos)){ array1[j]=split[1]; j=j+1; } }} catch(Exception e){e.printStackTrace();} Log.d(Integer.toString(v),"value of v(when a is 1)"); // prepare the list of all records for(int q = 0; q &lt;v; q++){ HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); map.put("col_1", array1[q]); fillMaps.add(map); lv.setOnItemClickListener(onListClick); } }catch(Exception E){E.printStackTrace(); } } a=a+1; // fill in the grid_item layout SimpleAdapter adapter = new SimpleAdapter(this, fillMaps, R.layout.grid_item, from, to); lv.setAdapter(adapter); } private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener(){ public void onItemClick(AdapterView&lt;?&gt; parent,View view, int position, long id) { Intent i=new Intent(ListViewA.this,ListViewA.class); i.putExtra("Key",fillMaps.get(position)); i.putExtra("instpos", a); i.putExtra("position",position); startActivity(i); } }; public int count(String filename) throws IOException { InputStream is = getAssets().open(filename); BufferedInputStream bis = new BufferedInputStream(is); try { byte[] c = new byte[1024]; int count = 0; int readChars = 0; boolean empty = true; while ((readChars = bis.read(c)) != -1) { empty = false; for (int i = 0; i &lt; readChars; ++i) { if (c[i] == '\n') { ++count; } } } return (count == 0 &amp;&amp; !empty) ? 1 : count+1; } finally { bis.close(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T04:09:00.407", "Id": "37013", "Score": "1", "body": "onCreate could really do with some splitting up into separate methods." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T09:00:56.430", "Id": "37015", "Score": "0", "body": "@Tyriar Will that give it a time advantage or just improve the cosmetic looks of the code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T09:42:02.890", "Id": "37019", "Score": "1", "body": "No impact on performance, but it's more modular and therefore maintainable and readable. Currently your code says onCreate \"do a bunch of stuff\", calling methods name that stuff." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T02:03:32.410", "Id": "37233", "Score": "1", "body": "It looks like you are going to read the same file 3 times. Please provide a small and clear code (the relevant part of the code) and an written example, so one could be able to see the problem without spending a lot of time figuring out what is happening or should happen." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-24T04:01:31.300", "Id": "39382", "Score": "0", "body": "as @tb- said please provide code with more comments and state your requirement clearly." } ]
[ { "body": "<ol>\n<li><p>These streams are never closed:</p>\n\n<blockquote>\n<pre><code>InputStream is = getAssets().open(\"USSTATES.txt\");\nInputStreamReader iz = new InputStreamReader(is);\nBufferedReader bis = new BufferedReader(iz);\n</code></pre>\n</blockquote>\n\n<p>You should close them in a <code>finally</code> block or use try-with-resources. See <em>Guideline 1-2: Release resources in all cases</em> in <a href=\"http://www.oracle.com/technetwork/java/seccodeguide-139067.html\" rel=\"nofollow noreferrer\">Secure Coding Guidelines for the Java Programming Language</a></p></li>\n<li><p>(Refactored code)</p>\n\n<pre><code>String line = bis.readLine();\nStringTokenizer st = new StringTokenizer(line, \",\");\nString substring = (String) st.nextElement();\nboolean a = substring.equals(pos);\nif (a == true) {\n counter = counter + 1;\n}\n</code></pre>\n\n<p>The code does not use too much from the <code>StringTokenizer</code>. The following is the same:</p>\n\n<pre><code>final boolean a = line.startsWith(pos + \",\");\nif (a) {\n counter++;\n}\n</code></pre>\n\n<p>I guess it might be faster. </p></li>\n<li><pre><code>String array1[] = new String[counter];\n</code></pre>\n\n<p>You could use an <code>ArrayList</code> which doesn't need a size on creation (it grows if you add elements to it), so you could eliminate the file reading which counts the lines as well as the second loop (including the second file reading) which counts the matching lines just to create a suitable sized array which will be used in the third loop.</p></li>\n<li><pre><code>String[] split = z.split(\",\");\nif (split[0].equals(pos)) {\n array1.add(split[1]);\n j = j + 1;\n}\n</code></pre>\n\n<p>Set the limit parameter of <code>split</code> if you are not using all values of the result array:</p>\n\n<pre><code>final String[] split = z.split(\",\", 3);\nif (split[0].equals(pos)) {\n array1.add(split[1]);\n j = j + 1;\n}\n</code></pre>\n\n<p>It could improve performance.</p></li>\n<li><blockquote>\n<pre><code>public int count(String filename) throws IOException {\n</code></pre>\n</blockquote>\n\n<p>A more descriptive method name would be better. What does this method count? Put it into the method name! I guess <code>countLines</code> would be fine.</p></li>\n<li><p>Short variable names are hard to read:</p>\n\n<blockquote>\n<pre><code>byte[] c = new byte[1024];\n</code></pre>\n</blockquote>\n\n<p>I suppose you have autocomplete, so using longer names does not mean more typing but it would help readers and maintainers a lot since they don't have to remember the purpose of each variable - the name would express the programmers intent. (<em>Clean Code</em> by <em>Robert C. Martin</em>, <em>Avoid Mental Mapping</em>, p25)</p>\n\n<p><code>buffer</code> would do it.</p></li>\n<li><p>If there is an error you should handle it, or maybe show an error message to the user instead of the <code>printStackTrace</code>:</p>\n\n<blockquote>\n<pre><code> } catch (Exception e) {\n e.printStackTrace();\n }\n</code></pre>\n</blockquote>\n\n<p>See also:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/q/3855187/843804\">It isn't the best idea to use <code>printStackTrace()</code> in Android exceptions</a></li>\n<li><a href=\"https://stackoverflow.com/q/10477607/843804\">Avoid printStackTrace(); use a logger call instead</a></li>\n<li><a href=\"https://stackoverflow.com/q/7469316/843804\">Why is exception.printStackTrace() considered bad practice?</a></li>\n</ul></li>\n<li><p>As others already mentioned, the <code>onCreate</code> method is too complex (and long). You should break it to separate methods with good names which explain their intent. Comments usually help, sometimes they are perfect method names.</p></li>\n<li><p>This variable is write-only, the code never read its value so it's superfluous:</p>\n\n<blockquote>\n<pre><code>String newString;// item clicked in previous list\n</code></pre>\n</blockquote>\n\n<p>Eclipse shows it with a yellow warning.</p></li>\n<li><p>You could eliminate the comment with better variable naming:</p>\n\n<blockquote>\n<pre><code> int instanceposition;// tells me which instance number is running\n int position = 0;// position of the click \n</code></pre>\n</blockquote>\n\n<p>Just rename them to <code>runningInstanceNumber</code> and <code>clickPosition</code>.</p></li>\n<li><p>This <code>runningInstanceNumbe</code> variable scope could be smaller:</p>\n\n<pre><code>if (extras == null) {\n final int runningInstanceNumber = 1;\n Log.d(Integer.toString(runningInstanceNumber), \"value of instanceposition\");\n a = runningInstanceNumber;\n position = 0;\n} else {\n final int runningInstanceNumber = extras.getInt(\"instpos\");\n Log.d(Integer.toString(runningInstanceNumber), \"value of instanceposition\");\n a = runningInstanceNumber;\n position = extras.getInt(\"position\");\n\n}\n</code></pre>\n\n<p>(<em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>)</p></li>\n<li><p>Widening its scope a little bit (but it's still smaller than in the original code) you could move the logging outside the if to remove some duplication:</p>\n\n<pre><code>final int runningInstanceNumber;\nif (extras == null) {\n runningInstanceNumber = 1;\n position = 0;\n} else {\n runningInstanceNumber = extras.getInt(\"instpos\");\n position = extras.getInt(\"position\");\n}\na = runningInstanceNumber;\nLog.d(Integer.toString(runningInstanceNumber), \"value of instanceposition\");\n</code></pre></li>\n<li><blockquote>\n<pre><code>int v = 0;\nv = count(\"USSTATES.txt\");\n</code></pre>\n</blockquote>\n\n<p>The following is the same:</p>\n\n<blockquote>\n<pre><code>int v = count(\"USSTATES.txt\");\n</code></pre>\n</blockquote></li>\n<li><blockquote>\n<pre><code>List&lt;HashMap&lt;String, String&gt;&gt; fillMaps =\n new ArrayList&lt;HashMap&lt;String, String&gt;&gt;();\n</code></pre>\n</blockquote>\n\n<p>&nbsp;</p>\n\n<blockquote>\n<pre><code>HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();\n</code></pre>\n</blockquote>\n\n<p><code>HashMap&lt;...&gt;</code> reference types should be simply <code>Map&lt;...&gt;</code>, as well as <code>ArrayList&lt;...&gt;</code> references could be <code>List&lt;...&gt;</code>. See: <em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em></p>\n\n<pre><code>Map&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();\n</code></pre>\n\n<p>&nbsp;</p>\n\n<pre><code>List&lt;Map&lt;String, String&gt;&gt; fillMaps =\n new ArrayList&lt;Map&lt;String, String&gt;&gt;();\n</code></pre></li>\n</ol>\n\n<p>Here is the <code>a == 2</code> branch after the refactoring mentioned above (nontested code) with only one file reading and file iteration:</p>\n\n<pre><code>// finding no. of counties to be displayed\nfinal int lines = count(\"USCOUNTIES.txt\");\nfinal String pos = Integer.toString(clickPosition);\nfinal List&lt;String&gt; machingValues = new ArrayList&lt;String&gt;();\nfinal InputStream countiesStream = getAssets().open(\"USCOUNTIES.txt\");\nfinal InputStreamReader countesReader = new InputStreamReader(countiesStream);\nfinal BufferedReader bufferedCountiesReader = new BufferedReader(countesReader);\ntry {\n while (true) {\n final String line = bufferedCountiesReader.readLine();\n if (line == null) {\n break;\n }\n Log.d(line, \"Value of zyo\");\n final String[] split = line.split(\",\", 3);\n if (split[0].equals(pos)) {\n machingValues.add(split[1]);\n }\n\n }\n} catch (final Exception e) {\n e.printStackTrace();\n} finally {\n bufferedCountiesReader.close();\n}\n\nLog.d(Integer.toString(lines), \"value of v(when a is 1)\");\n\n// prepare the list of all records\nfor (final String value: machingValues) {\n final Map&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();\n map.put(\"col_1\", value);\n fillMaps.add(map);\n lv.setOnItemClickListener(onListClick);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-02T00:42:33.437", "Id": "43184", "ParentId": "23995", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T21:58:44.457", "Id": "23995", "Score": "3", "Tags": [ "java", "optimization", "android" ], "Title": "Optimization of Android code suggestions? Iteration based" }
23995
<p>Looking for optimizations and cleaner, more pythonic ways of implementing the following code.</p> <pre><code>#Given an array find any three numbers which sum to zero. import unittest def sum_to_zero(a): a.sort(reverse=True) len_a = len(a) if len_a &lt; 3: return [] for i in xrange(0, len_a): j = i + 1 for k in xrange(j + 1, len_a): if a[j] + a[k] == -1 * a[i]: return [a[i], a[j], a[k]] return [] class SumToZeroTest(unittest.TestCase): def test_sum_to_zero_basic(self): a = [1, 2, 3, -1, -2, -3, -5, 1, 10, 100, -200] res = sum_to_zero(a) self.assertEqual([3, 2, -5], res, str(res)) def test_sum_to_zero_no_res(self): a = [1, 1, 1, 1] res = sum_to_zero(a) self.assertEqual(res, [], str(res)) def test_small_array(self): a = [1, 2, -3] res = sum_to_zero(a) self.assertEqual(res, [2, 1, -3], str(res)) def test_invalid_array(self): a = [1, 2] res = sum_to_zero(a) self.assertEqual(res, [], str(res)) #nosetests sum_to_zero.py </code></pre>
[]
[ { "body": "<p>Your code fails this test case:</p>\n\n<pre><code>def test_winston1(self):\n res = sum_to_zero([125, 124, -100, -25])\n self.assertEqual(res, [125,-100,-25])\n</code></pre>\n\n<p>As for the code</p>\n\n<pre><code>def sum_to_zero(a):\n a.sort(reverse=True)\n</code></pre>\n\n<p>Why sort?</p>\n\n<pre><code> len_a = len(a)\n if len_a &lt; 3:\n return []\n for i in xrange(0, len_a):\n</code></pre>\n\n<p>You can just do <code>xrange(len_a)</code>. I recommend doing <code>for i, a_i in enumerate(a)</code> to avoid having the index the array later.</p>\n\n<pre><code> j = i + 1\n</code></pre>\n\n<p>Thar be your bug, you can't assumed that j will be i + 1.</p>\n\n<pre><code> for k in xrange(j + 1, len_a):\n if a[j] + a[k] == -1 * a[i]:\n</code></pre>\n\n<p>Why this instead of <code>a[j] + a[k] + a[i] == 0</code>?</p>\n\n<pre><code> return [a[i], a[j], a[k]]\n return []\n</code></pre>\n\n<p>Not a good a choice of return value. I'd return None. An empty list isn't a natural continuation of the other outputs. </p>\n\n<p>Here is my implementation of it:</p>\n\n<pre><code>def sum_to_zero(a):\n a.sort(reverse = True)\n for triplet in itertools.combinations(a, 3):\n if sum(triplet) == 0:\n return list(triplet)\n return []\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T23:31:59.803", "Id": "37007", "Score": "1", "body": "Thanks for the feedback. I like the use of itertools.combinations... good to know." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T23:19:00.037", "Id": "23998", "ParentId": "23996", "Score": "15" } }, { "body": "<h3>1. Comments on your code</h3>\n\n<p>In addition to the improvements Winston made in <a href=\"https://codereview.stackexchange.com/a/23998/11728\">his answer</a>, I would add:</p>\n\n<ol>\n<li><p>Your function needs a docstring. What does it do and how do you call it?</p></li>\n<li><p>It's better to raise an exception rather than return an exceptional value as a result. It's too easy for the caller to omit the check for the exceptional value.</p></li>\n<li><p>The number zero is arbitrary, so why not generalize the code so that can find triples that sum to any target number?</p></li>\n<li><p>It's not clear to me what the purpose of <code>a.sort(reverse=True)</code> is. This has the side-effect of sorting the input <code>a</code> into reverse order, which is probably not what the caller expected. If you really need to process <code>a</code> in reverse order, you should write something like:</p>\n\n<pre><code>a = sorted(a, reverse=True)\n</code></pre>\n\n<p>so that the input to the function is unchanged. But here there doesn't seem to be any reason for the sort, so you could just omit it.</p></li>\n</ol>\n\n<p>So my implementation of the test-all-triples algorithm looks like this:</p>\n\n<pre><code>from itertools import combinations\n\nclass NotFoundError(Exception):\n pass\n\ndef triple_with_sum(a, target=0):\n \"\"\"Return a tuple of three numbers in the sequence a that sum to\n target (default: 0). Raise NotFoundError if no triple sums to\n target.\n\n \"\"\" \n for triple in combinations(a, 3):\n if sum(triple) == target:\n return triple\n raise NotFoundError('No triple sums to {}.'.format(target))\n</code></pre>\n\n<h3>2. A better algorithm</h3>\n\n<p>The test-all-triples algorithm is very straightforward, and runs in O(<em>n</em><sup>3</sup>) time and O(1) extra space.</p>\n\n<p>However, it's worth noting that it is possible to solve the problem in O(<em>n</em><sup>2</sup>) time and O(<em>n</em>) extra space, using the following algorithm:</p>\n\n<ol>\n<li><p>Store, for each number in the input, the set of positions in the input at which that number can be found. This step takes O(<em>n</em>) time and uses O(<em>n</em>) extra space.</p></li>\n<li><p>For each pair of distinct positions <em>i</em>, <em>j</em> in the input, consider the negation of the sum of the values of those two positions. If this appears at some position in the input (other than position <em>i</em> or <em>j</em>) then we have three numbers in the input that sum to 0. This step takes O(<em>n</em><sup>2</sup>) time.</p></li>\n</ol>\n\n<p>Here's a straightforward implementation:</p>\n\n<pre><code>from collections import defaultdict\n\ndef triple_with_sum2(a, target=0):\n \"\"\"Return a tuple of three numbers in the sequence a that sum to\n target (default: 0). Raise NotFoundError if no triple sums to\n target.\n\n \"\"\" \n positions = defaultdict(set)\n for i, n in enumerate(a):\n positions[n].add(i)\n for (i, ai), (j, aj) in combinations(enumerate(a), 2):\n n = target - ai - aj\n if positions[n].difference((i, j)):\n return n, ai, aj\n raise NotFoundError('No triple sums to {}.'.format(target))\n</code></pre>\n\n<p>There are some minor optimizations you can make (for example, there is no need to record more than three positions for any given number), but these do not affect the big-O analysis, and just complicate the implementation, so I haven't made them here.</p>\n\n<h3>3. Comparison of algorithms</h3>\n\n<p>Here's a test harness for comparing the two algorithms:</p>\n\n<pre><code>from random import randint\nfrom timeit import timeit\n\ndef test(n, m, cases=100):\n \"\"\"Create cases (default: 100) random testcases and run both\n algorithms on them. Each test case consists of n numbers in the\n range [-m, m].\n\n \"\"\"\n testcases = [[randint(-m, m) for _ in range(n)] for _ in range(cases)]\n for algorithm in triple_with_sum, triple_with_sum2:\n def run():\n for testcase in testcases:\n try:\n assert(sum(algorithm(testcase)) == 0)\n except NotFoundError:\n pass\n print(algorithm.__name__, timeit(run, number=1))\n</code></pre>\n\n<p>The <code>triple_with_sum</code> algorithm has the advantage that it might terminate early (after examining only a few triples), whereas <code>triple_with_sum2</code> takes Ω(<em>n</em>) even in the best case, because it builds the dictionary of positions before starting its search. This means that <code>triple_with_sum</code> runs faster than <code>triple_with_sum2</code> for test cases where there are many triples that sum to zero:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; test(1000, 100)\ntriple_with_sum 0.03754958091303706\ntriple_with_sum2 0.05412021093070507\n</code></pre>\n\n<p>But when triples that sum to zero are rare, the better asymptotic performance of <code>triple_with_sum2</code> wins big:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; test(1000, 1000)\ntriple_with_sum 0.10221871780231595\ntriple_with_sum2 0.07950551761314273\n&gt;&gt;&gt; test(1000, 10000)\ntriple_with_sum 0.9003877746872604\ntriple_with_sum2 0.08799532195553184\n&gt;&gt;&gt; test(1000, 100000)\ntriple_with_sum 9.874092630110681\ntriple_with_sum2 0.14182585570961237\n&gt;&gt;&gt; test(1000, 1000000)\ntriple_with_sum 97.11457079928368\ntriple_with_sum2 1.0804437939077616\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T16:41:42.413", "Id": "24013", "ParentId": "23996", "Score": "12" } } ]
{ "AcceptedAnswerId": "23998", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T22:10:11.573", "Id": "23996", "Score": "9", "Tags": [ "python", "algorithm" ], "Title": "Given an array find any three numbers which sum to zero" }
23996
<p>I am creating a multiple choice quiz game with PHP and Javascript. Questions can have 2 to 6 answers. I have been using the PHP queries in the code below to get arrays of the questions of a quiz, and the answers for each questions.</p> <p>I now want to use this data in Javascript, and want to make it so each time a user clicks next question, a question and corresponding answers are displayed.</p> <p>I think (but am not sure) that the best way to do this is to combine the arrays into one where the question array contains the answers arrays before converting to a javascript array.</p> <p>Is this really the way I should do this, and if so how do I do so?</p> <pre><code>$thisquizid = $_POST['quizidvalue']; for ($j = 0; $j &lt; $questionrows; ++$j) { $questionresult = pg_fetch_array($questionquery); $answerquery = pg_query($db_handle, "SELECT * FROM answer WHERE questionid = '$questionresult[0]'"); $answerrows = pg_num_rows($answerquery); for ($i = 0; $i &lt; $answerrows; ++$i) { $answerresult = pg_fetch_array($answerquery); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T23:58:26.000", "Id": "37008", "Score": "1", "body": "JSON - JavaScript Object Notation, is a better way to pass information to/from PHP and JS. PHP has built in functions to encode and decode to JSON. http://php.net/manual/en/book.json.php" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T13:21:08.080", "Id": "37033", "Score": "0", "body": "Javascript is perfectly capable of coping with arrays that themselves contain arrays. Your problem is simply how to transfer a data structure between PHP and Javascript. JSON should serve nicely, it's easily encoded and decoded in both JS and PHP and can export complicated structure. Failing that, there's XML." } ]
[ { "body": "<p>Running a SQL statement in a loop is in general a bad idea. Depending on your <code>$questionsrow</code> you might send a lot of not needed requests.</p>\n\n<p>In relation to MECUs hint you could use something like:</p>\n\n<pre><code>$questions=array();\n//add constrains to select only some questions or sort the answers\n$result=...query($db_handle, \"SELECT * FROM answer\");\nwhile ($row=...fetch_array($result))\n{\n $qid=$row['questionid'];\n if (!isset($questions[$qid])) =array(); //create subarray if new question\n $questions[$qid][]=$row //append a new element to the question array\n}\n$json=json_encode($questions);\n</code></pre>\n\n<p>I.e. <code>$questions[1]</code> will contain a array with all your answers to question 1. The sorting of the answers can be moved to SQL query, also if you don't need all fields you can restrict this in the SQL and don't need to take care of this in your PHP.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T16:04:46.880", "Id": "37038", "Score": "0", "body": "Many thanks I now have it working with your help" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T06:25:26.200", "Id": "24000", "ParentId": "23997", "Score": "1" } } ]
{ "AcceptedAnswerId": "24000", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T22:47:09.217", "Id": "23997", "Score": "1", "Tags": [ "javascript", "php", "array" ], "Title": "Turning multiple PHP arrays into one array ready for conversion to Javascript" }
23997
<p>I am trying to implement a stable radix sort in place with O(1) space. I've seen Wikipedia, and I notice the C implementation is using a temporary variable to hold the sorted value for each pass, and the section of "in-place" MSD radix sort implementation is quite confusing. </p> <p>I took the C code and tried to implement it in C++ for the stable in-place radix sort version: </p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;cstring&gt; using namespace std; void radix_sort(vector&lt;int&gt;&amp; v) { //search for maximum number int max_number = v[0]; for(int i = 1;i&lt;v.size();i++) { if(max_number &lt; v[i]) max_number = v[i]; } int bucket[10]; // store first index for that digit int bucket_max_index[10]; // store maximum index for that digit int exp = 1; while(max_number / exp &gt; 0) { memset(bucket, 0, 10 * sizeof(int)); memset(bucket_max_index, 0, 10 * sizeof(int)); for(int i=0;i&lt;v.size();i++) { bucket[(v[i] / exp) % 10]++; } int index = v.size(); for(int i=9;i&gt;=0;i--) { index -= bucket[i]; bucket_max_index[i] = index + bucket[i]; bucket[i] = index; } index = 0; vector&lt;int&gt; temp(v.size()); for(int i=0;i&lt;v.size();i++) { int digit = (v[i] / exp) % 10; temp[bucket[digit]] = v[i]; bucket[digit]++; } for(int i=0;i&lt;v.size();i++) { v[i] = temp[i]; } exp *= 10; } } </code></pre> <p><strong>EDIT:</strong></p> <p>Thanks to the comments, I checked and found out that I made a mistake. The original idea of the question is that I want to implement a stable in-place radix sort. </p> <p>I thought I succeeded in implementing it when I tested it with a several test cases (one of them is this test case: <code>{1, 3, 2, 5, 8, 2, 3, 1}</code>) .</p> <p>I changed the code to a stable radix sort with O(n) space and changed my questions to: </p> <ol> <li><p>Is this O(kn) time ? (with k as the maximum number of digits)</p></li> <li><p>Can we improve the above code to be a stable radix sort with O(1) space ?</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T02:15:51.647", "Id": "37009", "Score": "0", "body": "What is the question, whether your implementation of the algorithm is correct? whether the asymptotic costs are the ones of algorithm?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T02:43:38.650", "Id": "37010", "Score": "0", "body": "@David: That's the way I understand it... \"Does this code correctly sort inputs?\" and \"Is the stable radix sort algorithm (which implies its memory and runtime complexity) implemented by this code?\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T03:16:08.520", "Id": "37011", "Score": "0", "body": "@DavidRodríguez-dribeas yes, i was asking if this code is correct and whether the time complexity is O(kn) and the space complexity is O(1)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T06:15:50.713", "Id": "37066", "Score": "0", "body": "@DavidRodríguez-dribeas: This is code review. You are supposed to read and comment on the codes design/maintainability anything else that is important." } ]
[ { "body": "<p>Yes, your radix sort appears to be correct, and runs in O(<em>k n</em>) time.</p>\n\n<p><code>bucket_max_index</code> is written to, but otherwise never used. You can eliminate it completely.</p>\n\n<p>Before the creation of the <code>temp</code> vector, you set <code>index = 0</code>. It would be clearer to change that to <code>assert(index == 0)</code>, since that should have been the result of <code>v.size()</code> - Σ <code>bucket[i]</code> in the previous loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T06:10:35.763", "Id": "78580", "Score": "0", "body": "thanks for the answer. can you also answer the second part of the question ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T06:13:20.960", "Id": "78581", "Score": "1", "body": "Wikipedia says [radix sort uses O(_k_ + _n_) space](http://en.wikipedia.org/wiki/Radix_sort). I challenge you to do better than conventional wisdom. ☺" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T06:38:40.750", "Id": "78584", "Score": "0", "body": "Well, I guess for now, stable radix sort uses O(k+n) space. You would have to lose the stable property to achieve the O(1) space." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-22T09:42:36.683", "Id": "45074", "ParentId": "23999", "Score": "3" } } ]
{ "AcceptedAnswerId": "45074", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T01:55:01.933", "Id": "23999", "Score": "6", "Tags": [ "c++", "sorting", "complexity", "radix-sort" ], "Title": "Stable radix sort in-place using O(1) space" }
23999
<p>I'm using the <code>BigRational</code> beta off the BCL CodePlex (<a href="http://bcl.codeplex.com" rel="nofollow">bcl.codeplex.com</a>), and I realized it had no parsing method, so I tried to write one. However, it's quite inefficient (5.5ms for a 254 character number). That's over 45x slower than the BigInteger implementation. I'd like to lower it to .5ms if that's even possible.</p> <pre><code>private static Regex DigitDotDigit = new Regex(@"^(\-|\+)?(\d+\.\d+)$", RegexOptions.Compiled); private static Regex PlainDigit = new Regex(@"^(\-|\+)?\d+$", RegexOptions.Compiled); private static Regex DigitSlashDigit = new Regex(@"^(\-|\+)?\d+/\d+$", RegexOptions.Compiled); private static Regex DotDigit = new Regex(@"^(\-|\+)?(\.\d+)", RegexOptions.Compiled); private static bool RegexInitiated = false; public static bool TryParse(string parse, out BigRational result) { if (DigitDotDigit.IsMatch(parse)) { int zeros; bool isNegative = false; string[] parts = parse.TrimStart('+').Split('.'); parts[1] = parts[1].TrimEnd('0'); if (parts[0].StartsWith("-")) { isNegative = true; parts[0] = parts[0].Substring(1); } BigRational whole = new BigRational(BigInteger.Parse(parts[0]), BigInteger.Zero, BigInteger.One); BigRational decimalPart = new BigRational(BigInteger.Parse(parts[1]), BigInteger.Zero, BigInteger.One); zeros = parts[1].Length - parts[1].TrimStart('0').Length; toSubtract = toSubtract + zeros; if (zeros &gt; 0) { toSubtract = toSubtract - 1; } while (toSubtract != 0) { decimalPart /= 10; toSubtract = toSubtract - 1; } result = whole + decimalPart; if (isNegative) { result = -result; } return true; } else if (DotDigit.IsMatch(parse)) { return TryParse("0" + parse, out result); } else if (PlainDigit.IsMatch(parse)) { parse = parse.TrimStart('+'); if (parse.StartsWith("-")) { result = new BigRational(-BigInteger.Parse(parse), BigInteger.Zero, BigInteger.One); return true; } result = new BigRational(BigInteger.Parse(parse), BigInteger.Zero, BigInteger.One); return true; } else if (DigitSlashDigit.IsMatch(parse)) { string[] parts = parse.TrimStart('+').Split('/'); if (parts[0].StartsWith("-")) { parts[0] = parts[0].Substring(1); result = -(new BigRational(BigInteger.Parse(parts[0]), BigInteger.Parse(parts[1]))); return true; } result = new BigRational(BigInteger.Parse(parts[0]), BigInteger.Parse(parts[1])); return true; } result = BigInteger.Zero; return false; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T17:25:04.023", "Id": "37049", "Score": "0", "body": "I think that before worrying about performance, you should make sure that your code actually works correctly (hint: try parsing numbers like `0.1`, or even just `1`). And you should also include the whole method, so that we don't have to guess what the rest of it contains (even if it's quite obvious)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T17:52:26.817", "Id": "37050", "Score": "0", "body": "Whoops, missed the copy and paste. Wait one second. And it worked fine in ~25 tests that I did..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T17:57:47.233", "Id": "37051", "Score": "0", "body": "@svick Fixed that behaviour. Should've remembered to use >=." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T01:13:19.347", "Id": "37058", "Score": "0", "body": "It's still not completely fixed. Try `0.1001`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T20:59:53.097", "Id": "37129", "Score": "0", "body": "Setting a value in the middle of an expression is confusing, you shouldn't do that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T21:31:12.390", "Id": "37138", "Score": "0", "body": "More efficient. It's the key here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T21:40:10.067", "Id": "37140", "Score": "0", "body": "It really wouldn't be more efficient than setting `zeros` first and then using that value." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T21:41:17.307", "Id": "37141", "Score": "0", "body": "@svick Edited it." } ]
[ { "body": "<p>The answer, I found out now, was that if I moved the <code>Regex</code>es to private fields, and then used those, after the first use it will radically drop down to .4ms, and that's including a <code>WriteLine</code> call. So the real hotspot in this method was the <code>Regex</code>. Thanks everyone!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T13:55:43.257", "Id": "37096", "Score": "1", "body": "You might also want to look into compiling your [regex](http://msdn.microsoft.com/en-us/library/gg578045.aspx). Look for the section \"Interpreted vs Compiled Regular Expressions\". Compiling them is a huge speed improvement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T16:08:21.003", "Id": "37103", "Score": "0", "body": "Thought it did that by default, thanks for warning me :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T20:49:09.507", "Id": "24019", "ParentId": "24002", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T08:45:53.343", "Id": "24002", "Score": "6", "Tags": [ "c#", "performance", "parsing", "rational-numbers" ], "Title": "Parsing a BigRational efficiently" }
24002
<p>I am developing a web-application and I am encountering some trouble : I have some tabs and each one contains input forms with different values. I need to switch beetween these tabs and see the different contents of each one. So I thought I could create objects for every tab , but I have to name them , I use something like this :</p> <p><strong>Object</strong> </p> <pre><code>var step = function(params){ this.id = randID(); this.titolo = null; this.descrizione = null; this.dmax = null; $.extend(this,params); // this.render(); } </code></pre> <p><strong>When the button is clicked , it instance a new object</strong></p> <pre><code>$("#btn").on('click',function(){ stepA = new step({ "titolo" : $("#titolo").val(), "descrizione" : $("#descrizione").val() }) var id = stepA.id; var nome = "step"+id; console.log(nome); nome = stepA; console.log(nome); }); </code></pre> <p>As you can see , I used this solution to name every <code>step</code> object with his <code>ID</code> </p> <pre><code>var id = stepA.id; var nome = "step"+id; console.log(nome); nome = stepA; console.log(nome); </code></pre> <p>otherwise I think is a really bad solution. Notice that I will call every <code>object</code> by his <code>id</code> clicking on the tabs.</p> <p>Hope you can help me improve it, thank you guys.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T11:48:38.587", "Id": "37024", "Score": "0", "body": "If you are using jQuery and jQueryUI why don't you use the tab control in that library: http://api.jqueryui.com/tabs/" } ]
[ { "body": "<pre><code>var step = function(params){\n this.id = randID();\n this.titolo = params.titolo;\n this.descrizione = params.descrizione;\n this.dmax = null;\n}\n\n$(\"#btn\").on('click',function(){\n stepA = new step({\n \"titolo\" : $(\"#titolo\").val(),\n \"descrizione\" : $(\"#descrizione\").val()\n })\n var id = stepA.id;\n var nome = \"step\"+id;\n console.log(nome);\n console.log(stepA);\n});\n</code></pre>\n\n<p>You don't need to use extend in the constructor. And I don't understand the nome = stepA line too.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-01T10:06:51.413", "Id": "37020", "Score": "0", "body": "` nome = stepA ` is needed to give a different name every time I create a object , because ` nome = \"step\"+id ` so ` nome = step24904 `" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-01T10:21:45.803", "Id": "37021", "Score": "0", "body": "But you give nome value twice, that's what I don't understand." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-01T10:23:28.440", "Id": "37022", "Score": "0", "body": "I think it could be solved using an `array`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-01T11:22:58.630", "Id": "37023", "Score": "0", "body": "If you want more help, please provide more info." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-01T09:58:08.750", "Id": "24004", "ParentId": "24003", "Score": "0" } }, { "body": "<p>I would use some MV* library for this kind of task.\nMaybe you have a look at <a href=\"http://backbonejs.org/\" rel=\"nofollow\">Backbone</a>. A small library (about 7k in production) with lots of nice functionality for those kinds of tasks.</p>\n\n<p>1) You have <code>models</code> representing you data as a proper javascript object.\nEach model is instantiated with:</p>\n\n<pre><code>var MyModel = Backbone.Model.extend({});\nvar instance = new MyModel();\n</code></pre>\n\n<p>You could use defaults:</p>\n\n<pre><code>var MyModel = Backbone.Model.extend({ \n defaults: { name: 'Freddy Krueger', age: 0, child: '' }\n}); \n</code></pre>\n\n<p>Models have events to which you could subscribe. Most used is the \"change\" event. So you could bind a function to a general change by just declaring</p>\n\n<pre><code>model.on(\"change\", function(){});\n</code></pre>\n\n<p>Or if you want to watch a specific attribute to change</p>\n\n<pre><code>model.on(\"change:name\", function(){});\n</code></pre>\n\n<p>Of course you could \"trigger\" custom events</p>\n\n<pre><code>model.trigger(\"outOfOrder\");\n</code></pre>\n\n<p>2) You could use <code>views</code> to render the different forms</p>\n\n<pre><code>View = Backbone.View.extend({\n el: $(\"#placeToRender\"),\n render:function(){\n $(this.el).html(yourMagicHTML);\n }\n});\n</code></pre>\n\n<p>Even better: you have microtemplating on board, which means:\nYou could define HTML including placeholders within a script-tag</p>\n\n<pre><code>&lt;script type=\"text/template\" id=\"#maintemplate\"&gt;\n &lt;div&gt;\n &lt;%= content %&gt;\n &lt;/div&gt;\n&lt;/script&gt;\n</code></pre>\n\n<p>That wouldn't be rendered by your browser, but you could get its content by</p>\n\n<pre><code>$(\"#maintemplate\").html()\n</code></pre>\n\n<p>So that your view could render itself easily with:</p>\n\n<pre><code>View = Backbone.View.extend({\n el: $(\"#main\"),\n template:_template($(\"#maintemplate\").html()),\n render:function(){\n $(this.el).html(template(this.model.toJSON()));\n }\n});\n</code></pre>\n\n<p>Where</p>\n\n<pre><code>this.model.toJSON()\n</code></pre>\n\n<p>is in fact a model with a key called \"content\" (e.g. {content:\"blah!\"}), which is used to render the template, </p>\n\n<p>so that &lt;%= content %> is substituted with the actual content.\nAnd many more stuff to discover.</p>\n\n<p>Referring to your problem - you could abstract your problem with backbone like the following:\nEvery tab you need to display is a view to which belongs a template to determine its html as well as a model, which represents the content of the tab.\nYou could embed each tab in another view, such that you have one embracing view to control the whole tabbing system and nesting views, which represent each individual tab.</p>\n\n<p>You could write a custom show() method to show an individual tab and a method which coordinates which of the tabs is shown and which should be hidden.</p>\n\n<p>So instead of doing the annoying work yourself, it may be a good idea to use a library to help.</p>\n\n<p>Some places to start (besides the official API and documentation):</p>\n\n<p><a href=\"http://backbonetutorials.com/\" rel=\"nofollow\">http://backbonetutorials.com/</a></p>\n\n<p><a href=\"http://ricostacruz.com/backbone-patterns/\" rel=\"nofollow\">http://ricostacruz.com/backbone-patterns/</a></p>\n\n<p><a href=\"http://coenraets.org/blog/2011/12/backbone-js-wine-cellar-tutorial-part-1-getting-started/\" rel=\"nofollow\">http://coenraets.org/blog/2011/12/backbone-js-wine-cellar-tutorial-part-1-getting-started/</a></p>\n\n<p><a href=\"http://addyosmani.github.io/backbone-fundamentals/\" rel=\"nofollow\">http://addyosmani.github.io/backbone-fundamentals/</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-16T00:52:24.850", "Id": "27444", "ParentId": "24003", "Score": "1" } } ]
{ "AcceptedAnswerId": "27444", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-01T09:34:27.030", "Id": "24003", "Score": "1", "Tags": [ "javascript", "jquery", "object-oriented" ], "Title": "Dynamically create object" }
24003
<p>I don't know what this problem is named, so I can't Google for a solution about it. Here's the image:</p> <p><img src="https://i.stack.imgur.com/RcOcA.jpg" alt="3 Pitcher Problem"></p> <p>There are three pitchers with capacities of 10, 7 and 3 quarts.</p> <p>We need to move the water from a pitcher (or jar) to another pitcher so it will result in 5, 5 and 0.</p> <p>I have to print all the steps needed to make the pitchers contains 5, 5 and 0 quarts of water.</p> <p>Here's my working code. Please review it and tell me how to make it better, faster, shorter, more readable.</p> <pre><code>class Jar attr_accessor :max, :current, :target def initialize max, current, target @max = max @current = current @target = target raise 'max should not be 0' if max == 0 end def full? return @current == @max end def empty? return @current == 0 end def overflow return 0 if @current &lt; @max over = @current - @max; @current = max return over end def move_to o o.current += @current @current = o.overflow end end class Quartz MAX_STEPS = 12 def initialize max, init, target raise 'max.length must equal init.length' if max.length != init.length raise 'max.length must equal target.length' if max.length != target.length @ite = (0..(max.length-1)) @memoize = {} @targets = [] @steps = [] @all_solutions = [] @jars = @ite.collect { |x| Jar.new(max[x],init[x],target[x]) } @targets = current(:target) end def recurse step=1 orig = current @steps &lt;&lt; orig if orig == @targets p @steps return @steps.length end return false if step&gt;=MAX_STEPS @memoize[orig] = step @jars.each do |x| next if x.empty? @jars.each do |y| next if x == y next if y.full? x.move_to y done = @memoize[current] if done restore orig next end ok = recurse(step+1) #return ok if ok # return only first solution @steps.pop restore orig end end return false end def current attr=:current @jars.collect{ |x| x.send attr } end alias_method :to_array, :current def restore a @ite.each { |i| @jars[i].current = a[i] } end end q = Quartz.new [10,7,3], [10,0,0], [5,5,0] p q.recurse </code></pre> <p>This is the program's output:</p> <pre class="lang-none prettyprint-override"><code>[[10, 0, 0], [3, 7, 0], [3, 4, 3], [6, 4, 0], [6, 1, 3], [9, 1, 0], [9, 0, 1], [2, 7, 1], [2, 5, 3], [5, 5, 0]] </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T12:01:59.780", "Id": "37088", "Score": "1", "body": "See [this answer](http://stackoverflow.com/a/15089256/68063) over on Stack Overflow. (It's in Python, not Ruby, but it shouldn't be too difficult for you to follow.)" } ]
[ { "body": "<p>Some comments on your code:</p>\n\n<ul>\n<li><p><code>def initialize max, current, target</code>. The community consensus seems to be to put always parenthesis on method definitions. I'd definitely do it.</p></li>\n<li><p><code>return @current == @max</code>. It's not idiomatic to put explicits <code>return</code>, the last expression of a block/method is returned.</p></li>\n<li><p><code>MAX_STEPS = 12</code>. Isn't this kind of cheating? </p></li>\n<li><p><code>raise 'max.length must equal init.length' if max.length != init.length</code>. I wouldn't lose a second validating inputs. If the input data is wrong it's the caller's problem.</p></li>\n<li><p>[Lots of imperative code which, frankly, I don't understand] When you are dealing with mathematics-related problems (some would argue <strong>all</strong> computation is a mathematics-related problem) you'll get better algorithms with <a href=\"http://en.wikipedia.org/wiki/Functional_programming\" rel=\"nofollow\">functional programming</a>.</p></li>\n</ul>\n\n<p>I'd write it with a depth-first algorithm in functional style. Note that I've created two generic abstractions, <code>Enumerable#map_detect</code> (<a href=\"https://github.com/rubyworks/facets\" rel=\"nofollow\">Facets</a> has it) and <code>Array#merge</code>, so the main algorithm remains as clean and declarative as possible. Granted, it may be difficult to grasp at first if you have only experience with imperative programming, ask if you don't understand something (also, reviews of the review welcomed):</p>\n\n<pre><code>require 'facets/enumerable/map_detect'\n\nclass Array\n # [:a, :b, :c, :d].merge_from_hash(1 =&gt; :bb, 3 =&gt; :dd) #=&gt; [:a, :bb, :c, :dd]\n def merge_from_hash(hash)\n map.with_index { |x, idx| hash.fetch(idx, x) }\n end\nend\n\nclass PitchersProblem &lt; Struct.new(:total)\n def solve(current, final, solution = [])\n if current == final\n solution + [current]\n else\n (candidates(current) - solution).map_detect do |candidate|\n solve(candidate, final, solution + [current])\n end\n end\n end\n\n def candidates(current)\n (0...total.size).to_a.permutation(2).map do |i1, i2|\n free2 = total[i2] - current[i2]\n if current[i1] &gt; 0 &amp;&amp; free2 &gt; 0\n moved = [current[i1], free2].min\n current.merge_from_hash(i1 =&gt; current[i1] - moved, i2 =&gt; current[i2] + moved)\n end\n end.compact\n end\nend\n\np PitchersProblem.new([10, 7, 3]).solve([10, 0, 0], [5, 5, 0])\n#=&gt; [[10, 0, 0], [3, 7, 0], [0, 7, 3], [7, 0, 3], [7, 3, 0], \n# [4, 3, 3], [4, 6, 0], [1, 6, 3], [1, 7, 2], [8, 0, 2], \n# [8, 2, 0], [5, 2, 3], [5, 5, 0]]\n</code></pre>\n\n<p>Notes on my code:</p>\n\n<ul>\n<li><p><code>solve</code> can be read as: \"If the current state is the final, add it to the path solution and we are done. Otherwise, for each permutation of the pitchers, move water from one to the other if possible, and try to find a solution recursively (unless that state is already in our solution path)\".</p></li>\n<li><p>This algorith returns the first solution it gets (size 13), which is not the optimal (size 10?), that's because it's a depth-first algorithm, you can transform it into a breadth-first algorithm to get the shortest solution first.</p></li>\n<li><p>Ideally <code>solution</code> should be an insertion-ordered data-structure with O(1) lookup (because of <code>solution.include?(new_current)</code>), something like an <a href=\"https://gist.github.com/samleb/1071830\" rel=\"nofollow\">OrderedSet</a>. An array has O(n) lookup, but anyway, let's leave it just to keep it simple.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T10:31:43.323", "Id": "37080", "Score": "0", "body": "i like this part: PitchersProblem.new([10, 7, 3]).solve([10, 0, 0], [5, 5, 0])" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T10:32:00.890", "Id": "37081", "Score": "0", "body": "i like this part: moved = [current[i1], free2].min" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T10:32:29.547", "Id": "37082", "Score": "0", "body": "i like this part: current.merge_from_hash ..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T10:33:31.200", "Id": "37083", "Score": "0", "body": "and i don't understand this part (yet): map_detect XD" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T10:33:58.763", "Id": "37084", "Score": "0", "body": "and last one, i like this part ^^: (0...@total.size).to_a.permutation(2)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T11:11:17.550", "Id": "37087", "Score": "1", "body": "xs.map_detect { ... } equivalent to xs.map { ... }.first" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T09:27:31.143", "Id": "24033", "ParentId": "24007", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T12:42:25.680", "Id": "24007", "Score": "2", "Tags": [ "algorithm", "ruby", "recursion" ], "Title": "\"Three pitchers with water\" problem" }
24007
<p>I'm very new to Angular, and trying to get my head around whether or not I'm doing it the Right Way (tm).</p> <p>I want to filter a set of results by their properties, where if none of the filters are checked, all the results are displayed, but if one or more filters are checked, all results which match the checked properties are displayed.</p> <p>I've setup a simple demo with the colours of fruit. The JSFiddle is available at <a href="http://jsfiddle.net/mattdwen/u5eBH/2/" rel="nofollow">http://jsfiddle.net/mattdwen/u5eBH/2/</a></p> <p>The HTML has a series of checkboxs and a repeating list for the set results:</p> <pre><code>&lt;div ng-app="fruit"&gt; &lt;div ng-controller="FruitCtrl"&gt; &lt;input type="checkbox" ng-click="includeColour('Red')"/&gt; Red&lt;/br/&gt; &lt;input type="checkbox" ng-click="includeColour('Orange')"/&gt; Orange&lt;/br/&gt; &lt;input type="checkbox" ng-click="includeColour('Yellow')"/&gt; Yellow&lt;/br/&gt; &lt;ul&gt; &lt;li ng-repeat="f in fruit | filter:colourFilter"&gt; {{f.name}} &lt;/li&gt; &lt;/ul&gt; Filter dump: {{colourIncludes}} &lt;/div&gt; &lt;/div&gt; </code></pre> <p>And the JS adds the checked properties to a scope array, and the filter checks if the fruit colour is in that array:</p> <pre><code>'use strict' angular.module('fruit', []); function FruitCtrl($scope) { $scope.fruit = [ {'name': 'Apple', 'colour': 'Red'}, {'name': 'Orange', 'colour': 'Orange'}, {'name': 'Banana', 'colour': 'Yellow'}]; $scope.colourIncludes = []; $scope.includeColour = function(colour) { var i = $.inArray(colour, $scope.colourIncludes); if (i &gt; -1) { $scope.colourIncludes.splice(i, 1); } else { $scope.colourIncludes.push(colour); } } $scope.colourFilter = function(fruit) { if ($scope.colourIncludes.length &gt; 0) { if ($.inArray(fruit.colour, $scope.colourIncludes) &lt; 0) return; } return fruit; } } </code></pre> <p>It doesn't really feel 'Angular' enough to be the correct way to achieve this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T23:28:06.740", "Id": "37057", "Score": "0", "body": "I don't have the rep to create an 'Angular' tag unfortunately." } ]
[ { "body": "<p>You're attempting to handle the data binding yourself by creating arrays to store objects based on the click event. Angular does the two way binding for you. </p>\n\n<p>Basically, I assign a new property named \"included\" by assigning it as the model to the input checkbox. Then I use that property on the filter of the fruit array to display only the one's whose colour is selected.</p>\n\n<pre><code>&lt;div ng-app=\"fruit\"&gt;\n &lt;div ng-controller=\"FruitCtrl\"&gt;\n &lt;div ng-repeat=\"f in fruit\"&gt;\n &lt;input type='checkbox' ng-model='f.included'&gt;&lt;/input&gt;{{f.colour}}\n &lt;/div&gt;\n &lt;ul&gt;\n &lt;li ng-repeat=\"f in fruit | filter:{included:true}\"&gt;{{f.name}}&lt;/li&gt;\n &lt;/ul&gt;\n&lt;/div&gt;\n\n\nangular.module('fruit', []);\n\nfunction FruitCtrl($scope) {\n $scope.fruit = [\n {'name': 'Apple', 'colour': 'Red'},\n {'name': 'Orange', 'colour': 'Orange'},\n {'name': 'Banana', 'colour': 'Yellow'}\n ];\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-29T16:49:44.710", "Id": "117363", "Score": "0", "body": "What if $scope.fruit contains duplicate elements. it will break I think" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-06T18:08:11.043", "Id": "181934", "Score": "0", "body": "Your answer is very good, but it not working as it asked: \"if none of the filters are checked, all the results are displayed...\"" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T03:41:18.573", "Id": "30713", "ParentId": "24017", "Score": "6" } } ]
{ "AcceptedAnswerId": "30713", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T20:15:56.963", "Id": "24017", "Score": "0", "Tags": [ "javascript", "angular.js" ], "Title": "Angular Checkbox Filtering" }
24017
<p>I've discovered (and written) a way to object oriented programming in lua in a functional fashion instead of the standard metatable method. It carries much more functionality (no pun intended) but I'm afraid it might dent performance. My goal is to experiment with servers written in lua and I wanted to use this OOP solution. Anyways here's my class.lua which holds the functions for creating new objects and subclasses.</p> <pre><code>local classes = setmetatable({}, {__mode = "k"}) -- Allow the GC to empty this as needed. function class(f, super) classes[f] = {super = super} end function new(f, obj, ...) local fenv = getfenv(f) if type(obj) ~= "table" then error("bad argument: expected table, got " .. type(obj) , 2) end if classes[f] and classes[f].super then new(classes[f].super, obj, ...) local super = obj obj = setmetatable({}, { __index = super }) obj.super = super else setmetatable(obj,{__index = fenv}) end obj.this = obj setfenv(f, obj) f() setfenv(f, fenv) if obj.init then obj.init( ... ) end return obj end </code></pre> <p>Usage is fairly simple. Take the following example:</p> <pre><code>function Person() local privateVar = math.random() age, name, gender = nil, nil, nil function init(age, name, gender) this.age = age this.name = name this.gender = gender end function getPrivateVar() return privateVar end end </code></pre> <p>And to create the object</p> <pre><code>obj = new(Person, {}, "John", 30, "male") </code></pre> <p>Subclassing is also simple</p> <pre><code>function Female() function init(name, age) super.init(name, age, "female") end end class(Female, Person) </code></pre> <p>Note that you only have to call a function to make something a class if you want to subclass.</p> <p>When you call new, you pass in the class, object, and arguments. The object's metatable is set to have an index of the class's original environment. Then the super is determined and created. Then the class function is run to create all instance values. Next, init is called.</p> <p>One advantage of this over metatables are that other code can't change the class and have it change all instances of that class that already exist and that will exist. Now the only way to do something like that is to swizzle and hack around in environments to make sure all references to the class refer to the hacker's dummy class.</p> <p>On top of that, it supports private variables. Just declare them locally in your class function and you're good to go.</p> <p>But I'm wondering if the fact that it creates all the instance methods once for every instantiation is going to cause performance problems. Will this eat memory? What can go wrong here?</p> <p>Also, there's an issue. While this supports multiple inheritance, if you call a super method, and the super calls a method, it will call the method of the super class, not the instantiated class. Any ideas how to make it call from the instantiated class?</p>
[]
[ { "body": "<p>Even though this kind of inheritance is perfectly valid example of OOP designing in language like Lua; it is considered a bad practice of programming.</p>\n<p>According to <a href=\"http://www.lua.org/pil/16.html\" rel=\"nofollow noreferrer\">Programming in Lua</a> on <strong>Object-Oriented Programming</strong>.</p>\n<blockquote>\n<p>This kind of function is almost what we call a <em>method</em>. However, the use of the global name Account inside the function is a bad programming practice.</p>\n<ol>\n<li>This function will work only for this particular object.</li>\n<li>Even for this particular object the function will work only as long as the object is stored in that particular global variable; if we change the name of this object, withdraw does not work any more.</li>\n</ol>\n</blockquote>\n<p>The example they've used to depict is also quite to the point and small.</p>\n<p>You should also take a look at how they've explained creation of classes; their inheritance; <code>public</code>, <code>private</code> and <code>protected</code> datatypes/variables and many other OOP concepts using metamethods and tables depending on their usage.</p>\n<p>Here's the index of <a href=\"http://www.lua.org/pil/contents.html#16\" rel=\"nofollow noreferrer\">OOP concepts incorporated in Lua</a>.</p>\n<h2>Useful Links</h2>\n<ul>\n<li><a href=\"http://lua-users.org/wiki/ObjectOrientationTutorial\" rel=\"nofollow noreferrer\">Object Orientation Tutorial</a></li>\n<li><a href=\"http://lua-users.org/wiki/InheritanceTutorial\" rel=\"nofollow noreferrer\">Inheritance Tutorial</a></li>\n<li><a href=\"http://lua-users.org/wiki/MetamethodsTutorial\" rel=\"nofollow noreferrer\">Metamethods Tutorial</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T14:57:45.483", "Id": "24039", "ParentId": "24020", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T21:22:24.777", "Id": "24020", "Score": "10", "Tags": [ "object-oriented", "lua" ], "Title": "Object Oriented programming in lua in a functional fashion" }
24020
<p>I have a function that takes an XML document and parses out specific XML elements and appends those to a list for use by an Oracle executemany call. The placement of the elements matters as the executemany string uses positional binds, though I could easily use a dictionary to use named binds instead. I feel that while this works, it is pretty slow since it has to reparse the data 5x per document instead of pulling the whole thing into an array once. I know xml.etree is probably what I want here instead of minidom, but I'm not sure how to implement it.</p> <p>The data I'm working with is structured like this:</p> <pre><code>&lt;troubleshooter&gt; &lt;vendorsAndVersions&gt; &lt;versionInfo&gt; &lt;type&gt;TAX&lt;/type&gt; &lt;vendor&gt;My vendor&lt;/vendor&gt; &lt;version&gt;My version 23121&lt;/version&gt; &lt;/versionInfo&gt; &lt;versionInfo&gt; &lt;type&gt;OS&lt;/type&gt; &lt;vendor&gt;Windows Server 2008 R2 amd64&lt;/vendor&gt; &lt;version&gt;6.1&lt;/version&gt; &lt;/versionInfo&gt; &lt;versionInfo&gt; &lt;type&gt;APPSERVER&lt;/type&gt; &lt;vendor&gt;JBoss Web&lt;/vendor&gt; &lt;version&gt;3.0.0-CR1&lt;/version&gt; &lt;/versionInfo&gt; &lt;versionInfo&gt; &lt;type&gt;DATABASE&lt;/type&gt; &lt;vendor&gt;Microsoft SQL Server&lt;/vendor&gt; &lt;version&gt;10.50.1600&lt;/version&gt; &lt;/versionInfo&gt; &lt;versionInfo&gt; &lt;type&gt;JAVA&lt;/type&gt; &lt;vendor&gt;Sun Microsystems Inc.&lt;/vendor&gt; &lt;version&gt;1.6.0_26&lt;/version&gt; &lt;/versionInfo&gt; &lt;versionInfo&gt; &lt;type&gt;JDBC&lt;/type&gt; &lt;vendor&gt;Microsoft SQL Server JDBC Driver 3.0&lt;/vendor&gt; &lt;version&gt;3.0.1301.101&lt;/version&gt; &lt;/versionInfo&gt; &lt;/vendorsAndVersions&gt; ... &lt;/troubleshooter&gt; </code></pre> <p>And the function looks like this:</p> <pre><code>def parseDocumentData(document, cusNumber): "Take document from calling function, validate that the structure is \ correct, then process the XML elements and return the data as a list \ of lists." # Check filename for customer number if cusNumber isn't passed. if cusNumber == None: cusNumber = os.path.splitext(os.path.basename(document))[0] cusNumber = str(cusNumber).encode('ascii') # Verify that the destination customer record exists. Source was verified by input function. _dbCur.execute('select count(*) from pm_customer where customer_id=' + cusNumber) cusVerify = _dbCur.fetchone()[0] if cusVerify == 0: _dbCur.execute('insert into pm_customer (customer_id) values (' + cusNumber + ')') print 'Customer number,', cusNumber, 'was created. Moving on.' else: print 'Customer number,', cusNumber, 'exists. Moving on.' parseDoc = minidom.parse(document) dataSet = parseDoc.getElementsByTagName("versionInfo") isValid = None global dbWriteList prepList = [] # This for loop parses the document and matches XML objects using the typePattern list. # As each object is found, it is appended to the prepList. The prepList is then appended # to the dbWriteList list after the for loop has completed. for data in dataSet: typePattern = re.compile('(TAX|OS|APPSERVER|DATABASE|JAVA)') # Define XML elements to extract. try: vendorObj = data.getElementsByTagName("vendor")[0].childNodes[0].data except: vendorObj = 'Vendor Unavailable' try: versionObj = data.getElementsByTagName("version")[0].childNodes[0].data except: versionObj = 'Version Unavailable' # Convert XML elements to ascii strings. This makes it easier to write the objects to the database. vendorObj = str((vendorObj[:30] + '...')).encode('ascii') if len(vendorObj) &gt; 30 else str(vendorObj).encode('ascii') versionObj = str((versionObj[:65] + '...')).encode('ascii') if len(versionObj) &gt; 65 else str(versionObj).encode('ascii') typeObj = data.getElementsByTagName("type")[0].childNodes[0].data if typePattern.match(typeObj): isValid = 1 # TAX if typeObj == xmlTypeTuple[0]: prepList.append(versionObj) # OS if typeObj == xmlTypeTuple[1]: prepList.append(vendorObj) prepList.append(versionObj) # APPSERVER if typeObj == xmlTypeTuple[2]: prepList.append(vendorObj) prepList.append(versionObj) # DATABASE if typeObj == xmlTypeTuple[3]: prepList.append(vendorObj) prepList.append(versionObj) # JAVA if typeObj == xmlTypeTuple[4]: prepList.append(vendorObj) prepList.append(versionObj) prepList.append(cusNumber) if isValid == 1: print 'File processed successfully. Moving on.' dbWriteList.append(prepList) completedFiles.append(document) else: print 'File did not contain valid XML elements:', document failedFiles.append(document) return </code></pre> <p>This gives me a string that looks like:</p> <pre><code>['my version 23121', 'Windows Server 2008 R2 amd64', '6.1', 'JBoss Web', '3.0.0-CR1', 'Microsoft SQL Server', '10.50.1600', 'Sun Microsystems Inc.', '1.6.0_26', 'customer number'] </code></pre> <p>which gets appended to the list that is passed to the executemany command in the next function. Using executemany has cut a lot of processing time off, but look at this code and see myself repeating myself and it makes me think that this is not the best way to approach it.</p>
[]
[ { "body": "<p>I was able to simplify this by using BeautifulSoup4 to replace the block of code that searches for typePattern if: statements with one that matches against a simplified list and appends in one go. This still has to iterate through the section of code, but it is very fast. The slowest part is loading a large XML (3-5MB) file into memory before it gets parsed. I came to this solution before the answer above was posted. Here is the replacement code with the revised parser:</p>\n\n<pre><code>def parseDocumentData(document, cusNumber):\n \"Take document from calling function, validate that the structure is \\\n correct, then process the XML elements and return the data as a list.\"\n\n isValid = None\n global dbWriteList\n prepList = []\n\n # Check filename for customer number if cusNumber isn't passed.\n if cusNumber == None:\n cusNumber = os.path.splitext(os.path.basename(document))[0]\n cusNumber = str(cusNumber).encode('ascii')\n # Verify that the destination customer record exists. Source was verified by input function.\n _dbCur.execute('select count(*) from pm_customer where customer_id=' + cusNumber)\n cusVerify = _dbCur.fetchone()[0]\n if cusVerify == 0:\n _dbCur.execute('insert into pm_customer (customer_id) values (' + cusNumber + ')')\n print 'Customer number,', cusNumber, 'was created. Moving on.'\n else:\n print 'Customer number,', cusNumber, 'exists. Moving on.'\n\n xmlItems = BeautifulSoup(open(document))\n\n # This for loop parses the document and matches XML objects using the typePattern list.\n # As each object is found, it is appended to the prepList. The prepList is then appended\n # to the dbWriteList list after the for loop has completed.\n for data in xmlItems.find_all('versioninfo'):\n typePattern = ('OS', 'APPSERVER', 'DATABASE', 'JAVA')\n if data.type.text == 'TAX':\n prepList.append(data.version.text.encode('ascii'))\n isValid = 1\n elif data.type.text in typePattern:\n prepList.append(data.vendor.text[:30].encode('ascii'))\n prepList.append(data.version.text[:65].encode('ascii'))\n prepList.append(cusNumber)\n\n if isValid == 1:\n print 'File processed successfully. Moving on.'\n dbWriteList.append(prepList)\n completedFiles.append(document)\n else:\n print 'File did not contain valid XML elements:', document\n failedFiles.append(document)\n\n return\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T23:27:04.053", "Id": "37152", "Score": "0", "body": "Welcome to Code Review! Answering your own question is perfectly normal. I've moved your edit into your answer, where it belongs. It would be appreciated if you could add a better description to your answer (about the changes you made, what issues BeautifulSoup helped you solve, etc). That way, others in the community can enjoy the benefits of your work." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T23:09:44.263", "Id": "24063", "ParentId": "24022", "Score": "1" } }, { "body": "<h3>1. Comments on your code</h3>\n\n<ol>\n<li><p>Your database queries use string concatenation and so are subject to <a href=\"http://en.wikipedia.org/wiki/SQL_injection\" rel=\"nofollow noreferrer\">SQL injection attacks</a>. Consider this pair of lines:</p>\n\n<pre><code>cusNumber = os.path.splitext(os.path.basename(document))[0]\n# ...\n_dbCur.execute('select count(*) from pm_customer where customer_id=' + cusNumber)\n</code></pre>\n\n<p>Imagine that an attacker were able to trick you into a processing a customer file with the name <code>0;drop database.xml</code>. This would cause you to execute the SQL command</p>\n\n<pre><code>select count(*) from pm_customer where customer_id=0;drop database\n</code></pre>\n\n<p>which I am sure wasn't what you intended to happen. You need to use SQL query parameters to pass untrusted data safely to SQL queries:</p>\n\n<pre><code>_dbCur.execute('select count(*) from pm_customer where customer_id=?', cusNumber)\n</code></pre></li>\n<li><p>If you just want to know if a customer number is present in the database, use an <code>EXISTS</code> query to make it clear what you mean and to give the database engine a chance to make a better execution plan:</p>\n\n<pre><code>select exists(select * from pm_customer where customer_id=?)\n</code></pre>\n\n<p>Use a <code>COUNT</code> query only when you actually want to know the number of matching records.</p>\n\n<p><strong>But</strong> there's no point in checking to see whether the customer exists in the database if you are just going to add them if they are not present. You should use a <a href=\"http://www.oracle-developer.net/display.php?id=203\" rel=\"nofollow noreferrer\"><code>MERGE</code> statement</a>, like this:</p>\n\n<pre><code>MERGE INTO pm_customer ON (customer_id = ?)\nWHEN NOT MATCHED THEN INSERT (customer_id) VALUES (?)\n</code></pre>\n\n<p>But even better than that would be to save up all the customers that you plan to add to the database, and then add in one big <code>MERGE</code> statement which you call via <code>executemany</code> (preferably the same statement in which you add the customer attributes).</p></li>\n<li><p>You get the contents of the <code>&lt;vendor&gt;</code> and <code>&lt;version&gt;</code> elements by executing <code>getElementsByTagName</code> queries. It would be more efficient to process the elements in the order they appear. (See section 2 below for an illustration of how to do this.)</p></li>\n<li><p>Your code is delicate: it will break if the order of data within the XML file changes. This is because it assembles <code>prepList</code> in the order in which the <code>&lt;versionInfo&gt;</code> elements appear in the XML. But the values in <code>prepList</code> will eventually be fed to a prepared database query which expects them to appear in the right order (first the <code>TAX</code> data, then the <code>OS</code> data, etc.). It would be better to collect the data in whatever order it appears, and then put it into the right order at the end. That way your code will not break if the <code>&lt;versionInfo&gt;</code> elements appear in a different order.</p></li>\n<li><p>You don't give the definition of <code>xmlTypeTuple</code> but it must be something like this:</p>\n\n<pre><code>xmlTypeTuple = 'TAX OS APPSERVER DATABASE JAVA'.split()\n</code></pre>\n\n<p>You then repeat this sequence of type names in the line</p>\n\n<pre><code>typePattern = re.compile('(TAX|OS|APPSERVER|DATABASE|JAVA)')\n</code></pre>\n\n<p>This violates the DRY (Don't Repeat Yourself) principle: if you had to add a new type it would be easy to make a mistake and add it to one of these and not the other. So you should write something like this:</p>\n\n<pre><code>typePattern = re.compile('({})'.format('|'.join(map(re.escape, xmlTypeTuple))))\n</code></pre>\n\n<p>(But see the next comment.)</p></li>\n<li><p>You match the content of the <code>&lt;type&gt;</code> element against <code>typePattern</code>. But then you immediately check the content to see if it's equal to one of the members of the <code>xmlTypeTuple</code> list. It's not necessary to carry out <em>both</em> of these tests. If the latter passes, the former must too. So I would suggest dropping the regular expression match altogether and just seeing if the content is a member of <code>xmlTypeTuple</code>.</p></li>\n<li><p>It's not clear what the point of <code>isValid</code> is. You set it to true as soon as the content of any single <code>&lt;type&gt;</code> element matches against <code>typePattern</code>. But you supply default values for all vendors and versions, so why is this necessary? Why is an empty customer record considered invalid?</p>\n\n<p>(Edited to add: I see that in the revised code in <a href=\"https://codereview.stackexchange.com/a/24063/11728\">your answer</a> you changed the behaviour so that <code>isValid</code> is set to true if there is an element with type <code>TAX</code>. This is still not clear to me. What's special about <code>TAX</code>?)</p></li>\n<li><p>There's no need for your empty <code>return</code> statement: when Python reaches the end of a function body, it returns automatically.</p></li>\n<li><p>Your design involves global state variables <code>dbWriteList</code>, <code>completedFiles</code>, and <code>failedFiles</code>. It is usually best practice to encapsulate persistent state into objects belonging to classes, and to turn the functions operating on that state into methods on the objects. See section 2 for some example code showing how you might do this.</p></li>\n<li><p>Your success message</p>\n\n<pre><code> print 'File processed successfully. Moving on.'\n</code></pre>\n\n<p>would be more useful if it contained the name of the document that was processed successfully.</p></li>\n<li><p>Failure messages like</p>\n\n<pre><code>print 'File did not contain valid XML elements:', document\n</code></pre>\n\n<p>ought to be printed to standard error, not standard output.</p></li>\n<li><p>The Python style guide (<a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>) says that names of variables should be in lower case with underscores. So <code>cusNumber</code> should be something like <code>customer_id</code>.</p></li>\n<li><p>You don't check for XML parsing errors. <code>minidom.parse</code> can raise various exceptions, for example:</p>\n\n<pre><code>&gt;&gt;&gt; minidom.parse('nonexistent.xml')\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\n File \"minidom.py\", line 1920, in parse\n return expatbuilder.parse(file)\n File \"expatbuilder.py\", line 922, in parse\n fp = open(file, 'rb')\nIOError: [Errno 2] No such file or directory: 'nonexistent.xml'\n\n&gt;&gt;&gt; minidom.parse('malformed.xml')\nTraceback (most recent call last):\n File \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\n File \"minidom.py\", line 1920, in parse\n return expatbuilder.parse(file)\n File \"expatbuilder.py\", line 924, in parse\n result = builder.parseFile(fp)\n File \"expatbuilder.py\", line 207, in parseFile\n parser.Parse(buffer, 0)\nxml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 1\n</code></pre>\n\n<p>If you want errors like this to just result in the file being added to <code>failedFiles</code>, then you should check for them.</p></li>\n<li><p>Code like</p>\n\n<pre><code>typeObj = data.getElementsByTagName(\"type\")[0].childNodes[0].data\n</code></pre>\n\n<p>will raise an exception if there are no elements with the tag name <code>type</code>, or if the first such elements has no child nodes, or if the first child node is not a text node. If you want errors like this to just result in the file being added to <code>failedFiles</code>, then you should check for them.</p></li>\n<li><p>It looks odd to me that you don't record the <code>&lt;vendor&gt;</code> for the <code>TAX</code> type, but do record it for all other types. Is that right? It might be worth a comment explaining why.</p></li>\n<li><p>It's a bad idea to have constants like <code>30</code> and <code>65</code> in the text. You can fetch these from the database by executing a query like</p>\n\n<pre><code>SELECT LENGTH(vendor), LENGTH(version) FROM pm_customer\n</code></pre>\n\n<p>Also I find it suspicious that you test the length against 30 and if it's longer, you truncate it to 30 character and then append <code>...</code>. Wouldn't this make it 33 characters long, which would be too long? Shouldn't you truncate it to 27 characters if you want the string with <code>...</code> to fit into a 30-character field?</p></li>\n<li><p>I don't like the way you do string encoding. Normally one would expect the Python database interface to perform any necessary string encoding for you. This would certainly be the case in the database systems I am familiar with (MySQL, PostgreSQL, and SQLite). However, you're using Oracle, and for all I know things are different there. But you might think about this issue and read some documentation.</p></li>\n<li><p>Your variable names are generally rather vague. Consider <code>dbWriteList</code>. Yes, it's a list of things that are going to be written to a database. But we don't really care that it's a list (that's just a minor detail of its implementation), and <em>what you plan to do to it</em> is much less important than <em>what it is</em>. So I would use a name like <code>customer_records</code>.</p>\n\n<p>Most of your names are vague in this way. I suggest having a good think about the meaning of each of them and then renaming them all. Like this:</p>\n\n<ul>\n<li><code>parseDocumentData</code> → <code>load_customer_file</code></li>\n<li><code>_dbCur</code> → <code>db_cursor</code></li>\n<li><code>cusNumber</code> → <code>customer_id</code></li>\n<li><code>prepList</code> → <code>customer</code></li>\n<li><code>vendorObj</code> → <code>vendor</code></li>\n<li><code>versionObj</code> → <code>version</code></li>\n<li><code>completedFiles</code> → <code>valid_customer_files</code></li>\n<li><code>failedFiles</code> → <code>invalid_customer_files</code></li>\n</ul></li>\n</ol>\n\n<h3>2. Improved code</h3>\n\n<p>This is how I would start refactoring the code. Not having an Oracle database to hand, and not knowing your database schema, I haven't been able to test the <code>MERGE</code> statement. But hopefully you will get the idea.</p>\n\n<pre><code>from xml.dom import minidom\nimport os\nimport sys\n\nclass CustomerLoader(object):\n \"\"\"\n Process customer XML files and add them to the database.\n Call the load_customer(filename) method for each customer file.\n Then call the commit() method to commit them all to the database.\n \"\"\"\n\n data_tags = 'type vendor version'.split()\n types = 'TAX OS APPSERVER DATABASE JAVA'.split()\n merge_customer = '''\n MERGE INTO pm_customers\n ON (customer_id = ?)\n WHEN MATCHED THEN UPDATE SET\n tax_version = ?,\n os_vendor = ?,\n os_version = ?,\n appserver_vendor = ?,\n appserver_version = ?,\n database_vendor = ?,\n database_version = ?,\n java_vendor = ?,\n java_version = ?\n WHEN NOT MATCHED THEN INSERT\n (customer_id, tax_version, os_vendor, os_version,\n appserver_vendor, appserver_version, database_vendor,\n database_version, java_vendor, java_version)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n '''\n\n def __init__(self, cursor):\n self.cursor = cursor\n self.reset()\n cursor.execute('SELECT LENGTH(os_vendor), LENGTH(os_version) FROM pm_customer')\n self.vendor_length, self.version_length = cursor.fetchone()\n\n def reset(self):\n self.customers = []\n self.valid_customer_files = []\n self.invalid_customer_files = []\n\n def encode(self, s, length):\n \"\"\"\n Return `s`, truncated to `length` characters and encoded as ASCII.\n \"\"\"\n s = s.encode('ascii')\n if len(s) &lt;= length:\n return s\n else:\n return s[:length - 3] + '...'.encode('ascii')\n\n def load_customer(self, filename, customer_id = None):\n \"\"\"\n Load customer data for `customer_id` from `filename` but do\n not commit it to the database yet. If `customer_id` is not\n supplied, use the basename of `filename`.\n \"\"\"\n if customer_id is None:\n customer_id = os.path.splitext(os.path.basename(filename))[0]\n try:\n dom = minidom.parse(filename)\n customer_data = {t: dict(vendor = 'Vendor unavailable',\n version = 'Version unavailable')\n for t in self.types}\n for version_info in dom.getElementsByTagName('versionInfo'):\n info = dict()\n for element in version_info.childNodes:\n if (element.nodeType == element.ELEMENT_NODE\n and element.tagName in self.data_tags\n and len(element.childNodes) == 1\n and element.childNodes[0].nodeType == element.TEXT_NODE):\n info[element.tagName] = element.childNodes[0].data\n if 'type' not in info:\n raise Exception(\"versionInfo is missing &lt;type&gt; element\")\n customer_data[info['type']] = info\n customer = [customer_id]\n for t in self.types:\n if t != 'TAX':\n # Omit the TAX vendor. Why?\n customer.append(self.encode(customer_data[t]['vendor'],\n self.vendor_length))\n customer.append(self.encode(customer_data[t]['version'],\n self.version_length))\n self.customers.append(customer)\n self.valid_customer_files.append(filename)\n sys.stdout.write(\"Loaded customer {}\\n\".format(filename))\n except Exception as e:\n self.invalid_customer_files.append(filename)\n sys.stderr.write(\"Failed to load customer {}: {}\\n\".format(filename, e))\n\n def commit(self):\n \"\"\"\n Commit the loaded customers to the database and reset the loader \n object.\n \"\"\"\n self.cursor.executemany(self.merge_customer,\n (c + c for c in self.customers))\n self.reset()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T20:17:18.773", "Id": "37290", "Score": "0", "body": "Thank you for the well thought-out answer. I was running into issues with executemany and forgot that merge was available. cx_Oracle is a little... weird. The files I'm passing are named by me, but you make a good point about the filename check. The DB user I use for the connection has minimal permissions and is unable to drop the tablespace, but that may not be the case with future projects. This is my first python project, so I really appreciate your input. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T22:45:45.283", "Id": "37295", "Score": "0", "body": "You're welcome. Re SQL injection attacks: even if you're certain that in *this* case the data is safe to concatenate, it's still a good idea to get in the habit of using SQL query parameters instead. You may be working in a riskier execution environment in the future. (Or your code may be ported to such an environment.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T17:44:54.010", "Id": "37708", "Score": "0", "body": "Gareth Rees: I wanted to give you feedback based on the itemized list you provided, given that you took the time to give such a complete response. 3: I agree. 4: The XML is structured the same way every time in this case, but I see that I can't re-use the code if I need to parse another type of XML data. 7: I was using isValid to tell me if a given XML file contained valid customer data. My program sorts valid and invalid files into failed and completed folders. 13: The files lack a version string for validation. 15: My company is the vendor for TAX, so I omit it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T17:49:46.313", "Id": "37712", "Score": "0", "body": "16: I used constants to prevent the Oracle DB version from causing problems as it contains a newline character. It seemed easier to just cut it off rather than do a re search for the character and then modifying the string. 17: cx_Oracle says it can do unicode without issue, but the tuples I was appending to my dictionary were coming in as mixed ascii and unicode and it broke. I found it necessary to convert them to ascii before adding them into the dictionary. cx_Oracle's documentation provides poor guidance if you don't know what you're doing to begin with. 18: I agree. I'll work on this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T09:27:44.847", "Id": "37741", "Score": "0", "body": "@tthayer: Thanks for your feedback: it's very nice to hear which items in the review were useful and which weren't. [7: understood, but it's not clear from the code whether the validation test is effective. 15: that would a good explanation to put in a comment. 16: in this item I was trying to say that literal numbers like `30` and `65` are mysterious unless you explain or compute them; I can only guess that these numbers are related to the length of some columns in the database.]" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T21:09:13.400", "Id": "37799", "Score": "0", "body": "I am still trying to wrap my head around the use of classes, as provided in your code example, but I think I'm getting it down, slowly. In my head it seems like it's easier to differentiate it as: Classes give you a way to define how work is done in each def so work can be done by another script or another function outside of your class. A def without a class defines how work is done while also doing the work. I'm not sure how correct that is." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T23:37:14.967", "Id": "24065", "ParentId": "24022", "Score": "3" } } ]
{ "AcceptedAnswerId": "24063", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T22:42:10.663", "Id": "24022", "Score": "3", "Tags": [ "python" ], "Title": "How can I make my XML parser more pythonic?" }
24022
<p>i wish to improve my Progressbar in Python</p> <pre><code>from __future__ import division import sys import time class Progress(object): def __init__(self, maxval): self._seen = 0.0 self._pct = 0 self.maxval = maxval def update(self, value): self._seen = value pct = int((self._seen / self.maxval) * 100.0) if self._pct != pct: sys.stderr.write("|%-100s| %d%%" % (u"\u2588"*pct, pct) + '\n') sys.stdout.flush() self._pct = pct def start(self): pct = int((0.0 / self.maxval) * 100.0) sys.stdout.write("|%-100s| %d%%" % (u"\u2588"*pct, pct) + '\n') sys.stdout.flush() def finish(self): pct = int((self.maxval / self.maxval) * 100.0) sys.stdout.write("|%-100s| %d%%" % (u"\u2588"*pct, pct) + '\n') sys.stdout.flush() toolbar_width = 300 pbar = Progress(toolbar_width) pbar.start() for i in xrange(toolbar_width): time.sleep(0.1) # do real work here pbar.update(i) pbar.finish() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T02:05:07.600", "Id": "37061", "Score": "1", "body": "CodeReview is to get review on code which is working, not to get some help to add a feature." } ]
[ { "body": "<p>As per my comments, I've not sure SE.CodeReview is the right place to get the help you are looking for.</p>\n\n<p>However, as I didn't read your question properly at first, I had a look at your code and changed a few things (please note that it's not exactly the same behavior as it used to be):</p>\n\n<ul>\n<li>extract the display logic in a method on its own</li>\n<li>reuse update in start and finish (little changes here : this method now updates the object instead of just doing some display)</li>\n<li>removed self._seen because it didn't seem useful</li>\n</ul>\n\n<p>Here the code :</p>\n\n<pre><code>class Progress(object):\n def __init__(self, maxval):\n self._pct = 0\n self.maxval = maxval\n\n def update(self, value):\n pct = int((value / self.maxval) * 100.0)\n if self._pct != pct:\n self._pct = pct\n self.display()\n\n def start(self):\n self.update(0)\n\n def finish(self):\n self.update(self.maxval)\n\n def display(self):\n sys.stdout.write(\"|%-100s| %d%%\" % (u\"\\u2588\"*self._pct, self._pct) + '\\n')\n sys.stdout.flush()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T02:19:30.073", "Id": "37062", "Score": "0", "body": "Thank Josay for the review. What i wish to do is print the percentage (1%, 2%, 3%, ..., 100%) in the middle of the progress bar." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T06:22:48.020", "Id": "37067", "Score": "0", "body": "@Gianni unfortunately, that's off-topic for Code Review. You should edit your question to be a valid code review request as defined in the [faq], otherwise it will be closed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T10:58:08.810", "Id": "37086", "Score": "0", "body": "@codesparkle it's a fuzzy definition about SO (= stackoverflow) or CR (code review). Normally people use this approach: code works CR, code doesn't work SO, no code Programmer. In my case the code works and i want to improve the quality. With a with a working code (no error) i think (maybe i wrong) this question is more appropriate in CD" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T02:11:02.147", "Id": "24024", "ParentId": "24023", "Score": "2" } } ]
{ "AcceptedAnswerId": "24024", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T23:05:03.840", "Id": "24023", "Score": "0", "Tags": [ "python", "optimization" ], "Title": "Progressbar in Python" }
24023
<p>The following <a href="/questions/tagged/batch" class="post-tag" title="show questions tagged 'batch'" rel="tag">batch</a> script runs on a Scheduled Task on Windows 7 with a quad core 2.5GHz and 16GB of DDR3.</p> <p>It makes the <a href="/questions/tagged/svn" class="post-tag" title="show questions tagged 'svn'" rel="tag">svn</a> server unavailable for about 10 minutes, so it can produce a 500MB file, and this is only increasing.</p> <p>How can I speed this up?</p> <pre><code>@echo off mode con cols=33 lines=3 &gt;nul color 1F if "%1"=="done" goto runtime start "" /min %0 done exit :runtime title Backing up SVN echo. echo. echo Backing up SVN... do NOT close! for /f "tokens=1-4 delims=/ " %%a in ('date /t') do (set bdate=%%c-%%b-%%a) for /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set btime=%%a-%%b) cd %temp% rd /s /q svnbackup &gt;nul 2&gt;&amp;1 md svnbackup cd svnbackup md certs md conf md uncommitted_db-pc cd uncommitted_db-pc net stop VisualSVNServer &gt;nul 2&gt;&amp;1 svn status C:\SVN-EDGE&gt;files.txt for /F "tokens=1*" %%T in ('svn status C:\SVN-EDGE') do xcopy "%%U" ".\%%~pU" /F /H /K /X /Y /R /Q &gt;nul 2&gt;&amp;1 svn status C:\INTERNAL&gt;&gt;files.txt for /F "tokens=1*" %%T in ('svn status C:\INTERNAL') do xcopy "%%U" ".\%%~pU" /F /H /K /X /Y /R /Q &gt;nul 2&gt;&amp;1 svn status C:\RESTRICTED&gt;&gt;files.txt for /F "tokens=1*" %%T in ('svn status C:\RESTRICTED') do xcopy "%%U" ".\%%~pU" /F /H /K /X /Y /R /Q &gt;nul 2&gt;&amp;1 cd .. "%ProgramFiles%\7-Zip\7z.exe" a -mx9 uncommitted_files.7z uncommitted_db-pc\* &gt;nul 2&gt;&amp;1 rd /s /q uncommitted_db-pc &gt;nul 2&gt;&amp;1 svnadmin dump --deltas --quiet S:/Customers &gt; Customers.dump svnadmin dump --deltas --quiet S:/Internal &gt; Internal.dump svnadmin dump --deltas --quiet S:/Restricted &gt; Restricted.dump net start VisualSVNServer &gt;nul 2&gt;&amp;1 for %%I in (S:\authz S:\authz-windows S:\htpasswd C:\INTERNAL\SVN\Backup.bat) do copy %%I . &gt;nul copy "%VISUALSVN_SERVER%\certs\*" certs &gt;nul copy "%VISUALSVN_SERVER%\conf\*" conf &gt;nul "%ProgramFiles%\7-Zip\7z.exe" a -mx9 %bdate%_%btime%.7z * &gt;nul 2&gt;&amp;1 move 2*.7z C:\Users\DB\Dropbox\Backups\SVN &gt;nul cd .. rd /s /q svnbackup &gt;nul 2&gt;&amp;1 exit </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T06:41:37.677", "Id": "37068", "Score": "0", "body": "For starters you could remove ***all*** unnecessary code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T06:41:58.237", "Id": "37069", "Score": "0", "body": "@ProfPickle Such as? If you're referring to the first 12 lines, these take <1s to run. Otherwise I don't know what you're referring to." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T06:44:31.167", "Id": "37070", "Score": "0", "body": "Color, title, a majority of the `echo` commands... There's not a lot you can do to increase the speed of a batch file." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T06:45:36.987", "Id": "37071", "Score": "0", "body": "@ProfPickle I really don't mind waiting 100ms or however long it takes to run them lines... I'm looking at the bigger picture. I know 1 option is to use `svn hotcopy`, but I think it'd involve rewriting the majority of the script, and I don't know whether it would result in a speed increase? Related SO question: http://stackoverflow.com/q/33055/1563422" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T06:47:49.553", "Id": "37072", "Score": "0", "body": "To be perfectly honest, the only thing that's going to increase the speed by any significant time is to choose another language. I know it's not the answer you're looking for but it's really a one way street here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T07:50:42.420", "Id": "37075", "Score": "0", "body": "What's the time breakdown look like (more time 7zing or dumping?)? What are the svn repos like (tons of little files? a few huge files? etc)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T07:52:53.770", "Id": "37076", "Score": "0", "body": "@Corbin I'll get a breakdown of what takes how long, but before I do, I don't suppose you know of a batch file performance profiling program? I tried the top hit on Google for `profile performance batch script`, but there's way too much noise for it to be useful (kernel/unrelated programs being profiled)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T07:59:37.137", "Id": "37077", "Score": "0", "body": "@DannyBeckett No idea :(. I rarely work with Windows batch scripts, but the few times I've had to figure out slow stuff, I just run things by hand. Basically what I'm trying to figure out is if you *can* speed this up. For example, if dumping the repo is taking 95% of the time, then there's not much you can do about that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T21:07:02.567", "Id": "37131", "Score": "0", "body": "Quote from Max Bowsher FYI: \"**Full-dump + bzip2 is smaller than delta-dump + bzip2** for at least some\nkinds of data sets. Delta-dumps are **require more CPU-work to produce** *and consume*\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T21:20:24.950", "Id": "37137", "Score": "0", "body": "This isn't an answer, but a wacky suggestion, probably too wacky for your context: how about using git-svn and storing the backup as a git repository? You retain round-trip to svn, don't bring down the repo, don't have to re-read revs already backed up, and gain git's fast and efficient repository storage." } ]
[ { "body": "<p>This isn't a great answer but I've found <em>some</em> tips to hopefully (not guaranteed) increase the speed of your batch files.</p>\n\n<blockquote>\n <p>Load Batch Files on to a RAM Drive. Use a small-size RAM drive with\n small cluster sizes to preserve memory. Then place the RAM Drive batch\n directory at or near the start of your path statement. Your batch\n files will run much faster because they are always in memory. Automate\n the process by placing statements in your AUTOEXEC.bat to create a RAM\n drive and then a BATCH directory on that RAM Drive. Next have it copy\n the batch files to it.</p>\n \n <p>Give Full Path names for all Commands. This allows DOS to go\n immediately to the directory required, thus saving a path search. So,\n as an example, if the MOVE command is to be used, issue it as\n \"C:\\DOS\\MOVE...\" rather than just \"MOVE...\" .</p>\n \n <p>This method can also be extended to issuing full paths for the files on which actions are to take place. This means that a command\n will act upon only files on the stated drive and in the stated\n directory. This is good because if the batch file were to\n inadvertently be run in a wrong directory, unexpected things might</p>\n \n <p>happen. Unintended files might even be deleted or modified. Directing\n DOS to the place where you want actions to occur, even if it is still\n within the current directory, is a wise and safe method.</p>\n</blockquote>\n\n<p>Unfortunately those are the only tips I could find, and they probably aren't even worth it. </p>\n\n<p>Sorry.</p>\n\n<p><strong>Source:</strong><br>\n<a href=\"http://www.chebucto.ns.ca/~ak621/DOS/Bat-Tips.html\" rel=\"nofollow\">http://www.chebucto.ns.ca/~ak621/DOS/Bat-Tips.html</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T07:03:33.200", "Id": "37073", "Score": "0", "body": "Thanks for the effort! Are paragraphs 2 onwards still relevant? It mentions DOS a few times... also, what's the source for this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T07:44:52.050", "Id": "37074", "Score": "0", "body": "The source seems pretty old (it has that ***musky*** smell). That's why I added the disclaimer \"hopefully\", because generally modern computers don't care if you use direct paths or not." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T06:58:00.800", "Id": "24029", "ParentId": "24025", "Score": "1" } }, { "body": "<p>I'm afraid, you can't get reasonable speed change in your case:</p>\n\n<ul>\n<li>I think, most time your bat-file perform <code>svnadmin dump</code>, where you have minimal amount of possibilities to change anything (except testing changing from <code>--deltas</code> to incremental|revision-range dumps)</li>\n<li>You can think about changing backup-strategy: use svnsync or backup repositories as <em>ordinary directories and additional files</em></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T21:00:22.937", "Id": "24060", "ParentId": "24025", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T02:29:20.060", "Id": "24025", "Score": "0", "Tags": [ "windows", "batch", "svn" ], "Title": "Speed up SVN backup" }
24025
<p>I have a pack of cards and I am doing a 'deal' action. I am dealing <code>n</code> number of cards, for now to one player.</p> <p>How can I DRY up the <code>while</code> and <code>unless</code> loops to have fewer lines?</p> <pre><code>def deal(number_of_players, number_of_cards_each) # 1..number_of_players players_cards_array=[] (1..number_of_cards_each).each do |a_card| added_card=false while added_card==false new_card = choose_card() unless @currently_dealt_cards.include?(new_card) players_cards_array &lt;&lt; new_card added_card= true @currently_dealt_cards &lt;&lt; new_card end end end return players_cards_array end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T05:27:24.437", "Id": "37064", "Score": "1", "body": "You are not using `number_of_players` parameter, returning cards for one player only. You should get your algorithm straight first." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T13:04:14.777", "Id": "37092", "Score": "0", "body": "Yes that is true. It was commented out while I got the other bits right, left as a reminder, could have been marked #todo. I'm a bit looser with play around code" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T16:48:04.747", "Id": "37107", "Score": "2", "body": "Instead of getting *this* algorithm straight, you should choose a new algorithm, one which more closely matches what happens in real life. Collect the 52 cards into an array, and shuffle it. Then just pop cards off the top as required." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T17:38:09.970", "Id": "37259", "Score": "0", "body": "What's the name of the object with the `deal` method?" } ]
[ { "body": "<p>If I get your code right you are creating random cards while dealing. I would move this at the beginning to make your dealing cleaner. I'm no ruby guy, so I have to offer some pseudo code:</p>\n\n<pre><code>// List/Array of 52/32... Cards (just a trivial loop over the ranks and suits)\nall_cards=generateDeck() \n// use what ever ruby offers, i.e. array_shuffle in php\nshuffled_cards=shuffle(all_cards)\ncard_player[0]=subArray(all_cards,0,numberOfCardsPerPlayer)\n..\n</code></pre>\n\n<p>Of course you can use some fancy stuff here to deal card in the 3-2-4-2 order for skat. You could use some array_pop/shift to get the first/last card of you shuffled deck and assign it to a player.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T05:22:34.330", "Id": "24028", "ParentId": "24026", "Score": "0" } }, { "body": "<p>I agree with @mnhg: if you had the collection of cards beforehand, things would simplify dramatically:</p>\n\n<pre><code>players_cards = all_cards.sample(nplayers * ncards_each).each_slice(ncards_each).to_a\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T12:02:46.613", "Id": "24035", "ParentId": "24026", "Score": "2" } }, { "body": "<p>While I agree with the existing answers (you should refactor to simply shuffle and return the first <em>n</em> cards), you can clean up your existing code dramatically by getting rid of all the temporary variables. The result is 5 slim lines of Ruby:</p>\n\n<pre><code>def deal(number_of_players, number_of_cards_each)\n (1..number_of_cards_each).map do\n begin\n card = choose_card()\n end while @current_dealt_card.include? card\n @currently_dealt_cards &lt;&lt; card\n card\n end\nend\n</code></pre>\n\n<p>First thing, note the use of <code>map</code> to do away with the <code>players_card_array</code> stuff. Any time you see this very typical pattern....</p>\n\n<pre><code>def get_items\n # make an empty array\n items_to_return = []\n\n # map some existing array to a set of new values\n some_other_items.each do |item|\n items.to_return &lt;&lt; modify_item(item)\n end\n\n # return new values\n return items_to_return\nend\n</code></pre>\n\n<p>... you should be using map, and letting the result \"fall off\" the end of the method and be implicitly returned:</p>\n\n<pre><code>def get_items\n some_other_items.map |item|\n modoify_item(item)\n end\nend\n</code></pre>\n\n<p>Secondly, instead of initializing a watch variable (<code>added_card = false</code>) and looping until it's set to true by some condition inside the loop, make the condition a condition of the loop:</p>\n\n<pre><code>added_card=false\nwhile added_card==false\n new_card = choose_card()\n unless @currently_dealt_cards.include?(new_card)\n players_cards_array &lt;&lt; new_card\n added_card= true\n @currently_dealt_cards &lt;&lt; new_card\n end \nend \n</code></pre>\n\n<p>becomes Ruby's equivalent of a do/while loop:</p>\n\n<pre><code>begin\n card = choose_card()\nend while @currently_dealt_cards.include? card\n@currently_dealt_cards &lt;&lt; new_card\n</code></pre>\n\n<p>You could further DRY up the above, by having <code>@currently_dealt_cards</code> be a <code>Set</code>, and then use:</p>\n\n<pre><code>begin\n card = choose_card()\nend until @currently_dealt_cards.add? card\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T16:42:34.080", "Id": "24049", "ParentId": "24026", "Score": "0" } }, { "body": "<p>I would model the domain with objects. A good set of classes would be <code>Deck</code>, <code>Player</code>, and <code>Card</code>. This will hide away implementation details and keep things easy to read. It also helps with naming, e.g. a 'hand' attribute is much easier to grok than 'players_cards_array'.</p>\n\n<p>Then your code might look something like this:</p>\n\n<pre><code>players.each do |player|\n player.hand = @deck.draw(5)\nend\n</code></pre>\n\n<p>Simple, eh? Of course, the details are in the classes. The classes will start very simple but the nice thing is when you need to add more logic you'll have a place for it, and this will help prevent your application from becoming a BBOC (big ball of code). Sample supporting classes might look something like this:</p>\n\n<pre><code>class Player\n attr_accessor :hand\nend\n\nclass Deck\n attr_reader :cards\n\n def initialize\n # Create your 52 Cards\n @cards.shuffle!\n end\n\n def draw(n)\n @cards.take(n)\n end\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-21T12:43:24.070", "Id": "24200", "ParentId": "24026", "Score": "0" } } ]
{ "AcceptedAnswerId": "24035", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T02:37:36.570", "Id": "24026", "Score": "1", "Tags": [ "ruby", "playing-cards" ], "Title": "Deal action with a pack of cards" }
24026
<p>I have an abstract class which implements the <code>IDataCreator</code> interface:</p> <pre><code>public interface IDataCreator { public String getDataString(); } public abstract class AbstractCreator implements IDataCreator { protected IProject p; public AbstractCreator(IProject p) { this.p = p; } public abstract String getDataString(); } </code></pre> <p>Then I have 5 concrete classes which extend <code>AbstractCreator</code> and implement the <code>getDataString()</code> method:</p> <pre><code>public class ProjectManagerCreator extends AbstractCreator { public ProjectManagerCreator(IProject p) { super(p); } @Override public String getDataString() { if(p.getLead() != null) { String lead = p.getLead().getName(); return lead; } return ""; } } </code></pre> <p>Factory class is implemented like this:</p> <pre><code>public class ProjectDataCreatorFactory { IProject p = null; public ProjectDataCreatorFactory(IProject p) { this.p = p; } /** * Factory method which constructs a object from a given string value. * * @param column string of the column name TODO: Implement a interface which maps the strings into static variables * @return object which implements the {@link IDataCreator} interface */ public IDataCreator createFromString(String column) { IDataCreator creator = null; if(column.equals("name")) { return new URLCreator(p); } else if(column.equals("status")) { return new ProjectStatusCreator(p); } else if(column.equals("manager")) { return new ProjectManagerCreator(p); } else if(column.equals("setupdate")) { return new ProjectDateCreator(p, ProjectDateCreator.CREATION); } else if(column.equals("updatedate")) { return new ProjectDateCreator(p, ProjectDateCreator.UPDATED); } return creator; } } </code></pre> <p>The factory class is called like this:</p> <pre><code>ProjectDataCreatorFactory factory = new ProjectDataCreatorFactory(p); String s = factory.createFromString("name").getDataString(); </code></pre> <p><strong>Question</strong></p> <p>Is this the (or a) correct way to use the <a href="http://en.wikipedia.org/wiki/Abstract_factory_pattern" rel="noreferrer">Factory Pattern</a>? Is the approach with an interface and an abstract class a good design?</p>
[]
[ { "body": "<p>Note that there isn't a so called factory pattern, there is factory method and there is abstract factory.</p>\n\n<p>I would create a separate factory class for ProjectDateCreator.CREATION and ProjectDateCreation.UPDATED. To answer your original question, never be afraid of interfaces and abstract classes. Interfaces are good for you.</p>\n\n<p>Besides an abstract ProjectDateCreator class I would make each factory a singleton and if you know the value of createFromString's String argument compile-time then you can replace it with createURLCreator, createProjectStatusCreator etc. methods. That would make the code a bit more readable (yes, I know, this createFromString method is a small one, but we software developers are even too lazy for that). The IDataCreator --> AbstractCreator --> ProjectManagerCreator inheritance chain is good, no composition is needed here, the abstract class extension is a good approach. I would add that in an abstract class it's not necessary to include unimplemented interface methods.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T10:26:46.160", "Id": "24034", "ParentId": "24031", "Score": "1" } }, { "body": "<p>Some design considerations:</p>\n\n<ul>\n<li><p><strong>Returning Null</strong>: Your factory method <code>createFromString</code> returns a <code>null</code> creator if the column is unknown. It's good practice to note this in the javadoc or perhaps throw an <code>IllegalArgumentException</code> if a column you can't handle is passed in.</p></li>\n<li><p><strong>Date Abstraction:</strong> <code>ProjectDateCreator</code>looks like it could use either its own factory or two separate implementations based on the second constructor argument. That class isn't included here, but it appears <code>CREATION</code> and <code>UPDATED</code> are some sort of <code>public static final</code> type constants. Those would be better expressed as an enum:</p>\n\n<pre><code>// A factory can use this instead!\npublic enum ProjectDateOption {\n CREATION, UPDATED;\n}\n</code></pre></li>\n<li><p><strong>Interface Naming:</strong> Interfaces in Java aren't typically prefixed with an <code>I</code>, but if it's consistent through your code then that's a minor quibble.</p></li>\n<li><p><strong>Column Strings</strong>: Your <code>TODO</code> mentions this, but the column strings could also be placed into an enum, and then the checking could occur there.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T15:45:52.717", "Id": "37098", "Score": "1", "body": "Thanks for your considerations! I did not use \"enums\" before but it seems that this is a good way to handle with type constants." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T15:48:14.130", "Id": "37099", "Score": "0", "body": "Enums are the most under-used, yet one of the more powerful Java features. They can be really handy for these types of things: http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T14:02:59.743", "Id": "24037", "ParentId": "24031", "Score": "3" } } ]
{ "AcceptedAnswerId": "24037", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T08:05:42.860", "Id": "24031", "Score": "6", "Tags": [ "java", "design-patterns", "factory-method" ], "Title": "Is this a correct way to use Factory Pattern?" }
24031
<p>I haven't spent too much time with CoffeeScript and am trying to have a simple counter:</p> <pre><code>casper.on('step.complete', ( -&gt; i = 0 return (step) -&gt; i += 1 @echo "Step#{ i }" )()) </code></pre> <p>Which works fine but seems to have a bit too many parenthesis for CoffeeScript.</p>
[]
[ { "body": "<p>I would certainly distangle the code and create a named function instead of an anonymous one.</p>\n\n<pre><code>step_creator = -&gt;\n i = 0\n return (step) -&gt;\n i += 1\n @echo \"Step#{ i }\"\n\ncasper.on 'step.complete', step_creator()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T19:31:47.277", "Id": "37114", "Score": "1", "body": "This is *still* an anonymous function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T03:21:12.617", "Id": "37159", "Score": "1", "body": "@meagar, one of the functions is no longer anonymous, isn't it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T13:23:11.480", "Id": "37174", "Score": "0", "body": "@WinstonEwert Both functions are still anonymous. `step_creator = ->` compiles to `step_creator = function() {`, not to `function step_creator() {`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T15:43:47.650", "Id": "37188", "Score": "2", "body": "@meagar, isn't that an implementation detail? From the perspective of the programmer, he's creating a function named step_creator." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T16:04:08.813", "Id": "37189", "Score": "0", "body": "@WinstonEwert \"Anonymous function\" *means* something in JavaScript, and by extension, CoffeeScript. It's no more an implementation detail in CoffeeScript than it is in JavaScript; but regardless, saying \"It's now a named function instead of an anonymous one\" when it *isn't* is still wrong." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T16:28:35.580", "Id": "37192", "Score": "1", "body": "@meagar, some versions of CoffeeScript actually would compile it as a named function, they don't do it now because of bugs in IE. So I submit that it is in fact an implementation detail. From the perspective of the CoffeeScript programmer whether its a named or anonymous javascript function doesn't matter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T16:33:53.910", "Id": "37193", "Score": "0", "body": "@WinstonEwert I'm really confused about what you're arguing. This answer is still incorrect, regardless of whether this is or isn't an implementation detail. Are you suggesting that, because a statement concerns implementation details, it's OK for that statement to be false? I could say \"`true` in CoffeeScript cross-compiles to `false` in JavaScript\", which is obviously false, but apparently because that's an implementation detail, I am still \"correct\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T16:58:39.530", "Id": "37195", "Score": "1", "body": "@meagar, I'm saying that what it compiles into is irrelevant. In C++, a for loop compiles into a number of branches and conditions. But that's an implementation detail. It would be silly to claim that C++ doesn't really have a for loop because its compiled into conditions and branches. So I think its equally incorrect to claim that CoffeeScript doesn't have named function simply because they are always compiled into anonymous functions in Javascript." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T16:59:46.563", "Id": "37196", "Score": "1", "body": "@meagar, this is the equivalent of a named function in CoffeeScript. So I see no problem with calling it a named function. Robert wasn't making any sort of statement about how the function would be implemented in Javascript. He's not talking about what it would be cross-compiled as. He's talking about how the code functions in CoffeeScript. It functions by creating a function and giving it a name. The function is not anonymous because it has a name." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T17:06:55.087", "Id": "37198", "Score": "0", "body": "@WinstonEwert As I said, *words mean things*. This isn't a \"named function\" because there is no such thing in CoffeeScript. There are only anonymous functions. Calling it a \"named function\" is inventing a new meaning for something that *already has significant meaning*, and it doesn't make it a named function, which *is a real thing which already exists*." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T17:24:21.163", "Id": "37199", "Score": "0", "body": "@meagar, you can argue that. But I don't think that what you argued before. You argued that it wasn't a named function because of what it compiled into javascript. My argument was that I don't care what it compiles into in javascript. What matters is what it mean in CoffeeScript." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T17:26:32.303", "Id": "37200", "Score": "0", "body": "@meagar, I'll agree that it is a bit of a stretch to call this a named function because in CoffeeScript its a function expression assigned to a variable. But I think it a reasonable stretch to make because: 1) its perfectly clear what robert meant, 2) there is no other meaning of named function in CoffeeScript and 3) I can't see any other non-awkward way of stating what he did." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T17:26:56.963", "Id": "37201", "Score": "0", "body": "@meagar, so you can say that you're technically correct to claim that its not a real named function. But at that point I think you are just nitpicking." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T18:17:42.333", "Id": "37202", "Score": "0", "body": "@WinstonEwert It's not nitpicking to say somebody is wrong when they say something that is *wrong*, and if you want to give him a pass because his understanding of what \"anonymous function\" means is shaky, that's fine. But anonymous functions and named functions *are different*, and they do *different things*, and by calling this a named function he's stating that *named function behaviour* should be available, and it isn't. This isn't just a semantic debate, this is about actual, real, demonstrable incorrectness." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T18:22:03.623", "Id": "37204", "Score": "0", "body": "@WinstonEwert CoffeeScript may transcompile to JavaScript, but that doesn't mean the whole of JavaScript is simple \"implementation\" to be ignored. Telling somebody they should adopt alternate *incorrect* meanings for JavaScript terms in CoffeeScript is insane." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T19:02:26.787", "Id": "37206", "Score": "0", "body": "@meagar, its clear we aren't going to reach consensus. I've opened a question: http://programmers.stackexchange.com/questions/191196/coffeescript-and-named-functions, to see what others say. But I would like to say that I'm not trying to give him a pass for not understanding anonymous functions. I think he's using a broader definition of named function then you, I see no evidence that he doesn't understand." } ], "meta_data": { "CommentCount": "16", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T17:18:54.000", "Id": "24052", "ParentId": "24038", "Score": "1" } }, { "body": "<p>You could do this:</p>\n\n<pre><code>casper.on 'step.complete', do -&gt; # invoked right away\n i = 0\n -&gt; @echo \"Step#{ ++i }\" # implicitly returned function\n</code></pre>\n\n<p>Parentheses: None :-)</p>\n\n<p>The <code>do</code> keyword is the equivalent of <code>(-&gt; ...)()</code>, i.e. it means \"invoke the following function immediately\" (it's also useful to avoid closure pitfalls in loops, by the way.)</p>\n\n<p>The <code>++i</code> will increment <code>i</code> before it's echo'ed, and CoffeeScript has implicit return, so the <code>return</code> keyword can be skipped.</p>\n\n<p>Lastly, I left out the <code>step</code> function argument, as you're not using it for anything; you're always adding 1. You can always add it back in of course</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T17:40:19.623", "Id": "24054", "ParentId": "24038", "Score": "3" } }, { "body": "<p>A further tweak to Flambino's answer <a href=\"https://codereview.stackexchange.com/a/24054/27783\">https://codereview.stackexchange.com/a/24054/27783</a>:</p>\n\n<pre><code>casper.on 'step.complete', do (i=0) -&gt;\n -&gt; @echo \"Step#{ ++i }\"\n</code></pre>\n\n<p>which compiles to:</p>\n\n<pre><code>casper.on('step.complete', (function(i) {\n return function() {\n return this.echo(\"Step\" + (++i));\n };\n})(0));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-07T06:41:07.067", "Id": "29484", "ParentId": "24038", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T14:51:22.243", "Id": "24038", "Score": "1", "Tags": [ "coffeescript", "closure" ], "Title": "Cleanest way to close over a counter in CoffeeScript" }
24038
<p>I need the most efficient way to get the value of the searchName, or if null return searchName. I am returning just a single string, so maybe I should search itemRepository.Item instead of Items</p> <pre><code>return itemRepository.Items() .Where(i =&gt; i.Name.Contains(searchName)) .Select(i =&gt; i.Value) .FirstOrDefault() ?? searchName; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T15:56:46.863", "Id": "37100", "Score": "0", "body": "Why is `Items` a method rather than a property (as evidenced by the `()`)? Other than that question, this seems exactly the canonical way I'd do what you're looking for." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T16:00:54.010", "Id": "37101", "Score": "0", "body": "Yeah it is a bit weird, but its calling an API, which returns a set of Items, I can also pass in a filter and a sort to the method. I just feel like I am looping one too many times" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T16:05:04.633", "Id": "37102", "Score": "0", "body": "1. You should not be concerned with the internal workings of LINQ - the designers have gone through great lengths to make it as optimal as possible. There are no direct loops in your code.\n\n2. That being said, I only see a single loop - the one that goes over all items and pulls out the `Value` of those that contain `searchName` in its `Name`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T16:32:18.123", "Id": "37105", "Score": "1", "body": "You can combine the `.Select()` and the `.FirstOrDefault()`, but other than that, there's nothing else you can do to this query." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T16:47:48.440", "Id": "37106", "Score": "0", "body": "@Bobson combine them how?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T17:08:22.453", "Id": "37109", "Score": "0", "body": "ah right, looks good!" } ]
[ { "body": "<p>As long as <code>Items()</code> returns an <code>IQueryable&lt;Item&gt;</code> directly from the database, then this code is just about as fast as you can get it. If not, I think your <code>Items()</code> method will be the main bottleneck in this code. </p>\n\n<p>From your comment it sounds like <code>Items()</code> is indeed trying to do more work than necessary. You should either directly reference the <code>IQueryable</code> collection of the repository and bypass the <code>Items()</code> method <em>or</em> focus your efforts on improving the efficiency of that method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T16:26:03.410", "Id": "24047", "ParentId": "24042", "Score": "5" } } ]
{ "AcceptedAnswerId": "24047", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T15:39:36.797", "Id": "24042", "Score": "-1", "Tags": [ "c#", "linq" ], "Title": "making this linq query faster" }
24042
<p><a href="http://en.wikipedia.org/wiki/Transact-SQL" rel="nofollow">Transact-SQL</a> (TSQL) is a proprietary SQL dialect used by Microsoft and Sybase in their relational database products. Since Microsoft's SQL Server originated from a Sybase codebase, the general syntax and some system functions are very similar on both platforms, however they are not compatible and there are many differences in more recent versions as both vendors added support for new features.</p> <p>Questions about TSQL should also be tagged for <a href="/questions/tagged/sql-server" class="post-tag" title="show questions tagged 'sql-server'" rel="tag">sql-server</a> or <a href="/questions/tagged/sybase" class="post-tag" title="show questions tagged 'sybase'" rel="tag">sybase</a> as appropriate, and the product version is also important because some language features are only supported in specific versions of SQL Server or Sybase ASE.</p> <p>Details of both TSQL variants can be found in the <a href="http://msdn.microsoft.com/en-us/library/bb510741.aspx" rel="nofollow">Microsoft Transact-SQL Reference</a> and the <a href="http://manuals.sybase.com/onlinebooks/group-as/asg1250e/sqlug/@Generic__BookView" rel="nofollow">Sybase Transact-SQL User's Guide</a>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T15:43:30.327", "Id": "24043", "Score": "0", "Tags": null, "Title": null }
24043
Transact-SQL (TSQL) is the extended SQL dialect used in Microsoft SQL Server and Sybase. Please also tag with either [sql-server] or [sybase].
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T15:43:30.327", "Id": "24044", "Score": "0", "Tags": null, "Title": null }
24044
<p>A general question: For using matlabpool, I write the line</p> <pre><code>matlabpool open local 12; </code></pre> <p>as the first line in my code and the line:</p> <pre><code>matlabpool close; </code></pre> <p>as the last. Is this correct?</p>
[]
[ { "body": "<p>Seems to be fine according to <a href=\"http://www.mathworks.nl/help/distcomp/matlabpool.html\" rel=\"nofollow\">the documentation</a>.</p>\n\n<p>The only things you need to try are whether 12 is the best number for you, and whether it makes sense to close the matlabpool earlier (you might not gain anything from it for a postprocessing part). Furthermore it is of course always good to check whether it actually gives the speed increase that you are looking for.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T12:30:46.337", "Id": "30256", "ParentId": "24045", "Score": "2" } }, { "body": "<p>This is correct, but I would recommend you to use <code>matlabpool open local</code>. This lets matlab decide how many workers are used, 12 might require to much memory.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-13T11:54:34.863", "Id": "32638", "ParentId": "24045", "Score": "0" } }, { "body": "<p>My answer is very late, but I'd like to suggest a couple of improvements to your code.</p>\n\n<p>Firstly, I would use the functional form, rather than the command-dual form:</p>\n\n<pre><code>matlabpool('open', 'local', 12);\n</code></pre>\n\n<p>and</p>\n\n<pre><code>matlabpool('close');\n</code></pre>\n\n<p>as it's easier (if you later need to) to parameterize the number of workers or the cluster used.</p>\n\n<p>The next suggestion assumes that the instructions for opening and closing the pool are within a function. If you're just writing some quick code, this doesn't really matter, but for larger applications it's typically better to be writing reusable, modular functions with their own workspace rather than scripts.</p>\n\n<p>I would typically write two consecutive lines:</p>\n\n<pre><code>matlabpool('open', 'local', 12); \ncleaner = onCleanup(@()matlabpool('close'));\n</code></pre>\n\n<p>This creates an <code>onCleanup</code> object <code>cleaner</code> that will execute the supplied code (in other words <code>matlabpool('close')</code>) when it is deleted. It will be deleted when it goes out of scope, which happens <em>either</em> when the function completes and exits, <em>or</em> if the function exits due to an error or <kbd>Ctrl-C</kbd>.</p>\n\n<p>This pattern has two advantages:</p>\n\n<ol>\n<li>You are assured that the pool will always be closed, however the function terminates - if you leave the closing in a separate statement at the end, this may not always be reached due to an error earlier on.</li>\n<li>The commands for opening and closing the pool are right next to each other in the code, so when you're reading through it, you're more likely to be sure that the right thing is being done.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-10T11:37:08.470", "Id": "65262", "ParentId": "24045", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T15:59:22.620", "Id": "24045", "Score": "1", "Tags": [ "matlab" ], "Title": "Using matlabpool: Is my embedding correct?" }
24045
<p>Below is attempt to catch potential deadlocks at runtime in C#. Basically this class allows user to acquire locks in a pre-defined order only. I ran some basic tests and it appears to work. Please review and let me know if you find something wrong with implementation.</p> <pre><code>public class OrderedLock { [ThreadStatic] static HashSet&lt;int&gt; mAcquiredLocks; static ConcurrentDictionary&lt;int, object&gt; mCreatedLocks = new ConcurrentDictionary&lt;int, object&gt;(); private int mId; private ThreadLocal&lt;int&gt; mRefCount = new ThreadLocal&lt;int&gt;(false); private ReaderWriterLockSlim mLock; public OrderedLock(int id) { if (!mCreatedLocks.TryAdd(id, null)) throw new ApplicationException("Duplicate identifier detected"); mId = id; mRefCount.Value = 0; mLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); } public void AcquireReadLock() { CheckLockOrder(); mLock.EnterReadLock(); } public void AcquireWriteLock() { CheckLockOrder(); mLock.EnterWriteLock(); } public void ReleaseReadLock() { mRefCount.Value -= 1; mLock.ExitReadLock(); if (mRefCount.Value == 0) mAcquiredLocks.Remove(mId); } public void ReleaseWriteLock() { mRefCount.Value -= 1; mLock.ExitWriteLock(); if (mRefCount.Value == 0) mAcquiredLocks.Remove(mId); } private void CheckLockOrder() { if (mAcquiredLocks == null) mAcquiredLocks = new HashSet&lt;int&gt;(); if (!mAcquiredLocks.Contains(mId)) { if (mAcquiredLocks.Count &gt; 0 &amp;&amp; mAcquiredLocks.Max() &gt; mId) throw new ApplicationException("Invalid order of locking detected"); else mAcquiredLocks.Add(mId); } mRefCount.Value += 1; } } </code></pre>
[]
[ { "body": "<p>I haven't extensively tested it, but there are a few things I've noted:</p>\n\n<ul>\n<li>The class has two members which hold on to <code>IDisposable</code> resources. Therefore, the class <strong>must</strong> implement <code>IDisposable</code> as well and <code>Dispose()</code> of those members.</li>\n<li>Many of the class members are assigned at construction time only. Mark them as <a href=\"http://msdn.microsoft.com/en-us/library/acdd6hb7.aspx\" rel=\"nofollow noreferrer\"><code>readonly</code></a> to signify intent and to <em>potentially</em> allow the runtime to perform some optimizations.</li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/vstudio/ms229043.aspx\" rel=\"nofollow noreferrer\">Current naming conventions</a> favor <code>camelCasing</code> over Hungarian Notation for class members.</li>\n<li><code>+= 1</code> and <code>-= 1</code> can be simplified to <code>++</code> and <code>--</code>, respectively.</li>\n<li><code>ApplicationException</code> has been <a href=\"https://blogs.msdn.com/b/kcwalina/archive/2006/06/23/644822.aspx?Redirected=true\" rel=\"nofollow noreferrer\">out of favor</a> for quite a long time.</li>\n<li><a href=\"https://stackoverflow.com/a/2732076/3312\">Identify your class members with the <code>this</code> keyword</a>.</li>\n<li>Forgot to put this bullet point in on the first cut: replace <code>.Count() &gt; 0</code> with <code>.Any()</code>. This is idiomatic to <em>what</em> you want, rather than <em>how</em> to do it. In other words, the implementation of the former could very well iterate over the entire collection to get the count, while the latter may just check for the existence of one in its collection.</li>\n<li>Another omission: I replaced the declaration of <code>HashSet&lt;int&gt;</code> with <code>ISet&lt;int&gt;</code> since coding to interfaces allows for more flexibility in changing implementations later on.</li>\n</ul>\n\n<p>All that being said, here's a first-cut rework:</p>\n\n<pre><code>public class OrderedLock : IDisposable\n{\n private static readonly ConcurrentDictionary&lt;int, object&gt; createdLocks = new ConcurrentDictionary&lt;int, object&gt;();\n [ThreadStatic]\n private static ISet&lt;int&gt; acquiredLocks;\n\n private readonly ThreadLocal&lt;int&gt; refCount = new ThreadLocal&lt;int&gt;(false);\n private readonly ReaderWriterLockSlim locker = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);\n private readonly int id;\n\n /// &lt;exception cref=\"InvalidOperationException\"&gt;Duplicate identifier detected&lt;/exception&gt;\n public OrderedLock(int id)\n {\n if (!createdLocks.TryAdd(id, null))\n {\n throw new InvalidOperationException(\"Duplicate identifier detected\");\n }\n\n this.id = id;\n this.refCount.Value = 0;\n }\n\n public void AcquireReadLock()\n {\n this.CheckLockOrder();\n this.locker.EnterReadLock();\n }\n\n public void AcquireWriteLock()\n {\n this.CheckLockOrder();\n this.locker.EnterWriteLock();\n }\n\n public void ReleaseReadLock()\n {\n this.refCount.Value--;\n this.locker.ExitReadLock();\n if (this.refCount.Value == 0)\n {\n acquiredLocks.Remove(this.id);\n }\n }\n\n public void ReleaseWriteLock()\n {\n this.refCount.Value--;\n this.locker.ExitWriteLock();\n if (this.refCount.Value == 0)\n {\n acquiredLocks.Remove(this.id);\n }\n }\n\n public void Dispose()\n {\n while (this.locker.IsWriteLockHeld)\n {\n this.ReleaseWriteLock();\n }\n\n while (this.locker.IsReadLockHeld)\n {\n ReleaseReadLock();\n }\n\n this.locker.Dispose();\n this.refCount.Dispose();\n GC.SuppressFinalize(this);\n }\n\n /// &lt;exception cref=\"InvalidOperationException\"&gt;Invalid order of locking detected&lt;/exception&gt;\n private void CheckLockOrder()\n {\n if (acquiredLocks == null)\n {\n acquiredLocks = new HashSet&lt;int&gt;();\n }\n\n if (!acquiredLocks.Contains(this.id))\n {\n if (acquiredLocks.Any() &amp;&amp; acquiredLocks.Max() &gt; this.id)\n {\n throw new InvalidOperationException(\"Invalid order of locking detected\");\n }\n\n acquiredLocks.Add(this.id);\n }\n\n this.refCount.Value++;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T17:00:49.043", "Id": "24050", "ParentId": "24046", "Score": "1" } } ]
{ "AcceptedAnswerId": "24050", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T16:06:31.623", "Id": "24046", "Score": "3", "Tags": [ "c#", "multithreading" ], "Title": "Implementation of ordered lock pattern" }
24046
<p>In the project I work on there are several places where a switch statement is used on a type enum. (I know, better to use virtual functions or a visitor pattern or something, but sometimes switching on type codes is unavoidable - e.g., deserializing XML.) All of our type enums are of the simple form <code>enum { TypeA, TypeB, TypeC, NumTypes }</code> so it is known at compile time that all type codes for a given type are in the half-open range [0, NumTypes).</p> <p>I decided to see if I could make the compiler verify that all type codes were being checked, and this is what I came up with:</p> <pre><code>// Switch.h template &lt;int iIndex, int iCount, class Dispatcher&gt; struct Switcher { typename Dispatcher::ResultType operator()( const Dispatcher&amp; dispatcher, int iCase ) const { if ( iCase == iIndex ) { return dispatcher.template Case&lt;iIndex&gt;(); } else { return Switcher&lt;iIndex + 1, iCount, Dispatcher&gt;()( dispatcher, iCase ); } } }; template &lt;int iCount, class Dispatcher&gt; struct Switcher&lt;iCount, iCount, Dispatcher&gt; { typename Dispatcher::ResultType operator()( const Dispatcher&amp; dispatcher, int iCase ) const { return dispatcher.Default( iCase ); } }; template &lt;int iCount, class Dispatcher&gt; typename Dispatcher::ResultType Switch( const Dispatcher&amp; dispatcher, int iCase ) { return Switcher&lt;0, iCount, Dispatcher&gt;()( dispatcher, iCase ); } </code></pre> <p>Example use:</p> <pre><code>#include "Switch.h" #include &lt;iostream&gt; #include &lt;cassert&gt; #include &lt;string&gt; enum MyType { TypeA, TypeB, TypeC, NumTypes }; class MyDispatcher { public: typedef std::string ResultType; template &lt;int iType&gt; std::string Case() const; std::string Default( int iType ) const; }; template &lt;&gt; std::string MyDispatcher::Case&lt;TypeA&gt;() const { return "TypeA"; }; template &lt;&gt; std::string MyDispatcher::Case&lt;TypeB&gt;() const { return "TypeB"; }; template &lt;&gt; std::string MyDispatcher::Case&lt;TypeC&gt;() const { return "TypeC"; }; std::string MyDispatcher::Default( int iType ) const { std::cout&lt;&lt; "ERROR: Unexpected type " &lt;&lt; iType &lt;&lt; std::endl; assert( false ); return std::string(); } int main() { MyType iType = TypeB; std::string zTypeName = Switch&lt;NumTypes&gt;( MyDispatcher(), iType ); std::cout &lt;&lt; "Type name: " &lt;&lt; zTypeName &lt;&lt; std::endl; } </code></pre> <p>The <code>Switcher</code> template class will recursively instantiate versions of itself with increasing type codes, starting with zero and terminating at the <code>iCount</code> template parameter to the <code>Switch</code> function. Each instantiation will check its <code>iIndex</code> template parameter against the runtime <code>iCase</code> variable and call the dispatcher's <code>Case&lt;iIndex&gt;</code> function if it matches. The <code>Default</code> function will only be called if the runtime <code>iCase</code> variable is outside the expected range.</p> <p>The key is that if any specialization of <code>Case</code> is missing in the dispatcher class, a linker error will be given complaining about a missing function. I know that many (most?) compilers can be set to produce warnings if not all members of an enum are handled in a switch statement, but there are too many places in the codebase (and likely in external headers) where not all cases are handled by design.</p> <p>Thoughts? Any potential pitfalls? The system could be pretty easily extended to a range of enum values not starting at zero, but non-contiguous enum values would be a no-go.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T01:53:46.537", "Id": "37158", "Score": "0", "body": "You might want to edit your code so that it compiles in something other than MSVC. MSVC in non-compliant in this situation, specifically, explicit specializations must be at namespace scope." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T16:53:15.553", "Id": "37194", "Score": "0", "body": "Thanks - should be OK now. I'm at work so I don't have direct access to GCC/Clang, but it compiles/runs OK at ideone.com (GCC 4.7.2)." } ]
[ { "body": "<p>That seems like an awful lot of boilerplate code to replace a single diagnostic that already exists in a lot of compilers. You're replacing</p>\n\n<pre><code>switch (fruit) {\n case APPLE: return \"apple\"; break;\n case PEAR: return \"pear\"; break;\n case PLUM: return \"plum\"; break;\n}\n</code></pre>\n\n<p>with</p>\n\n<pre><code>&lt;at file scope&gt;\nNEWSWITCH(uniqueID, std::string);\nDEFCASE(uniqueID, APPLE) { return \"apple\"; }\nDEFCASE(uniqueID, PEAR) { return \"pear\"; }\nDEFCASE(uniqueID, PLUM) { return \"plum\"; }\nDEFDEFAULT(uniqueID) { assert(false); }\n\n...\nSwitch&lt;NumTypes&gt;(uniqueID(), fruit);\n</code></pre>\n\n<p>The most onerous requirement there is putting all the switch logic at file scope; you can't localize it to the actual codepath where it's going to be used. The second most onerous requirement is coming up with <code>uniqueID</code>, a global identifier which must be different for each switch that you convert using this pattern.</p>\n\n<p>A much better solution to your original problem would be to use an array:</p>\n\n<pre><code>int main() {\n MyType iType = TypeB;\n\n std::string typenames[NumTypes] = { \"TypeA\", \"TypeB\", \"TypeC\" };\n\n assert(0 &lt;= (int)iType &amp;&amp; (int)iType &lt; NumTypes);\n std::string zTypeName = typenames[iType];\n\n std::cout &lt;&lt; \"Type name: \" &lt;&lt; zTypeName &lt;&lt; std::endl;\n}\n</code></pre>\n\n<p>This code statically enforces that each index in <code>0..NumTypes-1</code> is associated with a <code>std::string</code> in the array; and (just like your original code) it dynamically asserts that <code>iType</code> is in the proper range.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-23T22:43:44.020", "Id": "37996", "ParentId": "24048", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T16:38:14.617", "Id": "24048", "Score": "6", "Tags": [ "c++", "template", "template-meta-programming" ], "Title": "C++ compile-time checked switch 'statement'" }
24048
<p>So I'm making a program that is a serial port wedge. In other words I want it to listen to a serial port. If data comes in, wait a given amount of time, then play a sound and finally send the data out.</p> <p>All of those things have a abstract class associated with it. I'm thinking that I might eventually want to monitor <code>USB:HID</code> things so I made a IInput class which has abstract methods of <code>Open</code>, <code>Close</code>, <code>ToXmlString</code>, <code>ParseXmlString</code> and has a event of <code>DataAvailable</code>. I extend that class with <code>ComPortInput</code>.</p> <p>This is the question of it: Do I subscribe to my data event in the Open method, then unsubscribe in close? Or should I just have it in the initializer. I have a GUI that a user can change any of the 4 elements on this wedge at any time. But I'm not sure what would be the cleanest way of doing this. I'm thinking that the GUI would always create a new instance of my <code>ComPortInput</code> class. Part of me wants to force that GUI to have another method like Check Input. which in this case if the COM port was invalid or busy it would return false. Then instead of making a <code>ComPortInput</code> I would then want a NoInputInput class (for when I don't want to port forward) If I did it this way then I could get rid of my null checks on the serial port (Much desired) but is that too tricky? (as in too hard to read?) I'm thinking that if i do that I could put in my constructor of <code>ComPortInput</code> to Assert not null of the <code>SerialPort</code>. To me this looks better</p> <pre><code>public ComPortInput(SerialPort sp, int delay) : base(delay) { if (sp == null) throw new System.ArgumentNullException("Serial port can not be null"); LibraryTrace.Start("ComPortInput", delay); serialPort = sp; serialPort.DataReceived += sp_DataReceived; LibraryTrace.End("ComportInput"); } ~ComPortInput() { serialPort.Dispose(); } </code></pre> <p>My thoughts on this way, though, is that it might be hard to have a abstract <code>CheckValidity</code>... Hmm just thought as I was typing what if I put a <code>params object[] args</code> for CheckValidity and just have the comport i could try a few things and return true or false. Then if I ever decide to accept other types of input I could do something similar (such as if it was <code>USB:HID</code> I could accept the <code>PID/VID</code>) What do you guys think? Am I on the right track?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T15:37:39.577", "Id": "37642", "Score": "3", "body": "Have your class implement `IDisposable` and follow the disposable pattern for it: http://stackoverflow.com/a/898867/3312" } ]
[ { "body": "<p>As Jesse C. Slicer mentioned, because your class <em>seems</em> to encapsulate an <code>IDisposable</code> object (assuming <code>serialPort</code> would be a private field - this would be clearer if you named it <code>_serialPort</code>), it's <em>asking</em> to implement the <code>IDisposable</code> interface.</p>\n\n<p>Thus, instead of a <em>destructor</em>, you would simply have a <code>Dispose</code> method:</p>\n\n<pre><code>public void Dispose()\n{\n serialPort.Dispose();\n}\n</code></pre>\n\n<p>Another thing is this <code>LibraryTrace</code> whose <code>Start</code> and <code>End</code> static methods are a testability hinderance. If it's at all possible, I would wrap that with an interface like <code>ILibraryTrace</code> and implement it in a <code>LibraryTraceWrapper : ILibraryTrace</code> class that exposes the static <code>LibraryTrace</code> methods as instance methods - and inject it into the constructor as a dependency - same goes for the <code>SerialPort</code>:</p>\n\n<pre><code>private readonly ILibraryTrace _trace;\nprivate readonly ISerialPort _serialPort;\n\npublic ComPortInput(ILibraryTrace tracer, ISerialPort sp, int delay) : base(delay)\n{\n // ...\n}\n</code></pre>\n\n<p>This way you could unit test your class and inject mocks as needed.</p>\n\n<p>As for your non-null assertion, that's called a <em>guard clause</em> and it's good because you're <em>failing fast</em>; by throwing in the constructor you thwart the instantiation of your class without a <em>serial port</em>.</p>\n\n<p>I don't know if it's a typo or if it could be an actual issue, but <code>LibraryTrace.Start</code> and <code>LibraryTrace.End</code> are not working off the same string parameter value (you have <code>\"ComPortInput\"</code> and <code>\"ComportInput\"</code> - those are <em>not</em> the same string in C#). Given you're passing in the type's name, I would seriously consider passing in <code>typeof(this).Name</code> instead of a magic string. This shields both calls from an eventual <em>rename</em> refactoring.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T05:23:16.380", "Id": "58271", "Score": "1", "body": "Yeah I hated updating those strings so I moved to reflection for those. End result is much better as I only have Start() ad End() now and Reflection puts in the name of the function for me. I know its a performance hit, but I use this method on another library that requires speed and it's not been hindering it enough to delete all logging. Thank your input." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T05:24:50.083", "Id": "58272", "Score": "1", "body": "Have you tried `typeof()`? I'm guessing you're using `GetType()` - if the type is in the same assembly, `typeof()` performs better (per MSDN - just closed the tab...sorry)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T05:26:28.120", "Id": "58273", "Score": "1", "body": "@RobertSnyder feel free to mark your [rather old] question as answered, as you [probably] know [we're on a mission](http://meta.codereview.stackexchange.com/q/999/23788) :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T05:31:45.773", "Id": "58274", "Score": "0", "body": "HA.. i didn't know that. I had to look up my code and apparently I had C++ on the mind. `public static string __FUNCTION__ {get{return new StackFrame(3).GetMethod().Name; }` hahahah. I did not know about typeof(this).Name I'll have to give that a shot if performance becomes an issue\n }" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T05:41:56.843", "Id": "58275", "Score": "0", "body": "You're unwinding the stack? That's another quite significant performance hit!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T04:53:09.657", "Id": "35804", "ParentId": "24051", "Score": "2" } } ]
{ "AcceptedAnswerId": "35804", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T17:18:48.870", "Id": "24051", "Score": "3", "Tags": [ "c#", "polymorphism" ], "Title": "Hardware resource Open/Close methods" }
24051
<p>This plugin displays a tooltip popup with the data obtained via Ajax. I am sure there are better ones out there, but my objective is to learn how to correctly build a plugin, not find the best one available. I would appreciate any comments, suggestions, criticism from a best practices and design pattern usage perspective.</p> <p>A live demo is located <a href="http://tapmeister.com/test/ajaxTip/index.html" rel="nofollow">here</a>.</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" /&gt; &lt;title&gt;screenshot&lt;/title&gt; &lt;script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="jquery.ajaxTip.js" type="text/javascript"&gt;&lt;/script&gt; &lt;style type="text/css"&gt; .myElement{margin:100px;} .ajaxToolActive{color:blue;} .myAjaxTip { border:1px solid #CECECE; background:white; padding:10px; display:none; color:black; font-size:11px;-moz-border-radius:4px; box-shadow: 3px 1px 6px #505050; -khtml-border-radius:4px; -webkit-border-radius:4px; border-radius:4px; } &lt;/style&gt; &lt;script type="text/javascript"&gt; $(function(){ $('.myElement').ajaxTip({ display: function(d){return '&lt;p&gt;'+d.name+'&lt;/p&gt;&lt;p&gt;'+d.address+'&lt;/p&gt;&lt;p&gt;'+d.city+', '+d.state+'&lt;/p&gt;';}, getData:function(){return {id:this.data('id')}}, 'class':'myAjaxTip' }); $('.destroy').click(function(){$('.myElement').ajaxTip('destroy');}); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;p class="myElement" data-id="1" title="ajaxTip Popup"&gt;John Doe&lt;/p&gt; &lt;p class="myElement" data-id="2" title="ajaxTip Popup"&gt;Jane Doe&lt;/p&gt; &lt;p class="myElement" data-id="3" title="ajaxTip Popup"&gt;Baby Doe&lt;/p&gt; &lt;p class="destroy"&gt;Destroy&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; /* * jQuery ajaxTip * Copyright 2013 Michael Reed * Dual licensed under the MIT and GPL licenses. */ (function( $ ){ var methods = { init : function( options ) { // Create some defaults, extending them with any options that were provided var settings = $.extend({ 'url' : 'getAjaxTip.php', //To include extra data sent to the server, included it in the url 'class' : '', //Class to be added to tooltip (along with class standardAjaxTip) 'mouseMove': true, //Whether to move tooltip with mouse 'speed' : 'fast', //fadeIn speed 'delay' : 250, //milliseconds to delay before requesting data from server 'xOffset' : 20, 'yOffset' : 10, 'dataType' : 'json', //Returned data. Options are json, text, etc 'getData' : function(){return {}}, //Use to set additional data to the server 'display' : function(data){ //User function must include function(data) {... return string} var string=''; for (var key in data) {string+='&lt;p&gt;'+data[key]+'&lt;/p&gt;';} return string; } }, options || {}); //Just in case user doesn't provide options return this.each(function(){ var showing,title,timeoutID,ajax,$t=$(this).wrapInner('&lt;span /&gt;'),ajaxTip; $t.children('span').hover(function(e) { if(!showing){ title = $t.attr('title');$t.attr('title','');//Prevent title from being displayed,and save for later to put back timeoutID=window.setTimeout(function() { ajax=$.get( settings.url,settings.getData.call($t),function(data){ ajaxTip=$('&lt;div /&gt;') .addClass('standardAjaxTip '+settings.class) .html(((title != '')?'&lt;h3&gt;'+title+'&lt;/h3&gt;':'')+settings.display(data)) .css("top",(e.pageY - settings.yOffset) + "px") .css("left",(e.pageX + settings.xOffset) + "px") .css("position","absolute") .appendTo('body').fadeIn(settings.speed); showing = true; $t.addClass('ajaxToolActive'); }, settings.dataType); },settings.delay); //Delay before requesting data from server } }, function() { //When not hover if (typeof ajax == 'object') {ajax.abort();} window.clearTimeout(timeoutID); $t.attr('title',title); $t.removeClass('ajaxToolActive'); if(showing){ajaxTip.remove();} showing = false; }); $t.mousemove(function(e) { if(settings.mouseMove &amp;&amp; showing) {ajaxTip.css("top",(e.pageY - settings.yOffset) + "px").css("left",(e.pageX + settings.xOffset) + "px");} }); }); }, //Add additional methods as needed destroy : function() { //console.log('destroy'); return this.each(function(){ var $e = $(this); $e.html($e.children('span').html()); }) }, }; $.fn.ajaxTip = function(method) { if ( methods[method] ) { return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof method === 'object' || ! method ) { return methods.init.apply( this, arguments ); } else { $.error( 'Method ' + method + ' does not exist on jQuery.ajaxTip' ); } }; })( jQuery ); </code></pre>
[]
[ { "body": "<p>Here's the code mostly the same with some changes to style and comments:</p>\n\n<pre><code>(function($){\n var defaults = {\n 'url' : 'getAjaxTip.php', // The url used to get the tooltip data.\n 'class' : '', // Css class(es) to add to tooltip (along with standardAjaxTip).\n 'mouseMove': true, // A flag indicating whether to move tooltip with mouse.\n 'speed' : 'fast', // The speed at which to fade in the tool tip.\n 'delay' : 250, // Delay (in ms) before requesting data from server.\n 'xOffset' : 20,\n 'yOffset' : 10,\n 'dataType' : 'json', \n 'getData' : function () { \n return {}; \n },\n // A function to transform the data from the server into an html fragment.\n 'display' : function(data) { \n var htmlString = '';\n $.each(data, function (key, val) {\n htmlString += '&lt;p&gt;' + val + '&lt;/p&gt;';\n });\n return htmlString;\n }\n };\n\n var methods = {\n init : function (options) {\n // Create settings using the defaults extended with any options provided.\n var settings = $.extend(defaults, options || {});\n\n return this.each(function () {\n var title,\n timeoutID,\n ajax,\n $t,\n ajaxTip;\n\n // Wrap the content of the current element in a span.\n $t = $(this).wrapInner('&lt;span /&gt;');\n\n $t.children('span').hover(function(e) {\n if(!$t.hasClass('ajaxToolActive')) {\n title = $t.attr('title');\n $t.attr('title',''); // Remove the title so that it doesn't show on hover.\n\n timeoutID = window.setTimeout(function () {\n ajax = $.get(settings.url, settings.getData.call($t), function (data) {\n\n // Create a div to be the tooltip pop up, add the styling as well as\n // the html (from the display function) to it and then fade the element in\n // using the speed specified in the settings.\n ajaxTip = $('&lt;div /&gt;')\n .addClass('standardAjaxTip ' + settings['class'])\n .html(((title !== '') ? '&lt;h3&gt;' + title + '&lt;/h3&gt;' : '') + settings.display(data))\n .css('top', (e.pageY - settings.yOffset) + 'px')\n .css('left', (e.pageX + settings.xOffset) + 'px')\n .css('position', 'absolute')\n .appendTo('body')\n .fadeIn(settings.speed);\n\n $t.addClass('ajaxToolActive');\n }, \n settings.dataType);\n }, settings.delay);\n }\n },\n function () {\n // User is no longer hovering so cancel the call to the server and hide the tooltip.\n if (typeof ajax === 'object') { \n ajax.abort(); \n }\n window.clearTimeout(timeoutID);\n $t.attr('title', title);\n\n if ($t.hasClass('ajaxToolActive')) {\n ajaxTip.remove();\n $t.removeClass('ajaxToolActive');\n }\n });\n\n $t.mousemove(function (e) {\n if (settings.mouseMove &amp;&amp; $t.hasClass('ajaxToolActive')) {\n ajaxTip.css('top', (e.pageY - settings.yOffset) + 'px')\n .css('left', (e.pageX + settings.xOffset) + 'px');\n }\n });\n });\n },\n destroy : function () {\n return this.each(function () {\n var $e = $(this);\n $e.html($e.children('span').html());\n });\n }\n };\n\n $.fn.ajaxTip = function(method) {\n if (methods[method]) {\n return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));\n } else if (typeof method === 'object' || ! method) {\n return methods.init.apply(this, arguments);\n } else {\n $.error('Method ' + method + ' does not exist on jQuery.ajaxTip');\n } \n };\n}(jQuery));\n</code></pre>\n\n<p>I think it would also be a good idea to keep lines to 80 characters. I also removed the showing variable and checked to see if the element had the active class instead. The other main thing I change was settings.class to settings['class'] as class is a future reserved word.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T13:16:06.547", "Id": "37171", "Score": "0", "body": "Thanks RobH! I like your use of using the class instead of variable \"showing\" as well as creating a new variable \"defaults\". I see you didn't define `$t` in the `var` definition as `$(this).wrapInner('<span />');` Also, you use `===` instead of `==` to check if \"ajax\" is an object. May I ask why?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T13:24:17.300", "Id": "37175", "Score": "0", "body": "@user1032531 I decided to split out the definition of $t and the assigning of it to leave a space for a comment as it wasn't obvious to me why you are wrapping it first (I meant to ask!). In JavaScript == and != use type coercion which isn't normally what you want to do so it's good to get into the habit of using === and !== which don't convert types while checking equality. There is a great SO answer on the topic [here](http://stackoverflow.com/a/359509/1402923)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T13:42:29.337", "Id": "37176", "Score": "0", "body": "Thanks again Rob, I really appreciate your time. I am 100% self taught, and while resources like SO definitely provide me with most of the knowledge I need, having someone look over the final results and critique is is invaluable. It would be nice to even get a grade! Maybe A to F for useability, best practices, etc. By the way, you think I might get a B?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T13:44:13.330", "Id": "37177", "Score": "0", "body": "PS. I wrapped the `<DIV>` with a `<SPAN>` so that hover is only active when over the text and not the entire row of the block element. Maybe a hack, but didn't know a better way. Do you have a better suggestion?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T14:05:16.220", "Id": "37181", "Score": "0", "body": "@user1032531 I don't think it's a bad effort at all. As for the wrapping with a `<span>` - you could style your block elements to be a certain width, or use inline elements instead of your `<p>`s." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T11:50:20.117", "Id": "24096", "ParentId": "24053", "Score": "2" } } ]
{ "AcceptedAnswerId": "24096", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T17:25:42.323", "Id": "24053", "Score": "2", "Tags": [ "javascript", "jquery", "ajax", "plugin" ], "Title": "Tooltip popup plugin" }
24053
<p>This is inside a method (basically its just this), I try to get the neededValue otherwise I pass back what was passed in...</p> <pre><code>private static string GetNeededValue(string param) { string tValue = ""; if (!string.IsNullOrEmpty(param)) { var map = repo.Item(string.Format("CoverageName LIKE '{0}'",param)); tValue = map == null ? param : map.theNeededValue; } return tValue; } </code></pre>
[]
[ { "body": "<p>Yes it's efficient. However, your code appears to be very vulnerable to <a href=\"http://en.wikipedia.org/wiki/SQL_injection\" rel=\"nofollow\">SQL Injection</a> attacks. For example, imagine what the result would be if a user ran this code:</p>\n\n<pre><code>var result = MyModule.GetNeededValue(\"' OR '0' &lt;&gt; '1\");\n</code></pre>\n\n<p>or worse</p>\n\n<pre><code>var result = MyModule.GetNeededValue(\"';DROP TABLE foo--\");\n</code></pre>\n\n<p>To fix this flaw, it should be easy enough to rewrite the <code>repo.Item</code> method to support a call like this using parameters in a prepared statement rather than dynamic SQL:</p>\n\n<pre><code>var map = repo.Item(\"CoverageName LIKE @p1\", param);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T19:36:59.830", "Id": "37116", "Score": "0", "body": "ah, it would look that way. the actually parameter is being grabbed from a database table that only admin has access to. Though something to think about" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T19:43:57.710", "Id": "37118", "Score": "0", "body": "+1 good point about the sql injection comment. Always something to consider...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T20:14:25.690", "Id": "37123", "Score": "0", "body": "Oh found out repo.item is using datatable.Select, so SQL injection is not possible" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T20:18:40.400", "Id": "37126", "Score": "0", "body": "@Spooks That's definitely better, but I think you could still be susceptible to the first kind of query I mentioned." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T20:23:47.707", "Id": "37127", "Score": "0", "body": "@p.s.w.g that does seem possible,though its a fixed list, so if someone wanted to change it they would need access to the database though. I would definitely use parameters in a prepared statement otherwise" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T21:13:13.007", "Id": "37132", "Score": "2", "body": "It still is worth refactoring out the potential attack because if this method is used elsewhere that is vulnerable later on, it would be extremely difficult to fix." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T20:34:34.583", "Id": "37566", "Score": "1", "body": "good point, refactored" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T19:26:45.197", "Id": "24056", "ParentId": "24055", "Score": "4" } }, { "body": "<p>Yes, it seems fine from an efficiency point of view. Here's a couple of simple alternatives you could consider.</p>\n\n<p>Remove the need for the ! condition. I quite like this option as I think it flows nicely and is easy to read.</p>\n\n<pre><code>private static string GetNeededValue(string param)\n{\n // do we care about whitespace. If so you could use IsNullOrWhiteSpace\n if(string.IsNullOrEmpty(param)) return param;\n\n var map = repo.Item(string.Format(\"CoverageName LIKE '{0}'\",param));\n return map == null ? param : map.theNeededValue; \n}\n</code></pre>\n\n<p>Or another alternative might be to be more explicit about when tValue is set.</p>\n\n<pre><code>private static string GetNeededValue(string param)\n{\n var tValue = param;\n\n // do we care about whitespace. If so you could use IsNullOrWhiteSpace\n if(!string.IsNullOrEmpty(tValue))\n\n var map = repo.Item(string.Format(\"CoverageName LIKE '{0}'\",tValue));\n\n if(map != null)\n tValue = map.theNeededValue; \n }\n\n return tValue;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T19:31:49.227", "Id": "37115", "Score": "0", "body": "+1 The first option is exactly how I would write this. (minus the sql injection flaw of course)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T20:15:00.200", "Id": "37124", "Score": "0", "body": "repo.item is using datatable.Select, so SQL injection is not possible" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T20:17:08.313", "Id": "37125", "Score": "0", "body": "@Spooks excellent!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T21:13:38.267", "Id": "37133", "Score": "1", "body": "To be honest, I prefer the way Spook originally formatted his code – I think that `!` is very easy to read and that the `if` block is easy to understand. Of course, this means that it's completely subjective which way is best." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T21:19:50.923", "Id": "37136", "Score": "0", "body": "@Kevin Yep they all have their merits and each is probably preferred between individuals. I must admit I've often written code myself that way so often it depends on how I'm thinking about the problem at the time..." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T19:26:59.143", "Id": "24057", "ParentId": "24055", "Score": "5" } }, { "body": "<p>I am going to assume that returning <code>\"\"</code> means \"You gave me garbage so here is some garbage.\" I have been working hard on pulling myself out of this same habit I have developed over the years. This method is a great example as it can have its domain tightened. Also because it is private it can possibly have that <code>IsNullOrEmpty</code> check removed entirely in a release build.</p>\n\n<pre><code>private static string GetNeededValue(string param)\n{\n Contract.Requires(!string.IsNullOrEmpty(param)); // [ConditionalAttribute(\"CONTRACTS_FULL\")]\n var map = repo.Item(string.Concat(\"CoverageName LIKE '\",param,'\\''));\n return = map == null ? param : map.theNeededValue;\n}\n</code></pre>\n\n<p>The tooling to support the Contract methods can be found here: <a href=\"http://research.microsoft.com/en-us/projects/contracts/\" rel=\"nofollow\">http://research.microsoft.com/en-us/projects/contracts/</a> .</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T22:45:53.807", "Id": "24264", "ParentId": "24055", "Score": "0" } } ]
{ "AcceptedAnswerId": "24057", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T18:27:22.243", "Id": "24055", "Score": "4", "Tags": [ "c#" ], "Title": "just making sure this is efficient, for the null checks" }
24055
<p>I have implemented a global <code>appIncluder</code> function which is imported as includeme with the <strong>init</strong>.py of the package to be included.</p> <p><code>includeme</code> (<code>ApplicationIncluder</code>) receives the config object, so it is then easy to use config.package and its variables/methods/classes (present in the same <strong>init</strong>.py and submodules.</p> <p>I would really appreciate getting some feedback on this and see what can be improved.</p> <p>project: 'foo'</p> <p>Apps to be deployed in foo.foo.apps directory.</p> <p>Structure:</p> <blockquote> <pre><code>foo |-foo |- __init__.py |- appincluder.py |-apps |-test |- __init__.py |- views.py |- templates |- test.jinja2 </code></pre> </blockquote> <h2>foo/foo/<strong>init</strong>.py</h2> <pre><code>config.include('foo.apps.test') </code></pre> <h2>foo/foo/appincluder.py</h2> <pre><code>def appIncluder(config): app = config.package prefix = app.prefix routes = app.routes for route,url in routes.items(): config.add_route(route,prefix + url) config.scan(app) log.info('app: %s included' % app.__name__) </code></pre> <h2>foo/foo/apps/test/<strong>init</strong>.py</h2> <pre><code>from foo.appincluder import appIncluder as includeme prefix = '/test' routes = { 'test': '/home' } </code></pre> <h2>foo/foo/apps/test/views.py</h2> <pre><code>from pyramid.view import view_config @view_config(route_name='test', renderer='templates/test.jinja2') def test(request): return {} </code></pre> <p><strong>Info</strong>: I prefer each app to come along with its config, hence the choice of putting the prefix in the app <strong>init</strong>.py file instead of specifying it in <code>config.include(app,prefix)</code>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T20:03:59.663", "Id": "24058", "Score": "4", "Tags": [ "python", "pyramid" ], "Title": "Global appIncluder function to include sub-applications dynamically" }
24058
<p>Please have a look at the code below:</p> <p>ClassLibrary1 has a structure as follows:</p> <pre><code>Namespace com.app.test Public Class Class1 End Class End Namespace </code></pre> <p>ClassLibrary2 has a structure as follows:</p> <pre><code>Namespace com.app.test Public Class Class2 End Class End Namespace </code></pre> <p>WindowsApplication1 has a structure like this:</p> <pre><code>Imports com.app.test Public Class Form1 Dim c1 As Class1 Dim c2 As Class2 End Class </code></pre> <p>Notice that Class1 and Class2 are in different projects (DLL's), but they have the same namespace. Is this poor practice? I have never seen it done before.</p>
[]
[ { "body": "<p>Yes it is poor practice, there is no reason really to deviate from best practice which is to have the last part of your namespace match the project name like this:</p>\n\n<pre><code>CompanyName.SolutionName.ProjectName\n</code></pre>\n\n<p>Say there is a company called \"ABC Solutions\" and they have a web project called \"ABC Editor\", here are some example project names:</p>\n\n<pre><code>AbcSolutions.AbcEditor.Data\nAbcSolutions.AbcEditor.Database\nAbcSolutions.AbcEditor.Web\n</code></pre>\n\n<p>Also you're using Java style package naming which I've never actually seen in C# before, it really looks quite odd :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T11:47:38.963", "Id": "37166", "Score": "0", "body": "Thanks. +1. The problem is that there are two DLLs for the Business Logic Layer. Therefore based on your answer I should have: com.application.businesslogiclayer.DLL1 and com.application.businesslogiclayer.DLL2. DLL1 and DLL2 will be named better. Can you confirm that I have understood your answer correctly?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T12:17:52.150", "Id": "37168", "Score": "0", "body": "What is the reason for their separation? Can a meaningful name be used to differentiate them? If they are they are all relate to one another maybe you should consider merging them or more clearly defining what makes each different?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T10:48:54.773", "Id": "24079", "ParentId": "24061", "Score": "3" } }, { "body": "<p>It is indeed better component design as @Tyriar mentioned, but it is also very common that the namespaces are being used among the projects. This is not always a wrong design.</p>\n\n<hr>\n\n<p>Let assume that you are implementing plug-ins. And every plug in has own assembly (normally). There, namespaces can be shared. </p>\n\n<p><strong>PluginA.dll</strong></p>\n\n<pre><code>Namespace CompanyName.SolutionName.ProjectName.PlugInNamespace\n{\n Class PlugInA {}\n}\n</code></pre>\n\n<p><strong>PluginB.dll</strong></p>\n\n<pre><code>Namespace CompanyName.SolutionName.ProjectName.PlugInNamespace\n{\n Class PlugInB {}\n}\n</code></pre>\n\n<hr>\n\n<p>Better practice for your case would be the sub-namespacing.</p>\n\n<p><strong>ClassLibrary1</strong> </p>\n\n<pre><code>Namespace Com.App.Test.FunctionalityGroupA\nPublic Class Class1\n\nEnd Class\nEnd Namespace\n</code></pre>\n\n<p><strong>ClassLibrary2</strong></p>\n\n<pre><code>Namespace Com.App.Test.FunctionalityGroupB \nPublic Class Class2\n\nEnd Class\nEnd Namespace\n</code></pre>\n\n<p><strong>WindowsApplication1</strong></p>\n\n<pre><code>Imports Com.App.Test.FunctionalityGroupA\nImports Com.App.Test.FunctionalityGroupB \n\nPublic Class Form1\n Dim c1 As Class1\n Dim c2 As Class2\nEnd Class\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T12:31:24.620", "Id": "24098", "ParentId": "24061", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-18T21:12:52.983", "Id": "24061", "Score": "2", "Tags": [ "design-patterns", "vb.net" ], "Title": ".NET - multiple DLLs and one namespace" }
24061
<p>I'm new to programming and even more new to Haskell. Below is a little tid-bit I wrote that operates on a bunch of lists. I am wondering if someone would be kind enough to walk through the function <code>margProbs</code> line-by-line, and enumerate their respective space/time complexities and/or just possibly suggest improvements. </p> <pre><code>import qualified Control.Monad as Mo import qualified Data.Map as M import qualified Data.List as L import Data.Maybe type PaIdx = Int margProbs :: [[Bool]] -&gt; PaIdx -&gt; [Double] -&gt; [[Double]] -&gt; Maybe [[Double]] margProbs bs idx vpa vs = Mo.sequence $ fmap (\( _, ms ) -&gt; collapseWith addV ms ) grouped where (p, q) = ( vpa !! 0, vpa !! 1 ) grouped = reverse . sortAndGroup $ zip ( snd probBool ) scaled scaled = zipWith (\p v -&gt; scaleV (*) p v ) ( fst probBool ) vs probBool = foldr (\b (probs, bools) -&gt; let (prob,bool) = reducePa b in (prob:probs, bool:bools) ) ([],[]) bs reducePa bs = let split = fromJust $ pluckL idx bs in ( if fst split == True then p else q, snd split ) ------------ -- Utils -- ------------ addV :: ( Num a ) =&gt; [a] -&gt; [a] -&gt; Maybe [a] addV v1 v2 = if length v1 == length v2 then Just $ zipWith (+) v1 v2 else Nothing scaleV :: ( Num a ) =&gt; ( a -&gt; a -&gt; a ) -&gt; a -&gt; [a] -&gt; [a] scaleV g num v = fmap (\e -&gt; g num e ) v collapseWith :: ( Num a ) =&gt; ( [a] -&gt; [a] -&gt; Maybe [a] ) -&gt; [[a]] -&gt; Maybe [a] collapseWith g vs = foldr (\v1 v2 -&gt; v2 &gt;&gt;= \w -&gt; g v1 w ) ( return $ head vs ) ( tail vs ) sortAndGroup :: Ord k =&gt; [ (k, a) ] -&gt; [ (k, [a]) ] sortAndGroup ts = M.toList $ M.fromListWith (++) [(k, [v]) | (k, v) &lt;- ts] pluckL :: Int -&gt; [a] -&gt; Maybe ( a, [a] ) pluckL idx xs = case splitAt idx xs of ( _, [] ) -&gt; Nothing ( hs, (t:ts) ) -&gt; Just ( t, hs ++ ts ) </code></pre> <p>Here are the params I used to test this snippet:</p> <pre><code>ret = margProbs bs 0 v m bs = [[True,True],[True,False],[False,True],[False,False]] v = [0.4,0.6] m = [[0.95,0.05], [0.94,0.06], [0.29,0.71], [0.1, 0.9]] </code></pre> <p><code>ret</code> should have value: <code>Just [[0.554,0.446],[0.436,0.564]]</code></p> <p><strong>Update</strong></p> <p>I got rid of all dependencies to the hmatrix library.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T14:45:55.073", "Id": "37184", "Score": "0", "body": "What do you expect as an answer: suggestions to improve performance or just analysis of space&time complexity?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T15:16:17.590", "Id": "37185", "Score": "1", "body": "Analysis of space/time complexity would be great but if simple suggestions would take less of your time, that'd be great too" } ]
[ { "body": "<p><strong><code>scaleV</code></strong></p>\n\n<p><code>scaleV</code> is very similar to <code>fmap</code>, it just has different precedence in its arguments, the following definition is simpler and highlights this similarity:</p>\n\n<pre><code>scaleV = (fmap .)\n</code></pre>\n\n<p><strong>Guards</strong></p>\n\n<p>While they have the same effect of conditionals, they are preferred because they are extensible and nicer to read:</p>\n\n<pre><code>addV v1 v2 = if length v1 == length v2 then Just $ zipWith (+) v1 v2 else Nothing\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>addV v1 v2 \n | length v1 == length v2 = Just $ zipWith (+) v1 v2\n | otherwise = Nothing\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-06T20:13:18.133", "Id": "113086", "ParentId": "24067", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T01:17:18.707", "Id": "24067", "Score": "3", "Tags": [ "optimization", "beginner", "haskell", "functional-programming", "complexity" ], "Title": "Space and time complexity of operation on lists" }
24067
<p>I have a website that keeps track of 'changes' that users make. These changes come in all shapes and sizes and each shape and size has a different MySQL table to store them in. In total there are 8 different tables. Each table has completely different columns, so I don't <em>think</em> a simple <code>JOIN</code> would be possible, however they all have a <code>time</code> column.</p> <p>What I would like to do is show the last <code>x</code> number of changes made across all tables (i.e. sorted by <code>time</code>). How I am doing it now is querying all tables like this:</p> <pre><code>foreach ($tables as $table) { $stmt = $this-&gt;_dbh-&gt;prepare("SELECT $table.*, realname, time, reservations.conf_num, reservations.conf_letters FROM $table LEFT JOIN users ON $table.user_id = users.id LEFT JOIN reservations ON $table.conf_num = reservations.conf_num ORDER BY time DESC LIMIT ".$this-&gt;_num_values); $stmt-&gt;execute(); $changes[$table] = $stmt-&gt;fetchAll(); } </code></pre> <p>Then I sort and slice the resultant array:</p> <pre><code>ksort($changes); $changes = array_reverse($changes); // Make sure to limit it if we have a maximum number of values if ($this-&gt;_num_values &gt; 0) { $changes = array_slice($changes, 0, $this-&gt;_num_values); } </code></pre> <p>This works fine, however it just seems extremely inefficient to me since we are retrieving the latest <code>x</code> values from <strong>all</strong> tables instead of just returning the exact number so that the sum of the number of rows from the individual queries equals <code>x</code>. Is there a better way to do this, or am I just trying to micro-optimize too much here?</p>
[]
[ { "body": "<p>Yes, there is: create a stored procedure and UNION the result sets then sort the records and return them to PHP.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T19:37:45.677", "Id": "37208", "Score": "0", "body": "Edit comment. I'm working on it. I'll keep you posted if I have any trouble working this out. I've never done `UNION` before." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T22:54:14.423", "Id": "37230", "Score": "0", "body": "It was complicated and took me 2-3 hours, but I finally have it working. Thanks for the suggestion." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T05:26:10.983", "Id": "24070", "ParentId": "24068", "Score": "1" } } ]
{ "AcceptedAnswerId": "24070", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T03:39:17.347", "Id": "24068", "Score": "1", "Tags": [ "php", "mysql" ], "Title": "MySQL limit across multiple tables in multiple queries" }
24068
<p>I would like to refactor this block, it looks clunky:</p> <pre><code># refactor me receive_payment_on = false config[:sections].each do |section| if section[:applicants] section[:applicants][:sections].each do |app_sec| if app_sec[:employment] &amp;&amp; app_sec[:employment][:receive_payment_on] receive_payment_on = true end end end end </code></pre>
[]
[ { "body": "<p>Put your code into a method. So you get rid of the temporary variable, its cleaner and you can leave your method with a return as soon as you find the first true. (A break to leave the loop will have the same effect.)</p>\n\n<p>In addition to that I'm a big friend of guard conditions. Invert <code>if section[:applicants] ... end</code> to <code>if !section[:applicants] next</code>, so you have one nesting level less. </p>\n\n<pre><code>...\nconfig[:sections].each do |section|\n if !section[:applicants] next\n section[:applicants][:sections].each do |app_sec|\n if app_sec[:employment] &amp;&amp; app_sec[:employment][:receive_payment_on]\n return true\n end\n end\nend\nreturn false\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T07:46:45.877", "Id": "37161", "Score": "0", "body": "thanks for the awnser but i ended up using" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T07:47:01.103", "Id": "37162", "Score": "0", "body": "receive_payment_on = true if config[:sections].join.include? 'next_paid_on'" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T06:29:30.493", "Id": "24072", "ParentId": "24071", "Score": "2" } }, { "body": "<p>Don't use a for-loop (<code>each</code>), that's how you'd do it in language like C, in Ruby we have handy functional abstractions (or can build them if not present) like <a href=\"http://www.ruby-doc.org/core-2.0/Enumerable.html#method-i-any-3F\" rel=\"nofollow\">Enumerable#any?</a>:</p>\n\n<pre><code>receive_payment_on = config[:sections].any? do |section|\n if section[:applicants]\n section[:applicants][:sections].any? do |app_sec|\n app_sec[:employment] &amp;&amp; app_sec[:employment][:receive_payment_on]\n end\n end\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T10:02:44.993", "Id": "24078", "ParentId": "24071", "Score": "2" } }, { "body": "<p>how about using modifiers</p>\n\n<pre><code>receive_payment_on = config[:sections].any? do |section|\n section[:applicants][:sections].any? do |app_sec|\n app_sec[:employment] ? app_sec[:employment][:receive_payment_on] : false \n end if section[:applicants]\nend\n</code></pre>\n\n<p>(based on tokland's answer)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T11:17:57.973", "Id": "24093", "ParentId": "24071", "Score": "1" } } ]
{ "AcceptedAnswerId": "24072", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T05:56:53.813", "Id": "24071", "Score": "0", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Setting receive_payment_on flag for employment applicants" }
24071
<p><a href="https://pypi.python.org/pypi/pyramid/" rel="nofollow">Pyramid</a> is a small, fast, down-to-earth, open source Python web application development framework. It makes real-world web application development and deployment more fun, more predictable, and more productive.</p> <p>Pyramid is produced by the <a href="http://pylonsproject.org/" rel="nofollow">Pylons Project</a>.</p> <blockquote> <p>Pyramid is offered under the <strong>BSD-derived Repoze Public License</strong>.</p> </blockquote> <p>A detailed <a href="http://docs.pylonsproject.org/en/latest/docs/pyramid.html" rel="nofollow">documentation</a> for Pyramid can be accessed <a href="http://docs.pylonsproject.org/en/latest/docs/pyramid.html" rel="nofollow">here</a>.</p> <p>The latest release(as of March, 2013) for Pyramid is 1.4 and can be <a href="https://pypi.python.org/packages/source/p/pyramid/pyramid-1.4.tar.gz" rel="nofollow">downloaded as tarball here</a>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T09:53:25.423", "Id": "24076", "Score": "0", "Tags": null, "Title": null }
24076
A Python-based web framework provided by the Pylons Project *Note: Don't use this for pyramid output (e.g. of numbers)
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-03-19T09:53:25.423", "Id": "24077", "Score": "0", "Tags": null, "Title": null }
24077
<h2>Definition from Wikipedia:</h2> <blockquote> <p>Microsoft Excel is a spreadsheet application developed by Microsoft.</p> </blockquote> <h2>Basic functionality:</h2> <ul> <li>Calculation</li> <li>Graphing and charting tools</li> <li>Pivot tables</li> <li>A macro programming language called Visual Basic for Applications (VBA)</li> </ul> <h2>Current version:</h2> <p><a href="http://office.microsoft.com/en-us/excel" rel="nofollow">Excel 2013</a></p> <h2>Links:</h2> <ul> <li><a href="http://en.wikipedia.org/wiki/Microsoft_Excel" rel="nofollow">Wikipedia</a></li> <li><a href="http://office.microsoft.com/en-us/excel" rel="nofollow">Official Microsoft site</a></li> <li><a href="http://office.microsoft.com/en-us/excel-help/training-courses-for-excel-2013-HA104032083.aspx" rel="nofollow">Training Courses for Excel 2013</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T10:56:59.527", "Id": "24080", "Score": "0", "Tags": null, "Title": null }
24080
Microsoft Excel is a commercial spreadsheet application written and distributed by Microsoft.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T10:56:59.527", "Id": "24081", "Score": "0", "Tags": null, "Title": null }
24081
Serialization is the process by which an object is converted into a format that can be stored and later retrieved.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T11:00:36.280", "Id": "24083", "Score": "0", "Tags": null, "Title": null }
24083
<p>The binary search algorithm begins by comparing the target value to value of the middle element of the sorted array. If the target value is equal to the middle element's value, the position is returned. If the target value is smaller, the search continues on the lower half of the array, or if the target value is larger, the search continues on the upper half of the array. This process continues until the element is found and its position is returned, or there are no more elements left to search for in the array and a "not found" indicator is returned.</p> <p><a href="https://en.wikipedia.org/wiki/Binary_search_algorithm" rel="nofollow"><sub>[Source]</sub></a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T11:11:04.857", "Id": "24086", "Score": "0", "Tags": null, "Title": null }
24086
Binary search is an efficient algorithm for finding a key in sorted data. It runs in O(log n) time.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T11:11:04.857", "Id": "24087", "Score": "0", "Tags": null, "Title": null }
24087
<p><a href="http://www.asp.net/mvc/mvc4" rel="nofollow">ASP.NET MVC 4</a> is the fourth major version of the ASP.NET Model-View-Controller platform for web applications.</p> <h3>New Features</h3> <p>Among the new features of the fourth release are:</p> <ul> <li>Refreshed and modernized default project templates</li> <li>New mobile project template</li> <li>Many new features to support mobile apps</li> <li>Enhanced support for asynchronous methods</li> <li>ASP.NET Web API for HTTP services</li> </ul> <p>Read the full feature list in the <a href="http://www.asp.net/whitepapers/mvc4-release-notes" rel="nofollow">release notes</a></p> <h3>Resources</h3> <ul> <li><a href="http://www.asp.net/mvc/mvc4" rel="nofollow">ASP.NET MVC 4</a> page on the official ASP.NET site</li> <li><a href="http://aspnet.codeplex.com/wikipage?title=ASP.NET%20MVC%204%20RoadMap" rel="nofollow">ASP.NET MVC 4 Roadmap</a></li> <li><a href="http://aspnet.uservoice.com/forums/41201-asp-net-mvc" rel="nofollow">UserVoice site for ASP.NET MVC features</a></li> <li><a href="http://www.asp.net/whitepapers/mvc4-release-notes" rel="nofollow">MSDN ASP.NET MVC Developer Reference</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T11:11:55.370", "Id": "24088", "Score": "0", "Tags": null, "Title": null }
24088
ASP.NET MVC 4 is the fourth major version of the ASP.NET Model-View-Controller platform for web applications.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T11:11:55.370", "Id": "24089", "Score": "0", "Tags": null, "Title": null }
24089
<h1> Representation in different languages</h1> <ul> <li><p>DateTime is a type in <a href="/questions/tagged/sql" class="post-tag" title="show questions tagged &#39;sql&#39;" rel="tag">sql</a> that represents the date with the time of day with fractional seconds (accuracy: rounded to increments of .000, .003 or .007 seconds)</p></li> <li><p>DateTime is a structure in <a href="/questions/tagged/.net" class="post-tag" title="show questions tagged &#39;.net&#39;" rel="tag">.net</a> that "represents an instant in time, typically expressed as a date and time of day." </p></li> <li><p>In Joda-Time, a popular <a href="/questions/tagged/java" class="post-tag" title="show questions tagged &#39;java&#39;" rel="tag">java</a> library, DateTime is a class serving similar purpose.</p></li> <li><p>In <a href="/questions/tagged/python" class="post-tag" title="show questions tagged &#39;python&#39;" rel="tag">python</a> it is both a similar object, and the module (library) that "supplies classes for manipulating dates and times in both simple and complex ways."</p></li> <li><p>In <a href="/questions/tagged/php" class="post-tag" title="show questions tagged &#39;php&#39;" rel="tag">php</a> the <a href="http://php.net/manual/en/class.datetime.php" rel="nofollow noreferrer">DateTime</a> <a href="/questions/tagged/class" class="post-tag" title="show questions tagged &#39;class&#39;" rel="tag">class</a> is a "representation of date and time".</p></li> </ul> <h1>Tag Usage</h1> <ul> <li>Use on questions about reviewing code involving date/time logic.</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-03-19T11:13:55.370", "Id": "24090", "Score": "0", "Tags": null, "Title": null }
24090
DateTime objects in many programming languages describe an instant in time, expressed as a date and time of day. Use on questions about reviewing code involving date/time logic.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T11:13:55.370", "Id": "24091", "Score": "0", "Tags": null, "Title": null }
24091