Search Results

Search found 15316 results on 613 pages for 'coding style'.

Page 67/613 | < Previous Page | 63 64 65 66 67 68 69 70 71 72 73 74  | Next Page >

  • Automatic .NET code, nhibernate session, and LINQ datacontext clean-up?

    - by AverageJoe719
    Hi all, in my goal to adopt better coding practices I have a few questions in general about automatic handling of code. I have heard different answers both from online and talking with other developers/programmers at my work. I am not sure if I should have split them into 3 questions, but they all seem sort of related: 1) How does .NET handle instances of classes and other code things that take up memory? I recently found out about using the factory pattern for certain things like service classes so that they are only instantiated once in the entire application, but then I was told that '.NET handles a lot of that stuff automatically when mentioning it.' 2) How does Nhibernate's session handle automatic clean-up of un-used things? I've seen some say that it is great at handling things automatically and you should just use a session factory and that's it, no need to close it. But I have also read and seem many examples where people close the hibernate session. 3) How does LINQ's datacontext handle this? Most of the time I never .disposed my datacontext's and the app didn't see to take a performance hit (though I am not running anything super intensively), but it seems like most people recommend disposing of your datacontext after you are done with it. However, I have seen many many code examples where the dispose method is never called. Also in general I found it kind of annoying that you couldn't access even one-deep child related objects after disposing of the datacontext unless you explicity also grabbed them in the query. Thanks all. I am loving this site so far, I kind of get lost and spend hours just reading things on here. =)

    Read the article

  • Learning libraries without books or tutorials

    - by Kawili-wili
    While many ask questions about where to find good books or tutorials, I'd like to take the opposite tack. I consider myself to be an entry-level programmer ready to move up to mid-level. I have written code in c, c++, c#, perl, python, clojure, vb, and java, so I'm not completely clueless. Where I see a problem in moving to the next level is learning to make better use of the literally hundreds upon hundreds of libraries available out there. I seem paralyzed unless there is a specific example in a book or tutorial to hand-hold me, yet I often read in various forums where another programmer attempts to assist with a question. He/she will look through the docs or scan the available classes/methods in their favorite IDE and seem to grok what's going on in a relatively short period of time, even if they had no previous experience with that specific library or function. I yearn to break the umbilical chord of constantly spending hour upon hour searching and reading, searching and reading, searching and reading. Many times there is no book or tutorial, or if there is, the discussion glosses over my specific needs or the examples shown are too far off the path for the usage I had in mind or the information is outdated and makes use of deprecated components or the library itself has fallen out of mainstream, yet is still perfectly usable (but no docs, books, or tutorials to hand-hold). My question is: In the absence of books or tutorials, what is the best way to grok new or unfamiliar libraries? I yearn to slicken the grok path so I can get down to the business of doing what I love most -- coding.

    Read the article

  • How do I stop Chrome from yellowing my site's input boxes?

    - by davebug
    Among other text and visual aids on a form submission, post-validation, I'm coloring my input boxes red to signify the interactive area needing attention. On Chrome (and for Google Toolbar users) the auto-fill feature re-colors my input forms yellow. Here's the complex issue: I want auto-complete allowed on my forms, as it speeds users logging in. I am going to check into the ability to turn the autocomplete attribute to off if/when there's an error triggered, but it is a complex bit of coding to programmatically turn off the auto-complete for the single effected input on a page. This, to put it simply, would be a major headache. So to try to avoid that issue, is there any simpler method of stopping Chrome from re-coloring the input boxes? [edit] I tried the !important suggestion below and it had no effect. I have not yet checked Google Toolbar to see if the !important attribute woudl work for that. As far as I can tell, there isn't any means other than using the autocomplete attribute (which does appear to work).

    Read the article

  • Do you ever make a code change and just test rather than trying to fully understand the change you'v

    - by Clay Nichols
    I'm working in a 12 year old code base which I have been the only developer on. There are times that I'll make a a very small change based on an intuition (or quantum leap in logic ;-). Usually I try to deconstruct that change and make sure I read thoroughly the code. However sometimes, (more and more these days) I just test and make sure it had the effect I wanted. (I'm a pretty thorough tester and would test even if I read the code). This works for me and we have surprisingly (compared to most software I see) few bugs escape into the wild. But what I'm wondering is whether this is just the "art" side of coding. Yes, in an ideal world you would exhaustively read every bit of code that your change modified, but I in practice, if you're confident that it only affects a small section of code, is this a common practice? I can obviously see where this would be a disastrous approach in the hands of a poor programmer. But then, I've seen programmers who ostensibly are reading the code and break stuff left and right (in their own code based which only they have been working on).

    Read the article

  • C++11 decltype requires instantiated object

    - by snipes83
    I was experimenting a little with the C++11 standard and came up with this problem: In C++11 you can use auto and decltype to automatically get return type for a function as, for example the begin() and end() functions below: #include <vector> template <typename T> class Container { private: std::vector<T> v; public: auto begin() -> decltype(v.begin()) { return v.begin(); }; auto end() -> decltype(v.end()) { return v.end(); }; }; My problem here is that I have to declare the private vector<T> v before the public declarations which is against my coding style. I would like to declare all my private members after my public members. You have to declare the vector before the function declaration because the expression in decltype is a call to vector member function begin() and requires an instance of the object. Is there a way around this?

    Read the article

  • WPF DatePicker IsEnabled property not changing appearance

    - by Jonathan
    I think I have found an issue with the DatePicker in the toolkit, perhaps some of you gurus can check it out. The issue is when setting the IsEnabled property of the DatePicker. If set in XAML, it stays grey even if you set the IsEnabled to true at run time. The same goes for the other way around should it start off being enabled. The button just changes the IsEnabled property of the date picker, you will see that when it becomes enabled, the style remains grayed out. <Window x:Class="WpfApplication3.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:tk="http://schemas.microsoft.com/wpf/2008/toolkit" Title="Window1" Height="300" Width="300"> <StackPanel> <tk:DatePicker x:Name="txtDate" IsEnabled="False"></tk:DatePicker> <Button Height="25" Click="Button_Click"></Button> </StackPanel> </Window> private void Button_Click(object sender, RoutedEventArgs e) { txtDate.IsEnabled = !txtDate.IsEnabled; }

    Read the article

  • Nested dereferencing arrows in Perl: to omit or not to omit?

    - by DVK
    In Perl, when you have a nested data structure, it is permissible to omit de-referencing arrows to 2d and more level of nesting. In other words, the following two syntaxes are identical: my $hash_ref = { 1 => [ 11, 12, 13 ], 3 => [31, 32] }; my $elem1 = $hash_ref->{1}->[1]; my $elem2 = $hash_ref->{1}[1]; # exactly the same as above Now, my question is, is there a good reason to choose one style over the other? It seems to be a popular bone of stylistic contention (Just on SO, I accidentally bumped into this and this in the space of 5 minutes). So far, none of the usual suspects says anything definitive: perldoc merely says "you are free to omit the pointer dereferencing arrow". Conway's "Perl Best Practices" says "whenever possible, dereference with arrows", but it appears to only apply to the context of dereferencing the main reference, not optional arrows on 2d level of nested data structures. "MAstering Perl for Bioinfirmatics" author James Tisdall doesn't give very solid preference either: "The sharp-witted reader may have noticed that we seem to be omitting arrow operators between array subscripts. (After all, these are anonymous arrays of anonymous arrays of anonymous arrays, etc., so shouldn't they be written [$array-[$i]-[$j]-[$k]?) Perl allows this; only the arrow operator between the variable name and the first array subscript is required. It make things easier on the eyes and helps avoid carpal tunnel syndrome. On the other hand, you may prefer to keep the dereferencing arrows in place, to make it clear you are dealing with references. Your choice." Personally, i'm on the side of "always put arrows in, since itg's more readable and obvious tiy're dealing with a reference".

    Read the article

  • Quick question - how to comment if-else structure?

    - by serg555
    Lets say you have: if(condition) { i = 1; } else { i = 2; } and you need to put comments explaining if and else blocks. What's the most readable way of doing it so someone can easily pick them up at first glance? I usually do it like this: //check for condition if(condition) { i = 1; } else { //condition isn't met i = 2; } which I find not good enough as comments are located at different levels, so at quick glance you would just pick up if comment and else comment would look like it belongs to some inner structure. Putting them like this: if(condition) { //check for condition i = 1; } else { //condition isn't met i = 2; } doesn't look good to me either as it would seem like the whole structure is not commented (condition might be big and take multiple lines). Something like that: //check for condition if(condition) { i = 1; //condition isn't met } else { i = 2; } would be probably the best style from comments point of view but confusing as a code structure. How do you comment such blocks?

    Read the article

  • general learning methodology

    - by momo
    just wanted to hear on the different general learning paths people embark on when learning a new language/framework. the one i currently use, which is how i learned bash and am currently learning python, is: instant hacking tutorial (very short tutorial introducing the basic syntax, variable declaration, loops, data types, etc. and how they are generally used) in depth tutorial with good programming style and slightly topic-specific (e.g. Mark Pilgrim's Dive into Python), important topics for me personally are regex methods, file IO, and ways the different data types are utilized best (i wrote a very primitive bayesian spam filter using python's dictionaries to keep track of word occurrences) spaced-repition of syntax or short recipes (i use anki, with questions like 'create dictionary with filename and filesize metadata, human-readable' or simpler ones like 'match 0 - 3 occurences of the letter M in a string', or 'return/create an iterator from two sequences') the use of spaced-repitition has been invaluable, and i credit it with the ease that i can recall/create python algorithms. however, i've recently started looking into django, and i've found that spaced-repitition, at least in my case, doesn't work very well for learning a framework, it works best with short code recipes (either that or i should start looking into more basic django framework tutorials). the problem i'm encountering is that since framework programming is not only algorithms, but actually learning the API, which can be quite complex since you have to learn all the methods, modules, the places where they are stored, and the sequence of which things have to be done. for ex. in django to start a project that deals with polls (from the django tutorial), one has to create the project, edit the settings.py file, create the polls app, edit the models.py file (which requires knowing the classes that are present in the module models), edit the urls.py file, etc. i found that my spaced-repition method didn't work very well for this type of learning, so i wanted to ask you guys what method(s) you use for learning the different frameworks/APIs.

    Read the article

  • What is the preferred way in C++ for converting a builtin type (int) to bool?

    - by Martin
    When programming with Visual C++, I think every developer is used to see the warning warning C4800: 'BOOL' : forcing value to bool 'true' or 'false' from time to time. The reason obviously is that BOOL is defined as int and directly assigning any of the built-in numerical types to bool is considered a bad idea. So my question is now, given any built-in numerical type (int, short, ...) that is to be interpreted as a boolean value, what is the/your preferred way of actually storing that value into a variable of type bool? Note: While mixing BOOL and bool is probably a bad idea, I think the problem will inevitably pop up whether on Windows or somewhere else, so I think this question is neither Visual-C++ nor Windows specific. Given int nBoolean; I prefer this style: bool b = nBoolean?true:false; The following might be alternatives: bool b = !!nBoolean; bool b = (nBoolean != 0); Is there a generally preferred way? Rationale? I should add: Since I only work with Visual-C++ I cannot really say if this is a VC++ specific question or if the same problem pops up with other compilers. So it would be interesting to specifically hear from g++ or users how they handle the int-bool case. Regarding Standard C++: As David Thornley notes in a comment, the C++ Standard does not require this behavior. In fact it seems to explicitly allow this, so one might consider this a VC++ weirdness. To quote the N3029 draft (which is what I have around atm.): 4.12 Boolean conversions [conv.bool] A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. (...)

    Read the article

  • CKEditor doesn't apply inline styles to links

    - by jomanlk
    I'm using ckeditor version 3 as a text editor to create markup to be sent through email. This means that I have to have all the styles inline and anything that needs to be styled will definitely need the style applied. I'm currently using addStylesSet to generate custom styles that can be applied to elements. The problem I have is that although this works on most elements, styles don't seem to be applied to <a> <ol> <ul> and <li> I really need to be able to apply inline styles to these elements as well. I've been looking at the examples on the ckeditor site, but even they just seem to be wrapping a <span> around the link. Is there anyway I can apply inline styles to <a> tags or failing that, can I just give ckeditor a bunch of classes that can be applied to any tag (Like TinyMCE does with it's link to an external css file)? so that I can at least do a textreplace on them to get the styles inline? I haven't pasted any code here because it's exactly the same as what's been done on the ckeditor site.

    Read the article

  • Strange issue with fixed form border styles in Vista

    - by Nazgulled
    My previous post about this issue didn't got too many answers and it was kinda specific and hard to understand. I think I've managed to understand the problem better and I now believe it to be a Vista issue... The problem lies on all types of fixed border styles like FixedDialog, Fixed3D, FixedSingle and FixedToolWindow. It does not happen on the sizable ones. This problem, like I said, it also happens only on Vista. Let's say you have a form with any of the fixed border styles and set the starting location to 0,0. What you want here is for the form to be snapped to the top left corner of the screen. This works just fine if the form border style is one of the sizable options, if it's fixed, well, the form will be a little bit outside of the screen working area both to the left and top. What's more strange about this is that the form location does not change, it sill is 0,0, but a few pixels of the form are still drawn outside of the working screen area. I tested this on XP and it didn't happen, the problem is Vista specific. On XP, the only difference was the border size that change a bit between any of the styles. But the form was always perfectly snapped to position 0,0. If possible, without finding how many pixels are being drawn outside of the working area and then add that to the form location, is there a possible way to fix or workaround this?

    Read the article

  • Modify columns in a data frame in R more cleanly - maybe using with() or apply()?

    - by Mittenchops
    I understand the answer in R to repetitive things is usually "apply()" rather than loop. Is there a better R-design pattern for a nasty bit of code I create frequently? So, pulling tabular data from HTML, I usually need to change the data type, and end up running something like this, to convert the first column to date format (from decimal), and columns 2-4 from character strings with comma thousand separators like "2,400,000" to numeric "2400000." X[,1] <- decYY2YY(as.numeric(X[,1])) X[,2] <- as.numeric(gsub(",", "", X[,2])) X[,3] <- as.numeric(gsub(",", "", X[,3])) X[,4] <- as.numeric(gsub(",", "", X[,4])) I don't like that I have X[,number] repeated on both the left and ride sides here, or that I have basically the same statement repeated for 2-4. Is there a very R-style way of making X[,2] less repetitive but still loop-free? Something that sort of says "apply this to columns 2,3,4---a function that reassigns the current column to a modified version in place?" I don't want to create a whole, repeatable cleaning function, really, just a quick anonymous function that does this with less repetition.

    Read the article

  • Nice way to break a reply up into pieces in ruby

    - by ChaosR
    Hello, I'm writing an IRCd. For this topic it doesn't really matter if you know much about IRC. Its a simple code style problem. Quick overview of the problem: No message may be longer than 512 characters If the message is more, it must be broken into pieces The NAMES reply sends all the nicknames of users on a channel, and quickly grows beyond 512 characters. I currently concocted this marvelous piece of code, it works perfectly. However, its just not "ruby-like". This piece of code is more what you expect in some piece of C code. # 11 is the number of all fixed characters combined in the reply pre_length = 11 + servername.length + mynick.length + channel.name.length list = [""] i = 0 channel.nicks.each do |nick, client| list[i+=1] = "" if list[i].length + nick.length + pre_length > 500 list[i] << "#{channel.mode_char(client)}#{client.nick} " end list.each { |l| send_numeric(RPL_NAMREPLY, channel.name, l.strip) } send_numeric(RPL_ENDOFNAMES, channel.name) So my question is, any ideas to do this more nicely? PS. code has been slightly modified to make it easier to understand out-of-context

    Read the article

  • Help- CSS styles for text links also affecting image links

    - by blabus
    I've been working on this one for about an hour now, and I'm about ready to pull my hair out. What seems like it should be a simple one or two lines of CSS apparently isn't. I have a Posterous blog with a custom theme I designed for a client, viewable here: http://phar-ma.com/ I obviously use CSS to style the text links in the posts. My problem is, the same styles are also being applied to images that have a larger version to view, since Posterous automatically turns them into links to the larger versions (the smaller images aren't turned into links). So basically I need to figure out how the return the styling of the link images to the same as the non-link images. Right now they have weird spacing and borders around them (because of the styles for the text links) and those change when you hover over them. They're also not centered correctly. I've tried just about every piece of CSS code I know, and I've had absolutely no luck. I also searched on Google and found this: http://perishablepress.com/press/2008/10/14/css-remove-link-underlines-borders-linked-images/ but still no luck with that either. So, if anyone has any ideas, I'd appreciate it. Thanks!

    Read the article

  • [jQuery UI - Accordion] Styling active header?

    - by RC
    Hi, Simple issue: I am using Accordion without any UI themes (just barebones, using my own CSS). So far, so good, except that I cannot figure out how to set an "active" style for the currently selected header. The jQuery code: $("#menu").accordion({ event:"mouseover",header:"a.top" }); The HTML code: <a href="#" class="top">XXX1</a> <div class="sub"> <a href="#">Subheading 1</a> <a href="#">Subheading 2</a> <a href="#">Subheading 3</a> </div> <a href="#" class="top">XXX2</a> <div class="sub"> <a href="#">Subheading 1</a> <a href="#">Subheading 2</a> <a href="#">Subheading 3</a> </div> This works great, except that I cannot find a way to define the styles for the active header without using ThemeRoller. Manually setting the following styles in my CSS has no effect: .ui-state-active .ui-widget-content .ui-state-active .ui-state-active a .ui-state-active a:link .ui-state-active a:visited Assistance, please?

    Read the article

  • Should I give the answer to a failed interview coding exercise?

    - by GlenH7
    We had a senior level interview candidate fail a nuance of the FizzBuzz question*. I mean, really, utterly, completely, failed the question - not even close. I even coached him through to thinking about using a loop and that 3 and 5 were really worth considering as special cases. He blew it. Just for QA purposes, I gave the same exact question to three teammates; gave them 5 minutes; and then came back to collect their pseudo-code. All of them nailed it and hadn't seen the question before. Two asked what the trick was... On a different logic exercise, the candidate showed some understanding of some of the features available within the language he chose to use (C#). So it's not as if he had never written a line of code. But his logic still stunk. My question is whether or not I should have given him the answer to the logic questions. He knew he blew them, and acknowledged it later in the interview. On the other hand, he never asked for the answer or what I was expecting to see. I know coding exercises can be used to set candidates up for failure (again, see second link from above). And I really tried to help him home in on answering the core of the question. But this was a senior level candidate and Fizz-Buzz is, frankly, ridiculously easy even with accounting for interview jitters. I felt like I should have shown him a way of solving the problem so that he could at least learn from the experience. But again, he didn't ask. What's the right way to handle that situation? *Okay, that's not the link to the actual FizzBuzz question, but it is a good P.SE discussion around FizzBuzz and links to the various aspects of it.

    Read the article

  • How to explain a layperson why a developer should not be interrupted while neck-deep in coding?

    - by András Szepesházi
    If you just consider the second part of my question, "Why a developer should not be interrupted while neck-deep in coding", that has been discussed a number of times by smart people. Heck, even the co-founder of SO, Joel Spolsky, wrote a blog post about "getting in the zone" and "being knocked out of the zone" and why it takes an average of 15 minutes to achieve productivity when participating in complex, software development related tasks. So I think the why has been established. What I'm interested in is how to explain all that to somebody who doesn't know beans about Beans (khmm I mean software development). How to tell the wife, or the funny guy from accounting at the workplace, or the long time friend who pings you on Skype every 30 minutes with a "Wazzzzzzup?!", that all the interruptions have a much deeper impact on your work than the obvious 30 seconds they took from your time. Obviously you can't explain it by sentences like "I have to juggle a lot of variable names in my short term memory" unless you want to be the target of blank stares or friendly abuse. I'd like to be able to explain all that to non-developers in a way that will make them clearly understand - without being offensive, elitist or too technical.

    Read the article

  • How to explain a layperson why a developer should not be interrupted while neck-deep in coding?

    - by András Szepesházi
    If you just consider the second part of my question, "Why a developer should not be interrupted while neck-deep in coding", that has been discussed a number of times by smart people. Heck, even the co-founder of SO, Joel Spolsky, wrote a blog post about "getting in the zone" and "being knocked out of the zone" and why it takes an average of 15 minutes to achieve productivity when participating in complex, software development related tasks. So I think the why has been established. What I'm interested in is how to explain all that to somebody who doesn't know beans about Beans (khmm I mean software development). How to tell the wife, or the funny guy from accounting at the workplace, or the long time friend who pings you on Skype every 30 minutes with a "Wazzzzzzup?!", that all the interruptions have a much deeper impact on your work than the obvious 30 seconds they took from your time. Obviously you can't explain it by sentences like "I have to juggle a lot of variable names in my short term memory" unless you want to be the target of blank stares or friendly abuse. I'd like to be able to explain all that to non-developers in a way that will make them clearly understand - without being offensive, elitist or too technical. EDIT: Thanks to everyone for their great insights. I've accepted EpsilonVector's answer as his analogy was the closest one to my original needs. The "falling asleep" explanation is neither offensive nor technical, almost anyone can relate to it, and the consequences of getting disturbed while falling asleep or while being in the zone are very similar: you experience frustration and you "lose" 15-20 minutes of time.

    Read the article

  • What are some Java patterns well-suited for fast, algorithmic coding?

    - by Casey Chu
    I'm in college, and I've recently started competing in programming competitions with my friends. These competitions involve solving algorithmic problems quickly. It's a lot of fun, but there's one problem: I'm forced to use Java. (My teammates use Java.) Background: I'm a self-taught JavaScript programmer, and it hurts to write Java code. I find it very verbose and inflexible, and I feel slowed down when having to declare types and decide which of the eighty list data structure to use. I'm also frustrated about the lack of functional programming features and how verbose using regular expressions, arrays, and dictionaries are. As an example, consider the problem of finding the length of the longest string of consecutive characters in a given string. So the string XX22BBBBccXX222 would give 4, for the string of four Bs. In Java, I'd have to loop through and manually count characters and manually keep track of the maximum. (That's at least as far as I'm aware -- I'm not as familiar with Java as I am with JavaScript.) In JavaScript, I'd find it like this: var max = Math.max.apply(Math, str.match(/(.)\1*/g).map(function (s) { return s.length; })); Much quicker and simpler, in my book. The question: what are some Java features, techniques, or patterns well-suited for fast, algorithmic coding?

    Read the article

  • Code Complete 2ed, composition and delegation.

    - by Arlukin
    Hi there. After a couple of weeks reading on this forum I thought it was time for me to do my first post. I'm currently rereading Code Complete. I think it's 15 years since the last time, and I find that I still can't write code ;-) Anyway on page 138 in Code Complete you find this coding horror example. (I have removed some of the code) class Emplyee { public: FullName GetName() const; Address GetAddress() const; PhoneNumber GetWorkPhone() const; ... bool IsZipCodeValid( Address address); ... private: ... } What Steve thinks is bad is that the functions are loosely related. Or has he writes "There's no logical connection between employees and routines that check ZIP codes, phone numbers or job classifications" Ok I totally agree with him. Maybe something like the below example is better. class ZipCode { public: bool IsValid() const; ... } class Address { public: ZipCode GetZipCode() const; ... } class Employee { public: Address GetAddress() const; ... } When checking if the zip is valid you would need to do something like this. employee.GetAddress().GetZipCode().IsValid(); And that is not good regarding to the Law of Demeter ([http://en.wikipedia.org/wiki/Law_of_Demeter][1]). So if you like to remove two of the three dots, you need to use delegation and a couple of wrapper functions like this. class ZipCode { public: bool IsValid(); } class Address { public: ZipCode GetZipCode() const; bool IsZipCodeValid() {return GetZipCode()->IsValid()); } class Employee { public: FullName GetName() const; Address GetAddress() const; bool IsZipCodeValid() {return GetAddress()->IsZipCodeValid()); PhoneNumber GetWorkPhone() const; } employee.IsZipCodeValid(); But then again you have routines that has no logical connection. I personally think that all three examples in this post are bad. Is it some other way that I haven't thougt about? //Daniel

    Read the article

  • Implicit vs explicit getters/setters in AS3, which to use and why?

    - by James
    Since the advent of AS3 I have been working like this: private var loggy:String; public function getLoggy ():String { return loggy; } public function setLoggy ( loggy:String ):void { // checking to make sure loggy's new value is kosher etc... this.loggy = loggy; } and have avoided working like this: private var _loggy:String; public function get loggy ():String { return loggy; } public function set loggy ( loggy:String ):void { // checking to make sure loggy's new value is kosher etc... this.loggy = loggy; } I have avoided using AS3's implicit getters/setters partly so that I can just start typing "get.." and content assist will give me a list of all my getters, and likewise for my setters. I also dislike underscores in my code which turned me off the implicit route. Another reason is that I prefer the feel of this: whateverObject.setLoggy( "loggy's awesome new value!" ); to this: whateverObject.loggy = "loggy's awesome new value!"; I feel that the former better reflects what is actually happening in the code. I am calling functions, not setting values directly. After installing Flash Builder and the great new plugin SourceMate ( which helps to get some of the useful features that FDT is famous into FB ) I realized that when I use SourceMate's "generate getters and setters" feature it automatically sets my code up using the implicit route: private var _loggy:String; public function get loggy ():String { return loggy; } public function set loggy ( loggy:String ):void { // do whatever is needed to check to make sure loggy is an acceptable value this.loggy = loggy; } I figure that these SourceMate people must know what they are doing or they wouldn't be writing workflow enhancement plugins for coding in AS3, so now I am questioning my ways. So my question to you is: Can anyone give me a good reason why I should give up my explicit g/s ways, start using the implicit technique, and embrace those stinky little _underscores for my private vars? Or back me up in my reasons for doing things the way that I do?

    Read the article

  • Why does WPF Style to show validation errors in ToolTip work for a TextBox but fails for a ComboBox?

    - by Mike B
    I am using a typical Style to display validation errors as a tooltip from IErrorDataInfo for a textbox as shown below and it works fine. <Style TargetType="{x:Type TextBox}"> <Style.Triggers> <Trigger Property="Validation.HasError" Value="true"> <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/> </Trigger> </Style.Triggers> </Style> But when i try to do the same thing for a ComboBox like this it fails <Style TargetType="{x:Type ComboBox}"> <Style.Triggers> <Trigger Property="Validation.HasError" Value="true"> <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/> </Trigger> </Style.Triggers> </Style> The error I get in the output window is: System.Windows.Data Error: 17 : Cannot get 'Item[]' value (type 'ValidationError') from '(Validation.Errors)' (type 'ReadOnlyObservableCollection`1'). BindingExpression:Path=(0)[0].ErrorContent; DataItem='ComboBox' (Name='ownerComboBox'); target element is 'ComboBox' (Name='ownerComboBox'); target property is 'ToolTip' (type 'Object') ArgumentOutOfRangeException:'System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.Parameter name: index' Oddly it also attempts to make invalid Database changes when I close the window if I change any ComboBox values (This is also when the binding error occurs)!!! Cannot insert the value NULL into column 'EmpFirstName', table 'OITaskManager.dbo.Employees'; column does not allow nulls. INSERT fails. The statement has been terminated. Simply by commenting the style out everyting works perfectly. How do I fix this? Just in case anyone needs it one of the comboBox' xaml follows: <ComboBox ItemsSource="{Binding Path=Employees}" SelectedValuePath="EmpID" SelectedValue="{Binding Path=SelectedIssue.Employee2.EmpID, Mode=OneWay, ValidatesOnDataErrors=True}" ItemTemplate="{StaticResource LastNameFirstComboBoxTemplate}" Height="28" Name="ownerComboBox" Width="120" Margin="2" SelectionChanged="ownerComboBox_SelectionChanged" /> <DataTemplate x:Key="LastNameFirstComboBoxTemplate"> <TextBlock> <TextBlock.Text> <MultiBinding StringFormat="{}{1}, {0}" > <Binding Path="EmpFirstName" /> <Binding Path="EmpLastName" /> </MultiBinding> </TextBlock.Text> </TextBlock> </DataTemplate> SelectionChanged: (I do plan to implement commanding before long but, as this is my first WPF project I have not gone full MVVM yet. I am trying to take things in small-medium sized bites) // This is done this way to maintain the DataContext Integrity // and avoid an error due to an Object being "Not New" in Linq-to-SQL private void ownerComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { Employee currentEmpl = ownerComboBox.SelectedItem as Employee; if (currentEmpl != null && currentEmpl != statusBoardViewModel.SelectedIssue.Employee2) { statusBoardViewModel.SelectedIssue.Employee2 = currentEmpl; } }

    Read the article

  • When should I use Perl's AUTOLOAD?

    - by Robert S. Barnes
    In "Perl Best Practices" the very first line in the section on AUTOLOAD is: Don't use AUTOLOAD However all the cases he describes are dealing with OO or Modules. I have a stand alone script in which some command line switches control which versions of particular functions get defined. Now I know I could just take the conditionals and the evals and stick them naked at the top of my file before everything else, but I find it convenient and cleaner to put them in AUTOLOAD at the end of the file. Is this bad practice / style? If you think so why, and is there a another way to do it? As per brian's request I'm basically using this to do conditional compilation based on command line switches. I don't mind some constructive criticism. sub AUTOLOAD { our $AUTOLOAD; (my $method = $AUTOLOAD) =~ s/.*:://s; # remove package name if ($method eq 'tcpdump' && $tcpdump) { eval q( sub tcpdump { my $msg = shift; warn gf_time()." Thread ".threads->tid().": $msg\n"; } ); } elsif ($method eq 'loginfo' && $debug) { eval q( sub loginfo { my $msg = shift; $msg =~ s/$CRLF/\n/g; print gf_time()." Thread ".threads->tid().": $msg\n"; } ); } elsif ($method eq 'build_get') { if ($pipelining) { eval q( sub build_get { my $url = shift; my $base = shift; $url = "http://".$url unless $url =~ /^http/; return "GET $url HTTP/1.1${CRLF}Host: $base$CRLF$CRLF"; } ); } else { eval q( sub build_get { my $url = shift; my $base = shift; $url = "http://".$url unless $url =~ /^http/; return "GET $url HTTP/1.1${CRLF}Host: $base${CRLF}Connection: close$CRLF$CRLF"; } ); } } elsif ($method eq 'grow') { eval q{ require Convert::Scalar qw(grow); }; if ($@) { eval q( sub grow {} ); } goto &$method; } else { eval "sub $method {}"; return; } die $@ if $@; goto &$method; }

    Read the article

  • Differing styles in Python program: what do you suggest?

    - by Noctis Skytower
    A friend of mine wanted help learning to program, so he gave me all the programs that he wrote for his previous classes. The last program that he wrote was an encryption program, and after rewriting all his programs in Python, this is how his encryption program turned out (after adding my own requirements). #! /usr/bin/env python ################################################################################ """\ CLASS INFORMATION ----------------- Program Name: Program 11 Programmer: Stephen Chappell Instructor: Stephen Chappell for CS 999-0, Python Due Date: 17 May 2010 DOCUMENTATION ------------- This is a simple encryption program that can encode and decode messages.""" ################################################################################ import sys KEY_FILE = 'Key.txt' BACKUP = '''\ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO\ PQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ _@/6-UC'GzaV0%5Mo9g+yNh8b">Bi=<Lx [sQn#^R.D2Xc(\ Jm!4e${lAEWud&t7]H\`}pvPw)FY,Z~?qK|3SOfk*:1;jTrI''' ################################################################################ def main(): "Run the program: loads key, runs processing loop, and saves key." encode_map, decode_map = load_key(KEY_FILE) try: run_interface_loop(encode_map, decode_map) except SystemExit: pass save_key(KEY_FILE, encode_map) def run_interface_loop(encode_map, decode_map): "Shows the menu and runs the appropriate command." print('This program handles encryption via a customizable key.') while True: print('''\ MENU ==== (1) Encode (2) Decode (3) Custom (4) Finish''') switch = get_character('Select: ', tuple('1234')) FUNC[switch](encode_map, decode_map) def get_character(prompt, choices): "Gets a valid menu option and returns it." while True: sys.stdout.write(prompt) sys.stdout.flush() line = sys.stdin.readline()[:-1] if not line: sys.exit() if line in choices: return line print(repr(line), 'is not a valid choice.') ################################################################################ def load_key(filename): "Gets the key file data and returns encoding/decoding dictionaries." plain, cypher = open_file(filename) return dict(zip(plain, cypher)), dict(zip(cypher, plain)) def open_file(filename): "Load the keys and tries to create it when not available." while True: try: with open(filename) as file: plain, cypher = file.read().split('\n') return plain, cypher except: with open(filename, 'w') as file: file.write(BACKUP) def save_key(filename, encode_map): "Dumps the map into two buffers and saves them to the key file." plain = cypher = str() for p, c in encode_map.items(): plain += p cypher += c with open(filename, 'w') as file: file.write(plain + '\n' + cypher) ################################################################################ def encode(encode_map, decode_map): "Encodes message for the user." print('Enter your message to encode (EOF when finished).') message = get_message() for char in message: sys.stdout.write(encode_map[char] if char in encode_map else char) def decode(encode_map, decode_map): "Decodes message for the user." print('Enter your message to decode (EOF when finished).') message = get_message() for char in message: sys.stdout.write(decode_map[char] if char in decode_map else char) def custom(encode_map, decode_map): "Allows user to edit the encoding/decoding dictionaries." plain, cypher = get_new_mapping() for p, c in zip(plain, cypher): encode_map[p] = c decode_map[c] = p ################################################################################ def get_message(): "Gets and returns text entered by the user (until EOF)." buffer = [] while True: line = sys.stdin.readline() if line: buffer.append(line) else: return ''.join(buffer) def get_new_mapping(): "Prompts for strings to edit encoding/decoding maps." while True: plain = get_unique_chars('What do you want to encode from?') cypher = get_unique_chars('What do you want to encode to?') if len(plain) == len(cypher): return plain, cypher print('Both lines should have the same length.') def get_unique_chars(prompt): "Gets strings that only contain unique characters." print(prompt) while True: line = input() if len(line) == len(set(line)): return line print('There were duplicate characters: please try again.') ################################################################################ # This map is used for dispatching commands in the interface loop. FUNC = {'1': encode, '2': decode, '3': custom, '4': lambda a, b: sys.exit()} ################################################################################ if __name__ == '__main__': main() For all those Python programmers out there, your help is being requested. How should the formatting (not necessarily the coding by altered to fit Python's style guide? My friend does not need to be learning things that are not correct. If you have suggestions on the code, feel free to post them to this wiki as well.

    Read the article

< Previous Page | 63 64 65 66 67 68 69 70 71 72 73 74  | Next Page >