Search Results

Search found 91526 results on 3662 pages for 'clean code'.

Page 51/3662 | < Previous Page | 47 48 49 50 51 52 53 54 55 56 57 58  | Next Page >

  • Why is design by contract considered an alternative to the pseudo programming process?

    - by zoopp
    Right now I'm reading Code Complete by Steve McConnell and in chapter 9 he talks about the Pseudo Programming Process (PPP). From what I've understood, the PPP is a way of programming in which the programmer first writes the pseudo code for the routine he's working on, then refines it up to the point where pretty much each pseudo code line can be implemented in 1-3 lines of code, then writes the code in the designated programming language and finally the pseudo code is saved as comments for the purpose of documenting the routine. In chapter 9.4 the author mentions alternatives to the PPP, one of which is 'design by contract'. In design by contract you basically assert preconditions and postconditions of each routine. Now why would that be considered an alternative? To me it seems obvious that I should use both techniques at the same time and not chose one over the other.

    Read the article

  • Code Reuse is (Damn) Hard

    - by James Michael Hare
    Being a development team lead, the task of interviewing new candidates was part of my job.  Like any typical interview, we started with some easy questions to get them warmed up and help calm their nerves before hitting the hard stuff. One of those easier questions was almost always: “Name some benefits of object-oriented development.”  Nearly every time, the candidate would chime in with a plethora of canned answers which typically included: “it helps ease code reuse.”  Of course, this is a gross oversimplification.  Tools only ease reuse, its developers that ultimately can cause code to be reusable or not, regardless of the language or methodology. But it did get me thinking…  we always used to say that as part of our mantra as to why Object-Oriented Programming was so great.  With polymorphism, inheritance, encapsulation, etc. we in essence set up the concepts to help facilitate reuse as much as possible.  And yes, as a developer now of many years, I unquestionably held that belief for ages before it really struck me how my views on reuse have jaded over the years.  In fact, in many ways Agile rightly eschews reuse as taking a backseat to developing what's needed for the here and now.  It used to be I was in complete opposition to that view, but more and more I've come to see the logic in it.  Too many times I've seen developers (myself included) get lost in design paralysis trying to come up with the perfect abstraction that would stand all time.  Nearly without fail, all of these pieces of code become obsolete in a matter of months or years. It’s not that I don’t like reuse – it’s just that reuse is hard.  In fact, reuse is DAMN hard.  Many times it is just a distraction that eats up architect and developer time, and worse yet can be counter-productive and force wrong decisions.  Now don’t get me wrong, I love the idea of reusable code when it makes sense.  These are in the few cases where you are designing something that is inherently reusable.  The problem is, most business-class code is inherently unfit for reuse! Furthermore, the code that is reusable will often fail to be reused if you don’t have the proper framework in place for effective reuse that includes standardized versioning, building, releasing, and documenting the components.  That should always be standard across the board when promoting reusable code.  All of this is hard, and it should only be done when you have code that is truly reusable or you will be exerting a large amount of development effort for very little bang for your buck. But my goal here is not to get into how to reuse (that is a topic unto itself) but what should be reused.  First, let’s look at an extension method.  There’s many times where I want to kick off a thread to handle a task, then when I want to reign that thread in of course I want to do a Join on it.  But what if I only want to wait a limited amount of time and then Abort?  Well, I could of course write that logic out by hand each time, but it seemed like a great extension method: 1: public static class ThreadExtensions 2: { 3: public static bool JoinOrAbort(this Thread thread, TimeSpan timeToWait) 4: { 5: bool isJoined = false; 6:  7: if (thread != null) 8: { 9: isJoined = thread.Join(timeToWait); 10:  11: if (!isJoined) 12: { 13: thread.Abort(); 14: } 15: } 16: return isJoined; 17: } 18: } 19:  When I look at this code, I can immediately see things that jump out at me as reasons why this code is very reusable.  Some of them are standard OO principles, and some are kind-of home grown litmus tests: Single Responsibility Principle (SRP) – The only reason this extension method need change is if the Thread class itself changes (one responsibility). Stable Dependencies Principle (SDP) – This method only depends on classes that are more stable than it is (System.Threading.Thread), and in itself is very stable, hence other classes may safely depend on it. It is also not dependent on any business domain, and thus isn't subject to changes as the business itself changes. Open-Closed Principle (OCP) – This class is inherently closed to change. Small and Stable Problem Domain – This method only cares about System.Threading.Thread. All-or-None Usage – A user of a reusable class should want the functionality of that class, not parts of that functionality.  That’s not to say they most use every method, but they shouldn’t be using a method just to get half of its result. Cost of Reuse vs. Cost to Recreate – since this class is highly stable and minimally complex, we can offer it up for reuse very cheaply by promoting it as “ready-to-go” and already unit tested (important!) and available through a standard release cycle (very important!). Okay, all seems good there, now lets look at an entity and DAO.  I don’t know about you all, but there have been times I’ve been in organizations that get the grand idea that all DAOs and entities should be standardized and shared.  While this may work for small or static organizations, it’s near ludicrous for anything large or volatile. 1: namespace Shared.Entities 2: { 3: public class Account 4: { 5: public int Id { get; set; } 6:  7: public string Name { get; set; } 8:  9: public Address HomeAddress { get; set; } 10:  11: public int Age { get; set;} 12:  13: public DateTime LastUsed { get; set; } 14:  15: // etc, etc, etc... 16: } 17: } 18:  19: ... 20:  21: namespace Shared.DataAccess 22: { 23: public class AccountDao 24: { 25: public Account FindAccount(int id) 26: { 27: // dao logic to query and return account 28: } 29:  30: ... 31:  32: } 33: } Now to be fair, I’m not saying there doesn’t exist an organization where some entites may be extremely static and unchanging.  But at best such entities and DAOs will be problematic cases of reuse.  Let’s examine those same tests: Single Responsibility Principle (SRP) – The reasons to change for these classes will be strongly dependent on what the definition of the account is which can change over time and may have multiple influences depending on the number of systems an account can cover. Stable Dependencies Principle (SDP) – This method depends on the data model beneath itself which also is largely dependent on the business definition of an account which can be very inherently unstable. Open-Closed Principle (OCP) – This class is not really closed for modification.  Every time the account definition may change, you’d need to modify this class. Small and Stable Problem Domain – The definition of an account is inherently unstable and in fact may be very large.  What if you are designing a system that aggregates account information from several sources? All-or-None Usage – What if your view of the account encompasses data from 3 different sources but you only care about one of those sources or one piece of data?  Should you have to take the hit of looking up all the other data?  On the other hand, should you have ten different methods returning portions of data in chunks people tend to ask for?  Neither is really a great solution. Cost of Reuse vs. Cost to Recreate – DAOs are really trivial to rewrite, and unless your definition of an account is EXTREMELY stable, the cost to promote, support, and release a reusable account entity and DAO are usually far higher than the cost to recreate as needed. It’s no accident that my case for reuse was a utility class and my case for non-reuse was an entity/DAO.  In general, the smaller and more stable an abstraction is, the higher its level of reuse.  When I became the lead of the Shared Components Committee at my workplace, one of the original goals we looked at satisfying was to find (or create), version, release, and promote a shared library of common utility classes, frameworks, and data access objects.  Now, of course, many of you will point to nHibernate and Entity for the latter, but we were looking at larger, macro collections of data that span multiple data sources of varying types (databases, web services, etc). As we got deeper and deeper in the details of how to manage and release these items, it quickly became apparent that while the case for reuse was typically a slam dunk for utilities and frameworks, the data access objects just didn’t “smell” right.  We ended up having session after session of design meetings to try and find the right way to share these data access components. When someone asked me why it was taking so long to iron out the shared entities, my response was quite simple, “Reuse is hard...”  And that’s when I realized, that while reuse is an awesome goal and we should strive to make code maintainable, often times you end up creating far more work for yourself than necessary by trying to force code to be reusable that inherently isn’t. Think about classes the times you’ve worked in a company where in the design session people fight over the best way to implement a class to make it maximally reusable, extensible, and any other buzzwordable.  Then think about how quickly that design became obsolete.  Many times I set out to do a project and think, “yes, this is the best design, I can extend it easily!” only to find out the business requirements change COMPLETELY in such a way that the design is rendered invalid.  Code, in general, tends to rust and age over time.  As such, writing reusable code can often be difficult and many times ends up being a futile exercise and worse yet, sometimes makes the code harder to maintain because it obfuscates the design in the name of extensibility or reusability. So what do I think are reusable components? Generic Utility classes – these tend to be small classes that assist in a task and have no business context whatsoever. Implementation Abstraction Frameworks – home-grown frameworks that try to isolate changes to third party products you may be depending on (like writing a messaging abstraction layer for publishing/subscribing that is independent of whether you use JMS, MSMQ, etc). Simplification and Uniformity Frameworks – To some extent this is similar to an abstraction framework, but there may be one chosen provider but a development shop mandate to perform certain complex items in a certain way.  Or, perhaps to simplify and dumb-down a complex task for the average developer (such as implementing a particular development-shop’s method of encryption). And what are less reusable? Application and Business Layers – tend to fluctuate a lot as requirements change and new features are added, so tend to be an unstable dependency.  May be reused across applications but also very volatile. Entities and Data Access Layers – these tend to be tuned to the scope of the application, so reusing them can be hard unless the abstract is very stable. So what’s the big lesson?  Reuse is hard.  In fact it’s damn hard.  And much of the time I’m not convinced we should focus too hard on it. If you’re designing a utility or framework, then by all means design it for reuse.  But you most also really set down a good versioning, release, and documentation process to maximize your chances.  For anything else, design it to be maintainable and extendable, but don’t waste the effort on reusability for something that most likely will be obsolete in a year or two anyway.

    Read the article

  • Five C# Code Snippets

    A snippet is a small section of text or source code that can be inserted into the code of a program. Snippets provide an easy way to implement commonly used code or functions into a larger section of code. Instead of rewriting the same code over and over again, a programmer can save the code [...] Related posts:How To Obtain Environment Details With .NET 3.5 How-to: Easily Send Emails With .NET Understanding SMTP Status Codes ...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Does a prose to code compiler exist?

    - by Raynos
    I have seen some horrible code in my time including people virtually duplicating the code in comments // add 4 to x x+=4; // for each i in 0 to 9 for (int i = 0; i < 10; i++) { // multiply x by i x *= i; } Taking this concept further, I'm curious whether prose to code compilers exist. Is there a valid use case for English prose to code? Do compilers exist that do this? The distinction between this and auto generated code, is that auto generated code is generally always a subset of a project. Can we have complete projects auto generated from english prose? I realise that this might overlap with the concept of declarative languages.

    Read the article

  • why not use unmanaged safe code in c#

    - by user613326
    There is an option in c# to execute code unchecked. It's generally not advised to do so, as managed code is much safer and it overcomes a lot of problems. However I am wondering, if you're sure your code won't cause errors, and you know how to handle memory then why (if you like fast code) follow the general advice? I am wondering this since I wrote a program for a video camera, which required some extremely fast bitmap manipulation. I made some fast graphical algorithms myself, and they work excellent on the bitmaps using unmanaged code. Now I wonder in general, if you're sure you don't have memory leaks, or risks of crashes, why not use unmanaged code more often ? PS my background: I kinda rolled into this programming world and I work alone (I do so for a few years) and so I hope this software design question isn't that strange. I don't really have other people out there like a teacher to ask such things.

    Read the article

  • Releasing a project under GPL v2 or later without the source code of libraries

    - by Luciano Silveira
    I wrote a system in Java that I want to release under the terms of GPL v2 or later. I've used Apache Maven to deal with all the dependencies of the system, so I don't have the source code of any of the libraries used. I've already checked, all the libraries were released under GPL-compatible licenses (Apache v2, 3-clause BSD, MIT, LGPL v2 and v2.1). I have 3 questions about this scenario: 1) Can I release a package with only the binaries of code I wrote, not including the libraries, and distribute only the source code I wrote? 2) Can I release a package with all the binaries, including the libraries, and distribute only the source code I wrote? 3) Can I release a package with all the binaries, including the libraries, and distribute only the source code I wrote plus the source code of the libraries licensed under the LGPL license?

    Read the article

  • How do you handle measuring Code Coverage in JavaScript

    - by Dancrumb
    In order to measure Code Coverage for JavaScript unit tests, one needs to instrument the code, run the tests and then perform post-processing. My concern is that, as a result, you are unit testing code that will never be run in production. Since JavaScript isn't compiled, what you test should be precisely what you execute. So here's my question, how do you handle this? One thought I had was to run Unit Testing on the production code and use that for my pass fail. I would then create a shadow of my production code, with instrumentation and run my unit tests again; this would give me my code coverage stats. Has anyone come across a method that is a little more graceful than this?

    Read the article

  • What is testable code?

    - by Michael Freidgeim
    We are improving quality of code and trying to develop more unit tests. The question that developers asked  was  "How to make code testable ?"  From http://openmymind.net/2010/8/17/Write-testable-code-even-if-you-dont-write-tests/ First and foremost, its loosely coupled, taking advantage of dependency injection (and auto-wiring), composition and interface-programming. Testable code is also readable - meaning it leverages single responsibility principle and Liskov substitution principle.A few practical suggestions are listed in http://misko.hevery.com/code-reviewers-guide/More recommendations are in http://googletesting.blogspot.com/2008/08/by-miko-hevery-so-you-decided-to.htmlIt is slightly too theoretical - " the trick is translating these abstract concepts into concrete decisions in your code."

    Read the article

  • Un espace de revue de code a ouvert ses portes dans la rubrique Qt, venez participer

    Bonjour à tous, Suite à une certaine demande après le défi, il nous a semblé utile d'organiser quelque peu une revue de code Qt. En deux mots, de quoi s'agit-il ? Des développeurs plus expérimentés lisent le code d'autres développeurs et le commentent : ceci aurait été mieux d'une autre manière, ce commentaire ne veut rien dire, ce pavé de code devrait être réécrit, etc. Des remarques sur le fond et la forme du code, sur son organisation, les patrons de conception utilisés, les concepts inhérents à Qt et/ou au C++ mal compris ou mal appliqués, etc. L'objectif est de confronter les opinions sur un code pour qu'au final tout le monde y gagne. Pour l'organisation, autant faire simple : pour ceux qui souhaitent une revue de code, créez un ...

    Read the article

  • Top X tips to code & debug efficiently [closed]

    - by user1510230
    I'm starting a big Java project and I wanted to have some advices that could benefit us all. What are the X (X could be 5 / 10 / ... or even 100 :) most important tips to code and debug efficiently in general (and in particular with java / javascript) ? I'll start with some basic ones : Use functions everytime a portion of code is used more than twice. Try not to code features with more than 15 lines of code in one shot. Rather write 5 lines of code then check if they work correctly then write 5 more... and so on start with the outcome of the function and then code it backwards (bottom-top approach) ... Thanks everybody

    Read the article

  • Where to find GUI code

    - by muffinz
    I've been rummaging through Unity's source code (Shell Interface) and I was a little curious about something; where in the code are you supposed to find positional code? I'll clarify a bit with some examples. How do you find in the code what tells the Launcher to sit on the left side of the screen? Where in the code does it tell the "Session" button on the panel (top) to sit at the very right of the screen? I guess my real question is how do I find this out for myself? I've looked through a big portion of the source code and can't find anything related to the actual position of these items, only their sub-items like text-align. Any guidance on this would be much appreciated.

    Read the article

  • Programmatically clean Word generated HTML while preserving styles?

    - by GeReV
    In my current company, we have this decade old... let's call it a "Hello World" application. While wanting to create a newer version of it, we also want to preserve older entries. These older entries contain hideous Word generated HTML which was never filtered before. If and when we move to a newer system, I'd generally prefer to have that HTML cleaned and filtered in order to have the site comply with HTML standards as much as possible. However, just cleaning that code like Jeff Atwood described in his blog or in any other way I know of would also ruin the style and formatting. Now, that just might cause our users to revolt and then all hell will break loose... Not a very good idea. Question is -- can Word's HTML be cleaned while preserving basic formatting? (e.g: coloring, italicized, bold text and so on) Preferably using publicly available code or library, such as HTML Tidy, examples in C# would be much appreciated. Thanks!

    Read the article

  • PL/SQL pre-compile and Code Quality checks in an automatted build environment?

    - by Lars Corneliussen
    We build software using Hudson and Maven. We have C#, java and last, but not least PL/SQL sources (sprocs, packages, DDL, crud) For C# and Java we do unit tests and code analysis, but we don't really know the health of our PL/SQL sources before we actually publish them to the target database. Requirements There are a couple of things we wan't to test in the following priority: Are the sources valid, hence "compilable"? For packages, with respect to a certain database, would they compile? Code Quality: Do we have code flaws like duplicates, too complex methods or other violations to a defined set of rules? Also, the tool must run head-less (commandline, ant, ...) we wan't to do analysis on a partial code base (changed sources only) Tools We did a little research and found the following tools that could potencially help: Cast Application Intelligence Platform (AIP): Seems to be a server that grasps information about "anything". Couldn't find a console version that would export in readable format. Toad for Oracle: The Professional version is said to include something called Xpert validates a set of rules against a code base. Sonar + PL/SQL-Plugin: Uses Toad for Oracle to display code-health the sonar-way. This is for browsing the current state of the code base. Semantic Designs DMSToolkit: Quite general analysis of source code base. Commandline available? Semantic Designs Clones Detector: Detects clones. But also via command line? Fortify Source Code Analyzer: Seems to be focussed on security issues. But maybe it is extensible? more... So far, Toad for Oracle together with Sonar seems to be an elegant solution. But may be we are missing something here? Any ideas? Other products? Experiences? Related Questions on SO: http://stackoverflow.com/questions/531430/any-static-code-analysis-tools-for-stored-procedures http://stackoverflow.com/questions/839707/any-code-quality-tool-for-pl-sql http://stackoverflow.com/questions/956104/is-there-a-static-analysis-tool-for-python-ruby-sql-cobol-perl-and-pl-sql

    Read the article

  • c#: Clean way to fit a collection into a multidimensional array?

    - by Rosarch
    I have an ICollection<MapNode>. Each MapNode has a Position attribute, which is a Point. I want to sort these points first by Y value, then by X value, and put them in a multidimensional array (MapNode[,]). The collection would look something like this: (30, 20) (20, 20) (20, 30) (30, 10) (30, 30) (20, 10) And the final product: (20, 10) (20, 20) (20, 30) (30, 10) (30, 20) (30, 30) Here is the code I have come up with to do it. Is this hideously unreadable? I feel like it's more hacky than it needs to be. private Map createWorldPathNodes() { ICollection<MapNode> points = new HashSet<MapNode>(); Rectangle worldBounds = WorldQueryUtils.WorldBounds(); for (float x = worldBounds.Left; x < worldBounds.Right; x += PATH_NODE_CHUNK_SIZE) { for (float y = worldBounds.Y; y > worldBounds.Height; y -= PATH_NODE_CHUNK_SIZE) { // default is that everywhere is navigable; // a different function is responsible for determining the real value points.Add(new MapNode(true, new Point((int)x, (int)y))); } } int distinctXValues = points.Select(node => node.Position.X).Distinct().Count(); int distinctYValues = points.Select(node => node.Position.Y).Distinct().Count(); IList<MapNode[]> mapNodeRowsToAdd = new List<MapNode[]>(); while (points.Count > 0) // every iteration will take a row out of points { // get all the nodes with the greatest Y value currently in the collection int currentMaxY = points.Select(node => node.Position.Y).Max(); ICollection<MapNode> ythRow = points.Where(node => node.Position.Y == currentMaxY).ToList(); // remove these nodes from the pool we're picking from points = points.Where(node => ! ythRow.Contains(node)).ToList(); // ToList() is just so it is still a collection // put the nodes with max y value in the array, sorting by X value mapNodeRowsToAdd.Add(ythRow.OrderByDescending(node => node.Position.X).ToArray()); } MapNode[,] mapNodes = new MapNode[distinctXValues, distinctYValues]; int xValuesAdded = 0; int yValuesAdded = 0; foreach (MapNode[] mapNodeRow in mapNodeRowsToAdd) { xValuesAdded = 0; foreach (MapNode node in mapNodeRow) { // [y, x] may seem backwards, but mapNodes[y] == the yth row mapNodes[yValuesAdded, xValuesAdded] = node; xValuesAdded++; } yValuesAdded++; } return pathNodes; } The above function seems to work pretty well, but it hasn't been subjected to bulletproof testing yet.

    Read the article

  • Clean way to output values in ASP.NET MVC Views when value is not null

    - by Swoop
    Is there a better way to write the code below? I have quite a few blocks that are similar, and this is making the code in the Viewpage very messy to work with. The data value with the associated label only needs to be output when certain conditions are met, which is almost always if the value is not null. The options I can think is to use a response.write to atleast minimize the usage of the ASP script tags, or to format the webpage is such a way that the label displays with an appropriate n/a type value. <% if (myData.Balance != null) { %> Balance: <%= String.Format("{0:C}", (myData.Balance))%> <% } %>

    Read the article

  • How can I clean up this SELECT query?

    - by Cruachan
    I'm running PHP 5 and MySQL 5 on a dedicated server (Ubuntu Server 8.10) with full root access. I'm cleaning up some LAMP code I've inherited and I've a large number of SQL selects with this type of construct: SELECT ... FROM table WHERE LCASE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE( strSomeField, ' ', '-'), ',', ''), '/', '-'), '&', ''), '+', '') ) = $somevalue Ignoring the fact that the database should never have been constructed to require such a select in the first place, and the $somevalue field will need to be parameterised to plug the gaping security hole, what is my best option for fixing the WHERE condition into something less offensive? If I was using MSSQL or Oracle I'd simply put together a user-defined function, but my experience with MySQL is more limited and I've not constructed a UDF with it before, although I'm happy coding C. Update: For all those who've already raised their eyebrows at this in the original code, $somevalue is actually something like $GET['product']—there are a few variations on the theme. In this case the select is pulling the product back from the database by product name—after stripping out characters so it matches what could be previously passed as a URI parameter.

    Read the article

  • Joining the same model twice in a clean way, but making the code reusable

    - by Shako
    I have a model Painting which has a Paintingtitle in each language and a Paintingdescription in each language: class Painting < ActiveRecord::Base has_many :paintingtitles, :dependent => :destroy has_many :paintingdescriptions, :dependent => :destroy end class Paintingtitle < ActiveRecord::Base belongs_to :painting belongs_to :language end class Paintingdescription < ActiveRecord::Base belongs_to :painting belongs_to :language end class Language < ActiveRecord::Base has_many :paintingtitles, :dependent => :nullify has_many :paintingdescriptions, :dependent => :nullify has_many :paintings, :through => :paintingtitles end As you might notice, I reference the Language model from my Painting model via both the Paintingtitle model and Paintingdescription model. This works for me when getting a list of paintings with their title and description in a specific language: cond = {"paintingdescription_languages.code" => language_code, "paintingtitle_languages.code" => language_code} cond['paintings.publish'] = 1 unless admin paginate( :all, :select => ["paintings.id, paintings.publish, paintings.photo_file_name, paintingtitles.title, paintingdescriptions.description"], :joins => " INNER JOIN paintingdescriptions ON (paintings.id = paintingdescriptions.painting_id) INNER JOIN paintingtitles ON (paintings.id = paintingtitles.painting_id) INNER JOIN languages paintingdescription_languages ON (paintingdescription_languages.id = paintingdescriptions.language_id) INNER JOIN languages paintingtitle_languages ON (paintingtitle_languages.id = paintingtitles.language_id) ", :conditions => cond, :page => page, :per_page => APP_CONFIG['per_page'], :order => "id DESC" ) Now I wonder if this is a correct way of doing this. I need to fetch paintings with their title and description in different functions, but I don't want to specify this long join statement each time. Is there a cleaner way, for instance making use of the has_many through? e.g. has_many :paintingdescription_languages, :through => :paintingdescriptions, :source => :language has_many :paintingtitle_languages, :through => :paintingtitles, :source => :language But if I implement above 2 lines together with the following ones, then only paintingtitles are filtered by language, and not the paintingdescriptions: cond = {"languages.code" => language_code} cond['paintings.publish'] = 1 unless admin paginate( :all, :select => ["paintings.id, paintings.publish, paintings.photo_file_name, paintingtitles.title, paintingdescriptions.description"], :joins => [:paintingdescription_languages, :paintingtitle_languages], :conditions => cond, :page => page, :per_page => APP_CONFIG['per_page'], :order => "id DESC" )

    Read the article

  • Overwrite clean method in Django Custom Forms

    - by John
    Hi I have wrote a custom widget class AutoCompleteWidget(widgets.TextInput): """ widget to show an autocomplete box which returns a list on nodes available to be tagged """ def render(self, name, value, attrs=None): final_attrs = self.build_attrs(attrs, name=name) if not self.attrs.has_key('id'): final_attrs['id'] = 'id_%s' % name if not value: value = '[]' jquery = u""" <script type="text/javascript"> $("#%s").tokenInput('%s', { hintText: "Enter the word", noResultsText: "No results", prePopulate: %s, searchingText: "Searching..." }); $("body").focus(); </script> """ % (final_attrs['id'], reverse('ajax_autocomplete'), value) output = super(AutoTagWidget, self).render(name, "", attrs) return output + mark_safe(jquery) class MyForm(forms.Form): AutoComplete = forms.CharField(widget=AutoCompleteWidget) this widget uses a jquery function which autocompletes a word based on entries from the database. You can preset its initial values by setting prePopulate to a json string in the form ['name': 'some name', 'id': 'some id'] I do this by setting the inital value of the form field to this json string jquery_string = ['name': 'some name', 'id': 'some id'] form = MyForm(initial={'AutoComplete':jquery_string}) When submitting the form the the value of AutoComplete is returned as a comma seperated list of the selected ids e.g. 12,45,43,66 which if what I want. However if there is an error in the form, for example a required field has not been entered the value of the AutoComplete field is now 12,45,43,66 and not the json string which it requires. What is the best way to solve this. I was thinking about overwriting the clean method in the form class but I'm not sure how to find out if any other element has returned an error. e.g. if forms.errors form.cleaned_date['autocomplete'] = json string return form.cleaned_data Thanks

    Read the article

  • Drupal with clean urls turned on is putting question marks in URL

    - by aussiegeek
    I have a drupal site with clean urls, the pages load correctly, but then the URL is rewritten, which I really don't to happen. My .htaccess is: <IfModule mod_rewrite.c> RewriteEngine on # If your site can be accessed both with and without the 'www.' prefix, you # can use one of the following settings to redirect users to your preferred # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option: # # To redirect all users to access the site WITH the 'www.' prefix, # (http://example.com/... will be redirected to http://www.example.com/...) # adapt and uncomment the following: # RewriteCond %{HTTP_HOST} ^example\.com$ [NC] # RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301] # # To redirect all users to access the site WITHOUT the 'www.' prefix, # (http://www.example.com/... will be redirected to http://example.com/...) # uncomment and adapt the following: # RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC] # RewriteRule ^(.*)$ http://example.com/$1 [L,R=301] # Modify the RewriteBase if you are using Drupal in a subdirectory or in a # VirtualDocumentRoot and the rewrite rules are not working properly. # For example if your site is at http://example.com/drupal uncomment and # modify the following line: # RewriteBase /drupal # # If your site is running in a VirtualDocumentRoot at http://example.com/, # uncomment the following line: RewriteBase / # Rewrite URLs of the form 'x' to the form 'index.php?q=x'. RewriteCond %{REQUEST_URI} !(connect|administration) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !=/favicon.ico RewriteRule ^(.*)$ index.php?q=$1 [L,QSA] </IfModule>

    Read the article

  • how to use git rebase to clean up a convoluted history

    - by lsiden
    After working for several weeks with a half dozen different branches and merges, on both my laptop and work and my desktop at home, my history has gotten a bit convoluted. For example, I just did a fetch, then merged master with origin/master. Now, when I do git show-branches, the output looks like this: ! [login] Changed domain name. ! [master] Merge remote branch 'origin/master' ! [migrate-1.9] Migrating to 1.9.1 on Heroku ! [rebase-master] Merge remote branch 'origin/master' ---- - - [master] Merge remote branch 'origin/master' + + [master^2] A bit of re-arranging and cleanup. - - [master^2^] Merge branch 'rpx-login' + + [master^2^^2] Commented out some debug logging. + + [master^2^^2^] Monkey-patched Rack::Request#ip + + [master^2^^2~2] dump each request to log .... I would like to clean this up with a git rebase. I created a new branch, rebase-master, for this purpose, and on this branch tried git rebase <common-ancestor>. However, I have to resolve many conflicts, and the end result on branch rebase-master no longer matches the corresponding version on master, which has already been tested and works! I thought I saw a solution to this somewhere but can't find it anymore. Does anyone know how to do this? Or will these convoluted ref names go away when I start deleting un-needed branches that I have already merged with? I am the sole developer on this project, so there is no one else who will be affected.

    Read the article

  • How to clean completly select2 control?

    - by Candil
    I'm working with the awesome select2 control. I'm trying to clean and disable the select2 with the content too so I do this: $("#select2id").empty(); $("#select2id").select2("disable"); Ok, it works, but if i had a value selected all the items are removed, the control is disabled, but the selected value is still displayed. I want to clear all content so the placeholder would be showed. Here is a example I did where you can see the issue: http://jsfiddle.net/BSEXM/ HTML: <select id="sel" data-placeholder="This is my placeholder"> <option></option> <option value="a">hello</option> <option value="b">all</option> <option value="c">stack</option> <option value="c">overflow</option> </select> <br> <button id="pres">Disable and clear</button> <button id="ena">Enable</button> Code: $(document).ready(function () { $("#sel").select2(); $("#pres").click(function () { $("#sel").empty(); $("#sel").select2("disable"); }); $("#ena").click(function () { $("#sel").select2("enable"); }); }); CSS: #sel { margin: 20px; } Do you have any idea or advice to this?

    Read the article

  • I want tell the VC++ Compiler to compile all code. Can it be done?

    - by KGB
    I am using VS2005 VC++ for unmanaged C++. I have VSTS and am trying to use the code coverage tool to accomplish two things with regards to unit tests: See how much of my referenced code under test is getting executed See how many methods of my code under test (if any) are not unit tested at all Setting up the VSTS code coverage tool (see the link text) and accomplishing task #1 was straightforward. However #2 has been a surprising challenge for me. Here is my test code. class CodeCoverageTarget { public: std::string ThisMethodRuns() { return "Running"; } std::string ThisMethodDoesNotRun() { return "Not Running"; } }; #include <iostream> #include "CodeCoverageTarget.h" using namespace std; int main() { CodeCoverageTarget cct; cout<<cct.ThisMethodRuns()<<endl; } When both methods are defined within the class as above the compiler automatically eliminates the ThisMethodDoesNotRun() from the obj file. If I move it's definition outside the class then it is included in the obj file and the code coverage tool shows it has not been exercised at all. Under most circumstances I want the compiler to do this elimination for me but for the code coverage tool it defeats a significant portion of the value (e.g. finding untested methods). I have tried a number of things to tell the compiler to stop being smart for me and compile everything but I am stumped. It would be nice if the code coverage tool compensated for this (I suppose by scanning the source and matching it up with the linker output) but I didn't find anything to suggest it has a special mode to be turned on. Am I totally missing something simple here or is this not possible with the VC++ compiler + VSTS code coverage tool? Thanks in advance, KGB

    Read the article

  • Delphi - Clean TListBox Items

    - by Brad
    I want to clean a list box by checking it against two other list boxes. Listbox1 would have the big list of items Listbox2 would have words I want removed from listbox1 Listbox3 would have mandatory words that have to exist for it to remain in listbox1 Below is the code I've got so far for this, it's VERY slow with large lists. // not very efficient Function checknegative ( instring : String; ListBox : TListBox ) : Boolean; Var i : Integer; Begin For I := listbox.Items.Count - 1 Downto 0 Do Begin If ExistWordInString ( instring, listbox.Items.Strings [i], [soWholeWord, soDown] ) = True Then Begin result := True; //True if in list, False if not. break; End Else Begin result := False; End; End; result:=false; End; Function ExistWordInString ( aString, aSearchString : String; aSearchOptions : TStringSearchOptions ) : Boolean; Var Size : Integer; Begin Size := Length ( aString ); If SearchBuf ( Pchar ( aString ), Size, 0, 0, aSearchString, aSearchOptions ) <> Nil Then Begin result := True; End Else Begin result := False; End; End;

    Read the article

  • Clean solution to this ruby iterator trickiness?

    - by mstksg
    k = [1,2,3,4,5] for n in k puts n if n == 2 k.delete(n) end end puts k.join(",") # Result: # 1 # 2 # 4 # 5 # [1,3,4,5] # Desired: # 1 # 2 # 3 # 4 # 5 # [1,3,4,5] This same effect happens with the other array iterator, k.each: k = [1,2,3,4,5] k.each do |n| puts n if n == 2 k.delete(n) end end puts k.join(",") has the same output. The reason this is happening is pretty clear...Ruby doesn't actually iterate through the objects stored in the array, but rather just turns it into a pretty array index iterator, starting at index 0 and each time increasing the index until it's over. But when you delete an item, it still increments the index, so it doesn't evaluate the same index twice, which I want it to. This might not be what's happening, but it's the best I can think of. Is there a clean way to do this? Is there already a built-in iterator that can do this? Or will I have to dirty it up and do an array index iterator, and not increment when the item is deleted?

    Read the article

  • need to clean malformed tags using regular expression

    - by Brian
    Looking to find the appropriate regular expression for the following conditions: I need to clean certain tags within free flowing text. For example, within the text I have two important tags: <2004:04:12 and . Unfortunately some of tags have missing "<" or "" delimiter. For example, some are as follows: 1) <2004:04:12 , I need this to be <2004:04:12> 2) 2004:04:12>, I need this to be <2004:04:12> 3) <John Doe , I need this to be <John Doe> I attempted to use the following for situation 1: String regex = "<\\d{4}-\\d{2}-\\d{2}\\w*{2}[^>]"; String output = content.replaceAll(regex,"$0>"); This did find all instances of "<2004:04:12" and the result was "<2004:04:12 ". However, I need to eliminate the space prior to the ending tag. Not sure this is the best way. Any suggestions. Thanks

    Read the article

< Previous Page | 47 48 49 50 51 52 53 54 55 56 57 58  | Next Page >